Merge remote-tracking branch 'origin/main' into side-by-side-diff-without-filtering

Cole Miller created

Change summary

.factory/prompts/docs-automation/phase2-explore.md                                                          |   55 
.factory/prompts/docs-automation/phase3-analyze.md                                                          |   57 
.factory/prompts/docs-automation/phase4-plan.md                                                             |   76 
.factory/prompts/docs-automation/phase5-apply.md                                                            |   67 
.factory/prompts/docs-automation/phase6-summarize.md                                                        |   54 
.factory/prompts/docs-automation/phase7-commit.md                                                           |   67 
.github/ISSUE_TEMPLATE/10_bug_report.yml                                                                    |   16 
.github/actionlint.yml                                                                                      |    1 
.github/actions/build_docs/action.yml                                                                       |   12 
.github/workflows/after_release.yml                                                                         |   25 
.github/workflows/autofix_pr.yml                                                                            |  132 
.github/workflows/cherry_pick.yml                                                                           |    2 
.github/workflows/community_champion_auto_labeler.yml                                                       |    1 
.github/workflows/community_close_stale_issues.yml                                                          |   25 
.github/workflows/docs_automation.yml                                                                       |  264 
.github/workflows/extension_bump.yml                                                                        |   30 
.github/workflows/extension_tests.yml                                                                       |    4 
.github/workflows/release.yml                                                                               |    8 
.github/workflows/run_tests.yml                                                                             |   13 
.gitignore                                                                                                  |    5 
.mailmap                                                                                                    |    3 
.rules                                                                                                      |    6 
CONTRIBUTING.md                                                                                             |   36 
Cargo.lock                                                                                                  |  447 
Cargo.toml                                                                                                  |   94 
Dockerfile-collab                                                                                           |    6 
README.md                                                                                                   |    3 
REVIEWERS.conl                                                                                              |   10 
assets/icons/box.svg                                                                                        |    5 
assets/icons/debug_step_back.svg                                                                            |    1 
assets/icons/debug_step_into.svg                                                                            |    6 
assets/icons/debug_step_out.svg                                                                             |    6 
assets/icons/debug_step_over.svg                                                                            |    6 
assets/icons/git_branch_plus.svg                                                                            |    8 
assets/icons/inception.svg                                                                                  |   11 
assets/icons/zed_agent_two.svg                                                                              |    5 
assets/keymaps/default-linux.json                                                                           |  440 
assets/keymaps/default-macos.json                                                                           |  453 
assets/keymaps/default-windows.json                                                                         |  419 
assets/keymaps/initial.json                                                                                 |    6 
assets/keymaps/linux/atom.json                                                                              |   34 
assets/keymaps/linux/cursor.json                                                                            |   33 
assets/keymaps/linux/emacs.json                                                                             |   42 
assets/keymaps/linux/jetbrains.json                                                                         |   54 
assets/keymaps/linux/sublime_text.json                                                                      |   26 
assets/keymaps/macos/atom.json                                                                              |   34 
assets/keymaps/macos/cursor.json                                                                            |   33 
assets/keymaps/macos/emacs.json                                                                             |   42 
assets/keymaps/macos/jetbrains.json                                                                         |   54 
assets/keymaps/macos/sublime_text.json                                                                      |   26 
assets/keymaps/macos/textmate.json                                                                          |   32 
assets/keymaps/storybook.json                                                                               |    6 
assets/keymaps/vim.json                                                                                     |  299 
assets/prompts/content_prompt_v2.hbs                                                                        |   40 
assets/settings/default.json                                                                                |  393 
assets/settings/initial_debug_tasks.json                                                                    |    8 
assets/settings/initial_server_settings.json                                                                |    2 
assets/settings/initial_tasks.json                                                                          |    4 
assets/settings/initial_user_settings.json                                                                  |    4 
assets/themes/ayu/ayu.json                                                                                  |    3 
assets/themes/gruvbox/gruvbox.json                                                                          |  298 
assets/themes/one/one.json                                                                                  |  106 
clippy.toml                                                                                                 |    1 
crates/acp_thread/Cargo.toml                                                                                |    1 
crates/acp_thread/src/acp_thread.rs                                                                         |  470 
crates/acp_thread/src/connection.rs                                                                         |   47 
crates/acp_thread/src/diff.rs                                                                               |    2 
crates/acp_thread/src/mention.rs                                                                            |   21 
crates/acp_thread/src/terminal.rs                                                                           |   40 
crates/acp_tools/src/acp_tools.rs                                                                           |    4 
crates/action_log/src/action_log.rs                                                                         |   10 
crates/agent/Cargo.toml                                                                                     |    1 
crates/agent/src/agent.rs                                                                                   |  430 
crates/agent/src/db.rs                                                                                      |    2 
crates/agent/src/edit_agent/evals.rs                                                                        |  719 
crates/agent/src/edit_agent/evals/fixtures/zode/prompt.md                                                   |    4 
crates/agent/src/history_store.rs                                                                           |   19 
crates/agent/src/native_agent_server.rs                                                                     |   40 
crates/agent/src/templates/system_prompt.hbs                                                                |    2 
crates/agent/src/tests/mod.rs                                                                               |  497 
crates/agent/src/thread.rs                                                                                  |  282 
crates/agent/src/tools.rs                                                                                   |    8 
crates/agent/src/tools/context_server_registry.rs                                                           |  200 
crates/agent/src/tools/edit_file_tool.rs                                                                    |   63 
crates/agent/src/tools/find_path_tool.rs                                                                    |   50 
crates/agent/src/tools/grep_tool.rs                                                                         |   19 
crates/agent/src/tools/read_file_tool.rs                                                                    |   67 
crates/agent/src/tools/restore_file_from_disk_tool.rs                                                       |  352 
crates/agent/src/tools/save_file_tool.rs                                                                    |  351 
crates/agent/src/tools/terminal_tool.rs                                                                     |   40 
crates/agent/src/tools/thinking_tool.rs                                                                     |    6 
crates/agent/src/tools/web_search_tool.rs                                                                   |   47 
crates/agent_servers/src/acp.rs                                                                             |  256 
crates/agent_servers/src/agent_servers.rs                                                                   |   31 
crates/agent_servers/src/claude.rs                                                                          |   53 
crates/agent_servers/src/codex.rs                                                                           |   53 
crates/agent_servers/src/custom.rs                                                                          |   78 
crates/agent_servers/src/e2e_tests.rs                                                                       |   27 
crates/agent_servers/src/gemini.rs                                                                          |    6 
crates/agent_settings/Cargo.toml                                                                            |    1 
crates/agent_settings/src/agent_settings.rs                                                                 |   20 
crates/agent_ui/Cargo.toml                                                                                  |   13 
crates/agent_ui/src/acp/entry_view_state.rs                                                                 |   35 
crates/agent_ui/src/acp/message_editor.rs                                                                   |  406 
crates/agent_ui/src/acp/mode_selector.rs                                                                    |   19 
crates/agent_ui/src/acp/model_selector.rs                                                                   |  480 
crates/agent_ui/src/acp/model_selector_popover.rs                                                           |   46 
crates/agent_ui/src/acp/thread_history.rs                                                                   |   24 
crates/agent_ui/src/acp/thread_view.rs                                                                      |  553 
crates/agent_ui/src/agent_configuration.rs                                                                  |   66 
crates/agent_ui/src/agent_configuration/add_llm_provider_modal.rs                                           |   10 
crates/agent_ui/src/agent_configuration/configure_context_server_modal.rs                                   |    2 
crates/agent_ui/src/agent_configuration/configure_context_server_tools_modal.rs                             |    2 
crates/agent_ui/src/agent_configuration/manage_profiles_modal.rs                                            |  147 
crates/agent_ui/src/agent_diff.rs                                                                           |   19 
crates/agent_ui/src/agent_model_selector.rs                                                                 |   73 
crates/agent_ui/src/agent_panel.rs                                                                          |  283 
crates/agent_ui/src/agent_ui.rs                                                                             |   56 
crates/agent_ui/src/buffer_codegen.rs                                                                       |  693 
crates/agent_ui/src/completion_provider.rs                                                                  |   14 
crates/agent_ui/src/favorite_models.rs                                                                      |   30 
crates/agent_ui/src/inline_assistant.rs                                                                     |  649 
crates/agent_ui/src/inline_prompt_editor.rs                                                                 |  528 
crates/agent_ui/src/language_model_selector.rs                                                              |  332 
crates/agent_ui/src/profile_selector.rs                                                                     |   58 
crates/agent_ui/src/slash_command.rs                                                                        |    1 
crates/agent_ui/src/terminal_codegen.rs                                                                     |   83 
crates/agent_ui/src/terminal_inline_assistant.rs                                                            |   89 
crates/agent_ui/src/text_thread_editor.rs                                                                   |  215 
crates/agent_ui/src/ui.rs                                                                                   |    4 
crates/agent_ui/src/ui/acp_onboarding_modal.rs                                                              |    4 
crates/agent_ui/src/ui/agent_notification.rs                                                                |    3 
crates/agent_ui/src/ui/claude_code_onboarding_modal.rs                                                      |    4 
crates/agent_ui/src/ui/hold_for_default.rs                                                                  |    2 
crates/agent_ui/src/ui/model_selector_components.rs                                                         |  249 
crates/agent_ui/src/ui/onboarding_modal.rs                                                                  |    4 
crates/agent_ui/src/ui/unavailable_editing_tooltip.rs                                                       |   29 
crates/agent_ui_v2/Cargo.toml                                                                               |   47 
crates/agent_ui_v2/LICENSE-GPL                                                                              |    0 
crates/agent_ui_v2/src/agent_thread_pane.rs                                                                 |  287 
crates/agent_ui_v2/src/agent_ui_v2.rs                                                                       |    4 
crates/agent_ui_v2/src/agents_panel.rs                                                                      |  437 
crates/agent_ui_v2/src/thread_history.rs                                                                    |  753 
crates/ai_onboarding/src/agent_api_keys_onboarding.rs                                                       |   20 
crates/ai_onboarding/src/agent_panel_onboarding_content.rs                                                  |   21 
crates/anthropic/src/anthropic.rs                                                                           |  222 
crates/anthropic/src/batches.rs                                                                             |  190 
crates/assistant_slash_commands/Cargo.toml                                                                  |    1 
crates/assistant_slash_commands/src/file_command.rs                                                         |  102 
crates/assistant_text_thread/Cargo.toml                                                                     |    2 
crates/assistant_text_thread/src/assistant_text_thread_tests.rs                                             |    9 
crates/assistant_text_thread/src/text_thread.rs                                                             |   68 
crates/assistant_text_thread/src/text_thread_store.rs                                                       |   79 
crates/bedrock/src/bedrock.rs                                                                               |    2 
crates/bedrock/src/models.rs                                                                                |  201 
crates/buffer_diff/src/buffer_diff.rs                                                                       |   46 
crates/call/src/call_impl/room.rs                                                                           |   12 
crates/cli/src/main.rs                                                                                      |   51 
crates/client/Cargo.toml                                                                                    |    2 
crates/client/src/client.rs                                                                                 |   72 
crates/cloud_llm_client/src/cloud_llm_client.rs                                                             |    2 
crates/cloud_llm_client/src/predict_edits_v3.rs                                                             |   88 
crates/cloud_zeta2_prompt/Cargo.toml                                                                        |   23 
crates/cloud_zeta2_prompt/src/cloud_zeta2_prompt.rs                                                         | 1075 
crates/cloud_zeta2_prompt/src/retrieval_prompt.rs                                                           |  244 
crates/codestral/Cargo.toml                                                                                 |    2 
crates/codestral/src/codestral.rs                                                                           |   23 
crates/collab/Cargo.toml                                                                                    |    2 
crates/collab/README.md                                                                                     |   12 
crates/collab/k8s/migrate.template.yml                                                                      |   21 
crates/collab/migrations.sqlite/20221109000000_test_schema.sql                                              |    2 
crates/collab/migrations/20210527024318_initial_schema.sql                                                  |   20 
crates/collab/migrations/20210607190313_create_access_tokens.sql                                            |    7 
crates/collab/migrations/20210805175147_create_chat_tables.sql                                              |   46 
crates/collab/migrations/20210916123647_add_nonce_to_channel_messages.sql                                   |    4 
crates/collab/migrations/20210920192001_add_interests_to_signups.sql                                        |    4 
crates/collab/migrations/20220421165757_drop_signups.sql                                                    |    1 
crates/collab/migrations/20220505144506_add_trigram_index_to_users.sql                                      |    2 
crates/collab/migrations/20220506130724_create_contacts.sql                                                 |   11 
crates/collab/migrations/20220518151305_add_invites_to_users.sql                                            |    9 
crates/collab/migrations/20220523232954_allow_user_deletes.sql                                              |    6 
crates/collab/migrations/20220620211403_create_projects.sql                                                 |   24 
crates/collab/migrations/20220913211150_create_signups.sql                                                  |   27 
crates/collab/migrations/20220929182110_add_metrics_id.sql                                                  |    2 
crates/collab/migrations/20221111092550_reconnection_support.sql                                            |   90 
crates/collab/migrations/20221125192125_add_added_to_mailing_list_to_signups.sql                            |    2 
crates/collab/migrations/20221207165001_add_connection_lost_to_room_participants.sql                        |    7 
crates/collab/migrations/20221213125710_index_room_participants_on_room_id.sql                              |    1 
crates/collab/migrations/20221214144346_change_epoch_from_uuid_to_integer.sql                               |   30 
crates/collab/migrations/20221219181850_project_reconnection_support.sql                                    |    3 
crates/collab/migrations/20230103200902_replace_is_completed_with_completed_scan_id.sql                     |    3 
crates/collab/migrations/20230202155735_followers.sql                                                       |   15 
crates/collab/migrations/20230508211523_add-repository-entries.sql                                          |   13 
crates/collab/migrations/20230511004019_add_repository_statuses.sql                                         |   15 
crates/collab/migrations/20230529164700_add_worktree_settings_files.sql                                     |   10 
crates/collab/migrations/20230605191135_remove_repository_statuses.sql                                      |    2 
crates/collab/migrations/20230616134535_add_is_external_to_worktree_entries.sql                             |    2 
crates/collab/migrations/20230727150500_add_channels.sql                                                    |   30 
crates/collab/migrations/20230819154600_add_channel_buffers.sql                                             |   40 
crates/collab/migrations/20230825190322_add_server_feature_flags.sql                                        |   16 
crates/collab/migrations/20230907114200_add_channel_messages.sql                                            |   19 
crates/collab/migrations/20230925210437_add_channel_changes.sql                                             |   19 
crates/collab/migrations/20230926102500_add_participant_index_to_room_participants.sql                      |    1 
crates/collab/migrations/20231004130100_create_notifications.sql                                            |   22 
crates/collab/migrations/20231009181554_add_release_channel_to_rooms.sql                                    |    1 
crates/collab/migrations/20231010114600_add_unique_index_on_rooms_channel_id.sql                            |    1 
crates/collab/migrations/20231011214412_add_guest_role.sql                                                  |    4 
crates/collab/migrations/20231017185833_projects_room_id_fkey_on_delete_cascade.sql                         |    8 
crates/collab/migrations/20231018102700_create_mentions.sql                                                 |   11 
crates/collab/migrations/20231024085546_move_channel_paths_to_channels_table.sql                            |   12 
crates/collab/migrations/20240103025509_add_role_to_room_participants.sql                                   |    1 
crates/collab/migrations/20240111085546_fix_column_name.sql                                                 |    1 
crates/collab/migrations/20240117150300_add_impersonator_to_access_tokens.sql                               |    1 
crates/collab/migrations/20240122174606_add_contributors.sql                                                |    5 
crates/collab/migrations/20240122224506_add_requires_zed_cla_column_to_channels.sql                         |    1 
crates/collab/migrations/20240129193601_fix_parent_path_index.sql                                           |    4 
crates/collab/migrations/20240203113741_add_reply_to_message.sql                                            |    1 
crates/collab/migrations/20240207041417_add_in_call_column_to_room_participants.sql                         |    3 
crates/collab/migrations/20240213200201_remove_unused_room_columns.sql                                      |    4 
crates/collab/migrations/20240214102900_add_extensions.sql                                                  |   22 
crates/collab/migrations/20240220234826_add_rate_buckets.sql                                                |   11 
crates/collab/migrations/20240221151017_add_edited_at_field_to_channel_message.sql                          |    1 
crates/collab/migrations/20240226163408_hosted_projects.sql                                                 |   11 
crates/collab/migrations/20240226164505_unique_channel_names.sql                                            |    3 
crates/collab/migrations/20240227215556_hosted_projects_in_projects.sql                                     |    3 
crates/collab/migrations/20240307163119_denormalize_buffer_ops.sql                                          |   17 
crates/collab/migrations/20240315182903_non_null_channel_role.sql                                           |    4 
crates/collab/migrations/20240315183903_channel_parent_path_not_null.sql                                    |    2 
crates/collab/migrations/20240320124800_add_extension_schema_version.sql                                    |    2 
crates/collab/migrations/20240321162658_add_devservers.sql                                                  |    7 
crates/collab/migrations/20240335123500_add_extension_wasm_api_version.sql                                  |    1 
crates/collab/migrations/20240402155003_add_dev_server_projects.sql                                         |    9 
crates/collab/migrations/20240409082755_create_embeddings.sql                                               |    9 
crates/collab/migrations/20240412165156_dev_servers_per_user.sql                                            |    7 
crates/collab/migrations/20240417192746_unique_remote_projects_by_paths.sql                                 |    3 
crates/collab/migrations/20240502150229_rename_to_dev_server_projects.sql                                   |   11 
crates/collab/migrations/20240502180204_remove_old_remote_projects.sql                                      |    2 
crates/collab/migrations/20240514164510_store_ssh_connect_string.sql                                        |    1 
crates/collab/migrations/20240715230940_add_worktrees_to_dev_server_projects.sql                            |    4 
crates/collab/migrations/20240729170526_add_billing_subscription.sql                                        |   12 
crates/collab/migrations/20240730014107_add_billing_customer.sql                                            |   18 
crates/collab/migrations/20240730122654_add_last_stripe_event_id.sql                                        |    2 
crates/collab/migrations/20240730182554_add_processed_stripe_events.sql                                     |   11 
crates/collab/migrations/20240731120800_add_stripe_cancel_at_to_billing_subscriptions.sql                   |    1 
crates/collab/migrations/20240812073542_add_accepted_tos_at.sql                                             |    1 
crates/collab/migrations/20240812204045_add_github_user_created_at_to_users.sql                             |    1 
crates/collab/migrations/20240816181658_add_enabled_for_all_to_feature_flags.sql                            |    1 
crates/collab/migrations/20240822215737_add_unique_constraint_on_github_user_id_on_users.sql                |    4 
crates/collab/migrations/20240823155956_add_is_fifo_to_worktree_entries.sql                                 |    2 
crates/collab/migrations/20241002120231_add_local_settings_kind.sql                                         |    1 
crates/collab/migrations/20241009190639_add_billing_preferences.sql                                         |    8 
crates/collab/migrations/20241019184824_adjust_symlink_data.sql                                             |    2 
crates/collab/migrations/20241021202606_add_custom_llm_monthly_allowance_in_cents_to_users.sql              |    1 
crates/collab/migrations/20241023201725_remove_dev_servers.sql                                              |    6 
crates/collab/migrations/20241121185750_add_breakpoints.sql                                                 |   11 
crates/collab/migrations/20250108184547_add_stripe_cancellation_reason_to_billing_subscriptions.sql         |    2 
crates/collab/migrations/20250113230049_expand_git_status_information.sql                                   |   13 
crates/collab/migrations/20250117100620_add_user_name.sql                                                   |    1 
crates/collab/migrations/20250204224004_add_has_overdue_invoices_to_billing_customers.sql                   |    2 
crates/collab/migrations/20250205192813_add_provides_fields_to_extension_versions.sql                       |   10 
crates/collab/migrations/20250205232017_add_conflicts_to_repositories.sql                                   |    2 
crates/collab/migrations/20250210223746_add_branch_summary.sql                                              |    2 
crates/collab/migrations/20250212060936_add_worktree_branch_summary.sql                                     |    1 
crates/collab/migrations/20250319182812_create_project_repositories.sql                                     |   32 
crates/collab/migrations/20250415164141_add_kind_and_period_to_billing_subscriptions.sql                    |    4 
crates/collab/migrations/20250422194500_add_trial_started_at_to_billing_customers.sql                       |    2 
crates/collab/migrations/20250423150129_add_head_commit_details_to_project_repositories.sql                 |    2 
crates/collab/migrations/20250425201930_add_model_request_overages_to_billing_preferences.sql               |    3 
crates/collab/migrations/20250530175450_add_channel_order.sql                                               |   16 
crates/collab/migrations/20250612153105_add_collaborator_commit_email.sql                                   |    4 
crates/collab/migrations/20250617082236_add_debug_adapter_provides_field_to_extensions.sql                  |    2 
crates/collab/migrations/20250618090000_add_agent_servers_provides_field_to_extensions.sql                  |    2 
crates/collab/migrations/20250702185129_add_cascading_delete_to_repository_entries.sql                      |   25 
crates/collab/migrations/20250707182700_add_access_tokens_cascade_delete_on_user.sql                        |    3 
crates/collab/migrations/20250804080620_language_server_capabilities.sql                                    |    5 
crates/collab/migrations/20250816124707_make_admin_required_on_users.sql                                    |    2 
crates/collab/migrations/20250816133027_add_orb_customer_id_to_billing_customers.sql                        |    2 
crates/collab/migrations/20250816135346_drop_rate_buckets_table.sql                                         |    1 
crates/collab/migrations/20250818192156_add_git_merge_message.sql                                           |    1 
crates/collab/migrations/20250819022421_add_orb_subscription_id_to_billing_subscriptions.sql                |    2 
crates/collab/migrations/20250819225916_make_stripe_fields_optional_on_billing_subscription.sql             |    3 
crates/collab/migrations/20250821133754_add_orb_subscription_status_and_period_to_billing_subscriptions.sql |    4 
crates/collab/migrations/20250827084812_worktree_in_servers.sql                                             |    2 
crates/collab/migrations/20250913035238_add_orb_cancellation_date_to_billing_subscriptions.sql              |    2 
crates/collab/migrations/20250914022147_add_orb_portal_url_to_billing_customers.sql                         |    2 
crates/collab/migrations/20250916173002_add_path_style_to_project.sql                                       |    1 
crates/collab/migrations/20251002214229_add_token_spend_in_cents_to_billing_subscriptions.sql               |    3 
crates/collab/migrations/20251008120000_add_is_hidden_to_worktree_entries.sql                               |    2 
crates/collab/migrations/20251110214057_drop_channel_messages.sql                                           |    3 
crates/collab/migrations/20251111161644_drop_embeddings.sql                                                 |    1 
crates/collab/migrations/20251117215316_add_external_id_to_billing_customers.sql                            |    4 
crates/collab/migrations/20251208000000_test_schema.sql                                                     |  899 
crates/collab/migrations_llm/20240806182921_create_providers_and_models.sql                                 |   19 
crates/collab/migrations_llm/20240806213401_create_usages.sql                                               |   19 
crates/collab/migrations_llm/20240809130000_change_rate_limit_columns_to_bigint.sql                         |    4 
crates/collab/migrations_llm/20240809160000_add_pricing_columns_to_models.sql                               |    3 
crates/collab/migrations_llm/20240812184444_add_is_staff_to_usages.sql                                      |    1 
crates/collab/migrations_llm/20240812225346_create_lifetime_usages.sql                                      |    9 
crates/collab/migrations_llm/20240813002237_add_revoked_access_tokens_table.sql                             |    7 
crates/collab/migrations_llm/20241007173634_add_cache_token_counts.sql                                      |   11 
crates/collab/migrations_llm/20241007220716_drop_incorrect_usages_columns.sql                               |    3 
crates/collab/migrations_llm/20241008155620_create_monthly_usages.sql                                       |   13 
crates/collab/migrations_llm/20241010151249_create_billing_events.sql                                       |   12 
crates/collab/migrations_llm/20250404141155_add_granular_token_limits_to_models.sql                         |    3 
crates/collab/migrations_llm/20250415213005_add_subscription_usages.sql                                     |   10 
crates/collab/migrations_llm/20250416181354_add_plan_to_subscription_usages.sql                             |    4 
crates/collab/migrations_llm/20250425171838_add_subscription_usage_meters.sql                               |    8 
crates/collab/migrations_llm/20250429143553_add_mode_to_subscription_usage_meters.sql                       |    6 
crates/collab/migrations_llm/20250503162708_add_v2_subscription_usage_and_meter_tables.sql                  |   23 
crates/collab/migrations_llm/20250504132836_drop_legacy_subscription_usage_and_meter_tables.sql             |    2 
crates/collab/migrations_llm/20250521211721_drop_monthly_and_lifetime_usages_tables.sql                     |    2 
crates/collab/migrations_llm/20250521222416_drop_billing_events_table.sql                                   |    1 
crates/collab/src/api/contributors.rs                                                                       |   85 
crates/collab/src/db/queries/projects.rs                                                                    |    6 
crates/collab/src/db/queries/rooms.rs                                                                       |    2 
crates/collab/src/db/tables.rs                                                                              |    1 
crates/collab/src/db/tables/project_repository.rs                                                           |    2 
crates/collab/src/db/tables/signup.rs                                                                       |   28 
crates/collab/src/db/tests.rs                                                                               |   17 
crates/collab/src/db/tests/migrations.rs                                                                    |    0 
crates/collab/src/lib.rs                                                                                    |    2 
crates/collab/src/llm.rs                                                                                    |    1 
crates/collab/src/llm/db.rs                                                                                 |   98 
crates/collab/src/main.rs                                                                                   |   62 
crates/collab/src/rpc.rs                                                                                    |    2 
crates/collab/src/tests.rs                                                                                  |   17 
crates/collab/src/tests/editor_tests.rs                                                                     |  147 
crates/collab/src/tests/integration_tests.rs                                                                |   13 
crates/collab/src/tests/remote_editing_collaboration_tests.rs                                               |  288 
crates/collab/src/tests/test_server.rs                                                                      |    3 
crates/collab_ui/src/collab_panel.rs                                                                        |   34 
crates/collab_ui/src/collab_panel/channel_modal.rs                                                          |    2 
crates/command_palette/src/command_palette.rs                                                               |  405 
crates/command_palette/src/persistence.rs                                                                   |   10 
crates/component_preview/Cargo.toml                                                                         |   45 
crates/component_preview/LICENSE-GPL                                                                        |    1 
crates/component_preview/examples/component_preview.rs                                                      |   18 
crates/component_preview/src/component_preview.rs                                                           |   18 
crates/component_preview/src/component_preview_example.rs                                                   |  145 
crates/component_preview/src/persistence.rs                                                                 |    0 
crates/context_server/Cargo.toml                                                                            |    2 
crates/context_server/src/client.rs                                                                         |  103 
crates/context_server/src/context_server.rs                                                                 |   16 
crates/context_server/src/protocol.rs                                                                       |    6 
crates/context_server/src/transport/stdio_transport.rs                                                      |   10 
crates/context_server/src/types.rs                                                                          |    2 
crates/copilot/Cargo.toml                                                                                   |    3 
crates/copilot/src/copilot.rs                                                                               |  234 
crates/copilot/src/copilot_edit_prediction_delegate.rs                                                      |  454 
crates/copilot/src/request.rs                                                                               |  100 
crates/copilot/src/sign_in.rs                                                                               |  708 
crates/crashes/Cargo.toml                                                                                   |    3 
crates/crashes/src/crashes.rs                                                                               |   58 
crates/dap_adapters/src/python.rs                                                                           |    2 
crates/debugger_tools/src/dap_log.rs                                                                        |    6 
crates/debugger_ui/Cargo.toml                                                                               |    2 
crates/debugger_ui/src/attach_modal.rs                                                                      |    4 
crates/debugger_ui/src/debugger_panel.rs                                                                    |  252 
crates/debugger_ui/src/debugger_ui.rs                                                                       |   13 
crates/debugger_ui/src/new_process_modal.rs                                                                 |   27 
crates/debugger_ui/src/onboarding_modal.rs                                                                  |    4 
crates/debugger_ui/src/session/running.rs                                                                   |   21 
crates/debugger_ui/src/session/running/breakpoint_list.rs                                                   |   10 
crates/debugger_ui/src/session/running/console.rs                                                           |    9 
crates/debugger_ui/src/session/running/loaded_source_list.rs                                                |    4 
crates/debugger_ui/src/session/running/memory_view.rs                                                       |    2 
crates/debugger_ui/src/session/running/module_list.rs                                                       |    4 
crates/debugger_ui/src/session/running/stack_frame_list.rs                                                  |   43 
crates/debugger_ui/src/session/running/variable_list.rs                                                     |   11 
crates/debugger_ui/src/tests/inline_values.rs                                                               |  121 
crates/debugger_ui/src/tests/stack_frame_list.rs                                                            |  182 
crates/deepseek/src/deepseek.rs                                                                             |    7 
crates/diagnostics/src/buffer_diagnostics.rs                                                                |   16 
crates/diagnostics/src/diagnostic_renderer.rs                                                               |    2 
crates/diagnostics/src/diagnostics.rs                                                                       |   97 
crates/docs_preprocessor/Cargo.toml                                                                         |    5 
crates/docs_preprocessor/src/main.rs                                                                        |   88 
crates/edit_prediction/Cargo.toml                                                                           |   63 
crates/edit_prediction/license_examples/0bsd.txt                                                            |    0 
crates/edit_prediction/license_examples/apache-2.0-ex0.txt                                                  |    0 
crates/edit_prediction/license_examples/apache-2.0-ex1.txt                                                  |    0 
crates/edit_prediction/license_examples/apache-2.0-ex2.txt                                                  |    0 
crates/edit_prediction/license_examples/apache-2.0-ex3.txt                                                  |    0 
crates/edit_prediction/license_examples/apache-2.0-ex4.txt                                                  |    0 
crates/edit_prediction/license_examples/bsd-1-clause.txt                                                    |    0 
crates/edit_prediction/license_examples/bsd-2-clause-ex0.txt                                                |    0 
crates/edit_prediction/license_examples/bsd-3-clause-ex0.txt                                                |    0 
crates/edit_prediction/license_examples/bsd-3-clause-ex1.txt                                                |    0 
crates/edit_prediction/license_examples/bsd-3-clause-ex2.txt                                                |    0 
crates/edit_prediction/license_examples/bsd-3-clause-ex3.txt                                                |    0 
crates/edit_prediction/license_examples/bsd-3-clause-ex4.txt                                                |    0 
crates/edit_prediction/license_examples/isc.txt                                                             |    0 
crates/edit_prediction/license_examples/mit-ex0.txt                                                         |    0 
crates/edit_prediction/license_examples/mit-ex1.txt                                                         |    0 
crates/edit_prediction/license_examples/mit-ex2.txt                                                         |    0 
crates/edit_prediction/license_examples/mit-ex3.txt                                                         |    0 
crates/edit_prediction/license_examples/upl-1.0.txt                                                         |    0 
crates/edit_prediction/license_examples/zlib-ex0.txt                                                        |    0 
crates/edit_prediction/license_patterns/0bsd-pattern                                                        |    0 
crates/edit_prediction/license_patterns/apache-2.0-pattern                                                  |    0 
crates/edit_prediction/license_patterns/apache-2.0-reference-pattern                                        |    0 
crates/edit_prediction/license_patterns/bsd-pattern                                                         |    0 
crates/edit_prediction/license_patterns/isc-pattern                                                         |    0 
crates/edit_prediction/license_patterns/mit-pattern                                                         |    0 
crates/edit_prediction/license_patterns/upl-1.0-pattern                                                     |    0 
crates/edit_prediction/license_patterns/zlib-pattern                                                        |    0 
crates/edit_prediction/src/capture_example.rs                                                               |  375 
crates/edit_prediction/src/cursor_excerpt.rs                                                                |   78 
crates/edit_prediction/src/edit_prediction.rs                                                               | 2320 
crates/edit_prediction/src/edit_prediction_tests.rs                                                         | 2156 
crates/edit_prediction/src/example_spec.rs                                                                  |  212 
crates/edit_prediction/src/license_detection.rs                                                             |    3 
crates/edit_prediction/src/mercury.rs                                                                       |  322 
crates/edit_prediction/src/onboarding_modal.rs                                                              |    4 
crates/edit_prediction/src/open_ai_response.rs                                                              |   31 
crates/edit_prediction/src/prediction.rs                                                                    |   82 
crates/edit_prediction/src/sweep_ai.rs                                                                      |  186 
crates/edit_prediction/src/udiff.rs                                                                         |  274 
crates/edit_prediction/src/zed_edit_prediction_delegate.rs                                                  |  230 
crates/edit_prediction/src/zeta1.rs                                                                         |  293 
crates/edit_prediction/src/zeta2.rs                                                                         |  243 
crates/edit_prediction_button/src/sweep_api_token_modal.rs                                                  |   84 
crates/edit_prediction_cli/Cargo.toml                                                                       |   32 
crates/edit_prediction_cli/LICENSE-GPL                                                                      |    0 
crates/edit_prediction_cli/build.rs                                                                         |    0 
crates/edit_prediction_cli/src/anthropic_client.rs                                                          |  418 
crates/edit_prediction_cli/src/distill.rs                                                                   |   22 
crates/edit_prediction_cli/src/example.rs                                                                   |  250 
crates/edit_prediction_cli/src/format_prompt.rs                                                             |  293 
crates/edit_prediction_cli/src/headless.rs                                                                  |   29 
crates/edit_prediction_cli/src/load_project.rs                                                              |  357 
crates/edit_prediction_cli/src/main.rs                                                                      |  343 
crates/edit_prediction_cli/src/metrics.rs                                                                   |   55 
crates/edit_prediction_cli/src/paths.rs                                                                     |   27 
crates/edit_prediction_cli/src/predict.rs                                                                   |  291 
crates/edit_prediction_cli/src/progress.rs                                                                  |  508 
crates/edit_prediction_cli/src/retrieve_context.rs                                                          |  192 
crates/edit_prediction_cli/src/score.rs                                                                     |  123 
crates/edit_prediction_cli/src/teacher.prompt.md                                                            |   53 
crates/edit_prediction_context/Cargo.toml                                                                   |   24 
crates/edit_prediction_context/src/assemble_excerpts.rs                                                     |  156 
crates/edit_prediction_context/src/declaration.rs                                                           |  350 
crates/edit_prediction_context/src/declaration_scoring.rs                                                   |  539 
crates/edit_prediction_context/src/edit_prediction_context.rs                                               |  741 
crates/edit_prediction_context/src/edit_prediction_context_tests.rs                                         |  510 
crates/edit_prediction_context/src/excerpt.rs                                                               |   93 
crates/edit_prediction_context/src/fake_definition_lsp.rs                                                   |  329 
crates/edit_prediction_context/src/imports.rs                                                               | 1319 
crates/edit_prediction_context/src/outline.rs                                                               |  126 
crates/edit_prediction_context/src/reference.rs                                                             |  173 
crates/edit_prediction_context/src/syntax_index.rs                                                          | 1069 
crates/edit_prediction_context/src/text_similarity.rs                                                       |  314 
crates/edit_prediction_types/Cargo.toml                                                                     |   18 
crates/edit_prediction_types/LICENSE-GPL                                                                    |    0 
crates/edit_prediction_types/src/edit_prediction_types.rs                                                   |  278 
crates/edit_prediction_ui/Cargo.toml                                                                        |   26 
crates/edit_prediction_ui/LICENSE-GPL                                                                       |    0 
crates/edit_prediction_ui/src/edit_prediction_button.rs                                                     |  576 
crates/edit_prediction_ui/src/edit_prediction_context_view.rs                                               |  370 
crates/edit_prediction_ui/src/edit_prediction_ui.rs                                                         |  191 
crates/edit_prediction_ui/src/rate_prediction_modal.rs                                                      |  106 
crates/editor/Cargo.toml                                                                                    |    6 
crates/editor/benches/editor_render.rs                                                                      |    6 
crates/editor/src/actions.rs                                                                                |   43 
crates/editor/src/bracket_colorization.rs                                                                   |   72 
crates/editor/src/code_context_menus.rs                                                                     |  170 
crates/editor/src/display_map.rs                                                                            |   91 
crates/editor/src/display_map/block_map.rs                                                                  |   55 
crates/editor/src/display_map/crease_map.rs                                                                 |   17 
crates/editor/src/display_map/custom_highlights.rs                                                          |   14 
crates/editor/src/display_map/fold_map.rs                                                                   |   35 
crates/editor/src/display_map/inlay_map.rs                                                                  |   37 
crates/editor/src/display_map/invisibles.rs                                                                 |    1 
crates/editor/src/display_map/tab_map.rs                                                                    |   27 
crates/editor/src/display_map/wrap_map.rs                                                                   |  146 
crates/editor/src/edit_prediction_tests.rs                                                                  |   78 
crates/editor/src/editor.rs                                                                                 |  611 
crates/editor/src/editor_settings.rs                                                                        |    3 
crates/editor/src/editor_tests.rs                                                                           |  606 
crates/editor/src/element.rs                                                                                |  481 
crates/editor/src/git/blame.rs                                                                              |  212 
crates/editor/src/highlight_matching_bracket.rs                                                             |    1 
crates/editor/src/hover_links.rs                                                                            |  203 
crates/editor/src/hover_popover.rs                                                                          |   19 
crates/editor/src/indent_guides.rs                                                                          |    4 
crates/editor/src/items.rs                                                                                  |   49 
crates/editor/src/jsx_tag_auto_close.rs                                                                     |    2 
crates/editor/src/mouse_context_menu.rs                                                                     |   33 
crates/editor/src/scroll.rs                                                                                 |    6 
crates/editor/src/scroll/autoscroll.rs                                                                      |   17 
crates/editor/src/selections_collection.rs                                                                  |   92 
crates/editor/src/split.rs                                                                                  |   13 
crates/editor/src/test.rs                                                                                   |    8 
crates/editor/src/test/editor_lsp_test_context.rs                                                           |   88 
crates/editor/src/test/editor_test_context.rs                                                               |   13 
crates/eval/src/example.rs                                                                                  |   13 
crates/eval/src/instance.rs                                                                                 |   19 
crates/eval_utils/Cargo.toml                                                                                |   18 
crates/eval_utils/LICENSE-GPL                                                                               |    0 
crates/eval_utils/README.md                                                                                 |    3 
crates/eval_utils/src/eval_utils.rs                                                                         |  146 
crates/extension/Cargo.toml                                                                                 |    4 
crates/extension/src/extension_builder.rs                                                                   |  271 
crates/extension/src/extension_host_proxy.rs                                                                |   48 
crates/extension/src/extension_manifest.rs                                                                  |   14 
crates/extension_api/Cargo.toml                                                                             |    5 
crates/extension_api/src/extension_api.rs                                                                   |   15 
crates/extension_api/wit/since_v0.8.0/common.wit                                                            |   12 
crates/extension_api/wit/since_v0.8.0/context-server.wit                                                    |   11 
crates/extension_api/wit/since_v0.8.0/dap.wit                                                               |  123 
crates/extension_api/wit/since_v0.8.0/extension.wit                                                         |  167 
crates/extension_api/wit/since_v0.8.0/github.wit                                                            |   35 
crates/extension_api/wit/since_v0.8.0/http-client.wit                                                       |   67 
crates/extension_api/wit/since_v0.8.0/lsp.wit                                                               |   90 
crates/extension_api/wit/since_v0.8.0/nodejs.wit                                                            |   13 
crates/extension_api/wit/since_v0.8.0/platform.wit                                                          |   24 
crates/extension_api/wit/since_v0.8.0/process.wit                                                           |   29 
crates/extension_api/wit/since_v0.8.0/settings.rs                                                           |   40 
crates/extension_api/wit/since_v0.8.0/slash-command.wit                                                     |   41 
crates/extension_cli/src/main.rs                                                                            |    1 
crates/extension_host/benches/extension_compilation_benchmark.rs                                            |   12 
crates/extension_host/src/capability_granter.rs                                                             |    1 
crates/extension_host/src/extension_host.rs                                                                 |    5 
crates/extension_host/src/extension_store_test.rs                                                           |   19 
crates/extension_host/src/wasm_host.rs                                                                      |   10 
crates/extension_host/src/wasm_host/wit.rs                                                                  |  114 
crates/extension_host/src/wasm_host/wit/since_v0_6_0.rs                                                     |  922 
crates/extension_host/src/wasm_host/wit/since_v0_8_0.rs                                                     | 1111 
crates/extensions_ui/src/extensions_ui.rs                                                                   |   57 
crates/feature_flags/src/flags.rs                                                                           |   18 
crates/file_finder/src/file_finder.rs                                                                       |   13 
crates/file_finder/src/open_path_prompt.rs                                                                  |    6 
crates/file_finder/src/open_path_prompt_tests.rs                                                            |   63 
crates/fs/src/fake_git_repo.rs                                                                              |   85 
crates/fs/src/fs.rs                                                                                         |   70 
crates/fuzzy/src/matcher.rs                                                                                 |   14 
crates/git/src/blame.rs                                                                                     |   29 
crates/git/src/commit.rs                                                                                    |   49 
crates/git/src/git.rs                                                                                       |    4 
crates/git/src/remote.rs                                                                                    |    3 
crates/git/src/repository.rs                                                                                |  192 
crates/git_hosting_providers/Cargo.toml                                                                     |    1 
crates/git_hosting_providers/src/git_hosting_providers.rs                                                   |    8 
crates/git_hosting_providers/src/providers/bitbucket.rs                                                     |  163 
crates/git_hosting_providers/src/providers/sourcehut.rs                                                     |  196 
crates/git_hosting_providers/src/settings.rs                                                                |    7 
crates/git_ui/Cargo.toml                                                                                    |    9 
crates/git_ui/src/blame_ui.rs                                                                               |   51 
crates/git_ui/src/branch_picker.rs                                                                          | 1714 
crates/git_ui/src/clone.rs                                                                                  |  155 
crates/git_ui/src/commit_modal.rs                                                                           |   76 
crates/git_ui/src/commit_tooltip.rs                                                                         |   53 
crates/git_ui/src/commit_view.rs                                                                            |  742 
crates/git_ui/src/conflict_view.rs                                                                          |    7 
crates/git_ui/src/file_diff_view.rs                                                                         |    2 
crates/git_ui/src/file_history_view.rs                                                                      |  135 
crates/git_ui/src/git_panel.rs                                                                              |  855 
crates/git_ui/src/git_panel_settings.rs                                                                     |    2 
crates/git_ui/src/git_ui.rs                                                                                 |    3 
crates/git_ui/src/onboarding.rs                                                                             |    4 
crates/git_ui/src/picker_prompt.rs                                                                          |    2 
crates/git_ui/src/project_diff.rs                                                                           |  231 
crates/git_ui/src/remote_output.rs                                                                          |    1 
crates/git_ui/src/stash_picker.rs                                                                           |    2 
crates/git_ui/src/text_diff_view.rs                                                                         |    2 
crates/git_ui/src/worktree_picker.rs                                                                        |   44 
crates/go_to_line/src/go_to_line.rs                                                                         |    2 
crates/google_ai/src/google_ai.rs                                                                           |   24 
crates/gpui/Cargo.toml                                                                                      |   17 
crates/gpui/README.md                                                                                       |    2 
crates/gpui/build.rs                                                                                        |    2 
crates/gpui/examples/focus_visible.rs                                                                       |   10 
crates/gpui/examples/input.rs                                                                               |   13 
crates/gpui/examples/mouse_pressure.rs                                                                      |   66 
crates/gpui/examples/on_window_close_quit.rs                                                                |    4 
crates/gpui/examples/painting.rs                                                                            |    6 
crates/gpui/examples/popover.rs                                                                             |  174 
crates/gpui/examples/tab_stop.rs                                                                            |   54 
crates/gpui/examples/window.rs                                                                              |   71 
crates/gpui/src/app.rs                                                                                      |  129 
crates/gpui/src/app/async_context.rs                                                                        |    2 
crates/gpui/src/app/context.rs                                                                              |   27 
crates/gpui/src/app/entity_map.rs                                                                           |  112 
crates/gpui/src/app/test_context.rs                                                                         |   14 
crates/gpui/src/bounds_tree.rs                                                                              |  464 
crates/gpui/src/elements/div.rs                                                                             |  234 
crates/gpui/src/elements/surface.rs                                                                         |    1 
crates/gpui/src/elements/text.rs                                                                            |   42 
crates/gpui/src/elements/uniform_list.rs                                                                    |    6 
crates/gpui/src/executor.rs                                                                                 |  230 
crates/gpui/src/geometry.rs                                                                                 |   22 
crates/gpui/src/gpui.rs                                                                                     |    9 
crates/gpui/src/interactive.rs                                                                              |   42 
crates/gpui/src/key_dispatch.rs                                                                             |  229 
crates/gpui/src/keymap.rs                                                                                   |   35 
crates/gpui/src/platform.rs                                                                                 |   35 
crates/gpui/src/platform/linux/dispatcher.rs                                                                |  348 
crates/gpui/src/platform/linux/platform.rs                                                                  |   57 
crates/gpui/src/platform/linux/wayland/client.rs                                                            |   98 
crates/gpui/src/platform/linux/wayland/window.rs                                                            |  106 
crates/gpui/src/platform/linux/x11/client.rs                                                                |   96 
crates/gpui/src/platform/linux/x11/window.rs                                                                |   89 
crates/gpui/src/platform/mac.rs                                                                             |    5 
crates/gpui/src/platform/mac/attributed_string.rs                                                           |  119 
crates/gpui/src/platform/mac/dispatcher.rs                                                                  |  145 
crates/gpui/src/platform/mac/display.rs                                                                     |   56 
crates/gpui/src/platform/mac/events.rs                                                                      |   25 
crates/gpui/src/platform/mac/metal_renderer.rs                                                              |   14 
crates/gpui/src/platform/mac/open_type.rs                                                                   |    5 
crates/gpui/src/platform/mac/pasteboard.rs                                                                  |  344 
crates/gpui/src/platform/mac/platform.rs                                                                    |  399 
crates/gpui/src/platform/mac/screen_capture.rs                                                              |   19 
crates/gpui/src/platform/mac/text_system.rs                                                                 |   26 
crates/gpui/src/platform/mac/window.rs                                                                      |   78 
crates/gpui/src/platform/test/dispatcher.rs                                                                 |   12 
crates/gpui/src/platform/test/platform.rs                                                                   |   24 
crates/gpui/src/platform/windows/dispatcher.rs                                                              |   20 
crates/gpui/src/platform/windows/display.rs                                                                 |   32 
crates/gpui/src/platform/windows/events.rs                                                                  |   13 
crates/gpui/src/platform/windows/platform.rs                                                                |    2 
crates/gpui/src/platform/windows/window.rs                                                                  |   32 
crates/gpui/src/profiler.rs                                                                                 |   16 
crates/gpui/src/queue.rs                                                                                    |  329 
crates/gpui/src/style.rs                                                                                    |   31 
crates/gpui/src/styled.rs                                                                                   |  138 
crates/gpui/src/taffy.rs                                                                                    |   15 
crates/gpui/src/test.rs                                                                                     |    5 
crates/gpui/src/text_system/line.rs                                                                         |   12 
crates/gpui/src/text_system/line_wrapper.rs                                                                 |  271 
crates/gpui/src/window.rs                                                                                   |  336 
crates/gpui/src/window/prompts.rs                                                                           |    6 
crates/gpui_macros/src/derive_visual_context.rs                                                             |    2 
crates/gpui_tokio/src/gpui_tokio.rs                                                                         |   47 
crates/http_client/Cargo.toml                                                                               |    1 
crates/http_client/src/async_body.rs                                                                        |   11 
crates/http_client/src/github_download.rs                                                                   |   61 
crates/http_client/src/http_client.rs                                                                       |   31 
crates/icons/src/icons.rs                                                                                   |   19 
crates/image_viewer/src/image_info.rs                                                                       |    4 
crates/image_viewer/src/image_viewer.rs                                                                     |    4 
crates/inspector_ui/src/div_inspector.rs                                                                    |    1 
crates/inspector_ui/src/inspector.rs                                                                        |    1 
crates/json_schema_store/Cargo.toml                                                                         |    1 
crates/json_schema_store/src/json_schema_store.rs                                                           |  204 
crates/keymap_editor/src/keymap_editor.rs                                                                   |  124 
crates/keymap_editor/src/ui_components/keystroke_input.rs                                                   |    4 
crates/language/Cargo.toml                                                                                  |    2 
crates/language/src/buffer.rs                                                                               |  446 
crates/language/src/buffer/row_chunk.rs                                                                     |   62 
crates/language/src/buffer_tests.rs                                                                         |  338 
crates/language/src/language.rs                                                                             |  198 
crates/language/src/language_registry.rs                                                                    |   34 
crates/language/src/language_settings.rs                                                                    |   25 
crates/language/src/outline.rs                                                                              |   50 
crates/language/src/proto.rs                                                                                |    7 
crates/language/src/syntax_map.rs                                                                           |   95 
crates/language/src/syntax_map/syntax_map_tests.rs                                                          |   70 
crates/language/src/text_diff.rs                                                                            |  209 
crates/language/src/toolchain.rs                                                                            |    7 
crates/language_extension/src/extension_lsp_adapter.rs                                                      |   58 
crates/language_model/Cargo.toml                                                                            |    3 
crates/language_model/src/api_key.rs                                                                        |   21 
crates/language_model/src/language_model.rs                                                                 |   78 
crates/language_model/src/registry.rs                                                                       |  200 
crates/language_model/src/request.rs                                                                        |  204 
crates/language_model/src/telemetry.rs                                                                      |  124 
crates/language_models/Cargo.toml                                                                           |    3 
crates/language_models/src/extension.rs                                                                     |   67 
crates/language_models/src/language_models.rs                                                               |   55 
crates/language_models/src/provider/anthropic.rs                                                            |  349 
crates/language_models/src/provider/bedrock.rs                                                              |  520 
crates/language_models/src/provider/cloud.rs                                                                |   20 
crates/language_models/src/provider/copilot_chat.rs                                                         |  125 
crates/language_models/src/provider/deepseek.rs                                                             |   64 
crates/language_models/src/provider/google.rs                                                               |   49 
crates/language_models/src/provider/lmstudio.rs                                                             |   19 
crates/language_models/src/provider/mistral.rs                                                              |  243 
crates/language_models/src/provider/ollama.rs                                                               |  202 
crates/language_models/src/provider/open_ai.rs                                                              |   70 
crates/language_models/src/provider/open_ai_compatible.rs                                                   |   32 
crates/language_models/src/provider/open_router.rs                                                          |   90 
crates/language_models/src/provider/vercel.rs                                                               |   54 
crates/language_models/src/provider/x_ai.rs                                                                 |   55 
crates/language_models/src/settings.rs                                                                      |    2 
crates/language_models/src/ui.rs                                                                            |    4 
crates/language_models/src/ui/instruction_list_item.rs                                                      |   69 
crates/language_tools/src/lsp_button.rs                                                                     |   32 
crates/language_tools/src/lsp_log_view.rs                                                                   |   35 
crates/language_tools/src/syntax_tree_view.rs                                                               |   18 
crates/languages/Cargo.toml                                                                                 |    1 
crates/languages/src/c.rs                                                                                   |   55 
crates/languages/src/c/highlights.scm                                                                       |    2 
crates/languages/src/c/injections.scm                                                                       |    5 
crates/languages/src/c/textobjects.scm                                                                      |    6 
crates/languages/src/cpp/brackets.scm                                                                       |    1 
crates/languages/src/cpp/injections.scm                                                                     |    5 
crates/languages/src/cpp/textobjects.scm                                                                    |    6 
crates/languages/src/css.rs                                                                                 |   10 
crates/languages/src/eslint.rs                                                                              |    4 
crates/languages/src/go.rs                                                                                  |    4 
crates/languages/src/go/injections.scm                                                                      |  959 
crates/languages/src/javascript/highlights.scm                                                              |  107 
crates/languages/src/javascript/injections.scm                                                              |   43 
crates/languages/src/javascript/textobjects.scm                                                             |   38 
crates/languages/src/jsdoc/highlights.scm                                                                   |    1 
crates/languages/src/json.rs                                                                                |   25 
crates/languages/src/json/config.toml                                                                       |    7 
crates/languages/src/jsonc/config.toml                                                                      |    9 
crates/languages/src/lib.rs                                                                                 |    3 
crates/languages/src/markdown/config.toml                                                                   |    8 
crates/languages/src/markdown/indents.scm                                                                   |    3 
crates/languages/src/python.rs                                                                              |  498 
crates/languages/src/python/injections.scm                                                                  |   31 
crates/languages/src/rust.rs                                                                                |  368 
crates/languages/src/tailwind.rs                                                                            |   70 
crates/languages/src/tsx/highlights.scm                                                                     |  161 
crates/languages/src/tsx/injections.scm                                                                     |   43 
crates/languages/src/tsx/textobjects.scm                                                                    |   38 
crates/languages/src/typescript.rs                                                                          |   83 
crates/languages/src/typescript/highlights.scm                                                              |  134 
crates/languages/src/typescript/injections.scm                                                              |   43 
crates/languages/src/typescript/textobjects.scm                                                             |   39 
crates/languages/src/vtsls.rs                                                                               |   83 
crates/languages/src/yaml.rs                                                                                |   11 
crates/languages/src/yaml/config.toml                                                                       |    2 
crates/livekit_client/examples/test_app.rs                                                                  |    2 
crates/livekit_client/src/livekit_client/playback/source.rs                                                 |   17 
crates/lsp/src/lsp.rs                                                                                       |   18 
crates/markdown/examples/markdown_as_child.rs                                                               |    4 
crates/markdown/src/markdown.rs                                                                             |  484 
crates/markdown_preview/Cargo.toml                                                                          |    1 
crates/markdown_preview/src/markdown_parser.rs                                                              |   21 
crates/markdown_preview/src/markdown_preview.rs                                                             |   14 
crates/markdown_preview/src/markdown_preview_view.rs                                                        |   73 
crates/markdown_preview/src/markdown_renderer.rs                                                            |   26 
crates/migrator/src/migrations.rs                                                                           |   18 
crates/migrator/src/migrations/m_2025_12_01/settings.rs                                                     |   55 
crates/migrator/src/migrations/m_2025_12_08/keymap.rs                                                       |   33 
crates/migrator/src/migrations/m_2025_12_15/settings.rs                                                     |   52 
crates/migrator/src/migrator.rs                                                                             |  135 
crates/mistral/src/mistral.rs                                                                               |   10 
crates/multi_buffer/Cargo.toml                                                                              |    5 
crates/multi_buffer/src/multi_buffer.rs                                                                     |   72 
crates/multi_buffer/src/multi_buffer_tests.rs                                                               |   13 
crates/multi_buffer/src/path_key.rs                                                                         |  896 
crates/node_runtime/src/node_runtime.rs                                                                     |   81 
crates/notifications/src/status_toast.rs                                                                    |    3 
crates/onboarding/Cargo.toml                                                                                |    1 
crates/onboarding/src/basics_page.rs                                                                        |   48 
crates/onboarding/src/onboarding.rs                                                                         |   28 
crates/onboarding/src/welcome.rs                                                                            |  443 
crates/open_ai/src/open_ai.rs                                                                               |   11 
crates/outline/src/outline.rs                                                                               |   90 
crates/outline_panel/src/outline_panel.rs                                                                   |  394 
crates/outline_panel/src/outline_panel_settings.rs                                                          |    8 
crates/paths/src/paths.rs                                                                                   |    6 
crates/picker/src/picker.rs                                                                                 |   30 
crates/prettier/src/prettier.rs                                                                             |   78 
crates/project/Cargo.toml                                                                                   |    7 
crates/project/src/agent_server_store.rs                                                                    |  231 
crates/project/src/buffer_store.rs                                                                          |   18 
crates/project/src/context_server_store.rs                                                                  |    2 
crates/project/src/debugger/breakpoint_store.rs                                                             |    4 
crates/project/src/debugger/dap_store.rs                                                                    |    2 
crates/project/src/debugger/locators/cargo.rs                                                               |   23 
crates/project/src/debugger/session.rs                                                                      |  290 
crates/project/src/git_store.rs                                                                             |  365 
crates/project/src/git_store/branch_diff.rs                                                                 |    3 
crates/project/src/git_store/conflict_set.rs                                                                |   72 
crates/project/src/invalid_item_view.rs                                                                     |  118 
crates/project/src/lsp_command.rs                                                                           |   76 
crates/project/src/lsp_store.rs                                                                             |  437 
crates/project/src/lsp_store/clangd_ext.rs                                                                  |    1 
crates/project/src/lsp_store/inlay_hint_cache.rs                                                            |   11 
crates/project/src/lsp_store/json_language_server_ext.rs                                                    |   10 
crates/project/src/persistence.rs                                                                           |   60 
crates/project/src/prettier_store.rs                                                                        |    2 
crates/project/src/project.rs                                                                               |  189 
crates/project/src/project_search.rs                                                                        |   29 
crates/project/src/project_settings.rs                                                                      |  212 
crates/project/src/project_tests.rs                                                                         |  189 
crates/project/src/telemetry_snapshot.rs                                                                    |    2 
crates/project/src/terminals.rs                                                                             |    4 
crates/project/src/toolchain_store.rs                                                                       |   26 
crates/project/src/trusted_worktrees.rs                                                                     | 1464 
crates/project/src/worktree_store.rs                                                                        |    9 
crates/project/src/x.py                                                                                     |    1 
crates/project_benchmarks/src/main.rs                                                                       |    1 
crates/project_panel/Cargo.toml                                                                             |    1 
crates/project_panel/src/project_panel.rs                                                                   |  152 
crates/project_panel/src/project_panel_settings.rs                                                          |    8 
crates/project_panel/src/project_panel_tests.rs                                                             |   68 
crates/project_symbols/src/project_symbols.rs                                                               |    5 
crates/prompt_store/Cargo.toml                                                                              |    5 
crates/prompt_store/src/prompt_store.rs                                                                     |  357 
crates/prompt_store/src/prompts.rs                                                                          |   94 
crates/proto/proto/buffer.proto                                                                             |    1 
crates/proto/proto/git.proto                                                                                |   19 
crates/proto/proto/lsp.proto                                                                                |    1 
crates/proto/proto/worktree.proto                                                                           |  180 
crates/proto/proto/zed.proto                                                                                |   10 
crates/proto/src/proto.rs                                                                                   |   16 
crates/recent_projects/Cargo.toml                                                                           |    4 
crates/recent_projects/src/dev_container.rs                                                                 |  295 
crates/recent_projects/src/dev_container_suggest.rs                                                         |  106 
crates/recent_projects/src/recent_projects.rs                                                               |  145 
crates/recent_projects/src/remote_connections.rs                                                            |  123 
crates/recent_projects/src/remote_servers.rs                                                                |  564 
crates/refineable/derive_refineable/src/derive_refineable.rs                                                |    7 
crates/refineable/src/refineable.rs                                                                         |    2 
crates/remote/Cargo.toml                                                                                    |    1 
crates/remote/src/remote.rs                                                                                 |    6 
crates/remote/src/remote_client.rs                                                                          |   99 
crates/remote/src/transport.rs                                                                              |  157 
crates/remote/src/transport/docker.rs                                                                       |  759 
crates/remote/src/transport/ssh.rs                                                                          |  429 
crates/remote/src/transport/wsl.rs                                                                          |   71 
crates/remote_server/Cargo.toml                                                                             |    2 
crates/remote_server/src/headless_project.rs                                                                |   60 
crates/remote_server/src/remote_editing_tests.rs                                                            |    9 
crates/remote_server/src/unix.rs                                                                            |   16 
crates/repl/src/kernels/mod.rs                                                                              |    2 
crates/repl/src/repl.rs                                                                                     |    4 
crates/reqwest_client/src/reqwest_client.rs                                                                 |   20 
crates/rope/Cargo.toml                                                                                      |    5 
crates/rope/src/chunk.rs                                                                                    |   61 
crates/rope/src/rope.rs                                                                                     |    4 
crates/rpc/src/proto_client.rs                                                                              |    5 
crates/rules_library/src/rules_library.rs                                                                   |  449 
crates/schema_generator/Cargo.toml                                                                          |    1 
crates/schema_generator/src/main.rs                                                                         |    6 
crates/search/Cargo.toml                                                                                    |    6 
crates/search/src/buffer_search.rs                                                                          |  159 
crates/search/src/project_search.rs                                                                         |  361 
crates/search/src/search.rs                                                                                 |    2 
crates/search/src/search_bar.rs                                                                             |    2 
crates/settings/src/keymap_file.rs                                                                          |   13 
crates/settings/src/merge_from.rs                                                                           |    1 
crates/settings/src/settings.rs                                                                             |    5 
crates/settings/src/settings_content.rs                                                                     |   44 
crates/settings/src/settings_content/agent.rs                                                               |   51 
crates/settings/src/settings_content/language.rs                                                            |   26 
crates/settings/src/settings_content/language_model.rs                                                      |    4 
crates/settings/src/settings_content/project.rs                                                             |   50 
crates/settings/src/settings_content/terminal.rs                                                            |    5 
crates/settings/src/settings_content/theme.rs                                                               |    3 
crates/settings/src/settings_content/workspace.rs                                                           |   30 
crates/settings/src/settings_store.rs                                                                       |   95 
crates/settings/src/vscode_import.rs                                                                        |    9 
crates/settings_ui/Cargo.toml                                                                               |    5 
crates/settings_ui/src/components.rs                                                                        |    2 
crates/settings_ui/src/components/input_field.rs                                                            |    1 
crates/settings_ui/src/components/section_items.rs                                                          |   56 
crates/settings_ui/src/page_data.rs                                                                         |  412 
crates/settings_ui/src/pages.rs                                                                             |    2 
crates/settings_ui/src/pages/edit_prediction_provider_setup.rs                                              |  365 
crates/settings_ui/src/settings_ui.rs                                                                       |  378 
crates/snippet_provider/src/format.rs                                                                       |    3 
crates/snippet_provider/src/lib.rs                                                                          |    2 
crates/sum_tree/Cargo.toml                                                                                  |    5 
crates/sum_tree/src/cursor.rs                                                                               |    5 
crates/sum_tree/src/sum_tree.rs                                                                             |   25 
crates/supermaven/Cargo.toml                                                                                |    2 
crates/supermaven/src/supermaven.rs                                                                         |    4 
crates/supermaven/src/supermaven_edit_prediction_delegate.rs                                                |   23 
crates/tab_switcher/src/tab_switcher.rs                                                                     |   73 
crates/tab_switcher/src/tab_switcher_tests.rs                                                               |   79 
crates/task/src/debug_format.rs                                                                             |    1 
crates/task/src/task_template.rs                                                                            |    3 
crates/tasks_ui/src/modal.rs                                                                                |    6 
crates/terminal/Cargo.toml                                                                                  |    4 
crates/terminal/src/terminal.rs                                                                             |  448 
crates/terminal/src/terminal_hyperlinks.rs                                                                  |  398 
crates/terminal/src/terminal_settings.rs                                                                    |    2 
crates/terminal_view/src/terminal_element.rs                                                                |   23 
crates/terminal_view/src/terminal_panel.rs                                                                  |  287 
crates/terminal_view/src/terminal_scrollbar.rs                                                              |   18 
crates/terminal_view/src/terminal_tab_tooltip.rs                                                            |   36 
crates/terminal_view/src/terminal_view.rs                                                                   |   61 
crates/text/src/anchor.rs                                                                                   |    8 
crates/text/src/text.rs                                                                                     |   41 
crates/theme/src/default_colors.rs                                                                          |    2 
crates/theme/src/fallback_themes.rs                                                                         |    1 
crates/theme/src/schema.rs                                                                                  |   15 
crates/theme/src/styles/colors.rs                                                                           |    3 
crates/title_bar/build.rs                                                                                   |   28 
crates/title_bar/src/application_menu.rs                                                                    |   28 
crates/title_bar/src/collab.rs                                                                              |   33 
crates/title_bar/src/platforms/platform_mac.rs                                                              |   14 
crates/title_bar/src/title_bar.rs                                                                           |  394 
crates/title_bar/src/title_bar_settings.rs                                                                  |    2 
crates/toolchain_selector/src/active_toolchain.rs                                                           |   11 
crates/toolchain_selector/src/toolchain_selector.rs                                                         |  191 
crates/ui/src/components.rs                                                                                 |    2 
crates/ui/src/components/ai.rs                                                                              |    3 
crates/ui/src/components/ai/configured_api_card.rs                                                          |   17 
crates/ui/src/components/ai/copilot_configuration_callout.rs                                                |    0 
crates/ui/src/components/button.rs                                                                          |    2 
crates/ui/src/components/button/button_link.rs                                                              |  102 
crates/ui/src/components/button/split_button.rs                                                             |   32 
crates/ui/src/components/callout.rs                                                                         |    2 
crates/ui/src/components/context_menu.rs                                                                    |   72 
crates/ui/src/components/data_table.rs                                                                      |   22 
crates/ui/src/components/divider.rs                                                                         |   16 
crates/ui/src/components/icon.rs                                                                            |   22 
crates/ui/src/components/keybinding_hint.rs                                                                 |    4 
crates/ui/src/components/label/label.rs                                                                     |    9 
crates/ui/src/components/label/label_like.rs                                                                |   29 
crates/ui/src/components/list/list_bullet_item.rs                                                           |   88 
crates/ui/src/components/navigable.rs                                                                       |    4 
crates/ui/src/components/notification/alert_modal.rs                                                        |  231 
crates/ui/src/components/popover_menu.rs                                                                    |   16 
crates/ui/src/components/right_click_menu.rs                                                                |   16 
crates/ui/src/components/tab_bar.rs                                                                         |   49 
crates/ui/src/components/toggle.rs                                                                          |  117 
crates/ui_input/src/number_field.rs                                                                         |  281 
crates/util/src/archive.rs                                                                                  |   54 
crates/util/src/command.rs                                                                                  |    2 
crates/util/src/paths.rs                                                                                    |   11 
crates/util/src/redact.rs                                                                                   |   34 
crates/util/src/rel_path.rs                                                                                 |    7 
crates/util/src/schemars.rs                                                                                 |   17 
crates/util/src/shell.rs                                                                                    |  322 
crates/util/src/shell_builder.rs                                                                            |  127 
crates/util/src/shell_env.rs                                                                                |   22 
crates/util/src/util.rs                                                                                     |    2 
crates/vim/Cargo.toml                                                                                       |    2 
crates/vim/src/command.rs                                                                                   |  234 
crates/vim/src/helix.rs                                                                                     |    3 
crates/vim/src/motion.rs                                                                                    |   39 
crates/vim/src/normal/change.rs                                                                             |    6 
crates/vim/src/normal/mark.rs                                                                               |   72 
crates/vim/src/normal/paste.rs                                                                              |   48 
crates/vim/src/normal/scroll.rs                                                                             |    5 
crates/vim/src/normal/yank.rs                                                                               |   22 
crates/vim/src/object.rs                                                                                    |  407 
crates/vim/src/replace.rs                                                                                   |    2 
crates/vim/src/state.rs                                                                                     |   10 
crates/vim/src/test.rs                                                                                      |   75 
crates/vim/src/test/neovim_backed_test_context.rs                                                           |    5 
crates/vim/src/test/vim_test_context.rs                                                                     |    2 
crates/vim/src/vim.rs                                                                                       |    2 
crates/vim/src/visual.rs                                                                                    |   16 
crates/vim/test_data/test_change_paragraph.json                                                             |    8 
crates/vim/test_data/test_matching_tags.json                                                                |    5 
crates/vim/test_data/test_yank_paragraph_with_paste.json                                                    |   10 
crates/which_key/Cargo.toml                                                                                 |   23 
crates/which_key/LICENSE-GPL                                                                                |    1 
crates/which_key/src/which_key.rs                                                                           |   98 
crates/which_key/src/which_key_modal.rs                                                                     |  308 
crates/which_key/src/which_key_settings.rs                                                                  |   18 
crates/workspace/Cargo.toml                                                                                 |    3 
crates/workspace/src/dock.rs                                                                                |  112 
crates/workspace/src/invalid_item_view.rs                                                                   |    1 
crates/workspace/src/item.rs                                                                                |   44 
crates/workspace/src/modal_layer.rs                                                                         |  108 
crates/workspace/src/notifications.rs                                                                       |   79 
crates/workspace/src/pane.rs                                                                                |  728 
crates/workspace/src/pane_group.rs                                                                          |   85 
crates/workspace/src/persistence.rs                                                                         |  591 
crates/workspace/src/persistence/model.rs                                                                   |    3 
crates/workspace/src/searchable.rs                                                                          |   19 
crates/workspace/src/security_modal.rs                                                                      |  334 
crates/workspace/src/shared_screen.rs                                                                       |    5 
crates/workspace/src/utility_pane.rs                                                                        |  282 
crates/workspace/src/welcome.rs                                                                             |  568 
crates/workspace/src/workspace.rs                                                                           |  473 
crates/worktree/Cargo.toml                                                                                  |    2 
crates/worktree/src/ignore.rs                                                                               |   37 
crates/worktree/src/worktree.rs                                                                             |  488 
crates/worktree/src/worktree_tests.rs                                                                       |  579 
crates/worktree_benchmarks/src/main.rs                                                                      |    4 
crates/x_ai/src/x_ai.rs                                                                                     |   38 
crates/zed/Cargo.toml                                                                                       |   26 
crates/zed/resources/Document.icns                                                                          |    0 
crates/zed/resources/zed.entitlements                                                                       |    4 
crates/zed/src/main.rs                                                                                      |  134 
crates/zed/src/reliability.rs                                                                               |   15 
crates/zed/src/zed-main.rs                                                                                  |    8 
crates/zed/src/zed.rs                                                                                       |  334 
crates/zed/src/zed/app_menus.rs                                                                             |   17 
crates/zed/src/zed/edit_prediction_registry.rs                                                              |   68 
crates/zed/src/zed/open_listener.rs                                                                         |  486 
crates/zed/src/zed/quick_action_bar.rs                                                                      |   16 
crates/zed_actions/src/lib.rs                                                                               |   16 
crates/zed_env_vars/src/zed_env_vars.rs                                                                     |    5 
crates/zeta/Cargo.toml                                                                                      |   84 
crates/zeta/src/assemble_excerpts.rs                                                                        |  173 
crates/zeta/src/provider.rs                                                                                 |  217 
crates/zeta/src/retrieval_search.rs                                                                         |  642 
crates/zeta/src/xml_edits.rs                                                                                |  637 
crates/zeta/src/zeta.rs                                                                                     | 4057 
crates/zeta/src/zeta1/input_excerpt.rs                                                                      |  231 
crates/zeta/src/zeta_tests.rs                                                                               |  671 
crates/zeta2_tools/Cargo.toml                                                                               |   49 
crates/zeta2_tools/src/zeta2_context_view.rs                                                                |  438 
crates/zeta2_tools/src/zeta2_tools.rs                                                                       | 1023 
crates/zeta_cli/src/evaluate.rs                                                                             |  641 
crates/zeta_cli/src/example.rs                                                                              |  561 
crates/zeta_cli/src/main.rs                                                                                 |  560 
1,000 files changed, 65,190 insertions(+), 35,809 deletions(-)

Detailed changes

.factory/prompts/docs-automation/phase2-explore.md 🔗

@@ -0,0 +1,55 @@
+# Phase 2: Explore Repository
+
+You are analyzing a codebase to understand its structure before reviewing documentation impact.
+
+## Objective
+Produce a structured overview of the repository to inform subsequent documentation analysis.
+
+## Instructions
+
+1. **Identify Primary Languages and Frameworks**
+   - Scan for Cargo.toml, package.json, or other manifest files
+   - Note the primary language(s) and key dependencies
+
+2. **Map Documentation Structure**
+   - This project uses **mdBook** (https://rust-lang.github.io/mdBook/)
+   - Documentation is in `docs/src/`
+   - Table of contents: `docs/src/SUMMARY.md` (mdBook format: https://rust-lang.github.io/mdBook/format/summary.html)
+   - Style guide: `docs/.rules`
+   - Agent guidelines: `docs/AGENTS.md`
+   - Formatting: Prettier (config in `docs/.prettierrc`)
+
+3. **Identify Build and Tooling**
+   - Note build systems (cargo, npm, etc.)
+   - Identify documentation tooling (mdbook, etc.)
+
+4. **Output Format**
+Produce a JSON summary:
+
+```json
+{
+  "primary_language": "Rust",
+  "frameworks": ["GPUI"],
+  "documentation": {
+    "system": "mdBook",
+    "location": "docs/src/",
+    "toc_file": "docs/src/SUMMARY.md",
+    "toc_format": "https://rust-lang.github.io/mdBook/format/summary.html",
+    "style_guide": "docs/.rules",
+    "agent_guidelines": "docs/AGENTS.md",
+    "formatter": "prettier",
+    "formatter_config": "docs/.prettierrc",
+    "custom_preprocessor": "docs_preprocessor (handles {#kb action::Name} syntax)"
+  },
+  "key_directories": {
+    "source": "crates/",
+    "docs": "docs/src/",
+    "extensions": "extensions/"
+  }
+}
+```
+
+## Constraints
+- Read-only: Do not modify any files
+- Focus on structure, not content details
+- Complete within 2 minutes

.factory/prompts/docs-automation/phase3-analyze.md 🔗

@@ -0,0 +1,57 @@
+# Phase 3: Analyze Changes
+
+You are analyzing code changes to understand their nature and scope.
+
+## Objective
+Produce a clear, neutral summary of what changed in the codebase.
+
+## Input
+You will receive:
+- List of changed files from the triggering commit/PR
+- Repository structure from Phase 2
+
+## Instructions
+
+1. **Categorize Changed Files**
+   - Source code (which crates/modules)
+   - Configuration
+   - Tests
+   - Documentation (already existing)
+   - Other
+
+2. **Analyze Each Change**
+   - Review diffs for files likely to impact documentation
+   - Focus on: public APIs, settings, keybindings, commands, user-visible behavior
+
+3. **Identify What Did NOT Change**
+   - Note stable interfaces or behaviors
+   - Important for avoiding unnecessary documentation updates
+
+4. **Output Format**
+Produce a markdown summary:
+
+```markdown
+## Change Analysis
+
+### Changed Files Summary
+| Category | Files | Impact Level |
+| --- | --- | --- |
+| Source - [crate] | file1.rs, file2.rs | High/Medium/Low |
+| Settings | settings.json | Medium |
+| Tests | test_*.rs | None |
+
+### Behavioral Changes
+- **[Feature/Area]**: Description of what changed from user perspective
+- **[Feature/Area]**: Description...
+
+### Unchanged Areas
+- [Area]: Confirmed no changes to [specific behavior]
+
+### Files Requiring Deeper Review
+- `path/to/file.rs`: Reason for deeper review
+```
+
+## Constraints
+- Read-only: Do not modify any files
+- Neutral tone: Describe what changed, not whether it's good/bad
+- Do not propose documentation changes yet

.factory/prompts/docs-automation/phase4-plan.md 🔗

@@ -0,0 +1,76 @@
+# Phase 4: Plan Documentation Impact
+
+You are determining whether and how documentation should be updated based on code changes.
+
+## Objective
+Produce a structured documentation plan that will guide Phase 5 execution.
+
+## Documentation System
+This is an **mdBook** site (https://rust-lang.github.io/mdBook/):
+- `docs/src/SUMMARY.md` defines book structure per https://rust-lang.github.io/mdBook/format/summary.html
+- If adding new pages, they MUST be added to SUMMARY.md
+- Use `{#kb action::ActionName}` syntax for keybindings (custom preprocessor expands these)
+- Prettier formatting (80 char width) will be applied automatically
+
+## Input
+You will receive:
+- Change analysis from Phase 3
+- Repository structure from Phase 2
+- Documentation guidelines from `docs/AGENTS.md`
+
+## Instructions
+
+1. **Review AGENTS.md**
+   - Load and apply all rules from `docs/AGENTS.md`
+   - Respect scope boundaries (in-scope vs out-of-scope)
+
+2. **Evaluate Documentation Impact**
+   For each behavioral change from Phase 3:
+   - Does existing documentation cover this area?
+   - Is the documentation now inaccurate or incomplete?
+   - Classify per AGENTS.md "Change Classification" section
+
+3. **Identify Specific Updates**
+   For each required update:
+   - Exact file path
+   - Specific section or heading
+   - Type of change (update existing, add new, deprecate)
+   - Description of the change
+
+4. **Flag Uncertainty**
+   Explicitly mark:
+   - Assumptions you're making
+   - Areas where human confirmation is needed
+   - Ambiguous requirements
+
+5. **Output Format**
+Use the exact format specified in `docs/AGENTS.md` Phase 4 section:
+
+```markdown
+## Documentation Impact Assessment
+
+### Summary
+Brief description of code changes analyzed.
+
+### Documentation Updates Required: [Yes/No]
+
+### Planned Changes
+
+#### 1. [File Path]
+- **Section**: [Section name or "New section"]
+- **Change Type**: [Update/Add/Deprecate]
+- **Reason**: Why this change is needed
+- **Description**: What will be added/modified
+
+### Uncertainty Flags
+- [ ] [Description of any assumptions or areas needing confirmation]
+
+### No Changes Needed
+- [List files reviewed but not requiring updates, with brief reason]
+```
+
+## Constraints
+- Read-only: Do not modify any files
+- Conservative: When uncertain, flag for human review rather than planning changes
+- Scoped: Only plan changes that trace directly to code changes from Phase 3
+- No scope expansion: Do not plan "improvements" unrelated to triggering changes

.factory/prompts/docs-automation/phase5-apply.md 🔗

@@ -0,0 +1,67 @@
+# Phase 5: Apply Documentation Plan
+
+You are executing a pre-approved documentation plan for an **mdBook** documentation site.
+
+## Objective
+Implement exactly the changes specified in the documentation plan from Phase 4.
+
+## Documentation System
+- **mdBook**: https://rust-lang.github.io/mdBook/
+- **SUMMARY.md**: Follows mdBook format (https://rust-lang.github.io/mdBook/format/summary.html)
+- **Prettier**: Will be run automatically after this phase (80 char line width)
+- **Custom preprocessor**: Use `{#kb action::ActionName}` for keybindings instead of hardcoding
+
+## Input
+You will receive:
+- Documentation plan from Phase 4
+- Documentation guidelines from `docs/AGENTS.md`
+- Style rules from `docs/.rules`
+
+## Instructions
+
+1. **Validate Plan**
+   - Confirm all planned files are within scope per AGENTS.md
+   - Verify no out-of-scope files are targeted
+
+2. **Execute Each Planned Change**
+   For each item in "Planned Changes":
+   - Navigate to the specified file
+   - Locate the specified section
+   - Apply the described change
+   - Follow style rules from `docs/.rules`
+
+3. **Style Compliance**
+   Every edit must follow `docs/.rules`:
+   - Second person, present tense
+   - No hedging words ("simply", "just", "easily")
+   - Proper keybinding format (`Cmd+Shift+P`)
+   - Settings Editor first, JSON second
+   - Correct terminology (folder not directory, etc.)
+
+4. **Preserve Context**
+   - Maintain surrounding content structure
+   - Keep consistent heading levels
+   - Preserve existing cross-references
+
+## Constraints
+- Execute ONLY changes listed in the plan
+- Do not discover new documentation targets
+- Do not make stylistic improvements outside planned sections
+- Do not expand scope beyond what Phase 4 specified
+- If a planned change cannot be applied (file missing, section not found), skip and note it
+
+## Output
+After applying changes, output a summary:
+
+```markdown
+## Applied Changes
+
+### Successfully Applied
+- `path/to/file.md`: [Brief description of change]
+
+### Skipped (Could Not Apply)
+- `path/to/file.md`: [Reason - e.g., "Section not found"]
+
+### Warnings
+- [Any issues encountered during application]
+```

.factory/prompts/docs-automation/phase6-summarize.md 🔗

@@ -0,0 +1,54 @@
+# Phase 6: Summarize Changes
+
+You are generating a summary of documentation updates for PR review.
+
+## Objective
+Create a clear, reviewable summary of all documentation changes made.
+
+## Input
+You will receive:
+- Applied changes report from Phase 5
+- Original change analysis from Phase 3
+- Git diff of documentation changes
+
+## Instructions
+
+1. **Gather Change Information**
+   - List all modified documentation files
+   - Identify the corresponding code changes that triggered each update
+
+2. **Generate Summary**
+   Use the format specified in `docs/AGENTS.md` Phase 6 section:
+
+```markdown
+## Documentation Update Summary
+
+### Changes Made
+| File | Change | Related Code |
+| --- | --- | --- |
+| docs/src/path.md | Brief description | PR #123 or commit SHA |
+
+### Rationale
+Brief explanation of why these updates were made, linking back to the triggering code changes.
+
+### Review Notes
+- Items reviewers should pay special attention to
+- Any uncertainty flags from Phase 4 that were addressed
+- Assumptions made during documentation
+```
+
+3. **Add Context for Reviewers**
+   - Highlight any changes that might be controversial
+   - Note if any planned changes were skipped and why
+   - Flag areas where reviewer expertise is especially needed
+
+## Output Format
+The summary should be suitable for:
+- PR description body
+- Commit message (condensed version)
+- Team communication
+
+## Constraints
+- Read-only (documentation changes already applied in Phase 5)
+- Factual: Describe what was done, not justify why it's good
+- Complete: Account for all changes, including skipped items

.factory/prompts/docs-automation/phase7-commit.md 🔗

@@ -0,0 +1,67 @@
+# Phase 7: Commit and Open PR
+
+You are creating a git branch, committing documentation changes, and opening a PR.
+
+## Objective
+Package documentation updates into a reviewable pull request.
+
+## Input
+You will receive:
+- Summary from Phase 6
+- List of modified files
+
+## Instructions
+
+1. **Create Branch**
+   ```sh
+   git checkout -b docs/auto-update-{date}
+   ```
+   Use format: `docs/auto-update-YYYY-MM-DD` or `docs/auto-update-{short-sha}`
+
+2. **Stage and Commit**
+   - Stage only documentation files in `docs/src/`
+   - Do not stage any other files
+   
+   Commit message format:
+   ```
+   docs: auto-update documentation for [brief description]
+   
+   [Summary from Phase 6, condensed]
+   
+   Triggered by: [commit SHA or PR reference]
+   
+   Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>
+   ```
+
+3. **Push Branch**
+   ```sh
+   git push -u origin docs/auto-update-{date}
+   ```
+
+4. **Create Pull Request**
+   Use the Phase 6 summary as the PR body.
+   
+   PR Title: `docs: [Brief description of documentation updates]`
+   
+   Labels (if available): `documentation`, `automated`
+   
+   Base branch: `main`
+
+## Constraints
+- Do NOT auto-merge
+- Do NOT request specific reviewers (let CODEOWNERS handle it)
+- Do NOT modify files outside `docs/src/`
+- If no changes to commit, exit gracefully with message "No documentation changes to commit"
+
+## Output
+```markdown
+## PR Created
+
+- **Branch**: docs/auto-update-{date}
+- **PR URL**: https://github.com/zed-industries/zed/pull/XXXX
+- **Status**: Ready for review
+
+### Commit
+- SHA: {commit-sha}
+- Files: {count} documentation files modified
+```

.github/ISSUE_TEMPLATE/10_bug_report.yml 🔗

@@ -75,6 +75,22 @@ body:
         </details>
     validations:
       required: false
+  - type: textarea
+    attributes:
+      label: Relevant Keymap
+      description: |
+        Open the command palette in Zed, then type “zed: open keymap file” and copy/paste the file's contents.
+      value: |
+        <details><summary>keymap.json</summary>
+
+        <!-- Paste your keymap file inside the code block. -->
+        ```json
+
+        ```
+
+        </details>
+    validations:
+      required: false
   - type: textarea
     attributes:
       label: (for AI issues) Model provider details

.github/actionlint.yml 🔗

@@ -25,6 +25,7 @@ self-hosted-runner:
     - namespace-profile-32x64-ubuntu-2204
     # Namespace Ubuntu 24.04 (like ubuntu-latest)
     - namespace-profile-2x4-ubuntu-2404
+    - namespace-profile-8x32-ubuntu-2404
     # Namespace Limited Preview
     - namespace-profile-8x16-ubuntu-2004-arm-m4
     - namespace-profile-8x32-ubuntu-2004-arm-m4

.github/actions/build_docs/action.yml 🔗

@@ -19,6 +19,18 @@ runs:
       shell: bash -euxo pipefail {0}
       run: ./script/linux
 
+    - name: Install mold linker
+      shell: bash -euxo pipefail {0}
+      run: ./script/install-mold
+
+    - name: Download WASI SDK
+      shell: bash -euxo pipefail {0}
+      run: ./script/download-wasi-sdk
+
+    - name: Generate action metadata
+      shell: bash -euxo pipefail {0}
+      run: ./script/generate-action-metadata
+
     - name: Check for broken links (in MD)
       uses: lycheeverse/lychee-action@82202e5e9c2f4ef1a55a3d02563e1cb6041e5332 # v2.4.1
       with:

.github/workflows/after_release.yml 🔗

@@ -5,13 +5,27 @@ on:
   release:
     types:
     - published
+  workflow_dispatch:
+    inputs:
+      tag_name:
+        description: tag_name
+        required: true
+        type: string
+      prerelease:
+        description: prerelease
+        required: true
+        type: boolean
+      body:
+        description: body
+        type: string
+        default: ''
 jobs:
   rebuild_releases_page:
     if: (github.repository_owner == 'zed-industries' || github.repository_owner == 'zed-extensions')
     runs-on: namespace-profile-2x4-ubuntu-2404
     steps:
     - name: after_release::rebuild_releases_page::refresh_cloud_releases
-      run: curl -fX POST https://cloud.zed.dev/releases/refresh?expect_tag=${{ github.event.release.tag_name }}
+      run: curl -fX POST https://cloud.zed.dev/releases/refresh?expect_tag=${{ github.event.release.tag_name || inputs.tag_name }}
       shell: bash -euxo pipefail {0}
     - name: after_release::rebuild_releases_page::redeploy_zed_dev
       run: npm exec --yes -- vercel@37 --token="$VERCEL_TOKEN" --scope zed-industries redeploy https://zed.dev
@@ -27,7 +41,7 @@ jobs:
     - id: get-release-url
       name: after_release::post_to_discord::get_release_url
       run: |
-        if [ "${{ github.event.release.prerelease }}" == "true" ]; then
+        if [ "${{ github.event.release.prerelease || inputs.prerelease }}" == "true" ]; then
             URL="https://zed.dev/releases/preview"
         else
             URL="https://zed.dev/releases/stable"
@@ -40,9 +54,9 @@ jobs:
       uses: 2428392/gh-truncate-string-action@b3ff790d21cf42af3ca7579146eedb93c8fb0757
       with:
         stringToTruncate: |
-          📣 Zed [${{ github.event.release.tag_name }}](<${{ steps.get-release-url.outputs.URL }}>) was just released!
+          📣 Zed [${{ github.event.release.tag_name || inputs.tag_name }}](<${{ steps.get-release-url.outputs.URL }}>)  was just released!
 
-          ${{ github.event.release.body }}
+          ${{ github.event.release.body || inputs.body }}
         maxLength: 2000
         truncationSymbol: '...'
     - name: after_release::post_to_discord::discord_webhook_action
@@ -56,7 +70,7 @@ jobs:
     - id: set-package-name
       name: after_release::publish_winget::set_package_name
       run: |
-        if ("${{ github.event.release.prerelease }}" -eq "true") {
+        if ("${{ github.event.release.prerelease || inputs.prerelease }}" -eq "true") {
             $PACKAGE_NAME = "ZedIndustries.Zed.Preview"
         } else {
             $PACKAGE_NAME = "ZedIndustries.Zed"
@@ -68,6 +82,7 @@ jobs:
       uses: vedantmgoyal9/winget-releaser@19e706d4c9121098010096f9c495a70a7518b30f
       with:
         identifier: ${{ steps.set-package-name.outputs.PACKAGE_NAME }}
+        release-tag: ${{ github.event.release.tag_name || inputs.tag_name }}
         max-versions-to-keep: 5
         token: ${{ secrets.WINGET_TOKEN }}
   create_sentry_release:

.github/workflows/autofix_pr.yml 🔗

@@ -0,0 +1,132 @@
+# Generated from xtask::workflows::autofix_pr
+# Rebuild with `cargo xtask workflows`.
+name: autofix_pr
+run-name: 'autofix PR #${{ inputs.pr_number }}'
+on:
+  workflow_dispatch:
+    inputs:
+      pr_number:
+        description: pr_number
+        required: true
+        type: string
+      run_clippy:
+        description: run_clippy
+        type: boolean
+        default: 'true'
+jobs:
+  run_autofix:
+    runs-on: namespace-profile-16x32-ubuntu-2204
+    steps:
+    - name: steps::checkout_repo
+      uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683
+      with:
+        clean: false
+    - name: autofix_pr::run_autofix::checkout_pr
+      run: gh pr checkout ${{ inputs.pr_number }}
+      shell: bash -euxo pipefail {0}
+      env:
+        GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+    - name: steps::setup_cargo_config
+      run: |
+        mkdir -p ./../.cargo
+        cp ./.cargo/ci-config.toml ./../.cargo/config.toml
+      shell: bash -euxo pipefail {0}
+    - name: steps::cache_rust_dependencies_namespace
+      uses: namespacelabs/nscloud-cache-action@v1
+      with:
+        cache: rust
+    - name: steps::setup_linux
+      run: ./script/linux
+      shell: bash -euxo pipefail {0}
+    - name: steps::install_mold
+      run: ./script/install-mold
+      shell: bash -euxo pipefail {0}
+    - name: steps::download_wasi_sdk
+      run: ./script/download-wasi-sdk
+      shell: bash -euxo pipefail {0}
+    - name: steps::setup_pnpm
+      uses: pnpm/action-setup@fe02b34f77f8bc703788d5817da081398fad5dd2
+      with:
+        version: '9'
+    - name: autofix_pr::run_autofix::run_prettier_fix
+      run: ./script/prettier --write
+      shell: bash -euxo pipefail {0}
+    - name: autofix_pr::run_autofix::run_cargo_fmt
+      run: cargo fmt --all
+      shell: bash -euxo pipefail {0}
+    - name: autofix_pr::run_autofix::run_cargo_fix
+      if: ${{ inputs.run_clippy }}
+      run: cargo fix --workspace --release --all-targets --all-features --allow-dirty --allow-staged
+      shell: bash -euxo pipefail {0}
+    - name: autofix_pr::run_autofix::run_clippy_fix
+      if: ${{ inputs.run_clippy }}
+      run: cargo clippy --workspace --release --all-targets --all-features --fix --allow-dirty --allow-staged
+      shell: bash -euxo pipefail {0}
+    - id: create-patch
+      name: autofix_pr::run_autofix::create_patch
+      run: |
+        if git diff --quiet; then
+            echo "No changes to commit"
+            echo "has_changes=false" >> "$GITHUB_OUTPUT"
+        else
+            git diff > autofix.patch
+            echo "has_changes=true" >> "$GITHUB_OUTPUT"
+        fi
+      shell: bash -euxo pipefail {0}
+    - name: upload artifact autofix-patch
+      uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4
+      with:
+        name: autofix-patch
+        path: autofix.patch
+        if-no-files-found: ignore
+        retention-days: '1'
+    - name: steps::cleanup_cargo_config
+      if: always()
+      run: |
+        rm -rf ./../.cargo
+      shell: bash -euxo pipefail {0}
+    outputs:
+      has_changes: ${{ steps.create-patch.outputs.has_changes }}
+  commit_changes:
+    needs:
+    - run_autofix
+    if: needs.run_autofix.outputs.has_changes == 'true'
+    runs-on: namespace-profile-2x4-ubuntu-2404
+    steps:
+    - id: get-app-token
+      name: steps::authenticate_as_zippy
+      uses: actions/create-github-app-token@bef1eaf1c0ac2b148ee2a0a74c65fbe6db0631f1
+      with:
+        app-id: ${{ secrets.ZED_ZIPPY_APP_ID }}
+        private-key: ${{ secrets.ZED_ZIPPY_APP_PRIVATE_KEY }}
+    - name: steps::checkout_repo_with_token
+      uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683
+      with:
+        clean: false
+        token: ${{ steps.get-app-token.outputs.token }}
+    - name: autofix_pr::commit_changes::checkout_pr
+      run: gh pr checkout ${{ inputs.pr_number }}
+      shell: bash -euxo pipefail {0}
+      env:
+        GITHUB_TOKEN: ${{ steps.get-app-token.outputs.token }}
+    - name: autofix_pr::download_patch_artifact
+      uses: actions/download-artifact@018cc2cf5baa6db3ef3c5f8a56943fffe632ef53
+      with:
+        name: autofix-patch
+    - name: autofix_pr::commit_changes::apply_patch
+      run: git apply autofix.patch
+      shell: bash -euxo pipefail {0}
+    - name: autofix_pr::commit_changes::commit_and_push
+      run: |
+        git commit -am "Autofix"
+        git push
+      shell: bash -euxo pipefail {0}
+      env:
+        GIT_COMMITTER_NAME: Zed Zippy
+        GIT_COMMITTER_EMAIL: 234243425+zed-zippy[bot]@users.noreply.github.com
+        GIT_AUTHOR_NAME: Zed Zippy
+        GIT_AUTHOR_EMAIL: 234243425+zed-zippy[bot]@users.noreply.github.com
+        GITHUB_TOKEN: ${{ steps.get-app-token.outputs.token }}
+concurrency:
+  group: ${{ github.workflow }}-${{ inputs.pr_number }}
+  cancel-in-progress: true

.github/workflows/cherry_pick.yml 🔗

@@ -30,7 +30,7 @@ jobs:
       with:
         clean: false
     - id: get-app-token
-      name: cherry_pick::run_cherry_pick::authenticate_as_zippy
+      name: steps::authenticate_as_zippy
       uses: actions/create-github-app-token@bef1eaf1c0ac2b148ee2a0a74c65fbe6db0631f1
       with:
         app-id: ${{ secrets.ZED_ZIPPY_APP_ID }}

.github/workflows/community_close_stale_issues.yml 🔗

@@ -1,29 +1,40 @@
 name: "Close Stale Issues"
 on:
   schedule:
-    - cron: "0 8 31 DEC *"
+    - cron: "0 2 * * 5"
   workflow_dispatch:
+    inputs:
+      debug-only:
+        description: "Run in dry-run mode (no changes made)"
+        type: boolean
+        default: false
+      operations-per-run:
+        description: "Max number of issues to process (default: 1000)"
+        type: number
+        default: 1000
 
 jobs:
   stale:
     if: github.repository_owner == 'zed-industries'
     runs-on: ubuntu-latest
     steps:
-      - uses: actions/stale@5bef64f19d7facfb25b37b414482c7164d639639 # v9
+      - uses: actions/stale@997185467fa4f803885201cee163a9f38240193d # v10
         with:
           repo-token: ${{ secrets.GITHUB_TOKEN }}
           stale-issue-message: >
-            Hi there! 👋
-
-            We're working to clean up our issue tracker by closing older bugs that might not be relevant anymore. If you are able to reproduce this issue in the latest version of Zed, please let us know by commenting on this issue, and it will be kept open. If you can't reproduce it, feel free to close the issue yourself. Otherwise, it will close automatically in 14 days.
+            Hi there!
+            Zed development moves fast and a significant number of bugs become outdated.
+            If you can reproduce this bug on the latest stable Zed, please let us know by leaving a comment with the Zed version.
+            If the bug doesn't appear for you anymore, feel free to close the issue yourself; otherwise, the bot will close it in a couple of weeks.
 
             Thanks for your help!
-          close-issue-message: "This issue was closed due to inactivity. If you're still experiencing this problem, please open a new issue with a link to this issue."
+          close-issue-message: "This issue was closed due to inactivity. If you're still experiencing this problem, please leave a comment with your Zed version so that we can reopen the issue."
           days-before-stale: 60
           days-before-close: 14
           only-issue-types: "Bug,Crash"
-          operations-per-run: 1000
+          operations-per-run: ${{ inputs.operations-per-run || 1000 }}
           ascending: true
           enable-statistics: true
+          debug-only: ${{ inputs.debug-only }}
           stale-issue-label: "stale"
           exempt-issue-labels: "never stale"

.github/workflows/docs_automation.yml 🔗

@@ -0,0 +1,264 @@
+name: Documentation Automation
+
+on:
+  # push:
+  #   branches: [main]
+  #   paths:
+  #     - 'crates/**'
+  #     - 'extensions/**'
+  workflow_dispatch:
+    inputs:
+      pr_number:
+        description: 'PR number to analyze (gets full PR diff)'
+        required: false
+        type: string
+      trigger_sha:
+        description: 'Commit SHA to analyze (ignored if pr_number is set)'
+        required: false
+        type: string
+
+permissions:
+  contents: write
+  pull-requests: write
+
+env:
+  FACTORY_API_KEY: ${{ secrets.FACTORY_API_KEY }}
+  DROID_MODEL: claude-opus-4-5-20251101
+
+jobs:
+  docs-automation:
+    runs-on: ubuntu-latest
+    timeout-minutes: 30
+
+    steps:
+      - name: Checkout repository
+        uses: actions/checkout@v4
+        with:
+          fetch-depth: 0
+
+      - name: Install Droid CLI
+        id: install-droid
+        run: |
+          curl -fsSL https://app.factory.ai/cli | sh
+          echo "${HOME}/.local/bin" >> "$GITHUB_PATH"
+          echo "DROID_BIN=${HOME}/.local/bin/droid" >> "$GITHUB_ENV"
+          # Verify installation
+          "${HOME}/.local/bin/droid" --version
+
+      - name: Setup Node.js (for Prettier)
+        uses: actions/setup-node@v4
+        with:
+          node-version: '20'
+
+      - name: Install Prettier
+        run: npm install -g prettier
+
+      - name: Get changed files
+        id: changed
+        run: |
+          if [ -n "${{ inputs.pr_number }}" ]; then
+            # Get full PR diff
+            echo "Analyzing PR #${{ inputs.pr_number }}"
+            echo "source=pr" >> "$GITHUB_OUTPUT"
+            echo "ref=${{ inputs.pr_number }}" >> "$GITHUB_OUTPUT"
+            gh pr diff "${{ inputs.pr_number }}" --name-only > /tmp/changed_files.txt
+          elif [ -n "${{ inputs.trigger_sha }}" ]; then
+            # Get single commit diff
+            SHA="${{ inputs.trigger_sha }}"
+            echo "Analyzing commit $SHA"
+            echo "source=commit" >> "$GITHUB_OUTPUT"
+            echo "ref=$SHA" >> "$GITHUB_OUTPUT"
+            git diff --name-only "${SHA}^" "$SHA" > /tmp/changed_files.txt
+          else
+            # Default to current commit
+            SHA="${{ github.sha }}"
+            echo "Analyzing commit $SHA"
+            echo "source=commit" >> "$GITHUB_OUTPUT"
+            echo "ref=$SHA" >> "$GITHUB_OUTPUT"
+            git diff --name-only "${SHA}^" "$SHA" > /tmp/changed_files.txt || git diff --name-only HEAD~1 HEAD > /tmp/changed_files.txt
+          fi
+
+          echo "Changed files:"
+          cat /tmp/changed_files.txt
+        env:
+          GH_TOKEN: ${{ github.token }}
+
+      # Phase 0: Guardrails are loaded via AGENTS.md in each phase
+
+      # Phase 2: Explore Repository (Read-Only - default)
+      - name: "Phase 2: Explore Repository"
+        id: phase2
+        run: |
+          "$DROID_BIN" exec \
+            -m "$DROID_MODEL" \
+            -f .factory/prompts/docs-automation/phase2-explore.md \
+            > /tmp/phase2-output.txt 2>&1 || true
+          echo "Repository exploration complete"
+          cat /tmp/phase2-output.txt
+
+      # Phase 3: Analyze Changes (Read-Only - default)
+      - name: "Phase 3: Analyze Changes"
+        id: phase3
+        run: |
+          CHANGED_FILES=$(tr '\n' ' ' < /tmp/changed_files.txt)
+          echo "Analyzing changes in: $CHANGED_FILES"
+
+          # Build prompt with context
+          cat > /tmp/phase3-prompt.md << 'EOF'
+          $(cat .factory/prompts/docs-automation/phase3-analyze.md)
+
+          ## Context
+
+          ### Changed Files
+          $CHANGED_FILES
+
+          ### Phase 2 Output
+          $(cat /tmp/phase2-output.txt)
+          EOF
+
+          "$DROID_BIN" exec \
+            -m "$DROID_MODEL" \
+            "$(cat .factory/prompts/docs-automation/phase3-analyze.md)
+
+            Changed files: $CHANGED_FILES" \
+            > /tmp/phase3-output.md 2>&1 || true
+          echo "Change analysis complete"
+          cat /tmp/phase3-output.md
+
+      # Phase 4: Plan Documentation Impact (Read-Only - default)
+      - name: "Phase 4: Plan Documentation Impact"
+        id: phase4
+        run: |
+          "$DROID_BIN" exec \
+            -m "$DROID_MODEL" \
+            -f .factory/prompts/docs-automation/phase4-plan.md \
+            > /tmp/phase4-plan.md 2>&1 || true
+          echo "Documentation plan complete"
+          cat /tmp/phase4-plan.md
+
+          # Check if updates are required
+          if grep -q "NO_UPDATES_REQUIRED" /tmp/phase4-plan.md; then
+            echo "updates_required=false" >> "$GITHUB_OUTPUT"
+          else
+            echo "updates_required=true" >> "$GITHUB_OUTPUT"
+          fi
+
+      # Phase 5: Apply Plan (Write-Enabled with --auto medium)
+      - name: "Phase 5: Apply Documentation Plan"
+        id: phase5
+        if: steps.phase4.outputs.updates_required == 'true'
+        run: |
+          "$DROID_BIN" exec \
+            -m "$DROID_MODEL" \
+            --auto medium \
+            -f .factory/prompts/docs-automation/phase5-apply.md \
+            > /tmp/phase5-report.md 2>&1 || true
+          echo "Documentation updates applied"
+          cat /tmp/phase5-report.md
+
+      # Phase 5b: Format with Prettier
+      - name: "Phase 5b: Format with Prettier"
+        id: phase5b
+        if: steps.phase4.outputs.updates_required == 'true'
+        run: |
+          echo "Formatting documentation with Prettier..."
+          cd docs && prettier --write src/
+
+          echo "Verifying Prettier formatting passes..."
+          cd docs && prettier --check src/
+
+          echo "Prettier formatting complete"
+
+      # Phase 6: Summarize Changes (Read-Only - default)
+      - name: "Phase 6: Summarize Changes"
+        id: phase6
+        if: steps.phase4.outputs.updates_required == 'true'
+        run: |
+          # Get git diff of docs
+          git diff docs/src/ > /tmp/docs-diff.txt || true
+
+          "$DROID_BIN" exec \
+            -m "$DROID_MODEL" \
+            -f .factory/prompts/docs-automation/phase6-summarize.md \
+            > /tmp/phase6-summary.md 2>&1 || true
+          echo "Summary generated"
+          cat /tmp/phase6-summary.md
+
+      # Phase 7: Commit and Open PR
+      - name: "Phase 7: Create PR"
+        id: phase7
+        if: steps.phase4.outputs.updates_required == 'true'
+        run: |
+          # Check if there are actual changes
+          if git diff --quiet docs/src/; then
+            echo "No documentation changes detected"
+            exit 0
+          fi
+
+          # Configure git
+          git config user.name "factory-droid[bot]"
+          git config user.email "138933559+factory-droid[bot]@users.noreply.github.com"
+
+          # Daily batch branch - one branch per day, multiple commits accumulate
+          BRANCH_NAME="docs/auto-update-$(date +%Y-%m-%d)"
+
+          # Stash local changes from phase 5
+          git stash push -m "docs-automation-changes" -- docs/src/
+
+          # Check if branch already exists on remote
+          if git ls-remote --exit-code --heads origin "$BRANCH_NAME" > /dev/null 2>&1; then
+            echo "Branch $BRANCH_NAME exists, checking out and updating..."
+            git fetch origin "$BRANCH_NAME"
+            git checkout -B "$BRANCH_NAME" "origin/$BRANCH_NAME"
+          else
+            echo "Creating new branch $BRANCH_NAME..."
+            git checkout -b "$BRANCH_NAME"
+          fi
+
+          # Apply stashed changes
+          git stash pop || true
+
+          # Stage and commit
+          git add docs/src/
+          SUMMARY=$(head -50 < /tmp/phase6-summary.md)
+          git commit -m "docs: auto-update documentation
+
+          ${SUMMARY}
+
+          Triggered by: ${{ steps.changed.outputs.source }} ${{ steps.changed.outputs.ref }}
+
+          Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>"
+
+          # Push
+          git push -u origin "$BRANCH_NAME"
+
+          # Check if PR already exists for this branch
+          EXISTING_PR=$(gh pr list --head "$BRANCH_NAME" --json number --jq '.[0].number' || echo "")
+
+          if [ -n "$EXISTING_PR" ]; then
+            echo "PR #$EXISTING_PR already exists for branch $BRANCH_NAME, updated with new commit"
+          else
+            # Create new PR
+            gh pr create \
+              --title "docs: automated documentation update ($(date +%Y-%m-%d))" \
+              --body-file /tmp/phase6-summary.md \
+              --base main || true
+            echo "PR created on branch: $BRANCH_NAME"
+          fi
+        env:
+          GH_TOKEN: ${{ github.token }}
+
+      # Summary output
+      - name: "Summary"
+        if: always()
+        run: |
+          echo "## Documentation Automation Summary" >> "$GITHUB_STEP_SUMMARY"
+          echo "" >> "$GITHUB_STEP_SUMMARY"
+
+          if [ "${{ steps.phase4.outputs.updates_required }}" == "false" ]; then
+            echo "No documentation updates required for this change." >> "$GITHUB_STEP_SUMMARY"
+          elif [ -f /tmp/phase6-summary.md ]; then
+            cat /tmp/phase6-summary.md >> "$GITHUB_STEP_SUMMARY"
+          else
+            echo "Workflow completed. Check individual phase outputs for details." >> "$GITHUB_STEP_SUMMARY"
+          fi

.github/workflows/extension_bump.yml 🔗

@@ -25,33 +25,6 @@ on:
         description: The app secret for the corresponding app ID
         required: true
 jobs:
-  check_extension:
-    if: (github.repository_owner == 'zed-industries' || github.repository_owner == 'zed-extensions')
-    runs-on: namespace-profile-2x4-ubuntu-2404
-    steps:
-    - name: steps::checkout_repo
-      uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683
-      with:
-        clean: false
-    - id: cache-zed-extension-cli
-      name: extension_tests::cache_zed_extension_cli
-      uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830
-      with:
-        path: zed-extension
-        key: zed-extension-${{ env.ZED_EXTENSION_CLI_SHA }}
-    - name: extension_tests::download_zed_extension_cli
-      if: steps.cache-zed-extension-cli.outputs.cache-hit != 'true'
-      run: |
-        wget --quiet "https://zed-extension-cli.nyc3.digitaloceanspaces.com/$ZED_EXTENSION_CLI_SHA/x86_64-unknown-linux-gnu/zed-extension"
-        chmod +x zed-extension
-      shell: bash -euxo pipefail {0}
-    - name: extension_tests::check
-      run: |
-        mkdir -p /tmp/ext-scratch
-        mkdir -p /tmp/ext-output
-        ./zed-extension --source-dir . --scratch-dir /tmp/ext-scratch --output-dir /tmp/ext-output
-      shell: bash -euxo pipefail {0}
-    timeout-minutes: 2
   check_bump_needed:
     if: (github.repository_owner == 'zed-industries' || github.repository_owner == 'zed-extensions')
     runs-on: namespace-profile-2x4-ubuntu-2404
@@ -89,7 +62,6 @@ jobs:
     timeout-minutes: 1
   bump_extension_version:
     needs:
-    - check_extension
     - check_bump_needed
     if: |-
       (github.repository_owner == 'zed-industries' || github.repository_owner == 'zed-extensions') &&
@@ -141,10 +113,10 @@ jobs:
         delete-branch: true
         token: ${{ steps.generate-token.outputs.token }}
         sign-commits: true
+        assignees: ${{ github.actor }}
     timeout-minutes: 1
   create_version_label:
     needs:
-    - check_extension
     - check_bump_needed
     if: (github.repository_owner == 'zed-industries' || github.repository_owner == 'zed-extensions') && github.event_name == 'push' && github.ref == 'refs/heads/main' && needs.check_bump_needed.outputs.needs_bump == 'false'
     runs-on: namespace-profile-8x16-ubuntu-2204

.github/workflows/extension_tests.yml 🔗

@@ -51,7 +51,7 @@ jobs:
     needs:
     - orchestrate
     if: needs.orchestrate.outputs.check_rust == 'true'
-    runs-on: namespace-profile-16x32-ubuntu-2204
+    runs-on: namespace-profile-4x8-ubuntu-2204
     steps:
     - name: steps::checkout_repo
       uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683
@@ -79,7 +79,7 @@ jobs:
     needs:
     - orchestrate
     if: needs.orchestrate.outputs.check_extension == 'true'
-    runs-on: namespace-profile-2x4-ubuntu-2404
+    runs-on: namespace-profile-8x32-ubuntu-2404
     steps:
     - name: steps::checkout_repo
       uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683

.github/workflows/release.yml 🔗

@@ -472,11 +472,17 @@ jobs:
     if: startsWith(github.ref, 'refs/tags/v') && endsWith(github.ref, '-pre') && !endsWith(github.ref, '.0-pre')
     runs-on: namespace-profile-2x4-ubuntu-2404
     steps:
+    - id: get-app-token
+      name: steps::authenticate_as_zippy
+      uses: actions/create-github-app-token@bef1eaf1c0ac2b148ee2a0a74c65fbe6db0631f1
+      with:
+        app-id: ${{ secrets.ZED_ZIPPY_APP_ID }}
+        private-key: ${{ secrets.ZED_ZIPPY_APP_PRIVATE_KEY }}
     - name: gh release edit "$GITHUB_REF_NAME" --repo=zed-industries/zed --draft=false
       run: gh release edit "$GITHUB_REF_NAME" --repo=zed-industries/zed --draft=false
       shell: bash -euxo pipefail {0}
       env:
-        GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+        GITHUB_TOKEN: ${{ steps.get-app-token.outputs.token }}
   notify_on_failure:
     needs:
     - upload_release_assets

.github/workflows/run_tests.yml 🔗

@@ -74,9 +74,12 @@ jobs:
       uses: pnpm/action-setup@fe02b34f77f8bc703788d5817da081398fad5dd2
       with:
         version: '9'
-    - name: ./script/prettier
+    - name: steps::prettier
       run: ./script/prettier
       shell: bash -euxo pipefail {0}
+    - name: steps::cargo_fmt
+      run: cargo fmt --all -- --check
+      shell: bash -euxo pipefail {0}
     - name: ./script/check-todos
       run: ./script/check-todos
       shell: bash -euxo pipefail {0}
@@ -87,9 +90,6 @@ jobs:
       uses: crate-ci/typos@2d0ce569feab1f8752f1dde43cc2f2aa53236e06
       with:
         config: ./typos.toml
-    - name: steps::cargo_fmt
-      run: cargo fmt --all -- --check
-      shell: bash -euxo pipefail {0}
     timeout-minutes: 60
   run_tests_windows:
     needs:
@@ -353,6 +353,9 @@ jobs:
     - name: steps::download_wasi_sdk
       run: ./script/download-wasi-sdk
       shell: bash -euxo pipefail {0}
+    - name: ./script/generate-action-metadata
+      run: ./script/generate-action-metadata
+      shell: bash -euxo pipefail {0}
     - name: run_tests::check_docs::install_mdbook
       uses: peaceiris/actions-mdbook@ee69d230fe19748b7abf22df32acaa93833fad08
       with:
@@ -497,6 +500,8 @@ jobs:
     env:
       GIT_AUTHOR_NAME: Protobuf Action
       GIT_AUTHOR_EMAIL: ci@zed.dev
+      GIT_COMMITTER_NAME: Protobuf Action
+      GIT_COMMITTER_EMAIL: ci@zed.dev
     steps:
     - name: steps::checkout_repo
       uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683

.gitignore 🔗

@@ -8,6 +8,7 @@
 .DS_Store
 .blob_store
 .build
+.claude/settings.local.json
 .envrc
 .flatpak-builder
 .idea
@@ -35,7 +36,11 @@
 DerivedData/
 Packages
 xcuserdata/
+crates/docs_preprocessor/actions.json
 
 # Don't commit any secrets to the repo.
 .env
 .env.secret.toml
+
+# `nix build` output
+/result

.mailmap 🔗

@@ -141,6 +141,9 @@ Uladzislau Kaminski <i@uladkaminski.com>
 Uladzislau Kaminski <i@uladkaminski.com> <uladzislau_kaminski@epam.com>
 Vitaly Slobodin <vitaliy.slobodin@gmail.com>
 Vitaly Slobodin <vitaliy.slobodin@gmail.com> <vitaly_slobodin@fastmail.com>
+Yara <davidsk@zed.dev>
+Yara <git@davidsk.dev>
+Yara <git@yara.blue>
 Will Bradley <williambbradley@gmail.com>
 Will Bradley <williambbradley@gmail.com> <will@zed.dev>
 WindSoilder <WindSoilder@outlook.com>

.rules 🔗

@@ -26,6 +26,12 @@
   });
   ```
 
+# Timers in tests
+
+* In GPUI tests, prefer GPUI executor timers over `smol::Timer::after(...)` when you need timeouts, delays, or to drive `run_until_parked()`:
+  - Use `cx.background_executor().timer(duration).await` (or `cx.background_executor.timer(duration).await` in `TestAppContext`) so the work is scheduled on GPUI's dispatcher.
+  - Avoid `smol::Timer::after(...)` for test timeouts when you rely on `run_until_parked()`, because it may not be tracked by GPUI's scheduler and can lead to "nothing left to run" when pumping.
+
 # GPUI
 
 GPUI is a UI framework which also provides primitives for state and concurrency management.

CONTRIBUTING.md 🔗

@@ -15,15 +15,16 @@ with the community to improve the product in ways we haven't thought of (or had
 
 In particular we love PRs that are:
 
-- Fixes to existing bugs and issues.
-- Small enhancements to existing features, particularly to make them work for more people.
+- Fixing or extending the docs.
+- Fixing bugs.
+- Small enhancements to existing features to make them work for more people (making things work on more platforms/modes/whatever).
 - Small extra features, like keybindings or actions you miss from other editors or extensions.
-- Work towards shipping larger features on our roadmap.
+- Part of a Community Program like [Let's Git Together](https://github.com/zed-industries/zed/issues/41541).
 
 If you're looking for concrete ideas:
 
-- Our [top-ranking issues](https://github.com/zed-industries/zed/issues/5393) based on votes by the community.
-- Our [public roadmap](https://zed.dev/roadmap) contains a rough outline of our near-term priorities for Zed.
+- [Triaged bugs with confirmed steps to reproduce](https://github.com/zed-industries/zed/issues?q=is%3Aissue%20state%3Aopen%20type%3ABug%20label%3Astate%3Areproducible).
+- [Area labels](https://github.com/zed-industries/zed/labels?q=area%3A*) to browse bugs in a specific part of the product you care about (after clicking on an area label, add type:Bug to the search).
 
 ## Sending changes
 
@@ -37,9 +38,17 @@ like, sorry).
 Although we will take a look, we tend to only merge about half the PRs that are
 submitted. If you'd like your PR to have the best chance of being merged:
 
-- Include a clear description of what you're solving, and why it's important to you.
-- Include tests.
-- If it changes the UI, attach screenshots or screen recordings.
+- Make sure the change is **desired**: we're always happy to accept bugfixes,
+  but features should be confirmed with us first if you aim to avoid wasted
+  effort. If there isn't already a GitHub issue for your feature with staff
+  confirmation that we want it, start with a GitHub discussion rather than a PR.
+- Include a clear description of **what you're solving**, and why it's important.
+- Include **tests**.
+- If it changes the UI, attach **screenshots** or screen recordings.
+- Make the PR about **one thing only**, e.g. if it's a bugfix, don't add two
+  features and a refactoring on top of that.
+- Keep AI assistance under your judgement and responsibility: it's unlikely
+  we'll merge a vibe-coded PR that the author doesn't understand.
 
 The internal advice for reviewers is as follows:
 
@@ -50,10 +59,9 @@ The internal advice for reviewers is as follows:
 If you need more feedback from us: the best way is to be responsive to
 Github comments, or to offer up time to pair with us.
 
-If you are making a larger change, or need advice on how to finish the change
-you're making, please open the PR early. We would love to help you get
-things right, and it's often easier to see how to solve a problem before the
-diff gets too big.
+If you need help deciding how to fix a bug, or finish implementing a feature
+that we've agreed we want, please open a PR early so we can discuss how to make
+the change with code in hand.
 
 ## Things we will (probably) not merge
 
@@ -61,11 +69,11 @@ Although there are few hard and fast rules, typically we don't merge:
 
 - Anything that can be provided by an extension. For example a new language, or theme. For adding themes or support for a new language to Zed, check out our [docs on developing extensions](https://zed.dev/docs/extensions/developing-extensions).
 - New file icons. Zed's default icon theme consists of icons that are hand-designed to fit together in a cohesive manner, please don't submit PRs with off-the-shelf SVGs.
+- Features where (in our subjective opinion) the extra complexity isn't worth it for the number of people who will benefit.
 - Giant refactorings.
 - Non-trivial changes with no tests.
 - Stylistic code changes that do not alter any app logic. Reducing allocations, removing `.unwrap()`s, fixing typos is great; making code "more readable" — maybe not so much.
-- Features where (in our subjective opinion) the extra complexity isn't worth it for the number of people who will benefit.
-- Anything that seems completely AI generated.
+- Anything that seems AI-generated without understanding the output.
 
 ## Bird's-eye view of Zed
 

Cargo.lock 🔗

@@ -37,6 +37,7 @@ dependencies = [
  "terminal",
  "ui",
  "url",
+ "urlencoding",
  "util",
  "uuid",
  "watch",
@@ -110,6 +111,15 @@ dependencies = [
  "workspace",
 ]
 
+[[package]]
+name = "addr2line"
+version = "0.24.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dfbe277e56a376000877090da837660b4427aad530e3028d44e0bffe4f89a1c1"
+dependencies = [
+ "gimli 0.31.1",
+]
+
 [[package]]
 name = "addr2line"
 version = "0.25.1"
@@ -159,6 +169,7 @@ dependencies = [
  "derive_more 0.99.20",
  "editor",
  "env_logger 0.11.8",
+ "eval_utils",
  "fs",
  "futures 0.3.31",
  "git",
@@ -210,14 +221,14 @@ dependencies = [
  "worktree",
  "zed_env_vars",
  "zlog",
- "zstd 0.11.2+zstd.1.5.2",
+ "zstd",
 ]
 
 [[package]]
 name = "agent-client-protocol"
-version = "0.7.0"
+version = "0.9.2"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "525705e39c11cd73f7bc784e3681a9386aa30c8d0630808d3dc2237eb4f9cb1b"
+checksum = "d3e527d7dfe0f334313d42d1d9318f0a79665f6f21c440d0798f230a77a7ed6c"
 dependencies = [
  "agent-client-protocol-schema",
  "anyhow",
@@ -226,22 +237,22 @@ dependencies = [
  "derive_more 2.0.1",
  "futures 0.3.31",
  "log",
- "parking_lot",
  "serde",
  "serde_json",
 ]
 
 [[package]]
 name = "agent-client-protocol-schema"
-version = "0.6.2"
+version = "0.10.5"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ecf16c18fea41282d6bbadd1549a06be6836bddb1893f44a6235f340fa24e2af"
+checksum = "6903a00e8ac822f9bacac59a1932754d7387c72ebb7c9c7439ad021505591da4"
 dependencies = [
  "anyhow",
  "derive_more 2.0.1",
  "schemars",
  "serde",
  "serde_json",
+ "strum 0.27.2",
 ]
 
 [[package]]
@@ -290,6 +301,7 @@ dependencies = [
 name = "agent_settings"
 version = "0.1.0"
 dependencies = [
+ "agent-client-protocol",
  "anyhow",
  "cloud_llm_client",
  "collections",
@@ -328,6 +340,7 @@ dependencies = [
  "buffer_diff",
  "chrono",
  "client",
+ "clock",
  "cloud_llm_client",
  "collections",
  "command_palette_hooks",
@@ -335,6 +348,7 @@ dependencies = [
  "context_server",
  "db",
  "editor",
+ "eval_utils",
  "extension",
  "extension_host",
  "feature_flags",
@@ -343,6 +357,7 @@ dependencies = [
  "futures 0.3.31",
  "fuzzy",
  "gpui",
+ "gpui_tokio",
  "html_to_markdown",
  "http_client",
  "image",
@@ -370,6 +385,7 @@ dependencies = [
  "proto",
  "rand 0.9.2",
  "release_channel",
+ "reqwest_client",
  "rope",
  "rules_library",
  "schemars",
@@ -383,7 +399,6 @@ dependencies = [
  "streaming_diff",
  "task",
  "telemetry",
- "telemetry_events",
  "terminal",
  "terminal_view",
  "text",
@@ -396,11 +411,43 @@ dependencies = [
  "unindent",
  "url",
  "util",
+ "uuid",
  "watch",
  "workspace",
  "zed_actions",
 ]
 
+[[package]]
+name = "agent_ui_v2"
+version = "0.1.0"
+dependencies = [
+ "agent",
+ "agent_servers",
+ "agent_settings",
+ "agent_ui",
+ "anyhow",
+ "assistant_text_thread",
+ "chrono",
+ "db",
+ "editor",
+ "feature_flags",
+ "fs",
+ "fuzzy",
+ "gpui",
+ "menu",
+ "project",
+ "prompt_store",
+ "serde",
+ "serde_json",
+ "settings",
+ "text",
+ "time",
+ "time_format",
+ "ui",
+ "util",
+ "workspace",
+]
+
 [[package]]
 name = "ahash"
 version = "0.7.8"
@@ -676,21 +723,6 @@ dependencies = [
  "syn 2.0.106",
 ]
 
-[[package]]
-name = "argminmax"
-version = "0.6.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "70f13d10a41ac8d2ec79ee34178d61e6f47a29c2edfe7ef1721c7383b0359e65"
-dependencies = [
- "num-traits",
-]
-
-[[package]]
-name = "array-init-cursor"
-version = "0.2.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ed51fe0f224d1d4ea768be38c51f9f831dee9d05c163c11fba0b8c44387b1fc3"
-
 [[package]]
 name = "arraydeque"
 version = "0.5.1"
@@ -761,7 +793,7 @@ dependencies = [
  "url",
  "wayland-backend",
  "wayland-client",
- "wayland-protocols 0.32.9",
+ "wayland-protocols",
  "zbus",
 ]
 
@@ -844,7 +876,6 @@ dependencies = [
  "fs",
  "futures 0.3.31",
  "fuzzy",
- "globset",
  "gpui",
  "html_to_markdown",
  "http_client",
@@ -903,7 +934,7 @@ dependencies = [
  "settings",
  "smallvec",
  "smol",
- "telemetry_events",
+ "telemetry",
  "text",
  "ui",
  "unindent",
@@ -1274,15 +1305,6 @@ dependencies = [
  "num-traits",
 ]
 
-[[package]]
-name = "atoi_simd"
-version = "0.16.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c2a49e05797ca52e312a0c658938b7d00693ef037799ef7187678f212d7684cf"
-dependencies = [
- "debug_unsafe",
-]
-
 [[package]]
 name = "atomic"
 version = "0.5.3"
@@ -1419,9 +1441,9 @@ dependencies = [
 
 [[package]]
 name = "aws-config"
-version = "1.8.8"
+version = "1.8.10"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "37cf2b6af2a95a20e266782b4f76f1a5e12bf412a9db2de9c1e9123b9d8c0ad8"
+checksum = "1856b1b48b65f71a4dd940b1c0931f9a7b646d4a924b9828ffefc1454714668a"
 dependencies = [
  "aws-credential-types",
  "aws-runtime",
@@ -1485,9 +1507,9 @@ dependencies = [
 
 [[package]]
 name = "aws-runtime"
-version = "1.5.12"
+version = "1.5.13"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "bfa006bb32360ed90ac51203feafb9d02e3d21046e1fd3a450a404b90ea73e5d"
+checksum = "9f2402da1a5e16868ba98725e5d73f26b8116eaa892e56f2cd0bf5eec7985f70"
 dependencies = [
  "aws-credential-types",
  "aws-sigv4",
@@ -1510,9 +1532,9 @@ dependencies = [
 
 [[package]]
 name = "aws-sdk-bedrockruntime"
-version = "1.109.0"
+version = "1.112.0"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "fbfdfd941dcb253c17bf70baddbf1e5b22f19e29d313d2e049bad4b1dadb2011"
+checksum = "c06c037e6823696d752702ec2bad758d3cf95d1b92b712c8ac7e93824b5e2391"
 dependencies = [
  "aws-credential-types",
  "aws-runtime",
@@ -1592,9 +1614,9 @@ dependencies = [
 
 [[package]]
 name = "aws-sdk-sso"
-version = "1.86.0"
+version = "1.88.0"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "4a0abbfab841446cce6e87af853a3ba2cc1bc9afcd3f3550dd556c43d434c86d"
+checksum = "d05b276777560aa9a196dbba2e3aada4d8006d3d7eeb3ba7fe0c317227d933c4"
 dependencies = [
  "aws-credential-types",
  "aws-runtime",
@@ -1614,9 +1636,9 @@ dependencies = [
 
 [[package]]
 name = "aws-sdk-ssooidc"
-version = "1.88.0"
+version = "1.90.0"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9a68d675582afea0e94d38b6ca9c5aaae4ca14f1d36faa6edb19b42e687e70d7"
+checksum = "f9be14d6d9cd761fac3fd234a0f47f7ed6c0df62d83c0eeb7012750e4732879b"
 dependencies = [
  "aws-credential-types",
  "aws-runtime",
@@ -1636,9 +1658,9 @@ dependencies = [
 
 [[package]]
 name = "aws-sdk-sts"
-version = "1.88.0"
+version = "1.90.0"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d30990923f4f675523c51eb1c0dec9b752fb267b36a61e83cbc219c9d86da715"
+checksum = "98a862d704c817d865c8740b62d8bbeb5adcb30965e93b471df8a5bcefa20a80"
 dependencies = [
  "aws-credential-types",
  "aws-runtime",
@@ -1659,9 +1681,9 @@ dependencies = [
 
 [[package]]
 name = "aws-sigv4"
-version = "1.3.5"
+version = "1.3.6"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "bffc03068fbb9c8dd5ce1c6fb240678a5cffb86fb2b7b1985c999c4b83c8df68"
+checksum = "c35452ec3f001e1f2f6db107b6373f1f48f05ec63ba2c5c9fa91f07dad32af11"
 dependencies = [
  "aws-credential-types",
  "aws-smithy-eventstream",
@@ -1718,9 +1740,9 @@ dependencies = [
 
 [[package]]
 name = "aws-smithy-eventstream"
-version = "0.60.12"
+version = "0.60.13"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9656b85088f8d9dc7ad40f9a6c7228e1e8447cdf4b046c87e152e0805dea02fa"
+checksum = "e29a304f8319781a39808847efb39561351b1bb76e933da7aa90232673638658"
 dependencies = [
  "aws-smithy-types",
  "bytes 1.10.1",
@@ -1729,9 +1751,9 @@ dependencies = [
 
 [[package]]
 name = "aws-smithy-http"
-version = "0.62.4"
+version = "0.62.5"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3feafd437c763db26aa04e0cc7591185d0961e64c61885bece0fb9d50ceac671"
+checksum = "445d5d720c99eed0b4aa674ed00d835d9b1427dd73e04adaf2f94c6b2d6f9fca"
 dependencies = [
  "aws-smithy-eventstream",
  "aws-smithy-runtime-api",
@@ -1739,6 +1761,7 @@ dependencies = [
  "bytes 1.10.1",
  "bytes-utils",
  "futures-core",
+ "futures-util",
  "http 0.2.12",
  "http 1.3.1",
  "http-body 0.4.6",
@@ -1750,9 +1773,9 @@ dependencies = [
 
 [[package]]
 name = "aws-smithy-http-client"
-version = "1.1.3"
+version = "1.1.4"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1053b5e587e6fa40ce5a79ea27957b04ba660baa02b28b7436f64850152234f1"
+checksum = "623254723e8dfd535f566ee7b2381645f8981da086b5c4aa26c0c41582bb1d2c"
 dependencies = [
  "aws-smithy-async",
  "aws-smithy-runtime-api",
@@ -1780,9 +1803,9 @@ dependencies = [
 
 [[package]]
 name = "aws-smithy-json"
-version = "0.61.6"
+version = "0.61.7"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "cff418fc8ec5cadf8173b10125f05c2e7e1d46771406187b2c878557d4503390"
+checksum = "2db31f727935fc63c6eeae8b37b438847639ec330a9161ece694efba257e0c54"
 dependencies = [
  "aws-smithy-types",
 ]
@@ -1808,9 +1831,9 @@ dependencies = [
 
 [[package]]
 name = "aws-smithy-runtime"
-version = "1.9.3"
+version = "1.9.4"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "40ab99739082da5347660c556689256438defae3bcefd66c52b095905730e404"
+checksum = "0bbe9d018d646b96c7be063dd07987849862b0e6d07c778aad7d93d1be6c1ef0"
 dependencies = [
  "aws-smithy-async",
  "aws-smithy-http",
@@ -1832,9 +1855,9 @@ dependencies = [
 
 [[package]]
 name = "aws-smithy-runtime-api"
-version = "1.9.1"
+version = "1.9.2"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3683c5b152d2ad753607179ed71988e8cfd52964443b4f74fd8e552d0bbfeb46"
+checksum = "ec7204f9fd94749a7c53b26da1b961b4ac36bf070ef1e0b94bb09f79d4f6c193"
 dependencies = [
  "aws-smithy-async",
  "aws-smithy-types",
@@ -1849,9 +1872,9 @@ dependencies = [
 
 [[package]]
 name = "aws-smithy-types"
-version = "1.3.3"
+version = "1.3.4"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9f5b3a7486f6690ba25952cabf1e7d75e34d69eaff5081904a47bc79074d6457"
+checksum = "25f535879a207fce0db74b679cfc3e91a3159c8144d717d55f5832aea9eef46e"
 dependencies = [
  "base64-simd",
  "bytes 1.10.1",
@@ -1875,18 +1898,18 @@ dependencies = [
 
 [[package]]
 name = "aws-smithy-xml"
-version = "0.60.11"
+version = "0.60.12"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e9c34127e8c624bc2999f3b657e749c1393bedc9cd97b92a804db8ced4d2e163"
+checksum = "eab77cdd036b11056d2a30a7af7b775789fb024bf216acc13884c6c97752ae56"
 dependencies = [
  "xmlparser",
 ]
 
 [[package]]
 name = "aws-types"
-version = "1.3.9"
+version = "1.3.10"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e2fd329bf0e901ff3f60425691410c69094dc2a1f34b331f37bfc4e9ac1565a1"
+checksum = "d79fb68e3d7fe5d4833ea34dc87d2e97d26d3086cb3da660bb6b1f76d98680b6"
 dependencies = [
  "aws-credential-types",
  "aws-smithy-async",
@@ -1985,7 +2008,7 @@ version = "0.3.76"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "bb531853791a215d7c62a30daf0dde835f381ab5de4589cfe7c649d2cbe92bd6"
 dependencies = [
- "addr2line",
+ "addr2line 0.25.1",
  "cfg-if",
  "libc",
  "miniz_oxide",
@@ -2066,26 +2089,6 @@ dependencies = [
  "serde",
 ]
 
-[[package]]
-name = "bincode"
-version = "2.0.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "36eaf5d7b090263e8150820482d5d93cd964a81e4019913c972f4edcc6edb740"
-dependencies = [
- "bincode_derive",
- "serde",
- "unty",
-]
-
-[[package]]
-name = "bincode_derive"
-version = "2.0.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "bf95709a440f45e986983918d0e8a1f30a9b1df04918fc828670606804ac3c09"
-dependencies = [
- "virtue",
-]
-
 [[package]]
 name = "bindgen"
 version = "0.71.1"
@@ -2126,30 +2129,15 @@ dependencies = [
  "syn 2.0.106",
 ]
 
-[[package]]
-name = "bit-set"
-version = "0.5.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0700ddab506f33b20a03b13996eccd309a48e5ff77d0d95926aa0210fb4e95f1"
-dependencies = [
- "bit-vec 0.6.3",
-]
-
 [[package]]
 name = "bit-set"
 version = "0.8.0"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3"
 dependencies = [
- "bit-vec 0.8.0",
+ "bit-vec",
 ]
 
-[[package]]
-name = "bit-vec"
-version = "0.6.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "349f9b6a179ed607305526ca489b34ad0a41aed5f7980fa90eb03160b69598fb"
-
 [[package]]
 name = "bit-vec"
 version = "0.8.0"
@@ -2253,19 +2241,6 @@ dependencies = [
  "profiling",
 ]
 
-[[package]]
-name = "blake3"
-version = "1.8.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3888aaa89e4b2a40fca9848e400f6a658a5a3978de7be858e209cafa8be9a4a0"
-dependencies = [
- "arrayref",
- "arrayvec",
- "cc",
- "cfg-if",
- "constant_time_eq 0.3.1",
-]
-
 [[package]]
 name = "block"
 version = "0.1.6"
@@ -2328,9 +2303,9 @@ dependencies = [
 
 [[package]]
 name = "borrow-or-share"
-version = "0.2.2"
+version = "0.2.4"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3eeab4423108c5d7c744f4d234de88d18d636100093ae04caf4825134b9c3a32"
+checksum = "dc0b364ead1874514c8c2855ab558056ebfeb775653e7ae45ff72f28f8f3166c"
 
 [[package]]
 name = "borsh"
@@ -2355,12 +2330,6 @@ dependencies = [
  "syn 2.0.106",
 ]
 
-[[package]]
-name = "boxcar"
-version = "0.2.14"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "36f64beae40a84da1b4b26ff2761a5b895c12adc41dc25aaee1c4f2bbfe97a6e"
-
 [[package]]
 name = "breadcrumbs"
 version = "0.1.0"
@@ -2527,9 +2496,6 @@ name = "bytes"
 version = "1.10.1"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "d71b6127be86fdcfddb610f7182ac57211d4b18a3e9c82eb2d17662f2227ad6a"
-dependencies = [
- "serde",
-]
 
 [[package]]
 name = "bytes-utils"
@@ -2816,15 +2782,6 @@ version = "0.3.0"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5"
 
-[[package]]
-name = "castaway"
-version = "0.2.4"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "dec551ab6e7578819132c713a93c022a05d60159dc86e7a7050223577484c55a"
-dependencies = [
- "rustversion",
-]
-
 [[package]]
 name = "cbc"
 version = "0.1.2"
@@ -2854,9 +2811,9 @@ dependencies = [
 
 [[package]]
 name = "cc"
-version = "1.2.41"
+version = "1.2.49"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ac9fe6cdbb24b6ade63616c0a0688e45bb56732262c158df3c0c4bea4ca47cb7"
+checksum = "90583009037521a116abf44494efecd645ba48b6622457080f080b85544e2215"
 dependencies = [
  "find-msvc-tools",
  "jobserver",
@@ -2939,6 +2896,17 @@ dependencies = [
  "util",
 ]
 
+[[package]]
+name = "chardetng"
+version = "0.1.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "14b8f0b65b7b08ae3c8187e8d77174de20cb6777864c6b832d8ad365999cf1ea"
+dependencies = [
+ "cfg-if",
+ "encoding_rs",
+ "memchr",
+]
+
 [[package]]
 name = "chrono"
 version = "0.4.42"
@@ -2953,16 +2921,6 @@ dependencies = [
  "windows-link 0.2.1",
 ]
 
-[[package]]
-name = "chrono-tz"
-version = "0.10.4"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a6139a8597ed92cf816dfb33f5dd6cf0bb93a6adc938f11039f371bc5bcd26c3"
-dependencies = [
- "chrono",
- "phf 0.12.1",
-]
-
 [[package]]
 name = "chunked_transfer"
 version = "1.5.0"
@@ -3205,26 +3163,11 @@ dependencies = [
  "uuid",
 ]
 
-[[package]]
-name = "cloud_zeta2_prompt"
-version = "0.1.0"
-dependencies = [
- "anyhow",
- "cloud_llm_client",
- "indoc",
- "ordered-float 2.10.1",
- "rustc-hash 2.1.1",
- "schemars",
- "serde",
- "serde_json",
- "strum 0.27.2",
-]
-
 [[package]]
 name = "cmake"
-version = "0.1.54"
+version = "0.1.56"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e7caa3f9de89ddbe2c607f4101924c5abec803763ae9534e4f4d7d8f84aa81f0"
+checksum = "b042e5d8a74ae91bb0961acd039822472ec99f8ab0948cbf6d1369588f8be586"
 dependencies = [
  "cc",
 ]
@@ -3325,8 +3268,8 @@ name = "codestral"
 version = "0.1.0"
 dependencies = [
  "anyhow",
- "edit_prediction",
  "edit_prediction_context",
+ "edit_prediction_types",
  "futures 0.3.31",
  "gpui",
  "http_client",
@@ -3516,17 +3459,6 @@ dependencies = [
  "memchr",
 ]
 
-[[package]]
-name = "comfy-table"
-version = "7.2.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b03b7db8e0b4b2fdad6c551e634134e99ec000e5c8c3b6856c65e8bbaded7a3b"
-dependencies = [
- "crossterm",
- "unicode-segmentation",
- "unicode-width",
-]
-
 [[package]]
 name = "command-fds"
 version = "0.3.2"
@@ -3580,21 +3512,6 @@ dependencies = [
  "workspace",
 ]
 
-[[package]]
-name = "compact_str"
-version = "0.9.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3fdb1325a1cece981e8a296ab8f0f9b63ae357bd0784a9faaf548cc7b480707a"
-dependencies = [
- "castaway",
- "cfg-if",
- "itoa",
- "rustversion",
- "ryu",
- "serde",
- "static_assertions",
-]
-
 [[package]]
 name = "component"
 version = "0.1.0"
@@ -3608,6 +3525,33 @@ dependencies = [
  "theme",
 ]
 
+[[package]]
+name = "component_preview"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "client",
+ "collections",
+ "component",
+ "db",
+ "fs",
+ "gpui",
+ "language",
+ "log",
+ "node_runtime",
+ "notifications",
+ "project",
+ "release_channel",
+ "reqwest_client",
+ "session",
+ "settings",
+ "theme",
+ "ui",
+ "ui_input",
+ "uuid",
+ "workspace",
+]
+
 [[package]]
 name = "compression-codecs"
 version = "0.4.31"
@@ -3700,12 +3644,6 @@ version = "0.1.5"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "245097e9a4535ee1e3e3931fcfcd55a796a44c643e8596ff6566d68f09b87bbc"
 
-[[package]]
-name = "constant_time_eq"
-version = "0.3.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7c74b8349d32d297c9134b8c88677813a227df8f779daa29bfc29c183fe3dca6"
-
 [[package]]
 name = "context_server"
 version = "0.1.0"
@@ -3724,8 +3662,10 @@ dependencies = [
  "serde",
  "serde_json",
  "settings",
+ "slotmap",
  "smol",
  "tempfile",
+ "terminal",
  "url",
  "util",
 ]
@@ -3758,7 +3698,7 @@ dependencies = [
  "command_palette_hooks",
  "ctor",
  "dirs 4.0.0",
- "edit_prediction",
+ "edit_prediction_types",
  "editor",
  "fs",
  "futures 0.3.31",
@@ -3783,6 +3723,7 @@ dependencies = [
  "task",
  "theme",
  "ui",
+ "url",
  "util",
  "workspace",
  "zlog",
@@ -4033,20 +3974,38 @@ dependencies = [
  "libc",
 ]
 
+[[package]]
+name = "cranelift-assembler-x64"
+version = "0.120.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a5023e06632d8f351c2891793ccccfe4aef957954904392434038745fb6f1f68"
+dependencies = [
+ "cranelift-assembler-x64-meta",
+]
+
+[[package]]
+name = "cranelift-assembler-x64-meta"
+version = "0.120.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b1c4012b4c8c1f6eb05c0a0a540e3e1ee992631af51aa2bbb3e712903ce4fd65"
+dependencies = [
+ "cranelift-srcgen",
+]
+
 [[package]]
 name = "cranelift-bforest"
-version = "0.116.1"
+version = "0.120.2"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e15d04a0ce86cb36ead88ad68cf693ffd6cda47052b9e0ac114bc47fd9cd23c4"
+checksum = "4d6d883b4942ef3a7104096b8bc6f2d1a41393f159ac8de12aed27b25d67f895"
 dependencies = [
  "cranelift-entity",
 ]
 
 [[package]]
 name = "cranelift-bitset"
-version = "0.116.1"
+version = "0.120.2"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7c6e3969a7ce267259ce244b7867c5d3bc9e65b0a87e81039588dfdeaede9f34"
+checksum = "db7b2ee9eec6ca8a716d900d5264d678fb2c290c58c46c8da7f94ee268175d17"
 dependencies = [
  "serde",
  "serde_derive",
@@ -4054,11 +4013,12 @@ dependencies = [
 
 [[package]]
 name = "cranelift-codegen"
-version = "0.116.1"
+version = "0.120.2"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "2c22032c4cb42558371cf516bb47f26cdad1819d3475c133e93c49f50ebf304e"
+checksum = "aeda0892577afdce1ac2e9a983a55f8c5b87a59334e1f79d8f735a2d7ba4f4b4"
 dependencies = [
  "bumpalo",
+ "cranelift-assembler-x64",
  "cranelift-bforest",
  "cranelift-bitset",
  "cranelift-codegen-meta",
@@ -4067,9 +4027,10 @@ dependencies = [
  "cranelift-entity",
  "cranelift-isle",
  "gimli 0.31.1",
- "hashbrown 0.14.5",
+ "hashbrown 0.15.5",
  "log",
  "postcard",
+ "pulley-interpreter",
  "regalloc2",
  "rustc-hash 2.1.1",
  "serde",
@@ -4081,33 +4042,36 @@ dependencies = [
 
 [[package]]
 name = "cranelift-codegen-meta"
-version = "0.116.1"
+version = "0.120.2"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c904bc71c61b27fc57827f4a1379f29de64fe95653b620a3db77d59655eee0b8"
+checksum = "e461480d87f920c2787422463313326f67664e68108c14788ba1676f5edfcd15"
 dependencies = [
+ "cranelift-assembler-x64-meta",
  "cranelift-codegen-shared",
+ "cranelift-srcgen",
+ "pulley-interpreter",
 ]
 
 [[package]]
 name = "cranelift-codegen-shared"
-version = "0.116.1"
+version = "0.120.2"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "40180f5497572f644ce88c255480981ae2ec1d7bb4d8e0c0136a13b87a2f2ceb"
+checksum = "976584d09f200c6c84c4b9ff7af64fc9ad0cb64dffa5780991edd3fe143a30a1"
 
 [[package]]
 name = "cranelift-control"
-version = "0.116.1"
+version = "0.120.2"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "26d132c6d0bd8a489563472afc171759da0707804a65ece7ceb15a8c6d7dd5ef"
+checksum = "46d43d70f4e17c545aa88dbf4c84d4200755d27c6e3272ebe4de65802fa6a955"
 dependencies = [
  "arbitrary",
 ]
 
 [[package]]
 name = "cranelift-entity"
-version = "0.116.1"
+version = "0.120.2"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "4b2d0d9618275474fbf679dd018ac6e009acbd6ae6850f6a67be33fb3b00b323"
+checksum = "d75418674520cb400c8772bfd6e11a62736c78fc1b6e418195696841d1bf91f1"
 dependencies = [
  "cranelift-bitset",
  "serde",
@@ -4116,9 +4080,9 @@ dependencies = [
 
 [[package]]
 name = "cranelift-frontend"
-version = "0.116.1"
+version = "0.120.2"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "4fac41e16729107393174b0c9e3730fb072866100e1e64e80a1a963b2e484d57"
+checksum = "3c8b1a91c86687a344f3c52dd6dfb6e50db0dfa7f2e9c7711b060b3623e1fdeb"
 dependencies = [
  "cranelift-codegen",
  "log",
@@ -4128,21 +4092,27 @@ dependencies = [
 
 [[package]]
 name = "cranelift-isle"
-version = "0.116.1"
+version = "0.120.2"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1ca20d576e5070044d0a72a9effc2deacf4d6aa650403189d8ea50126483944d"
+checksum = "711baa4e3432d4129295b39ec2b4040cc1b558874ba0a37d08e832e857db7285"
 
 [[package]]
 name = "cranelift-native"
-version = "0.116.1"
+version = "0.120.2"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b8dee82f3f1f2c4cba9177f1cc5e350fe98764379bcd29340caa7b01f85076c7"
+checksum = "41c83e8666e3bcc5ffeaf6f01f356f0e1f9dcd69ce5511a1efd7ca5722001a3f"
 dependencies = [
  "cranelift-codegen",
  "libc",
  "target-lexicon 0.13.3",
 ]
 
+[[package]]
+name = "cranelift-srcgen"
+version = "0.120.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "02e3f4d783a55c64266d17dc67d2708852235732a100fc40dd9f1051adc64d7b"
+
 [[package]]
 name = "crash-context"
 version = "0.6.3"
@@ -4171,7 +4141,7 @@ dependencies = [
 name = "crashes"
 version = "0.1.0"
 dependencies = [
- "bincode 1.3.3",
+ "bincode",
  "cfg-if",
  "crash-handler",
  "extension_host",
@@ -4184,7 +4154,8 @@ dependencies = [
  "serde_json",
  "smol",
  "system_specs",
- "zstd 0.11.2+zstd.1.5.2",
+ "windows 0.61.3",
+ "zstd",
 ]
 
 [[package]]
@@ -4329,29 +4300,6 @@ version = "0.8.21"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28"
 
-[[package]]
-name = "crossterm"
-version = "0.29.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d8b9f2e4c67f833b660cdb0a3523065869fb35570177239812ed4c905aeff87b"
-dependencies = [
- "bitflags 2.9.4",
- "crossterm_winapi",
- "document-features",
- "parking_lot",
- "rustix 1.1.2",
- "winapi",
-]
-
-[[package]]
-name = "crossterm_winapi"
-version = "0.9.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "acdd7c62a3665c7f6830a51635d9ac9b23ed385797f70a83bb8bafe9c572ab2b"
-dependencies = [
- "winapi",
-]
-
 [[package]]
 name = "crunchy"
 version = "0.2.4"
@@ -4706,12 +4654,6 @@ dependencies = [
  "util",
 ]
 
-[[package]]
-name = "debug_unsafe"
-version = "0.1.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "85d3cef41d236720ed453e102153a53e4cc3d2fde848c0078a50cf249e8e3e5b"
-
 [[package]]
 name = "debugger_tools"
 version = "0.1.0"
@@ -4744,6 +4686,7 @@ dependencies = [
  "db",
  "debugger_tools",
  "editor",
+ "feature_flags",
  "file_icons",
  "futures 0.3.31",
  "fuzzy",
@@ -5105,8 +5048,6 @@ name = "docs_preprocessor"
 version = "0.1.0"
 dependencies = [
  "anyhow",
- "command_palette",
- "gpui",
  "mdbook",
  "regex",
  "serde",

Cargo.toml 🔗

@@ -9,6 +9,7 @@ members = [
     "crates/agent_servers",
     "crates/agent_settings",
     "crates/agent_ui",
+    "crates/agent_ui_v2",
     "crates/ai_onboarding",
     "crates/anthropic",
     "crates/askpass",
@@ -32,13 +33,13 @@ members = [
     "crates/cloud_api_client",
     "crates/cloud_api_types",
     "crates/cloud_llm_client",
-    "crates/cloud_zeta2_prompt",
     "crates/collab",
     "crates/collab_ui",
     "crates/collections",
     "crates/command_palette",
     "crates/command_palette_hooks",
     "crates/component",
+    "crates/component_preview",
     "crates/context_server",
     "crates/copilot",
     "crates/crashes",
@@ -54,11 +55,12 @@ members = [
     "crates/diagnostics",
     "crates/docs_preprocessor",
     "crates/edit_prediction",
-    "crates/edit_prediction_button",
+    "crates/edit_prediction_types",
+    "crates/edit_prediction_ui",
     "crates/edit_prediction_context",
-    "crates/zeta2_tools",
     "crates/editor",
     "crates/eval",
+    "crates/eval_utils",
     "crates/explorer_command_injector",
     "crates/extension",
     "crates/extension_api",
@@ -191,19 +193,23 @@ members = [
     "crates/vercel",
     "crates/vim",
     "crates/vim_mode_setting",
+    "crates/which_key",
     "crates/watch",
     "crates/web_search",
     "crates/web_search_providers",
     "crates/workspace",
     "crates/worktree",
+    "crates/worktree_benchmarks",
     "crates/x_ai",
     "crates/zed",
     "crates/zed_actions",
     "crates/zed_env_vars",
-    "crates/zeta",
-    "crates/zeta_cli",
+    "crates/edit_prediction_cli",
+    "crates/zeta_prompt",
     "crates/zlog",
     "crates/zlog_settings",
+    "crates/ztracing",
+    "crates/ztracing_macro",
 
     #
     # Extensions
@@ -240,9 +246,9 @@ action_log = { path = "crates/action_log" }
 agent = { path = "crates/agent" }
 activity_indicator = { path = "crates/activity_indicator" }
 agent_ui = { path = "crates/agent_ui" }
+agent_ui_v2 = { path = "crates/agent_ui_v2" }
 agent_settings = { path = "crates/agent_settings" }
 agent_servers = { path = "crates/agent_servers" }
-ai = { path = "crates/ai" }
 ai_onboarding = { path = "crates/ai_onboarding" }
 anthropic = { path = "crates/anthropic" }
 askpass = { path = "crates/askpass" }
@@ -252,7 +258,6 @@ assistant_slash_command = { path = "crates/assistant_slash_command" }
 assistant_slash_commands = { path = "crates/assistant_slash_commands" }
 audio = { path = "crates/audio" }
 auto_update = { path = "crates/auto_update" }
-auto_update_helper = { path = "crates/auto_update_helper" }
 auto_update_ui = { path = "crates/auto_update_ui" }
 aws_http_client = { path = "crates/aws_http_client" }
 bedrock = { path = "crates/bedrock" }
@@ -266,13 +271,12 @@ clock = { path = "crates/clock" }
 cloud_api_client = { path = "crates/cloud_api_client" }
 cloud_api_types = { path = "crates/cloud_api_types" }
 cloud_llm_client = { path = "crates/cloud_llm_client" }
-cloud_zeta2_prompt = { path = "crates/cloud_zeta2_prompt" }
-collab = { path = "crates/collab" }
 collab_ui = { path = "crates/collab_ui" }
 collections = { path = "crates/collections", version = "0.1.0" }
 command_palette = { path = "crates/command_palette" }
 command_palette_hooks = { path = "crates/command_palette_hooks" }
 component = { path = "crates/component" }
+component_preview  = { path = "crates/component_preview" }
 context_server = { path = "crates/context_server" }
 copilot = { path = "crates/copilot" }
 crashes = { path = "crates/crashes" }
@@ -288,6 +292,7 @@ deepseek = { path = "crates/deepseek" }
 derive_refineable = { path = "crates/refineable/derive_refineable" }
 diagnostics = { path = "crates/diagnostics" }
 editor = { path = "crates/editor" }
+eval_utils = { path = "crates/eval_utils" }
 extension = { path = "crates/extension" }
 extension_host = { path = "crates/extension_host" }
 extensions_ui = { path = "crates/extensions_ui" }
@@ -311,10 +316,9 @@ http_client = { path = "crates/http_client" }
 http_client_tls = { path = "crates/http_client_tls" }
 icons = { path = "crates/icons" }
 image_viewer = { path = "crates/image_viewer" }
-edit_prediction = { path = "crates/edit_prediction" }
-edit_prediction_button = { path = "crates/edit_prediction_button" }
+edit_prediction_types = { path = "crates/edit_prediction_types" }
+edit_prediction_ui = { path = "crates/edit_prediction_ui" }
 edit_prediction_context = { path = "crates/edit_prediction_context" }
-zeta2_tools = { path = "crates/zeta2_tools" }
 inspector_ui = { path = "crates/inspector_ui" }
 install_cli = { path = "crates/install_cli" }
 journal = { path = "crates/journal" }
@@ -356,8 +360,6 @@ panel = { path = "crates/panel" }
 paths = { path = "crates/paths" }
 perf = { path = "tooling/perf" }
 picker = { path = "crates/picker" }
-plugin = { path = "crates/plugin" }
-plugin_macros = { path = "crates/plugin_macros" }
 prettier = { path = "crates/prettier" }
 settings_profile_selector = { path = "crates/settings_profile_selector" }
 project = { path = "crates/project" }
@@ -368,12 +370,10 @@ proto = { path = "crates/proto" }
 recent_projects = { path = "crates/recent_projects" }
 refineable = { path = "crates/refineable" }
 release_channel = { path = "crates/release_channel" }
-scheduler = { path = "crates/scheduler" }
 remote = { path = "crates/remote" }
 remote_server = { path = "crates/remote_server" }
 repl = { path = "crates/repl" }
 reqwest_client = { path = "crates/reqwest_client" }
-rich_text = { path = "crates/rich_text" }
 rodio = { git = "https://github.com/RustAudio/rodio", rev ="e2074c6c2acf07b57cf717e076bdda7a9ac6e70b", features = ["wav", "playback", "wav_output", "recording"] }
 rope = { path = "crates/rope" }
 rpc = { path = "crates/rpc" }
@@ -390,7 +390,6 @@ snippets_ui = { path = "crates/snippets_ui" }
 sqlez = { path = "crates/sqlez" }
 sqlez_macros = { path = "crates/sqlez_macros" }
 story = { path = "crates/story" }
-storybook = { path = "crates/storybook" }
 streaming_diff = { path = "crates/streaming_diff" }
 sum_tree = { path = "crates/sum_tree" }
 supermaven = { path = "crates/supermaven" }
@@ -407,7 +406,6 @@ terminal_view = { path = "crates/terminal_view" }
 text = { path = "crates/text" }
 theme = { path = "crates/theme" }
 theme_extension = { path = "crates/theme_extension" }
-theme_importer = { path = "crates/theme_importer" }
 theme_selector = { path = "crates/theme_selector" }
 time_format = { path = "crates/time_format" }
 title_bar = { path = "crates/title_bar" }
@@ -421,6 +419,7 @@ util_macros = { path = "crates/util_macros" }
 vercel = { path = "crates/vercel" }
 vim = { path = "crates/vim" }
 vim_mode_setting = { path = "crates/vim_mode_setting" }
+which_key = { path = "crates/which_key" }
 
 watch = { path = "crates/watch" }
 web_search = { path = "crates/web_search" }
@@ -431,15 +430,18 @@ x_ai = { path = "crates/x_ai" }
 zed = { path = "crates/zed" }
 zed_actions = { path = "crates/zed_actions" }
 zed_env_vars = { path = "crates/zed_env_vars" }
-zeta = { path = "crates/zeta" }
+edit_prediction = { path = "crates/edit_prediction" }
+zeta_prompt = { path = "crates/zeta_prompt" }
 zlog = { path = "crates/zlog" }
 zlog_settings = { path = "crates/zlog_settings" }
+ztracing = { path = "crates/ztracing" }
+ztracing_macro = { path = "crates/ztracing_macro" }
 
 #
 # External crates
 #
 
-agent-client-protocol = { version = "0.7.0", features = ["unstable"] }
+agent-client-protocol = { version = "=0.9.2", features = ["unstable"] }
 aho-corasick = "1.1"
 alacritty_terminal = "0.25.1-rc1"
 any_vec = "0.14"
@@ -458,15 +460,15 @@ async-task = "4.7"
 async-trait = "0.1"
 async-tungstenite = "0.31.0"
 async_zip = { version = "0.0.18", features = ["deflate", "deflate64"] }
-aws-config = { version = "1.6.1", features = ["behavior-version-latest"] }
-aws-credential-types = { version = "1.2.2", features = [
+aws-config = { version = "1.8.10", features = ["behavior-version-latest"] }
+aws-credential-types = { version = "1.2.8", features = [
     "hardcoded-credentials",
 ] }
-aws-sdk-bedrockruntime = { version = "1.80.0", features = [
+aws-sdk-bedrockruntime = { version = "1.112.0", features = [
     "behavior-version-latest",
 ] }
-aws-smithy-runtime-api = { version = "1.7.4", features = ["http-1x", "client"] }
-aws-smithy-types = { version = "1.3.0", features = ["http-body-1-x"] }
+aws-smithy-runtime-api = { version = "1.9.2", features = ["http-1x", "client"] }
+aws-smithy-types = { version = "1.3.4", features = ["http-body-1-x"] }
 backtrace = "0.3"
 base64 = "0.22"
 bincode = "1.2.1"
@@ -479,6 +481,7 @@ bytes = "1.0"
 cargo_metadata = "0.19"
 cargo_toml = "0.21"
 cfg-if = "1.0.3"
+chardetng = "0.1"
 chrono = { version = "0.4", features = ["serde"] }
 ciborium = "0.2"
 circular-buffer = "1.0"
@@ -502,17 +505,16 @@ dotenvy = "0.15.0"
 ec4rs = "1.1"
 emojis = "0.6.1"
 env_logger = "0.11"
+encoding_rs = "0.8"
 exec = "0.3.1"
-fancy-regex = "0.14.0"
+fancy-regex = "0.16.0"
 fork = "0.4.0"
 futures = "0.3"
-futures-batch = "0.6.1"
 futures-lite = "1.13"
-gh-workflow = { git = "https://github.com/zed-industries/gh-workflow", rev = "e5f883040530b4df36437f140084ee5cc7c1c9be" }
+gh-workflow = { git = "https://github.com/zed-industries/gh-workflow", rev = "09acfdf2bd5c1d6254abefd609c808ff73547b2c" }
 git2 = { version = "0.20.1", default-features = false }
 globset = "0.4"
 handlebars = "4.3"
-hashbrown = "0.15.3"
 heck = "0.5"
 heed = { version = "0.21.0", features = ["read-txn-no-tls"] }
 hex = "0.4.3"
@@ -529,7 +531,7 @@ indoc = "2"
 inventory = "0.3.19"
 itertools = "0.14.0"
 json_dotpath = "1.1"
-jsonschema = "0.30.0"
+jsonschema = "0.37.0"
 jsonwebtoken = "9.3"
 jupyter-protocol = "0.10.0"
 jupyter-websocket-client = "0.15.0"
@@ -548,7 +550,6 @@ nanoid = "0.4"
 nbformat = "0.15.0"
 nix = "0.29"
 num-format = "0.4.4"
-num-traits = "0.2"
 objc = "0.2"
 objc2-foundation = { version = "=0.3.1", default-features = false, features = [
     "NSArray",
@@ -587,7 +588,6 @@ pet = { git = "https://github.com/microsoft/python-environment-tools.git", rev =
 pet-conda = { git = "https://github.com/microsoft/python-environment-tools.git", rev = "1e86914c3ce2f3a08c0cedbcb0615a7f9fa7a5da" }
 pet-core = { git = "https://github.com/microsoft/python-environment-tools.git", rev = "1e86914c3ce2f3a08c0cedbcb0615a7f9fa7a5da" }
 pet-fs = { git = "https://github.com/microsoft/python-environment-tools.git", rev = "1e86914c3ce2f3a08c0cedbcb0615a7f9fa7a5da" }
-pet-pixi = { git = "https://github.com/microsoft/python-environment-tools.git", rev = "1e86914c3ce2f3a08c0cedbcb0615a7f9fa7a5da" }
 pet-poetry = { git = "https://github.com/microsoft/python-environment-tools.git", rev = "1e86914c3ce2f3a08c0cedbcb0615a7f9fa7a5da" }
 pet-reporter = { git = "https://github.com/microsoft/python-environment-tools.git", rev = "1e86914c3ce2f3a08c0cedbcb0615a7f9fa7a5da" }
 pet-virtualenv = { git = "https://github.com/microsoft/python-environment-tools.git", rev = "1e86914c3ce2f3a08c0cedbcb0615a7f9fa7a5da" }
@@ -627,7 +627,6 @@ scap = { git = "https://github.com/zed-industries/scap", rev = "4afea48c3b002197
 schemars = { version = "1.0", features = ["indexmap2"] }
 semver = { version = "1.0", features = ["serde"] }
 serde = { version = "1.0.221", features = ["derive", "rc"] }
-serde_derive = "1.0.221"
 serde_json = { version = "1.0.144", features = ["preserve_order", "raw_value"] }
 serde_json_lenient = { version = "0.2", features = [
     "preserve_order",
@@ -639,10 +638,9 @@ serde_urlencoded = "0.7"
 sha2 = "0.10"
 shellexpand = "2.1.0"
 shlex = "1.3.0"
-similar = "2.6"
 simplelog = "0.12.2"
 slotmap = "1.0.6"
-smallvec = { version = "1.6", features = ["union"] }
+smallvec = { version = "1.6", features = ["union", "const_new"] }
 smol = "2.0"
 sqlformat = "0.2"
 stacksafe = "0.1"
@@ -656,7 +654,7 @@ sysinfo = "0.37.0"
 take-until = "0.2.0"
 tempfile = "3.20.0"
 thiserror = "2.0.12"
-tiktoken-rs = { git = "https://github.com/zed-industries/tiktoken-rs", rev = "7249f999c5fdf9bf3cc5c288c964454e4dac0c00" }
+tiktoken-rs = { git = "https://github.com/zed-industries/tiktoken-rs", rev = "2570c4387a8505fb8f1d3f3557454b474f1e8271" }
 time = { version = "0.3", features = [
     "macros",
     "parsing",
@@ -668,11 +666,12 @@ time = { version = "0.3", features = [
 tiny_http = "0.8"
 tokio = { version = "1" }
 tokio-tungstenite = { version = "0.26", features = ["__rustls-tls"] }
+tokio-socks = { version = "0.5.2", default-features = false, features = ["futures-io", "tokio"] }
 toml = "0.8"
 toml_edit = { version = "0.22", default-features = false, features = ["display", "parse", "serde"] }
 tower-http = "0.4.4"
-tree-sitter = { version = "0.25.10", features = ["wasm"] }
-tree-sitter-bash = "0.25.0"
+tree-sitter = { version = "0.26", features = ["wasm"] }
+tree-sitter-bash = "0.25.1"
 tree-sitter-c = "0.23"
 tree-sitter-cpp = { git = "https://github.com/tree-sitter/tree-sitter-cpp", rev = "5cb9b693cfd7bfacab1d9ff4acac1a4150700609" }
 tree-sitter-css = "0.23"
@@ -694,6 +693,7 @@ tree-sitter-ruby = "0.23"
 tree-sitter-rust = "0.24"
 tree-sitter-typescript = { git = "https://github.com/zed-industries/tree-sitter-typescript", rev = "e2c53597d6a5d9cf7bbe8dccde576fe1e46c5899" } # https://github.com/tree-sitter/tree-sitter-typescript/pull/347
 tree-sitter-yaml = { git = "https://github.com/zed-industries/tree-sitter-yaml", rev = "baff0b51c64ef6a1fb1f8390f3ad6015b83ec13a" }
+tracing = "0.1.40"
 unicase = "2.6"
 unicode-script = "0.5.7"
 unicode-segmentation = "1.10"
@@ -704,7 +704,7 @@ uuid = { version = "1.1.2", features = ["v4", "v5", "v7", "serde"] }
 walkdir = "2.5"
 wasm-encoder = "0.221"
 wasmparser = "0.221"
-wasmtime = { version = "29", default-features = false, features = [
+wasmtime = { version = "33", default-features = false, features = [
     "async",
     "demangle",
     "runtime",
@@ -713,11 +713,10 @@ wasmtime = { version = "29", default-features = false, features = [
     "incremental-cache",
     "parallel-compilation",
 ] }
-wasmtime-wasi = "29"
+wasmtime-wasi = "33"
 wax = "0.6"
 which = "6.0.0"
 windows-core = "0.61"
-wit-component = "0.221"
 yawc = "0.2.5"
 zeroize = "1.8"
 zstd = "0.11"
@@ -799,20 +798,13 @@ settings_macros = { opt-level = 3 }
 sqlez_macros = { opt-level = 3, codegen-units = 1 }
 ui_macros = { opt-level = 3 }
 util_macros = { opt-level = 3 }
-serde_derive = { opt-level = 3 }
 quote = { opt-level = 3 }
 syn = { opt-level = 3 }
 proc-macro2 = { opt-level = 3 }
 # proc-macros end
 
 taffy = { opt-level = 3 }
-cranelift-codegen = { opt-level = 3 }
-cranelift-codegen-meta = { opt-level = 3 }
-cranelift-codegen-shared = { opt-level = 3 }
 resvg = { opt-level = 3 }
-rustybuzz = { opt-level = 3 }
-ttf-parser = { opt-level = 3 }
-wasmtime-cranelift = { opt-level = 3 }
 wasmtime = { opt-level = 3 }
 # Build single-source-file crates with cg=1 as it helps make `cargo build` of a whole workspace a bit faster
 activity_indicator = { codegen-units = 1 }
@@ -821,12 +813,11 @@ breadcrumbs = { codegen-units = 1 }
 collections = { codegen-units = 1 }
 command_palette = { codegen-units = 1 }
 command_palette_hooks = { codegen-units = 1 }
-extension_cli = { codegen-units = 1 }
 feature_flags = { codegen-units = 1 }
 file_icons = { codegen-units = 1 }
 fsevent = { codegen-units = 1 }
 image_viewer = { codegen-units = 1 }
-edit_prediction_button = { codegen-units = 1 }
+edit_prediction_ui = { codegen-units = 1 }
 install_cli = { codegen-units = 1 }
 journal = { codegen-units = 1 }
 json_schema_store = { codegen-units = 1 }
@@ -841,7 +832,6 @@ project_symbols = { codegen-units = 1 }
 refineable = { codegen-units = 1 }
 release_channel = { codegen-units = 1 }
 reqwest_client = { codegen-units = 1 }
-rich_text = { codegen-units = 1 }
 session = { codegen-units = 1 }
 snippet = { codegen-units = 1 }
 snippets_ui = { codegen-units = 1 }
@@ -874,8 +864,6 @@ unexpected_cfgs = { level = "allow" }
 dbg_macro = "deny"
 todo = "deny"
 
-# This is not a style lint, see https://github.com/rust-lang/rust-clippy/pull/15454
-# Remove when the lint gets promoted to `suspicious`.
 declare_interior_mutable_const = "deny"
 
 redundant_clone = "deny"

Dockerfile-collab 🔗

@@ -1,6 +1,6 @@
 # syntax = docker/dockerfile:1.2
 
-FROM rust:1.91.1-bookworm as builder
+FROM rust:1.92-bookworm as builder
 WORKDIR app
 COPY . .
 
@@ -34,8 +34,4 @@ RUN apt-get update; \
     linux-perf binutils
 WORKDIR app
 COPY --from=builder /app/collab /app/collab
-COPY --from=builder /app/crates/collab/migrations /app/migrations
-COPY --from=builder /app/crates/collab/migrations_llm /app/migrations_llm
-ENV MIGRATIONS_PATH=/app/migrations
-ENV LLM_DATABASE_MIGRATIONS_PATH=/app/migrations_llm
 ENTRYPOINT ["/app/collab"]

README.md 🔗

@@ -9,7 +9,7 @@ Welcome to Zed, a high-performance, multiplayer code editor from the creators of
 
 ### Installation
 
-On macOS, Linux, and Windows you can [download Zed directly](https://zed.dev/download) or [install Zed via your local package manager](https://zed.dev/docs/linux#installing-via-a-package-manager).
+On macOS, Linux, and Windows you can [download Zed directly](https://zed.dev/download) or install Zed via your local package manager ([macOS](https://zed.dev/docs/installation#macos)/[Linux](https://zed.dev/docs/linux#installing-via-a-package-manager)/[Windows](https://zed.dev/docs/windows#package-managers)).
 
 Other platforms are not yet available:
 
@@ -20,7 +20,6 @@ Other platforms are not yet available:
 - [Building Zed for macOS](./docs/src/development/macos.md)
 - [Building Zed for Linux](./docs/src/development/linux.md)
 - [Building Zed for Windows](./docs/src/development/windows.md)
-- [Running Collaboration Locally](./docs/src/development/local-collaboration.md)
 
 ### Contributing
 

REVIEWERS.conl 🔗

@@ -28,7 +28,7 @@ ai
   = @rtfeldman
 
 audio
-  = @dvdsk
+  = @yara-blue
 
 crashes
   = @p1n3appl3
@@ -53,6 +53,10 @@ extension
 git
   = @cole-miller
   = @danilo-leal
+  = @yara-blue
+  = @kubkon
+  = @Anthony-Eid
+  = @cameron1024
 
 gpui
   = @Anthony-Eid
@@ -72,7 +76,7 @@ languages
 
 linux
   = @cole-miller
-  = @dvdsk
+  = @yara-blue
   = @p1n3appl3
   = @probably-neb
   = @smitbarmase
@@ -88,7 +92,7 @@ multi_buffer
   = @SomeoneToIgnore
 
 pickers
-  = @dvdsk
+  = @yara-blue
   = @p1n3appl3
   = @SomeoneToIgnore
 

assets/icons/box.svg 🔗

@@ -0,0 +1,5 @@
+<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path d="M13.3996 5.59852C13.3994 5.3881 13.3439 5.18144 13.2386 4.99926C13.1333 4.81709 12.9819 4.66581 12.7997 4.56059L8.59996 2.16076C8.41755 2.05544 8.21063 2 8 2C7.78937 2 7.58246 2.05544 7.40004 2.16076L3.20033 4.56059C3.0181 4.66581 2.86674 4.81709 2.76144 4.99926C2.65613 5.18144 2.60059 5.3881 2.60037 5.59852V10.3982C2.60059 10.6086 2.65613 10.8153 2.76144 10.9975C2.86674 11.1796 3.0181 11.3309 3.20033 11.4361L7.40004 13.836C7.58246 13.9413 7.78937 13.9967 8 13.9967C8.21063 13.9967 8.41755 13.9413 8.59996 13.836L12.7997 11.4361C12.9819 11.3309 13.1333 11.1796 13.2386 10.9975C13.3439 10.8153 13.3994 10.6086 13.3996 10.3982V5.59852Z" stroke="white" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M2.78033 4.99857L7.99998 7.99836L13.2196 4.99857" stroke="white" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M8 13.9979V7.99829" stroke="white" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/>
+</svg>

assets/icons/debug_step_back.svg 🔗

@@ -1 +0,0 @@
-<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="none"><path stroke="#000" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.2" d="M14 11.333A6 6 0 0 0 4 6.867l-1 .9"/><path stroke="#000" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.333" d="M2 4.667v4h4"/><path fill="#000" stroke="#000" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.2" d="M8 12a.667.667 0 1 0 0-1.333A.667.667 0 0 0 8 12Z"/></svg>

assets/icons/debug_step_into.svg 🔗

@@ -1 +1,5 @@
-<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="none"><path stroke="#000" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.2" d="M3.333 10 8 14.667 12.667 10M8 5.333v9.334"/><path fill="#000" stroke="#000" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.2" d="M8 2.667a.667.667 0 1 0 0-1.334.667.667 0 0 0 0 1.334Z"/></svg>
+<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path d="M2 13H5" stroke="#C6CAD0" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M11 13H14" stroke="#C6CAD0" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M11.5 8.5L8 12M8 12L4.5 8.5M8 12L8 3" stroke="#C6CAD0" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/>
+</svg>

assets/icons/debug_step_out.svg 🔗

@@ -1 +1,5 @@
-<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="none"><path stroke="#000" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.2" d="M3.333 6 8 1.333 12.667 6M8 10.667V1.333"/><path fill="#000" stroke="#000" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.2" d="M8 13.333a.667.667 0 1 1 0 1.334.667.667 0 0 1 0-1.334Z"/></svg>
+<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path d="M4.5 6.5L8 3M8 3L11.5 6.5M8 3V12" stroke="#C6CAD0" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M2 13H5" stroke="#C6CAD0" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M11 13H14" stroke="#C6CAD0" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/>
+</svg>

assets/icons/debug_step_over.svg 🔗

@@ -1 +1,5 @@
-<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="none"><path stroke="#000" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.2" d="M2 11.333a6 6 0 0 1 10-4.466l1 .9"/><path stroke="#000" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.333" d="M14 4.667v4h-4"/><path fill="#000" stroke="#000" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.2" d="M8 12a.667.667 0 1 1 0-1.333A.667.667 0 0 1 8 12Z"/></svg>
+<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path d="M2 11.333C2.00118 10.1752 2.33729 9.04258 2.96777 8.07159C3.59826 7.10059 4.49621 6.33274 5.55331 5.86064C6.61041 5.38853 7.78152 5.23235 8.9254 5.41091C10.0693 5.58947 11.1371 6.09516 12 6.86698L13 7.76698" stroke="#C6CAD0" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M14 4.66699V8.66699H10" stroke="#C6CAD0" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M7 13H10" stroke="#C6CAD0" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/>
+</svg>

assets/icons/git_branch_plus.svg 🔗

@@ -0,0 +1,8 @@
+<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path d="M4 2V10" stroke="#C6CAD0" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M12 6C12.5304 6 13.0391 5.78929 13.4142 5.41421C13.7893 5.03914 14 4.53043 14 4C14 3.46957 13.7893 2.96086 13.4142 2.58579C13.0391 2.21071 12.5304 2 12 2C11.4696 2 10.9609 2.21071 10.5858 2.58579C10.2107 2.96086 10 3.46957 10 4C10 4.53043 10.2107 5.03914 10.5858 5.41421C10.9609 5.78929 11.4696 6 12 6Z" stroke="#C6CAD0" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M4 14C4.53043 14 5.03914 13.7893 5.41421 13.4142C5.78929 13.0391 6 12.5304 6 12C6 11.4696 5.78929 10.9609 5.41421 10.5858C5.03914 10.2107 4.53043 10 4 10C3.46957 10 2.96086 10.2107 2.58579 10.5858C2.21071 10.9609 2 11.4696 2 12C2 12.5304 2.21071 13.0391 2.58579 13.4142C2.96086 13.7893 3.46957 14 4 14Z" stroke="#C6CAD0" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M10 4C8.4087 4 6.88258 4.63214 5.75736 5.75736C4.63214 6.88258 4 8.4087 4 10" stroke="#C6CAD0" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M12 10V14" stroke="#C6CAD0" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M14 12H10" stroke="#C6CAD0" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/>
+</svg>

assets/icons/inception.svg 🔗

@@ -0,0 +1,11 @@
+<svg width="28" height="28" viewBox="0 0 28 28" fill="none" id="svg1378540956_510">
+<g clip-path="url(#svg1378540956_510_clip0_1_1506)" transform="translate(4, 4) scale(0.857)">
+<path d="M17.0547 0.372066H8.52652L-0.00165176 8.90024V17.4284H8.52652V8.90024H17.0547V0.372066Z" fill="#1A1C20"></path>
+<path d="M10.1992 27.6279H18.7274L27.2556 19.0998V10.5716H18.7274V19.0998H10.1992V27.6279Z" fill="#1A1C20"></path>
+</g>
+<defs>
+<clipPath id="svg1378540956_510_clip0_1_1506">
+<rect width="27.2559" height="27.2559" fill="white" transform="translate(0 0.37207)"></rect>
+</clipPath>
+</defs>
+</svg>

assets/icons/zed_agent_two.svg 🔗

@@ -0,0 +1,5 @@
+<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path d="M6.2224 1.32129L5.2036 4.41875C5.15145 4.57727 5.06282 4.72134 4.94481 4.83934C4.82681 4.95735 4.68274 5.04598 4.52422 5.09813L1.42676 6.11693L4.52422 7.13574C4.68274 7.18788 4.82681 7.27652 4.94481 7.39453C5.06282 7.51253 5.15145 7.6566 5.2036 7.81512L6.2224 10.9126L7.24121 7.81512C7.29335 7.6566 7.38199 7.51253 7.5 7.39453C7.618 7.27652 7.76207 7.18788 7.9206 7.13574L11.018 6.11693L7.9206 5.09813C7.76207 5.04598 7.618 4.95735 7.5 4.83934C7.38199 4.72134 7.29335 4.57727 7.24121 4.41875L6.2224 1.32129Z" fill="black" fill-opacity="0.15" stroke="black" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M9.76681 13.9373C9.76681 13.6048 9.95997 13.3083 10.5126 12.7917L11.8872 11.4978C12.3545 11.0575 12.5612 10.77 12.5612 10.4735C12.5612 10.1411 12.3185 9.91643 11.9681 9.91643C11.6986 9.91643 11.5054 10.0242 11.2673 10.3208C10.9933 10.6622 10.7956 10.779 10.4946 10.779C10.0633 10.779 9.75781 10.4915 9.75781 10.0916C9.75781 9.21559 10.8136 8.44287 12.067 8.44287C13.3743 8.44287 14.3492 9.22907 14.3492 10.2848C14.3492 10.9452 13.9988 11.5742 13.2845 12.2077L12.2242 13.1511V13.223H13.7292C14.2503 13.223 14.5738 13.5015 14.5738 13.9552C14.5738 14.4089 14.2593 14.6785 13.7292 14.6785H10.5979C10.1037 14.6785 9.76681 14.3775 9.76681 13.9373Z" fill="black"/>
+<path d="M12.8994 1.32129V4.00482M11.5576 2.66302H14.2412" stroke="black" stroke-opacity="0.75" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/>
+</svg>

assets/keymaps/default-linux.json 🔗

@@ -25,7 +25,8 @@
       "ctrl-shift-w": "workspace::CloseWindow",
       "shift-escape": "workspace::ToggleZoom",
       "open": "workspace::Open",
-      "ctrl-o": "workspace::Open",
+      "ctrl-o": "workspace::OpenFiles",
+      "ctrl-k ctrl-o": "workspace::Open",
       "ctrl-=": ["zed::IncreaseBufferFontSize", { "persist": false }],
       "ctrl-+": ["zed::IncreaseBufferFontSize", { "persist": false }],
       "ctrl--": ["zed::DecreaseBufferFontSize", { "persist": false }],
@@ -41,17 +42,18 @@
       "ctrl-f11": "debugger::StepInto",
       "shift-f11": "debugger::StepOut",
       "f11": "zed::ToggleFullScreen",
-      "ctrl-alt-z": "edit_prediction::RateCompletions",
+      "ctrl-alt-z": "edit_prediction::RatePredictions",
       "ctrl-alt-shift-i": "edit_prediction::ToggleMenu",
-      "ctrl-alt-l": "lsp_tool::ToggleMenu"
-    }
+      "ctrl-alt-l": "lsp_tool::ToggleMenu",
+      "ctrl-alt-shift-s": "workspace::ToggleWorktreeSecurity",
+    },
   },
   {
     "context": "Picker || menu",
     "bindings": {
       "up": "menu::SelectPrevious",
-      "down": "menu::SelectNext"
-    }
+      "down": "menu::SelectNext",
+    },
   },
   {
     "context": "Editor",
@@ -62,7 +64,6 @@
       "delete": "editor::Delete",
       "tab": "editor::Tab",
       "shift-tab": "editor::Backtab",
-      "ctrl-k": "editor::CutToEndOfLine",
       "ctrl-k ctrl-q": "editor::Rewrap",
       "ctrl-k q": "editor::Rewrap",
       "ctrl-backspace": ["editor::DeleteToPreviousWordStart", { "ignore_newlines": false, "ignore_brackets": false }],
@@ -124,8 +125,8 @@
       "shift-f10": "editor::OpenContextMenu",
       "ctrl-alt-shift-e": "editor::ToggleEditPrediction",
       "f9": "editor::ToggleBreakpoint",
-      "shift-f9": "editor::EditLogBreakpoint"
-    }
+      "shift-f9": "editor::EditLogBreakpoint",
+    },
   },
   {
     "context": "Editor && mode == full",
@@ -144,44 +145,44 @@
       "ctrl-alt-e": "editor::SelectEnclosingSymbol",
       "ctrl-shift-backspace": "editor::GoToPreviousChange",
       "ctrl-shift-alt-backspace": "editor::GoToNextChange",
-      "alt-enter": "editor::OpenSelectionsInMultibuffer"
-    }
+      "alt-enter": "editor::OpenSelectionsInMultibuffer",
+    },
   },
   {
     "context": "Editor && mode == full && edit_prediction",
     "bindings": {
       "alt-]": "editor::NextEditPrediction",
-      "alt-[": "editor::PreviousEditPrediction"
-    }
+      "alt-[": "editor::PreviousEditPrediction",
+    },
   },
   {
     "context": "Editor && !edit_prediction",
     "bindings": {
-      "alt-\\": "editor::ShowEditPrediction"
-    }
+      "alt-\\": "editor::ShowEditPrediction",
+    },
   },
   {
     "context": "Editor && mode == auto_height",
     "bindings": {
       "ctrl-enter": "editor::Newline",
       "shift-enter": "editor::Newline",
-      "ctrl-shift-enter": "editor::NewlineBelow"
-    }
+      "ctrl-shift-enter": "editor::NewlineBelow",
+    },
   },
   {
     "context": "Markdown",
     "bindings": {
       "copy": "markdown::Copy",
       "ctrl-insert": "markdown::Copy",
-      "ctrl-c": "markdown::Copy"
-    }
+      "ctrl-c": "markdown::Copy",
+    },
   },
   {
     "context": "Editor && jupyter && !ContextEditor",
     "bindings": {
       "ctrl-shift-enter": "repl::Run",
-      "ctrl-alt-enter": "repl::RunInPlace"
-    }
+      "ctrl-alt-enter": "repl::RunInPlace",
+    },
   },
   {
     "context": "Editor && !agent_diff",
@@ -189,8 +190,8 @@
       "ctrl-k ctrl-r": "git::Restore",
       "ctrl-alt-y": "git::ToggleStaged",
       "alt-y": "git::StageAndNext",
-      "alt-shift-y": "git::UnstageAndNext"
-    }
+      "alt-shift-y": "git::UnstageAndNext",
+    },
   },
   {
     "context": "Editor && editor_agent_diff",
@@ -199,8 +200,8 @@
       "ctrl-n": "agent::Reject",
       "ctrl-shift-y": "agent::KeepAll",
       "ctrl-shift-n": "agent::RejectAll",
-      "shift-ctrl-r": "agent::OpenAgentDiff"
-    }
+      "shift-ctrl-r": "agent::OpenAgentDiff",
+    },
   },
   {
     "context": "AgentDiff",
@@ -208,8 +209,8 @@
       "ctrl-y": "agent::Keep",
       "ctrl-n": "agent::Reject",
       "ctrl-shift-y": "agent::KeepAll",
-      "ctrl-shift-n": "agent::RejectAll"
-    }
+      "ctrl-shift-n": "agent::RejectAll",
+    },
   },
   {
     "context": "ContextEditor > Editor",
@@ -225,8 +226,9 @@
       "ctrl-k c": "assistant::CopyCode",
       "ctrl-g": "search::SelectNextMatch",
       "ctrl-shift-g": "search::SelectPreviousMatch",
-      "ctrl-k l": "agent::OpenRulesLibrary"
-    }
+      "ctrl-k l": "agent::OpenRulesLibrary",
+      "ctrl-shift-v": "agent::PasteRaw",
+    },
   },
   {
     "context": "AgentPanel",
@@ -239,6 +241,7 @@
       "ctrl-alt-l": "agent::OpenRulesLibrary",
       "ctrl-i": "agent::ToggleProfileSelector",
       "ctrl-alt-/": "agent::ToggleModelSelector",
+      "alt-tab": "agent::CycleFavoriteModels",
       "ctrl-shift-j": "agent::ToggleNavigationMenu",
       "ctrl-alt-i": "agent::ToggleOptionsMenu",
       "ctrl-alt-shift-n": "agent::ToggleNewThreadMenu",
@@ -250,108 +253,86 @@
       "alt-enter": "agent::ContinueWithBurnMode",
       "ctrl-y": "agent::AllowOnce",
       "ctrl-alt-y": "agent::AllowAlways",
-      "ctrl-alt-z": "agent::RejectOnce"
-    }
+      "ctrl-alt-z": "agent::RejectOnce",
+    },
   },
   {
     "context": "AgentPanel > NavigationMenu",
     "bindings": {
-      "shift-backspace": "agent::DeleteRecentlyOpenThread"
-    }
+      "shift-backspace": "agent::DeleteRecentlyOpenThread",
+    },
   },
   {
     "context": "AgentPanel > Markdown",
     "bindings": {
       "copy": "markdown::CopyAsMarkdown",
       "ctrl-insert": "markdown::CopyAsMarkdown",
-      "ctrl-c": "markdown::CopyAsMarkdown"
-    }
+      "ctrl-c": "markdown::CopyAsMarkdown",
+    },
   },
   {
     "context": "AgentPanel && text_thread",
     "bindings": {
       "ctrl-n": "agent::NewTextThread",
-      "ctrl-alt-t": "agent::NewThread"
-    }
+      "ctrl-alt-t": "agent::NewThread",
+    },
   },
   {
     "context": "AgentPanel && acp_thread",
     "use_key_equivalents": true,
     "bindings": {
       "ctrl-n": "agent::NewExternalAgentThread",
-      "ctrl-alt-t": "agent::NewThread"
-    }
-  },
-  {
-    "context": "MessageEditor && !Picker > Editor && !use_modifier_to_send",
-    "bindings": {
-      "enter": "agent::Chat",
-      "ctrl-enter": "agent::ChatWithFollow",
-      "ctrl-i": "agent::ToggleProfileSelector",
-      "shift-ctrl-r": "agent::OpenAgentDiff",
-      "ctrl-shift-y": "agent::KeepAll",
-      "ctrl-shift-n": "agent::RejectAll"
-    }
+      "ctrl-alt-t": "agent::NewThread",
+    },
   },
   {
-    "context": "MessageEditor && !Picker > Editor && use_modifier_to_send",
-    "bindings": {
-      "ctrl-enter": "agent::Chat",
-      "enter": "editor::Newline",
-      "ctrl-i": "agent::ToggleProfileSelector",
-      "shift-ctrl-r": "agent::OpenAgentDiff",
-      "ctrl-shift-y": "agent::KeepAll",
-      "ctrl-shift-n": "agent::RejectAll"
-    }
-  },
-  {
-    "context": "EditMessageEditor > Editor",
+    "context": "AgentFeedbackMessageEditor > Editor",
     "bindings": {
       "escape": "menu::Cancel",
       "enter": "menu::Confirm",
-      "alt-enter": "editor::Newline"
-    }
+      "alt-enter": "editor::Newline",
+    },
   },
   {
-    "context": "AgentFeedbackMessageEditor > Editor",
+    "context": "AcpThread > ModeSelector",
     "bindings": {
-      "escape": "menu::Cancel",
-      "enter": "menu::Confirm",
-      "alt-enter": "editor::Newline"
-    }
+      "ctrl-enter": "menu::Confirm",
+    },
   },
   {
-    "context": "AcpThread > ModeSelector",
+    "context": "AcpThread > Editor",
+    "use_key_equivalents": true,
     "bindings": {
-      "ctrl-enter": "menu::Confirm"
-    }
+      "ctrl-enter": "agent::ChatWithFollow",
+      "ctrl-i": "agent::ToggleProfileSelector",
+      "ctrl-shift-r": "agent::OpenAgentDiff",
+      "ctrl-shift-y": "agent::KeepAll",
+      "ctrl-shift-n": "agent::RejectAll",
+      "ctrl-shift-v": "agent::PasteRaw",
+      "shift-tab": "agent::CycleModeSelector",
+      "alt-tab": "agent::CycleFavoriteModels",
+    },
   },
   {
     "context": "AcpThread > Editor && !use_modifier_to_send",
     "use_key_equivalents": true,
     "bindings": {
       "enter": "agent::Chat",
-      "shift-ctrl-r": "agent::OpenAgentDiff",
-      "ctrl-shift-y": "agent::KeepAll",
-      "ctrl-shift-n": "agent::RejectAll"
-    }
+    },
   },
   {
     "context": "AcpThread > Editor && use_modifier_to_send",
     "use_key_equivalents": true,
     "bindings": {
       "ctrl-enter": "agent::Chat",
-      "shift-ctrl-r": "agent::OpenAgentDiff",
-      "ctrl-shift-y": "agent::KeepAll",
-      "ctrl-shift-n": "agent::RejectAll",
-      "shift-tab": "agent::CycleModeSelector"
-    }
+      "enter": "editor::Newline",
+    },
   },
   {
     "context": "ThreadHistory",
     "bindings": {
-      "backspace": "agent::RemoveSelectedThread"
-    }
+      "backspace": "agent::RemoveSelectedThread",
+    },
   },
   {
     "context": "RulesLibrary",
@@ -359,8 +340,8 @@
       "new": "rules_library::NewRule",
       "ctrl-n": "rules_library::NewRule",
       "ctrl-shift-s": "rules_library::ToggleDefaultRule",
-      "ctrl-w": "workspace::CloseWindow"
-    }
+      "ctrl-w": "workspace::CloseWindow",
+    },
   },
   {
     "context": "BufferSearchBar",
@@ -373,22 +354,22 @@
       "find": "search::FocusSearch",
       "ctrl-f": "search::FocusSearch",
       "ctrl-h": "search::ToggleReplace",
-      "ctrl-l": "search::ToggleSelection"
-    }
+      "ctrl-l": "search::ToggleSelection",
+    },
   },
   {
     "context": "BufferSearchBar && in_replace > Editor",
     "bindings": {
       "enter": "search::ReplaceNext",
-      "ctrl-enter": "search::ReplaceAll"
-    }
+      "ctrl-enter": "search::ReplaceAll",
+    },
   },
   {
     "context": "BufferSearchBar && !in_replace > Editor",
     "bindings": {
       "up": "search::PreviousHistoryQuery",
-      "down": "search::NextHistoryQuery"
-    }
+      "down": "search::NextHistoryQuery",
+    },
   },
   {
     "context": "ProjectSearchBar",
@@ -399,22 +380,22 @@
       "ctrl-shift-f": "search::FocusSearch",
       "ctrl-shift-h": "search::ToggleReplace",
       "alt-ctrl-g": "search::ToggleRegex",
-      "alt-ctrl-x": "search::ToggleRegex"
-    }
+      "alt-ctrl-x": "search::ToggleRegex",
+    },
   },
   {
     "context": "ProjectSearchBar > Editor",
     "bindings": {
       "up": "search::PreviousHistoryQuery",
-      "down": "search::NextHistoryQuery"
-    }
+      "down": "search::NextHistoryQuery",
+    },
   },
   {
     "context": "ProjectSearchBar && in_replace > Editor",
     "bindings": {
       "enter": "search::ReplaceNext",
-      "ctrl-alt-enter": "search::ReplaceAll"
-    }
+      "ctrl-alt-enter": "search::ReplaceAll",
+    },
   },
   {
     "context": "ProjectSearchView",
@@ -422,8 +403,8 @@
       "escape": "project_search::ToggleFocus",
       "ctrl-shift-h": "search::ToggleReplace",
       "alt-ctrl-g": "search::ToggleRegex",
-      "alt-ctrl-x": "search::ToggleRegex"
-    }
+      "alt-ctrl-x": "search::ToggleRegex",
+    },
   },
   {
     "context": "Pane",
@@ -472,8 +453,8 @@
       "ctrl-alt-shift-r": "search::ToggleRegex",
       "ctrl-alt-shift-x": "search::ToggleRegex",
       "alt-r": "search::ToggleRegex",
-      "ctrl-k shift-enter": "pane::TogglePinTab"
-    }
+      "ctrl-k shift-enter": "pane::TogglePinTab",
+    },
   },
   // Bindings from VS Code
   {
@@ -500,6 +481,7 @@
       "ctrl-k ctrl-i": "editor::Hover",
       "ctrl-k ctrl-b": "editor::BlameHover",
       "ctrl-/": ["editor::ToggleComments", { "advance_downwards": false }],
+      "ctrl-k ctrl-c": ["editor::ToggleComments", { "advance_downwards": false }],
       "f8": ["editor::GoToDiagnostic", { "severity": { "min": "hint", "max": "error" } }],
       "shift-f8": ["editor::GoToPreviousDiagnostic", { "severity": { "min": "hint", "max": "error" } }],
       "f2": "editor::Rename",
@@ -536,31 +518,31 @@
       "ctrl-\\": "pane::SplitRight",
       "ctrl-alt-shift-c": "editor::DisplayCursorNames",
       "alt-.": "editor::GoToHunk",
-      "alt-,": "editor::GoToPreviousHunk"
-    }
+      "alt-,": "editor::GoToPreviousHunk",
+    },
   },
   {
     "context": "Editor && extension == md",
     "use_key_equivalents": true,
     "bindings": {
       "ctrl-k v": "markdown::OpenPreviewToTheSide",
-      "ctrl-shift-v": "markdown::OpenPreview"
-    }
+      "ctrl-shift-v": "markdown::OpenPreview",
+    },
   },
   {
     "context": "Editor && extension == svg",
     "use_key_equivalents": true,
     "bindings": {
       "ctrl-k v": "svg::OpenPreviewToTheSide",
-      "ctrl-shift-v": "svg::OpenPreview"
-    }
+      "ctrl-shift-v": "svg::OpenPreview",
+    },
   },
   {
     "context": "Editor && mode == full",
     "bindings": {
       "ctrl-shift-o": "outline::Toggle",
-      "ctrl-g": "go_to_line::Toggle"
-    }
+      "ctrl-g": "go_to_line::Toggle",
+    },
   },
   {
     "context": "Workspace",
@@ -616,8 +598,8 @@
       "ctrl-alt-super-p": "settings_profile_selector::Toggle",
       "ctrl-t": "project_symbols::Toggle",
       "ctrl-p": "file_finder::Toggle",
-      "ctrl-tab": "tab_switcher::Toggle",
       "ctrl-shift-tab": ["tab_switcher::Toggle", { "select_last": true }],
+      "ctrl-tab": "tab_switcher::Toggle",
       "ctrl-e": "file_finder::Toggle",
       "f1": "command_palette::Toggle",
       "ctrl-shift-p": "command_palette::Toggle",
@@ -654,28 +636,28 @@
       // "foo-bar": ["task::Spawn", { "task_tag": "MyTag" }],
       "f5": "debugger::Rerun",
       "ctrl-f4": "workspace::CloseActiveDock",
-      "ctrl-w": "workspace::CloseActiveDock"
-    }
+      "ctrl-w": "workspace::CloseActiveDock",
+    },
   },
   {
     "context": "Workspace && debugger_running",
     "bindings": {
-      "f5": "zed::NoAction"
-    }
+      "f5": "zed::NoAction",
+    },
   },
   {
     "context": "Workspace && debugger_stopped",
     "bindings": {
-      "f5": "debugger::Continue"
-    }
+      "f5": "debugger::Continue",
+    },
   },
   {
     "context": "ApplicationMenu",
     "bindings": {
       "f10": "menu::Cancel",
       "left": "app_menu::ActivateMenuLeft",
-      "right": "app_menu::ActivateMenuRight"
-    }
+      "right": "app_menu::ActivateMenuRight",
+    },
   },
   // Bindings from Sublime Text
   {
@@ -693,8 +675,8 @@
       "ctrl-alt-shift-left": "editor::SelectToPreviousSubwordStart",
       "ctrl-alt-shift-b": "editor::SelectToPreviousSubwordStart",
       "ctrl-alt-shift-right": "editor::SelectToNextSubwordEnd",
-      "ctrl-alt-shift-f": "editor::SelectToNextSubwordEnd"
-    }
+      "ctrl-alt-shift-f": "editor::SelectToNextSubwordEnd",
+    },
   },
   // Bindings from Atom
   {
@@ -703,37 +685,37 @@
       "ctrl-k up": "pane::SplitUp",
       "ctrl-k down": "pane::SplitDown",
       "ctrl-k left": "pane::SplitLeft",
-      "ctrl-k right": "pane::SplitRight"
-    }
+      "ctrl-k right": "pane::SplitRight",
+    },
   },
   // Bindings that should be unified with bindings for more general actions
   {
     "context": "Editor && renaming",
     "bindings": {
-      "enter": "editor::ConfirmRename"
-    }
+      "enter": "editor::ConfirmRename",
+    },
   },
   {
     "context": "Editor && showing_completions",
     "bindings": {
       "enter": "editor::ConfirmCompletion",
       "shift-enter": "editor::ConfirmCompletionReplace",
-      "tab": "editor::ComposeCompletion"
-    }
+      "tab": "editor::ComposeCompletion",
+    },
   },
   {
     "context": "Editor && in_snippet && has_next_tabstop && !showing_completions",
     "use_key_equivalents": true,
     "bindings": {
-      "tab": "editor::NextSnippetTabstop"
-    }
+      "tab": "editor::NextSnippetTabstop",
+    },
   },
   {
     "context": "Editor && in_snippet && has_previous_tabstop && !showing_completions",
     "use_key_equivalents": true,
     "bindings": {
-      "shift-tab": "editor::PreviousSnippetTabstop"
-    }
+      "shift-tab": "editor::PreviousSnippetTabstop",
+    },
   },
   // Bindings for accepting edit predictions
   //
@@ -745,22 +727,24 @@
       "alt-tab": "editor::AcceptEditPrediction",
       "alt-l": "editor::AcceptEditPrediction",
       "tab": "editor::AcceptEditPrediction",
-      "alt-right": "editor::AcceptPartialEditPrediction"
-    }
+      "alt-right": "editor::AcceptNextWordEditPrediction",
+      "alt-down": "editor::AcceptNextLineEditPrediction",
+    },
   },
   {
     "context": "Editor && edit_prediction_conflict",
     "bindings": {
       "alt-tab": "editor::AcceptEditPrediction",
       "alt-l": "editor::AcceptEditPrediction",
-      "alt-right": "editor::AcceptPartialEditPrediction"
-    }
+      "alt-right": "editor::AcceptNextWordEditPrediction",
+      "alt-down": "editor::AcceptNextLineEditPrediction",
+    },
   },
   {
     "context": "Editor && showing_code_actions",
     "bindings": {
-      "enter": "editor::ConfirmCodeAction"
-    }
+      "enter": "editor::ConfirmCodeAction",
+    },
   },
   {
     "context": "Editor && (showing_code_actions || showing_completions)",
@@ -770,29 +754,29 @@
       "ctrl-n": "editor::ContextMenuNext",
       "down": "editor::ContextMenuNext",
       "pageup": "editor::ContextMenuFirst",
-      "pagedown": "editor::ContextMenuLast"
-    }
+      "pagedown": "editor::ContextMenuLast",
+    },
   },
   {
     "context": "Editor && showing_signature_help && !showing_completions",
     "bindings": {
       "up": "editor::SignatureHelpPrevious",
-      "down": "editor::SignatureHelpNext"
-    }
+      "down": "editor::SignatureHelpNext",
+    },
   },
   // Custom bindings
   {
     "bindings": {
       "ctrl-alt-shift-f": "workspace::FollowNextCollaborator",
       // Only available in debug builds: opens an element inspector for development.
-      "ctrl-alt-i": "dev::ToggleInspector"
-    }
+      "ctrl-alt-i": "dev::ToggleInspector",
+    },
   },
   {
     "context": "!Terminal",
     "bindings": {
-      "ctrl-shift-c": "collab_panel::ToggleFocus"
-    }
+      "ctrl-shift-c": "collab_panel::ToggleFocus",
+    },
   },
   {
     "context": "!ContextEditor > Editor && mode == full",
@@ -804,15 +788,17 @@
       "ctrl-f8": "editor::GoToHunk",
       "ctrl-shift-f8": "editor::GoToPreviousHunk",
       "ctrl-enter": "assistant::InlineAssist",
-      "ctrl-:": "editor::ToggleInlayHints"
-    }
+      "ctrl-:": "editor::ToggleInlayHints",
+    },
   },
   {
-    "context": "PromptEditor",
+    "context": "InlineAssistant",
     "bindings": {
       "ctrl-[": "agent::CyclePreviousInlineAssist",
-      "ctrl-]": "agent::CycleNextInlineAssist"
-    }
+      "ctrl-]": "agent::CycleNextInlineAssist",
+      "ctrl-shift-enter": "inline_assistant::ThumbsUpResult",
+      "ctrl-shift-backspace": "inline_assistant::ThumbsDownResult",
+    },
   },
   {
     "context": "Prompt",
@@ -820,14 +806,14 @@
       "left": "menu::SelectPrevious",
       "right": "menu::SelectNext",
       "h": "menu::SelectPrevious",
-      "l": "menu::SelectNext"
-    }
+      "l": "menu::SelectNext",
+    },
   },
   {
     "context": "ProjectSearchBar && !in_replace",
     "bindings": {
-      "ctrl-enter": "project_search::SearchInNew"
-    }
+      "ctrl-enter": "project_search::SearchInNew",
+    },
   },
   {
     "context": "OutlinePanel && not_editing",
@@ -844,8 +830,8 @@
       "shift-down": "menu::SelectNext",
       "shift-up": "menu::SelectPrevious",
       "alt-enter": "editor::OpenExcerpts",
-      "ctrl-alt-enter": "editor::OpenExcerptsSplit"
-    }
+      "ctrl-alt-enter": "editor::OpenExcerptsSplit",
+    },
   },
   {
     "context": "ProjectPanel",
@@ -883,20 +869,22 @@
       "ctrl-alt-shift-f": "project_panel::NewSearchInDirectory",
       "shift-down": "menu::SelectNext",
       "shift-up": "menu::SelectPrevious",
-      "escape": "menu::Cancel"
-    }
+      "escape": "menu::Cancel",
+    },
   },
   {
     "context": "ProjectPanel && not_editing",
     "bindings": {
-      "space": "project_panel::Open"
-    }
+      "space": "project_panel::Open",
+    },
   },
   {
     "context": "GitPanel && ChangesList",
     "bindings": {
-      "up": "menu::SelectPrevious",
-      "down": "menu::SelectNext",
+      "left": "git_panel::CollapseSelectedEntry",
+      "right": "git_panel::ExpandSelectedEntry",
+      "up": "git_panel::PreviousEntry",
+      "down": "git_panel::NextEntry",
       "enter": "menu::Confirm",
       "alt-y": "git::StageFile",
       "alt-shift-y": "git::UnstageFile",
@@ -911,15 +899,15 @@
       "backspace": ["git::RestoreFile", { "skip_prompt": false }],
       "shift-delete": ["git::RestoreFile", { "skip_prompt": false }],
       "ctrl-backspace": ["git::RestoreFile", { "skip_prompt": false }],
-      "ctrl-delete": ["git::RestoreFile", { "skip_prompt": false }]
-    }
+      "ctrl-delete": ["git::RestoreFile", { "skip_prompt": false }],
+    },
   },
   {
     "context": "GitPanel && CommitEditor",
     "use_key_equivalents": true,
     "bindings": {
-      "escape": "git::Cancel"
-    }
+      "escape": "git::Cancel",
+    },
   },
   {
     "context": "GitCommit > Editor",
@@ -928,8 +916,8 @@
       "enter": "editor::Newline",
       "ctrl-enter": "git::Commit",
       "ctrl-shift-enter": "git::Amend",
-      "alt-l": "git::GenerateCommitMessage"
-    }
+      "alt-l": "git::GenerateCommitMessage",
+    },
   },
   {
     "context": "GitPanel",
@@ -945,8 +933,8 @@
       "ctrl-space": "git::StageAll",
       "ctrl-shift-space": "git::UnstageAll",
       "ctrl-enter": "git::Commit",
-      "ctrl-shift-enter": "git::Amend"
-    }
+      "ctrl-shift-enter": "git::Amend",
+    },
   },
   {
     "context": "GitDiff > Editor",
@@ -954,14 +942,14 @@
       "ctrl-enter": "git::Commit",
       "ctrl-shift-enter": "git::Amend",
       "ctrl-space": "git::StageAll",
-      "ctrl-shift-space": "git::UnstageAll"
-    }
+      "ctrl-shift-space": "git::UnstageAll",
+    },
   },
   {
     "context": "AskPass > Editor",
     "bindings": {
-      "enter": "menu::Confirm"
-    }
+      "enter": "menu::Confirm",
+    },
   },
   {
     "context": "CommitEditor > Editor",
@@ -973,16 +961,16 @@
       "ctrl-enter": "git::Commit",
       "ctrl-shift-enter": "git::Amend",
       "alt-up": "git_panel::FocusChanges",
-      "alt-l": "git::GenerateCommitMessage"
-    }
+      "alt-l": "git::GenerateCommitMessage",
+    },
   },
   {
     "context": "DebugPanel",
     "bindings": {
       "ctrl-t": "debugger::ToggleThreadPicker",
       "ctrl-i": "debugger::ToggleSessionPicker",
-      "shift-alt-escape": "debugger::ToggleExpandItem"
-    }
+      "shift-alt-escape": "debugger::ToggleExpandItem",
+    },
   },
   {
     "context": "VariableList",
@@ -994,8 +982,8 @@
       "ctrl-alt-c": "variable_list::CopyVariableName",
       "delete": "variable_list::RemoveWatch",
       "backspace": "variable_list::RemoveWatch",
-      "alt-enter": "variable_list::AddWatch"
-    }
+      "alt-enter": "variable_list::AddWatch",
+    },
   },
   {
     "context": "BreakpointList",
@@ -1003,35 +991,35 @@
       "space": "debugger::ToggleEnableBreakpoint",
       "backspace": "debugger::UnsetBreakpoint",
       "left": "debugger::PreviousBreakpointProperty",
-      "right": "debugger::NextBreakpointProperty"
-    }
+      "right": "debugger::NextBreakpointProperty",
+    },
   },
   {
     "context": "CollabPanel && not_editing",
     "bindings": {
       "ctrl-backspace": "collab_panel::Remove",
-      "space": "menu::Confirm"
-    }
+      "space": "menu::Confirm",
+    },
   },
   {
     "context": "CollabPanel",
     "bindings": {
       "alt-up": "collab_panel::MoveChannelUp",
       "alt-down": "collab_panel::MoveChannelDown",
-      "alt-enter": "collab_panel::OpenSelectedChannelNotes"
-    }
+      "alt-enter": "collab_panel::OpenSelectedChannelNotes",
+    },
   },
   {
     "context": "(CollabPanel && editing) > Editor",
     "bindings": {
-      "space": "collab_panel::InsertSpace"
-    }
+      "space": "collab_panel::InsertSpace",
+    },
   },
   {
     "context": "ChannelModal",
     "bindings": {
-      "tab": "channel_modal::ToggleMode"
-    }
+      "tab": "channel_modal::ToggleMode",
+    },
   },
   {
     "context": "Picker > Editor",
@@ -1040,29 +1028,29 @@
       "up": "menu::SelectPrevious",
       "down": "menu::SelectNext",
       "tab": "picker::ConfirmCompletion",
-      "alt-enter": ["picker::ConfirmInput", { "secondary": false }]
-    }
+      "alt-enter": ["picker::ConfirmInput", { "secondary": false }],
+    },
   },
   {
     "context": "ChannelModal > Picker > Editor",
     "bindings": {
-      "tab": "channel_modal::ToggleMode"
-    }
+      "tab": "channel_modal::ToggleMode",
+    },
   },
   {
     "context": "ToolchainSelector",
     "use_key_equivalents": true,
     "bindings": {
-      "ctrl-shift-a": "toolchain::AddToolchain"
-    }
+      "ctrl-shift-a": "toolchain::AddToolchain",
+    },
   },
   {
     "context": "FileFinder || (FileFinder > Picker > Editor)",
     "bindings": {
       "ctrl-p": "file_finder::Toggle",
       "ctrl-shift-a": "file_finder::ToggleSplitMenu",
-      "ctrl-shift-i": "file_finder::ToggleFilterMenu"
-    }
+      "ctrl-shift-i": "file_finder::ToggleFilterMenu",
+    },
   },
   {
     "context": "FileFinder || (FileFinder > Picker > Editor) || (FileFinder > Picker > menu)",
@@ -1071,8 +1059,8 @@
       "ctrl-j": "pane::SplitDown",
       "ctrl-k": "pane::SplitUp",
       "ctrl-h": "pane::SplitLeft",
-      "ctrl-l": "pane::SplitRight"
-    }
+      "ctrl-l": "pane::SplitRight",
+    },
   },
   {
     "context": "TabSwitcher",
@@ -1080,15 +1068,15 @@
       "ctrl-shift-tab": "menu::SelectPrevious",
       "ctrl-up": "menu::SelectPrevious",
       "ctrl-down": "menu::SelectNext",
-      "ctrl-backspace": "tab_switcher::CloseSelectedItem"
-    }
+      "ctrl-backspace": "tab_switcher::CloseSelectedItem",
+    },
   },
   {
     "context": "StashList || (StashList > Picker > Editor)",
     "bindings": {
       "ctrl-shift-backspace": "stash_picker::DropStashItem",
-      "ctrl-shift-v": "stash_picker::ShowStashItem"
-    }
+      "ctrl-shift-v": "stash_picker::ShowStashItem",
+    },
   },
   {
     "context": "Terminal",
@@ -1133,65 +1121,69 @@
       "ctrl-shift-r": "terminal::RerunTask",
       "ctrl-alt-r": "terminal::RerunTask",
       "alt-t": "terminal::RerunTask",
-      "ctrl-shift-5": "pane::SplitRight"
-    }
+      "ctrl-shift-5": "pane::SplitRight",
+    },
   },
   {
     "context": "ZedPredictModal",
     "bindings": {
-      "escape": "menu::Cancel"
-    }
+      "escape": "menu::Cancel",
+    },
   },
   {
     "context": "ConfigureContextServerModal > Editor",
     "bindings": {
       "escape": "menu::Cancel",
       "enter": "editor::Newline",
-      "ctrl-enter": "menu::Confirm"
-    }
+      "ctrl-enter": "menu::Confirm",
+    },
   },
   {
     "context": "ContextServerToolsModal",
     "use_key_equivalents": true,
     "bindings": {
-      "escape": "menu::Cancel"
-    }
+      "escape": "menu::Cancel",
+    },
   },
   {
     "context": "OnboardingAiConfigurationModal",
     "use_key_equivalents": true,
     "bindings": {
-      "escape": "menu::Cancel"
-    }
+      "escape": "menu::Cancel",
+    },
   },
   {
     "context": "Diagnostics",
     "use_key_equivalents": true,
     "bindings": {
-      "ctrl-r": "diagnostics::ToggleDiagnosticsRefresh"
-    }
+      "ctrl-r": "diagnostics::ToggleDiagnosticsRefresh",
+    },
   },
   {
     "context": "DebugConsole > Editor",
     "use_key_equivalents": true,
     "bindings": {
       "enter": "menu::Confirm",
-      "alt-enter": "console::WatchExpression"
-    }
+      "alt-enter": "console::WatchExpression",
+    },
   },
   {
     "context": "RunModal",
     "bindings": {
       "ctrl-tab": "pane::ActivateNextItem",
-      "ctrl-shift-tab": "pane::ActivatePreviousItem"
-    }
+      "ctrl-shift-tab": "pane::ActivatePreviousItem",
+    },
   },
   {
     "context": "MarkdownPreview",
     "bindings": {
-      "pageup": "markdown::MovePageUp",
-      "pagedown": "markdown::MovePageDown"
-    }
+      "pageup": "markdown::ScrollPageUp",
+      "pagedown": "markdown::ScrollPageDown",
+      "up": "markdown::ScrollUp",
+      "down": "markdown::ScrollDown",
+      "alt-up": "markdown::ScrollUpByItem",
+      "alt-down": "markdown::ScrollDownByItem",
+    },
   },
   {
     "context": "KeymapEditor",
@@ -1205,8 +1197,8 @@
       "alt-enter": "keymap_editor::CreateBinding",
       "ctrl-c": "keymap_editor::CopyAction",
       "ctrl-shift-c": "keymap_editor::CopyContext",
-      "ctrl-t": "keymap_editor::ShowMatchingKeybinds"
-    }
+      "ctrl-t": "keymap_editor::ShowMatchingKeybinds",
+    },
   },
   {
     "context": "KeystrokeInput",

assets/keymaps/default-macos.json 🔗

@@ -47,11 +47,12 @@
       "cmd-m": "zed::Minimize",
       "fn-f": "zed::ToggleFullScreen",
       "ctrl-cmd-f": "zed::ToggleFullScreen",
-      "ctrl-cmd-z": "edit_prediction::RateCompletions",
+      "ctrl-cmd-z": "edit_prediction::RatePredictions",
       "ctrl-cmd-i": "edit_prediction::ToggleMenu",
       "ctrl-cmd-l": "lsp_tool::ToggleMenu",
-      "ctrl-cmd-c": "editor::DisplayCursorNames"
-    }
+      "ctrl-cmd-c": "editor::DisplayCursorNames",
+      "ctrl-cmd-s": "workspace::ToggleWorktreeSecurity",
+    },
   },
   {
     "context": "Editor",
@@ -148,8 +149,8 @@
       "shift-f9": "editor::EditLogBreakpoint",
       "ctrl-f12": "editor::GoToDeclaration",
       "alt-ctrl-f12": "editor::GoToDeclarationSplit",
-      "ctrl-cmd-e": "editor::ToggleEditPrediction"
-    }
+      "ctrl-cmd-e": "editor::ToggleEditPrediction",
+    },
   },
   {
     "context": "Editor && mode == full",
@@ -167,8 +168,8 @@
       "cmd->": "agent::AddSelectionToThread",
       "cmd-<": "assistant::InsertIntoEditor",
       "cmd-alt-e": "editor::SelectEnclosingSymbol",
-      "alt-enter": "editor::OpenSelectionsInMultibuffer"
-    }
+      "alt-enter": "editor::OpenSelectionsInMultibuffer",
+    },
   },
   {
     "context": "Editor && multibuffer",
@@ -177,23 +178,23 @@
       "cmd-up": "editor::MoveToStartOfExcerpt",
       "cmd-down": "editor::MoveToStartOfNextExcerpt",
       "cmd-shift-up": "editor::SelectToStartOfExcerpt",
-      "cmd-shift-down": "editor::SelectToStartOfNextExcerpt"
-    }
+      "cmd-shift-down": "editor::SelectToStartOfNextExcerpt",
+    },
   },
   {
     "context": "Editor && mode == full && edit_prediction",
     "use_key_equivalents": true,
     "bindings": {
       "alt-tab": "editor::NextEditPrediction",
-      "alt-shift-tab": "editor::PreviousEditPrediction"
-    }
+      "alt-shift-tab": "editor::PreviousEditPrediction",
+    },
   },
   {
     "context": "Editor && !edit_prediction",
     "use_key_equivalents": true,
     "bindings": {
-      "alt-tab": "editor::ShowEditPrediction"
-    }
+      "alt-tab": "editor::ShowEditPrediction",
+    },
   },
   {
     "context": "Editor && mode == auto_height",
@@ -201,23 +202,23 @@
     "bindings": {
       "ctrl-enter": "editor::Newline",
       "shift-enter": "editor::Newline",
-      "ctrl-shift-enter": "editor::NewlineBelow"
-    }
+      "ctrl-shift-enter": "editor::NewlineBelow",
+    },
   },
   {
     "context": "Markdown",
     "use_key_equivalents": true,
     "bindings": {
-      "cmd-c": "markdown::Copy"
-    }
+      "cmd-c": "markdown::Copy",
+    },
   },
   {
     "context": "Editor && jupyter && !ContextEditor",
     "use_key_equivalents": true,
     "bindings": {
       "ctrl-shift-enter": "repl::Run",
-      "ctrl-alt-enter": "repl::RunInPlace"
-    }
+      "ctrl-alt-enter": "repl::RunInPlace",
+    },
   },
   {
     "context": "Editor && !agent_diff && !AgentPanel",
@@ -226,8 +227,8 @@
       "cmd-alt-z": "git::Restore",
       "cmd-alt-y": "git::ToggleStaged",
       "cmd-y": "git::StageAndNext",
-      "cmd-shift-y": "git::UnstageAndNext"
-    }
+      "cmd-shift-y": "git::UnstageAndNext",
+    },
   },
   {
     "context": "AgentDiff",
@@ -236,8 +237,8 @@
       "cmd-y": "agent::Keep",
       "cmd-n": "agent::Reject",
       "cmd-shift-y": "agent::KeepAll",
-      "cmd-shift-n": "agent::RejectAll"
-    }
+      "cmd-shift-n": "agent::RejectAll",
+    },
   },
   {
     "context": "Editor && editor_agent_diff",
@@ -247,8 +248,8 @@
       "cmd-n": "agent::Reject",
       "cmd-shift-y": "agent::KeepAll",
       "cmd-shift-n": "agent::RejectAll",
-      "shift-ctrl-r": "agent::OpenAgentDiff"
-    }
+      "shift-ctrl-r": "agent::OpenAgentDiff",
+    },
   },
   {
     "context": "ContextEditor > Editor",
@@ -264,8 +265,10 @@
       "cmd-k c": "assistant::CopyCode",
       "cmd-g": "search::SelectNextMatch",
       "cmd-shift-g": "search::SelectPreviousMatch",
-      "cmd-k l": "agent::OpenRulesLibrary"
-    }
+      "cmd-k l": "agent::OpenRulesLibrary",
+      "alt-tab": "agent::CycleFavoriteModels",
+      "cmd-shift-v": "agent::PasteRaw",
+    },
   },
   {
     "context": "AgentPanel",
@@ -279,6 +282,7 @@
       "cmd-alt-p": "agent::ManageProfiles",
       "cmd-i": "agent::ToggleProfileSelector",
       "cmd-alt-/": "agent::ToggleModelSelector",
+      "alt-tab": "agent::CycleFavoriteModels",
       "cmd-shift-j": "agent::ToggleNavigationMenu",
       "cmd-alt-m": "agent::ToggleOptionsMenu",
       "cmd-alt-shift-n": "agent::ToggleNewThreadMenu",
@@ -290,70 +294,37 @@
       "alt-enter": "agent::ContinueWithBurnMode",
       "cmd-y": "agent::AllowOnce",
       "cmd-alt-y": "agent::AllowAlways",
-      "cmd-alt-z": "agent::RejectOnce"
-    }
+      "cmd-alt-z": "agent::RejectOnce",
+    },
   },
   {
     "context": "AgentPanel > NavigationMenu",
     "bindings": {
-      "shift-backspace": "agent::DeleteRecentlyOpenThread"
-    }
+      "shift-backspace": "agent::DeleteRecentlyOpenThread",
+    },
   },
   {
     "context": "AgentPanel > Markdown",
     "use_key_equivalents": true,
     "bindings": {
-      "cmd-c": "markdown::CopyAsMarkdown"
-    }
+      "cmd-c": "markdown::CopyAsMarkdown",
+    },
   },
   {
     "context": "AgentPanel && text_thread",
     "use_key_equivalents": true,
     "bindings": {
       "cmd-n": "agent::NewTextThread",
-      "cmd-alt-n": "agent::NewExternalAgentThread"
-    }
+      "cmd-alt-n": "agent::NewExternalAgentThread",
+    },
   },
   {
     "context": "AgentPanel && acp_thread",
     "use_key_equivalents": true,
     "bindings": {
       "cmd-n": "agent::NewExternalAgentThread",
-      "cmd-alt-t": "agent::NewThread"
-    }
-  },
-  {
-    "context": "MessageEditor && !Picker > Editor && !use_modifier_to_send",
-    "use_key_equivalents": true,
-    "bindings": {
-      "enter": "agent::Chat",
-      "cmd-enter": "agent::ChatWithFollow",
-      "cmd-i": "agent::ToggleProfileSelector",
-      "shift-ctrl-r": "agent::OpenAgentDiff",
-      "cmd-shift-y": "agent::KeepAll",
-      "cmd-shift-n": "agent::RejectAll"
-    }
-  },
-  {
-    "context": "MessageEditor && !Picker > Editor && use_modifier_to_send",
-    "use_key_equivalents": true,
-    "bindings": {
-      "cmd-enter": "agent::Chat",
-      "enter": "editor::Newline",
-      "cmd-i": "agent::ToggleProfileSelector",
-      "shift-ctrl-r": "agent::OpenAgentDiff",
-      "cmd-shift-y": "agent::KeepAll",
-      "cmd-shift-n": "agent::RejectAll"
-    }
-  },
-  {
-    "context": "EditMessageEditor > Editor",
-    "use_key_equivalents": true,
-    "bindings": {
-      "escape": "menu::Cancel",
-      "enter": "menu::Confirm",
-      "alt-enter": "editor::Newline"
-    }
+      "cmd-alt-t": "agent::NewThread",
+    },
   },
   {
     "context": "AgentFeedbackMessageEditor > Editor",
@@ -361,54 +332,61 @@
     "bindings": {
       "escape": "menu::Cancel",
       "enter": "menu::Confirm",
-      "alt-enter": "editor::Newline"
-    }
+      "alt-enter": "editor::Newline",
+    },
   },
   {
     "context": "AgentConfiguration",
     "bindings": {
-      "ctrl--": "pane::GoBack"
-    }
+      "ctrl--": "pane::GoBack",
+    },
   },
   {
     "context": "AcpThread > ModeSelector",
     "bindings": {
-      "cmd-enter": "menu::Confirm"
-    }
+      "cmd-enter": "menu::Confirm",
+    },
   },
   {
-    "context": "AcpThread > Editor && !use_modifier_to_send",
+    "context": "AcpThread > Editor",
     "use_key_equivalents": true,
     "bindings": {
-      "enter": "agent::Chat",
       "shift-ctrl-r": "agent::OpenAgentDiff",
       "cmd-shift-y": "agent::KeepAll",
       "cmd-shift-n": "agent::RejectAll",
-      "shift-tab": "agent::CycleModeSelector"
-    }
+      "cmd-enter": "agent::ChatWithFollow",
+      "cmd-shift-v": "agent::PasteRaw",
+      "cmd-i": "agent::ToggleProfileSelector",
+      "shift-tab": "agent::CycleModeSelector",
+      "alt-tab": "agent::CycleFavoriteModels",
+    },
+  },
+  {
+    "context": "AcpThread > Editor && !use_modifier_to_send",
+    "use_key_equivalents": true,
+    "bindings": {
+      "enter": "agent::Chat",
+    },
   },
   {
     "context": "AcpThread > Editor && use_modifier_to_send",
     "use_key_equivalents": true,
     "bindings": {
       "cmd-enter": "agent::Chat",
-      "shift-ctrl-r": "agent::OpenAgentDiff",
-      "cmd-shift-y": "agent::KeepAll",
-      "cmd-shift-n": "agent::RejectAll",
-      "shift-tab": "agent::CycleModeSelector"
-    }
+      "enter": "editor::Newline",
+    },
   },
   {
     "context": "ThreadHistory",
     "bindings": {
-      "ctrl--": "pane::GoBack"
-    }
+      "ctrl--": "pane::GoBack",
+    },
   },
   {
     "context": "ThreadHistory > Editor",
     "bindings": {
-      "shift-backspace": "agent::RemoveSelectedThread"
-    }
+      "shift-backspace": "agent::RemoveSelectedThread",
+    },
   },
   {
     "context": "RulesLibrary",
@@ -416,8 +394,8 @@
     "bindings": {
       "cmd-n": "rules_library::NewRule",
       "cmd-shift-s": "rules_library::ToggleDefaultRule",
-      "cmd-w": "workspace::CloseWindow"
-    }
+      "cmd-w": "workspace::CloseWindow",
+    },
   },
   {
     "context": "BufferSearchBar",
@@ -431,24 +409,24 @@
       "cmd-f": "search::FocusSearch",
       "cmd-alt-f": "search::ToggleReplace",
       "cmd-alt-l": "search::ToggleSelection",
-      "cmd-shift-o": "outline::Toggle"
-    }
+      "cmd-shift-o": "outline::Toggle",
+    },
   },
   {
     "context": "BufferSearchBar && in_replace > Editor",
     "use_key_equivalents": true,
     "bindings": {
       "enter": "search::ReplaceNext",
-      "cmd-enter": "search::ReplaceAll"
-    }
+      "cmd-enter": "search::ReplaceAll",
+    },
   },
   {
     "context": "BufferSearchBar && !in_replace > Editor",
     "use_key_equivalents": true,
     "bindings": {
       "up": "search::PreviousHistoryQuery",
-      "down": "search::NextHistoryQuery"
-    }
+      "down": "search::NextHistoryQuery",
+    },
   },
   {
     "context": "ProjectSearchBar",
@@ -460,24 +438,24 @@
       "cmd-shift-f": "search::FocusSearch",
       "cmd-shift-h": "search::ToggleReplace",
       "alt-cmd-g": "search::ToggleRegex",
-      "alt-cmd-x": "search::ToggleRegex"
-    }
+      "alt-cmd-x": "search::ToggleRegex",
+    },
   },
   {
     "context": "ProjectSearchBar > Editor",
     "use_key_equivalents": true,
     "bindings": {
       "up": "search::PreviousHistoryQuery",
-      "down": "search::NextHistoryQuery"
-    }
+      "down": "search::NextHistoryQuery",
+    },
   },
   {
     "context": "ProjectSearchBar && in_replace > Editor",
     "use_key_equivalents": true,
     "bindings": {
       "enter": "search::ReplaceNext",
-      "cmd-enter": "search::ReplaceAll"
-    }
+      "cmd-enter": "search::ReplaceAll",
+    },
   },
   {
     "context": "ProjectSearchView",
@@ -488,8 +466,8 @@
       "shift-enter": "project_search::ToggleAllSearchResults",
       "cmd-shift-h": "search::ToggleReplace",
       "alt-cmd-g": "search::ToggleRegex",
-      "alt-cmd-x": "search::ToggleRegex"
-    }
+      "alt-cmd-x": "search::ToggleRegex",
+    },
   },
   {
     "context": "Pane",
@@ -519,8 +497,8 @@
       "alt-cmd-w": "search::ToggleWholeWord",
       "alt-cmd-f": "project_search::ToggleFilters",
       "alt-cmd-x": "search::ToggleRegex",
-      "cmd-k shift-enter": "pane::TogglePinTab"
-    }
+      "cmd-k shift-enter": "pane::TogglePinTab",
+    },
   },
   // Bindings from VS Code
   {
@@ -590,24 +568,24 @@
       "cmd-.": "editor::ToggleCodeActions",
       "cmd-k r": "editor::RevealInFileManager",
       "cmd-k p": "editor::CopyPath",
-      "cmd-\\": "pane::SplitRight"
-    }
+      "cmd-\\": "pane::SplitRight",
+    },
   },
   {
     "context": "Editor && extension == md",
     "use_key_equivalents": true,
     "bindings": {
       "cmd-k v": "markdown::OpenPreviewToTheSide",
-      "cmd-shift-v": "markdown::OpenPreview"
-    }
+      "cmd-shift-v": "markdown::OpenPreview",
+    },
   },
   {
     "context": "Editor && extension == svg",
     "use_key_equivalents": true,
     "bindings": {
       "cmd-k v": "svg::OpenPreviewToTheSide",
-      "cmd-shift-v": "svg::OpenPreview"
-    }
+      "cmd-shift-v": "svg::OpenPreview",
+    },
   },
   {
     "context": "Editor && mode == full",
@@ -616,8 +594,8 @@
       "cmd-shift-o": "outline::Toggle",
       "ctrl-g": "go_to_line::Toggle",
       "cmd-shift-backspace": "editor::GoToPreviousChange",
-      "cmd-shift-alt-backspace": "editor::GoToNextChange"
-    }
+      "cmd-shift-alt-backspace": "editor::GoToNextChange",
+    },
   },
   {
     "context": "Pane",
@@ -635,8 +613,8 @@
       "ctrl-0": "pane::ActivateLastItem",
       "ctrl--": "pane::GoBack",
       "ctrl-_": "pane::GoForward",
-      "cmd-shift-f": "pane::DeploySearch"
-    }
+      "cmd-shift-f": "pane::DeploySearch",
+    },
   },
   {
     "context": "Workspace",
@@ -684,8 +662,8 @@
       "ctrl-alt-cmd-p": "settings_profile_selector::Toggle",
       "cmd-t": "project_symbols::Toggle",
       "cmd-p": "file_finder::Toggle",
-      "ctrl-tab": "tab_switcher::Toggle",
       "ctrl-shift-tab": ["tab_switcher::Toggle", { "select_last": true }],
+      "ctrl-tab": "tab_switcher::Toggle",
       "cmd-shift-p": "command_palette::Toggle",
       "cmd-shift-m": "diagnostics::Deploy",
       "cmd-shift-e": "project_panel::ToggleFocus",
@@ -707,8 +685,8 @@
       "cmd-k shift-down": "workspace::SwapPaneDown",
       "cmd-shift-x": "zed::Extensions",
       "f5": "debugger::Rerun",
-      "cmd-w": "workspace::CloseActiveDock"
-    }
+      "cmd-w": "workspace::CloseActiveDock",
+    },
   },
   {
     "context": "Workspace && !Terminal",
@@ -719,27 +697,27 @@
       // All task parameters are captured and unchanged between reruns by default.
       // Use the `"reevaluate_context"` parameter to control this.
       "cmd-alt-r": ["task::Rerun", { "reevaluate_context": false }],
-      "ctrl-alt-shift-r": ["task::Spawn", { "reveal_target": "center" }]
+      "ctrl-alt-shift-r": ["task::Spawn", { "reveal_target": "center" }],
       // also possible to spawn tasks by name:
       // "foo-bar": ["task::Spawn", { "task_name": "MyTask", "reveal_target": "dock" }]
       // or by tag:
       // "foo-bar": ["task::Spawn", { "task_tag": "MyTag" }],
-    }
+    },
   },
   {
     "context": "Workspace && debugger_running",
     "use_key_equivalents": true,
     "bindings": {
       "f5": "zed::NoAction",
-      "f11": "debugger::StepInto"
-    }
+      "f11": "debugger::StepInto",
+    },
   },
   {
     "context": "Workspace && debugger_stopped",
     "use_key_equivalents": true,
     "bindings": {
-      "f5": "debugger::Continue"
-    }
+      "f5": "debugger::Continue",
+    },
   },
   // Bindings from Sublime Text
   {
@@ -760,8 +738,8 @@
       "ctrl-alt-shift-left": "editor::SelectToPreviousSubwordStart",
       "ctrl-alt-shift-b": "editor::SelectToPreviousSubwordStart",
       "ctrl-alt-shift-right": "editor::SelectToNextSubwordEnd",
-      "ctrl-alt-shift-f": "editor::SelectToNextSubwordEnd"
-    }
+      "ctrl-alt-shift-f": "editor::SelectToNextSubwordEnd",
+    },
   },
   // Bindings from Atom
   {
@@ -771,16 +749,16 @@
       "cmd-k up": "pane::SplitUp",
       "cmd-k down": "pane::SplitDown",
       "cmd-k left": "pane::SplitLeft",
-      "cmd-k right": "pane::SplitRight"
-    }
+      "cmd-k right": "pane::SplitRight",
+    },
   },
   // Bindings that should be unified with bindings for more general actions
   {
     "context": "Editor && renaming",
     "use_key_equivalents": true,
     "bindings": {
-      "enter": "editor::ConfirmRename"
-    }
+      "enter": "editor::ConfirmRename",
+    },
   },
   {
     "context": "Editor && showing_completions",
@@ -788,45 +766,47 @@
     "bindings": {
       "enter": "editor::ConfirmCompletion",
       "shift-enter": "editor::ConfirmCompletionReplace",
-      "tab": "editor::ComposeCompletion"
-    }
+      "tab": "editor::ComposeCompletion",
+    },
   },
   {
     "context": "Editor && in_snippet && has_next_tabstop && !showing_completions",
     "use_key_equivalents": true,
     "bindings": {
-      "tab": "editor::NextSnippetTabstop"
-    }
+      "tab": "editor::NextSnippetTabstop",
+    },
   },
   {
     "context": "Editor && in_snippet && has_previous_tabstop && !showing_completions",
     "use_key_equivalents": true,
     "bindings": {
-      "shift-tab": "editor::PreviousSnippetTabstop"
-    }
+      "shift-tab": "editor::PreviousSnippetTabstop",
+    },
   },
   {
     "context": "Editor && edit_prediction",
     "bindings": {
       "alt-tab": "editor::AcceptEditPrediction",
       "tab": "editor::AcceptEditPrediction",
-      "ctrl-cmd-right": "editor::AcceptPartialEditPrediction"
-    }
+      "ctrl-cmd-right": "editor::AcceptNextWordEditPrediction",
+      "ctrl-cmd-down": "editor::AcceptNextLineEditPrediction",
+    },
   },
   {
     "context": "Editor && edit_prediction_conflict",
     "use_key_equivalents": true,
     "bindings": {
       "alt-tab": "editor::AcceptEditPrediction",
-      "ctrl-cmd-right": "editor::AcceptPartialEditPrediction"
-    }
+      "ctrl-cmd-right": "editor::AcceptNextWordEditPrediction",
+      "ctrl-cmd-down": "editor::AcceptNextLineEditPrediction",
+    },
   },
   {
     "context": "Editor && showing_code_actions",
     "use_key_equivalents": true,
     "bindings": {
-      "enter": "editor::ConfirmCodeAction"
-    }
+      "enter": "editor::ConfirmCodeAction",
+    },
   },
   {
     "context": "Editor && (showing_code_actions || showing_completions)",
@@ -837,15 +817,15 @@
       "down": "editor::ContextMenuNext",
       "ctrl-n": "editor::ContextMenuNext",
       "pageup": "editor::ContextMenuFirst",
-      "pagedown": "editor::ContextMenuLast"
-    }
+      "pagedown": "editor::ContextMenuLast",
+    },
   },
   {
     "context": "Editor && showing_signature_help && !showing_completions",
     "bindings": {
       "up": "editor::SignatureHelpPrevious",
-      "down": "editor::SignatureHelpNext"
-    }
+      "down": "editor::SignatureHelpNext",
+    },
   },
   // Custom bindings
   {
@@ -855,8 +835,8 @@
       // TODO: Move this to a dock open action
       "cmd-shift-c": "collab_panel::ToggleFocus",
       // Only available in debug builds: opens an element inspector for development.
-      "cmd-alt-i": "dev::ToggleInspector"
-    }
+      "cmd-alt-i": "dev::ToggleInspector",
+    },
   },
   {
     "context": "!ContextEditor > Editor && mode == full",
@@ -869,17 +849,20 @@
       "cmd-f8": "editor::GoToHunk",
       "cmd-shift-f8": "editor::GoToPreviousHunk",
       "ctrl-enter": "assistant::InlineAssist",
-      "ctrl-:": "editor::ToggleInlayHints"
-    }
+      "ctrl-:": "editor::ToggleInlayHints",
+    },
   },
   {
-    "context": "PromptEditor",
+    "context": "InlineAssistant > Editor",
     "use_key_equivalents": true,
     "bindings": {
       "cmd-alt-/": "agent::ToggleModelSelector",
+      "alt-tab": "agent::CycleFavoriteModels",
       "ctrl-[": "agent::CyclePreviousInlineAssist",
-      "ctrl-]": "agent::CycleNextInlineAssist"
-    }
+      "ctrl-]": "agent::CycleNextInlineAssist",
+      "cmd-shift-enter": "inline_assistant::ThumbsUpResult",
+      "cmd-shift-backspace": "inline_assistant::ThumbsDownResult",
+    },
   },
   {
     "context": "Prompt",
@@ -888,15 +871,15 @@
       "left": "menu::SelectPrevious",
       "right": "menu::SelectNext",
       "h": "menu::SelectPrevious",
-      "l": "menu::SelectNext"
-    }
+      "l": "menu::SelectNext",
+    },
   },
   {
     "context": "ProjectSearchBar && !in_replace",
     "use_key_equivalents": true,
     "bindings": {
-      "cmd-enter": "project_search::SearchInNew"
-    }
+      "cmd-enter": "project_search::SearchInNew",
+    },
   },
   {
     "context": "OutlinePanel && not_editing",
@@ -912,8 +895,8 @@
       "shift-down": "menu::SelectNext",
       "shift-up": "menu::SelectPrevious",
       "alt-enter": "editor::OpenExcerpts",
-      "cmd-alt-enter": "editor::OpenExcerptsSplit"
-    }
+      "cmd-alt-enter": "editor::OpenExcerptsSplit",
+    },
   },
   {
     "context": "ProjectPanel",
@@ -943,15 +926,15 @@
       "cmd-alt-shift-f": "project_panel::NewSearchInDirectory",
       "shift-down": "menu::SelectNext",
       "shift-up": "menu::SelectPrevious",
-      "escape": "menu::Cancel"
-    }
+      "escape": "menu::Cancel",
+    },
   },
   {
     "context": "ProjectPanel && not_editing",
     "use_key_equivalents": true,
     "bindings": {
-      "space": "project_panel::Open"
-    }
+      "space": "project_panel::Open",
+    },
   },
   {
     "context": "VariableList",
@@ -964,17 +947,19 @@
       "cmd-alt-c": "variable_list::CopyVariableName",
       "delete": "variable_list::RemoveWatch",
       "backspace": "variable_list::RemoveWatch",
-      "alt-enter": "variable_list::AddWatch"
-    }
+      "alt-enter": "variable_list::AddWatch",
+    },
   },
   {
     "context": "GitPanel && ChangesList",
     "use_key_equivalents": true,
     "bindings": {
-      "up": "menu::SelectPrevious",
-      "down": "menu::SelectNext",
-      "cmd-up": "menu::SelectFirst",
-      "cmd-down": "menu::SelectLast",
+      "up": "git_panel::PreviousEntry",
+      "down": "git_panel::NextEntry",
+      "cmd-up": "git_panel::FirstEntry",
+      "cmd-down": "git_panel::LastEntry",
+      "left": "git_panel::CollapseSelectedEntry",
+      "right": "git_panel::ExpandSelectedEntry",
       "enter": "menu::Confirm",
       "cmd-alt-y": "git::ToggleStaged",
       "space": "git::ToggleStaged",
@@ -988,15 +973,15 @@
       "backspace": ["git::RestoreFile", { "skip_prompt": false }],
       "delete": ["git::RestoreFile", { "skip_prompt": false }],
       "cmd-backspace": ["git::RestoreFile", { "skip_prompt": true }],
-      "cmd-delete": ["git::RestoreFile", { "skip_prompt": true }]
-    }
+      "cmd-delete": ["git::RestoreFile", { "skip_prompt": true }],
+    },
   },
   {
     "context": "GitPanel && CommitEditor",
     "use_key_equivalents": true,
     "bindings": {
-      "escape": "git::Cancel"
-    }
+      "escape": "git::Cancel",
+    },
   },
   {
     "context": "GitDiff > Editor",
@@ -1005,8 +990,8 @@
       "cmd-enter": "git::Commit",
       "cmd-shift-enter": "git::Amend",
       "cmd-ctrl-y": "git::StageAll",
-      "cmd-ctrl-shift-y": "git::UnstageAll"
-    }
+      "cmd-ctrl-shift-y": "git::UnstageAll",
+    },
   },
   {
     "context": "CommitEditor > Editor",
@@ -1019,8 +1004,8 @@
       "shift-tab": "git_panel::FocusChanges",
       "alt-up": "git_panel::FocusChanges",
       "shift-escape": "git::ExpandCommitEditor",
-      "alt-tab": "git::GenerateCommitMessage"
-    }
+      "alt-tab": "git::GenerateCommitMessage",
+    },
   },
   {
     "context": "GitPanel",
@@ -1037,8 +1022,8 @@
       "cmd-ctrl-y": "git::StageAll",
       "cmd-ctrl-shift-y": "git::UnstageAll",
       "cmd-enter": "git::Commit",
-      "cmd-shift-enter": "git::Amend"
-    }
+      "cmd-shift-enter": "git::Amend",
+    },
   },
   {
     "context": "GitCommit > Editor",
@@ -1048,16 +1033,16 @@
       "escape": "menu::Cancel",
       "cmd-enter": "git::Commit",
       "cmd-shift-enter": "git::Amend",
-      "alt-tab": "git::GenerateCommitMessage"
-    }
+      "alt-tab": "git::GenerateCommitMessage",
+    },
   },
   {
     "context": "DebugPanel",
     "bindings": {
       "cmd-t": "debugger::ToggleThreadPicker",
       "cmd-i": "debugger::ToggleSessionPicker",
-      "shift-alt-escape": "debugger::ToggleExpandItem"
-    }
+      "shift-alt-escape": "debugger::ToggleExpandItem",
+    },
   },
   {
     "context": "BreakpointList",
@@ -1065,16 +1050,16 @@
       "space": "debugger::ToggleEnableBreakpoint",
       "backspace": "debugger::UnsetBreakpoint",
       "left": "debugger::PreviousBreakpointProperty",
-      "right": "debugger::NextBreakpointProperty"
-    }
+      "right": "debugger::NextBreakpointProperty",
+    },
   },
   {
     "context": "CollabPanel && not_editing",
     "use_key_equivalents": true,
     "bindings": {
       "ctrl-backspace": "collab_panel::Remove",
-      "space": "menu::Confirm"
-    }
+      "space": "menu::Confirm",
+    },
   },
   {
     "context": "CollabPanel",
@@ -1082,22 +1067,22 @@
     "bindings": {
       "alt-up": "collab_panel::MoveChannelUp",
       "alt-down": "collab_panel::MoveChannelDown",
-      "alt-enter": "collab_panel::OpenSelectedChannelNotes"
-    }
+      "alt-enter": "collab_panel::OpenSelectedChannelNotes",
+    },
   },
   {
     "context": "(CollabPanel && editing) > Editor",
     "use_key_equivalents": true,
     "bindings": {
-      "space": "collab_panel::InsertSpace"
-    }
+      "space": "collab_panel::InsertSpace",
+    },
   },
   {
     "context": "ChannelModal",
     "use_key_equivalents": true,
     "bindings": {
-      "tab": "channel_modal::ToggleMode"
-    }
+      "tab": "channel_modal::ToggleMode",
+    },
   },
   {
     "context": "Picker > Editor",
@@ -1108,30 +1093,30 @@
       "down": "menu::SelectNext",
       "tab": "picker::ConfirmCompletion",
       "alt-enter": ["picker::ConfirmInput", { "secondary": false }],
-      "cmd-alt-enter": ["picker::ConfirmInput", { "secondary": true }]
-    }
+      "cmd-alt-enter": ["picker::ConfirmInput", { "secondary": true }],
+    },
   },
   {
     "context": "ChannelModal > Picker > Editor",
     "use_key_equivalents": true,
     "bindings": {
-      "tab": "channel_modal::ToggleMode"
-    }
+      "tab": "channel_modal::ToggleMode",
+    },
   },
   {
     "context": "ToolchainSelector",
     "use_key_equivalents": true,
     "bindings": {
-      "cmd-shift-a": "toolchain::AddToolchain"
-    }
+      "cmd-shift-a": "toolchain::AddToolchain",
+    },
   },
   {
     "context": "FileFinder || (FileFinder > Picker > Editor)",
     "use_key_equivalents": true,
     "bindings": {
       "cmd-shift-a": "file_finder::ToggleSplitMenu",
-      "cmd-shift-i": "file_finder::ToggleFilterMenu"
-    }
+      "cmd-shift-i": "file_finder::ToggleFilterMenu",
+    },
   },
   {
     "context": "FileFinder || (FileFinder > Picker > Editor) || (FileFinder > Picker > menu)",
@@ -1141,8 +1126,8 @@
       "cmd-j": "pane::SplitDown",
       "cmd-k": "pane::SplitUp",
       "cmd-h": "pane::SplitLeft",
-      "cmd-l": "pane::SplitRight"
-    }
+      "cmd-l": "pane::SplitRight",
+    },
   },
   {
     "context": "TabSwitcher",
@@ -1151,16 +1136,16 @@
       "ctrl-shift-tab": "menu::SelectPrevious",
       "ctrl-up": "menu::SelectPrevious",
       "ctrl-down": "menu::SelectNext",
-      "ctrl-backspace": "tab_switcher::CloseSelectedItem"
-    }
+      "ctrl-backspace": "tab_switcher::CloseSelectedItem",
+    },
   },
   {
     "context": "StashList || (StashList > Picker > Editor)",
     "use_key_equivalents": true,
     "bindings": {
       "ctrl-shift-backspace": "stash_picker::DropStashItem",
-      "ctrl-shift-v": "stash_picker::ShowStashItem"
-    }
+      "ctrl-shift-v": "stash_picker::ShowStashItem",
+    },
   },
   {
     "context": "Terminal",
@@ -1215,8 +1200,8 @@
       "ctrl-alt-left": "pane::SplitLeft",
       "ctrl-alt-right": "pane::SplitRight",
       "cmd-d": "pane::SplitRight",
-      "cmd-alt-r": "terminal::RerunTask"
-    }
+      "cmd-alt-r": "terminal::RerunTask",
+    },
   },
   {
     "context": "RatePredictionsModal",
@@ -1226,8 +1211,8 @@
       "cmd-shift-backspace": "zeta::ThumbsDownActivePrediction",
       "shift-down": "zeta::NextEdit",
       "shift-up": "zeta::PreviousEdit",
-      "right": "zeta::PreviewPrediction"
-    }
+      "right": "zeta::PreviewPrediction",
+    },
   },
   {
     "context": "RatePredictionsModal > Editor",
@@ -1235,15 +1220,15 @@
     "bindings": {
       "escape": "zeta::FocusPredictions",
       "cmd-shift-enter": "zeta::ThumbsUpActivePrediction",
-      "cmd-shift-backspace": "zeta::ThumbsDownActivePrediction"
-    }
+      "cmd-shift-backspace": "zeta::ThumbsDownActivePrediction",
+    },
   },
   {
     "context": "ZedPredictModal",
     "use_key_equivalents": true,
     "bindings": {
-      "escape": "menu::Cancel"
-    }
+      "escape": "menu::Cancel",
+    },
   },
   {
     "context": "ConfigureContextServerModal > Editor",
@@ -1251,52 +1236,56 @@
     "bindings": {
       "escape": "menu::Cancel",
       "enter": "editor::Newline",
-      "cmd-enter": "menu::Confirm"
-    }
+      "cmd-enter": "menu::Confirm",
+    },
   },
   {
     "context": "ContextServerToolsModal",
     "use_key_equivalents": true,
     "bindings": {
-      "escape": "menu::Cancel"
-    }
+      "escape": "menu::Cancel",
+    },
   },
   {
     "context": "OnboardingAiConfigurationModal",
     "use_key_equivalents": true,
     "bindings": {
-      "escape": "menu::Cancel"
-    }
+      "escape": "menu::Cancel",
+    },
   },
   {
     "context": "Diagnostics",
     "use_key_equivalents": true,
     "bindings": {
-      "ctrl-r": "diagnostics::ToggleDiagnosticsRefresh"
-    }
+      "ctrl-r": "diagnostics::ToggleDiagnosticsRefresh",
+    },
   },
   {
     "context": "DebugConsole > Editor",
     "use_key_equivalents": true,
     "bindings": {
       "enter": "menu::Confirm",
-      "alt-enter": "console::WatchExpression"
-    }
+      "alt-enter": "console::WatchExpression",
+    },
   },
   {
     "context": "RunModal",
     "use_key_equivalents": true,
     "bindings": {
       "ctrl-tab": "pane::ActivateNextItem",
-      "ctrl-shift-tab": "pane::ActivatePreviousItem"
-    }
+      "ctrl-shift-tab": "pane::ActivatePreviousItem",
+    },
   },
   {
     "context": "MarkdownPreview",
     "bindings": {
-      "pageup": "markdown::MovePageUp",
-      "pagedown": "markdown::MovePageDown"
-    }
+      "pageup": "markdown::ScrollPageUp",
+      "pagedown": "markdown::ScrollPageDown",
+      "up": "markdown::ScrollUp",
+      "down": "markdown::ScrollDown",
+      "alt-up": "markdown::ScrollUpByItem",
+      "alt-down": "markdown::ScrollDownByItem",
+    },
   },
   {
     "context": "KeymapEditor",

assets/keymaps/default-windows.json 🔗

@@ -24,7 +24,8 @@
       "ctrl-alt-enter": ["picker::ConfirmInput", { "secondary": true }],
       "ctrl-shift-w": "workspace::CloseWindow",
       "shift-escape": "workspace::ToggleZoom",
-      "ctrl-o": "workspace::Open",
+      "ctrl-o": "workspace::OpenFiles",
+      "ctrl-k ctrl-o": "workspace::Open",
       "ctrl-=": ["zed::IncreaseBufferFontSize", { "persist": false }],
       "ctrl-shift-=": ["zed::IncreaseBufferFontSize", { "persist": false }],
       "ctrl--": ["zed::DecreaseBufferFontSize", { "persist": false }],
@@ -41,16 +42,17 @@
       "f11": "zed::ToggleFullScreen",
       "ctrl-shift-i": "edit_prediction::ToggleMenu",
       "shift-alt-l": "lsp_tool::ToggleMenu",
-      "ctrl-shift-alt-c": "editor::DisplayCursorNames"
-    }
+      "ctrl-shift-alt-c": "editor::DisplayCursorNames",
+      "ctrl-shift-alt-s": "workspace::ToggleWorktreeSecurity",
+    },
   },
   {
     "context": "Picker || menu",
     "use_key_equivalents": true,
     "bindings": {
       "up": "menu::SelectPrevious",
-      "down": "menu::SelectNext"
-    }
+      "down": "menu::SelectNext",
+    },
   },
   {
     "context": "Editor",
@@ -62,7 +64,6 @@
       "delete": "editor::Delete",
       "tab": "editor::Tab",
       "shift-tab": "editor::Backtab",
-      "ctrl-k": "editor::CutToEndOfLine",
       "ctrl-k ctrl-q": "editor::Rewrap",
       "ctrl-k q": "editor::Rewrap",
       "ctrl-backspace": ["editor::DeleteToPreviousWordStart", { "ignore_newlines": false, "ignore_brackets": false }],
@@ -119,8 +120,8 @@
       "shift-f10": "editor::OpenContextMenu",
       "ctrl-alt-e": "editor::ToggleEditPrediction",
       "f9": "editor::ToggleBreakpoint",
-      "shift-f9": "editor::EditLogBreakpoint"
-    }
+      "shift-f9": "editor::EditLogBreakpoint",
+    },
   },
   {
     "context": "Editor && mode == full",
@@ -139,23 +140,23 @@
       "shift-alt-e": "editor::SelectEnclosingSymbol",
       "ctrl-shift-backspace": "editor::GoToPreviousChange",
       "ctrl-shift-alt-backspace": "editor::GoToNextChange",
-      "alt-enter": "editor::OpenSelectionsInMultibuffer"
-    }
+      "alt-enter": "editor::OpenSelectionsInMultibuffer",
+    },
   },
   {
     "context": "Editor && mode == full && edit_prediction",
     "use_key_equivalents": true,
     "bindings": {
       "alt-]": "editor::NextEditPrediction",
-      "alt-[": "editor::PreviousEditPrediction"
-    }
+      "alt-[": "editor::PreviousEditPrediction",
+    },
   },
   {
     "context": "Editor && !edit_prediction",
     "use_key_equivalents": true,
     "bindings": {
-      "alt-\\": "editor::ShowEditPrediction"
-    }
+      "alt-\\": "editor::ShowEditPrediction",
+    },
   },
   {
     "context": "Editor && mode == auto_height",
@@ -163,23 +164,23 @@
     "bindings": {
       "ctrl-enter": "editor::Newline",
       "shift-enter": "editor::Newline",
-      "ctrl-shift-enter": "editor::NewlineBelow"
-    }
+      "ctrl-shift-enter": "editor::NewlineBelow",
+    },
   },
   {
     "context": "Markdown",
     "use_key_equivalents": true,
     "bindings": {
-      "ctrl-c": "markdown::Copy"
-    }
+      "ctrl-c": "markdown::Copy",
+    },
   },
   {
     "context": "Editor && jupyter && !ContextEditor",
     "use_key_equivalents": true,
     "bindings": {
       "ctrl-shift-enter": "repl::Run",
-      "ctrl-alt-enter": "repl::RunInPlace"
-    }
+      "ctrl-alt-enter": "repl::RunInPlace",
+    },
   },
   {
     "context": "Editor && !agent_diff",
@@ -187,8 +188,8 @@
     "bindings": {
       "ctrl-k ctrl-r": "git::Restore",
       "alt-y": "git::StageAndNext",
-      "shift-alt-y": "git::UnstageAndNext"
-    }
+      "shift-alt-y": "git::UnstageAndNext",
+    },
   },
   {
     "context": "Editor && editor_agent_diff",
@@ -198,8 +199,8 @@
       "ctrl-n": "agent::Reject",
       "ctrl-shift-y": "agent::KeepAll",
       "ctrl-shift-n": "agent::RejectAll",
-      "ctrl-shift-r": "agent::OpenAgentDiff"
-    }
+      "ctrl-shift-r": "agent::OpenAgentDiff",
+    },
   },
   {
     "context": "AgentDiff",
@@ -208,8 +209,8 @@
       "ctrl-y": "agent::Keep",
       "ctrl-n": "agent::Reject",
       "ctrl-shift-y": "agent::KeepAll",
-      "ctrl-shift-n": "agent::RejectAll"
-    }
+      "ctrl-shift-n": "agent::RejectAll",
+    },
   },
   {
     "context": "ContextEditor > Editor",
@@ -225,8 +226,9 @@
       "ctrl-k c": "assistant::CopyCode",
       "ctrl-g": "search::SelectNextMatch",
       "ctrl-shift-g": "search::SelectPreviousMatch",
-      "ctrl-k l": "agent::OpenRulesLibrary"
-    }
+      "ctrl-k l": "agent::OpenRulesLibrary",
+      "ctrl-shift-v": "agent::PasteRaw",
+    },
   },
   {
     "context": "AgentPanel",
@@ -239,6 +241,7 @@
       "shift-alt-l": "agent::OpenRulesLibrary",
       "shift-alt-p": "agent::ManageProfiles",
       "ctrl-i": "agent::ToggleProfileSelector",
+      "alt-tab": "agent::CycleFavoriteModels",
       "shift-alt-/": "agent::ToggleModelSelector",
       "shift-alt-j": "agent::ToggleNavigationMenu",
       "shift-alt-i": "agent::ToggleOptionsMenu",
@@ -251,71 +254,38 @@
       "alt-enter": "agent::ContinueWithBurnMode",
       "shift-alt-a": "agent::AllowOnce",
       "ctrl-alt-y": "agent::AllowAlways",
-      "shift-alt-z": "agent::RejectOnce"
-    }
+      "shift-alt-z": "agent::RejectOnce",
+    },
   },
   {
     "context": "AgentPanel > NavigationMenu",
     "use_key_equivalents": true,
     "bindings": {
-      "shift-backspace": "agent::DeleteRecentlyOpenThread"
-    }
+      "shift-backspace": "agent::DeleteRecentlyOpenThread",
+    },
   },
   {
     "context": "AgentPanel > Markdown",
     "use_key_equivalents": true,
     "bindings": {
-      "ctrl-c": "markdown::CopyAsMarkdown"
-    }
+      "ctrl-c": "markdown::CopyAsMarkdown",
+    },
   },
   {
     "context": "AgentPanel && text_thread",
     "use_key_equivalents": true,
     "bindings": {
       "ctrl-n": "agent::NewTextThread",
-      "ctrl-alt-t": "agent::NewThread"
-    }
+      "ctrl-alt-t": "agent::NewThread",
+    },
   },
   {
     "context": "AgentPanel && acp_thread",
     "use_key_equivalents": true,
     "bindings": {
       "ctrl-n": "agent::NewExternalAgentThread",
-      "ctrl-alt-t": "agent::NewThread"
-    }
-  },
-  {
-    "context": "MessageEditor && !Picker > Editor && !use_modifier_to_send",
-    "use_key_equivalents": true,
-    "bindings": {
-      "enter": "agent::Chat",
-      "ctrl-enter": "agent::ChatWithFollow",
-      "ctrl-i": "agent::ToggleProfileSelector",
-      "ctrl-shift-r": "agent::OpenAgentDiff",
-      "ctrl-shift-y": "agent::KeepAll",
-      "ctrl-shift-n": "agent::RejectAll"
-    }
-  },
-  {
-    "context": "MessageEditor && !Picker > Editor && use_modifier_to_send",
-    "use_key_equivalents": true,
-    "bindings": {
-      "ctrl-enter": "agent::Chat",
-      "enter": "editor::Newline",
-      "ctrl-i": "agent::ToggleProfileSelector",
-      "ctrl-shift-r": "agent::OpenAgentDiff",
-      "ctrl-shift-y": "agent::KeepAll",
-      "ctrl-shift-n": "agent::RejectAll"
-    }
-  },
-  {
-    "context": "EditMessageEditor > Editor",
-    "use_key_equivalents": true,
-    "bindings": {
-      "escape": "menu::Cancel",
-      "enter": "menu::Confirm",
-      "alt-enter": "editor::Newline"
-    }
+      "ctrl-alt-t": "agent::NewThread",
+    },
   },
   {
     "context": "AgentFeedbackMessageEditor > Editor",
@@ -323,43 +293,50 @@
     "bindings": {
       "escape": "menu::Cancel",
       "enter": "menu::Confirm",
-      "alt-enter": "editor::Newline"
-    }
+      "alt-enter": "editor::Newline",
+    },
   },
   {
     "context": "AcpThread > ModeSelector",
     "bindings": {
-      "ctrl-enter": "menu::Confirm"
-    }
+      "ctrl-enter": "menu::Confirm",
+    },
   },
   {
-    "context": "AcpThread > Editor && !use_modifier_to_send",
+    "context": "AcpThread > Editor",
     "use_key_equivalents": true,
     "bindings": {
-      "enter": "agent::Chat",
+      "ctrl-enter": "agent::ChatWithFollow",
+      "ctrl-i": "agent::ToggleProfileSelector",
       "ctrl-shift-r": "agent::OpenAgentDiff",
       "ctrl-shift-y": "agent::KeepAll",
       "ctrl-shift-n": "agent::RejectAll",
-      "shift-tab": "agent::CycleModeSelector"
-    }
+      "ctrl-shift-v": "agent::PasteRaw",
+      "shift-tab": "agent::CycleModeSelector",
+      "alt-tab": "agent::CycleFavoriteModels",
+    },
+  },
+  {
+    "context": "AcpThread > Editor && !use_modifier_to_send",
+    "use_key_equivalents": true,
+    "bindings": {
+      "enter": "agent::Chat",
+    },
   },
   {
     "context": "AcpThread > Editor && use_modifier_to_send",
     "use_key_equivalents": true,
     "bindings": {
       "ctrl-enter": "agent::Chat",
-      "ctrl-shift-r": "agent::OpenAgentDiff",
-      "ctrl-shift-y": "agent::KeepAll",
-      "ctrl-shift-n": "agent::RejectAll",
-      "shift-tab": "agent::CycleModeSelector"
-    }
+      "enter": "editor::Newline",
+    },
   },
   {
     "context": "ThreadHistory",
     "use_key_equivalents": true,
     "bindings": {
-      "backspace": "agent::RemoveSelectedThread"
-    }
+      "backspace": "agent::RemoveSelectedThread",
+    },
   },
   {
     "context": "RulesLibrary",
@@ -367,8 +344,8 @@
     "bindings": {
       "ctrl-n": "rules_library::NewRule",
       "ctrl-shift-s": "rules_library::ToggleDefaultRule",
-      "ctrl-w": "workspace::CloseWindow"
-    }
+      "ctrl-w": "workspace::CloseWindow",
+    },
   },
   {
     "context": "BufferSearchBar",
@@ -381,24 +358,24 @@
       "alt-enter": "search::SelectAllMatches",
       "ctrl-f": "search::FocusSearch",
       "ctrl-h": "search::ToggleReplace",
-      "ctrl-l": "search::ToggleSelection"
-    }
+      "ctrl-l": "search::ToggleSelection",
+    },
   },
   {
     "context": "BufferSearchBar && in_replace > Editor",
     "use_key_equivalents": true,
     "bindings": {
       "enter": "search::ReplaceNext",
-      "ctrl-enter": "search::ReplaceAll"
-    }
+      "ctrl-enter": "search::ReplaceAll",
+    },
   },
   {
     "context": "BufferSearchBar && !in_replace > Editor",
     "use_key_equivalents": true,
     "bindings": {
       "up": "search::PreviousHistoryQuery",
-      "down": "search::NextHistoryQuery"
-    }
+      "down": "search::NextHistoryQuery",
+    },
   },
   {
     "context": "ProjectSearchBar",
@@ -407,24 +384,24 @@
       "escape": "project_search::ToggleFocus",
       "ctrl-shift-f": "search::FocusSearch",
       "ctrl-shift-h": "search::ToggleReplace",
-      "alt-r": "search::ToggleRegex" // vscode
-    }
+      "alt-r": "search::ToggleRegex", // vscode
+    },
   },
   {
     "context": "ProjectSearchBar > Editor",
     "use_key_equivalents": true,
     "bindings": {
       "up": "search::PreviousHistoryQuery",
-      "down": "search::NextHistoryQuery"
-    }
+      "down": "search::NextHistoryQuery",
+    },
   },
   {
     "context": "ProjectSearchBar && in_replace > Editor",
     "use_key_equivalents": true,
     "bindings": {
       "enter": "search::ReplaceNext",
-      "ctrl-alt-enter": "search::ReplaceAll"
-    }
+      "ctrl-alt-enter": "search::ReplaceAll",
+    },
   },
   {
     "context": "ProjectSearchView",
@@ -432,8 +409,8 @@
     "bindings": {
       "escape": "project_search::ToggleFocus",
       "ctrl-shift-h": "search::ToggleReplace",
-      "alt-r": "search::ToggleRegex" // vscode
-    }
+      "alt-r": "search::ToggleRegex", // vscode
+    },
   },
   {
     "context": "Pane",
@@ -464,8 +441,10 @@
       "ctrl-k ctrl-w": "workspace::CloseAllItemsAndPanes",
       "back": "pane::GoBack",
       "alt--": "pane::GoBack",
+      "alt-left": "pane::GoBack",
       "forward": "pane::GoForward",
       "alt-=": "pane::GoForward",
+      "alt-right": "pane::GoForward",
       "f3": "search::SelectNextMatch",
       "shift-f3": "search::SelectPreviousMatch",
       "ctrl-shift-f": "project_search::ToggleFocus",
@@ -478,8 +457,8 @@
       "shift-enter": "project_search::ToggleAllSearchResults",
       "alt-r": "search::ToggleRegex",
       // "ctrl-shift-alt-x": "search::ToggleRegex",
-      "ctrl-k shift-enter": "pane::TogglePinTab"
-    }
+      "ctrl-k shift-enter": "pane::TogglePinTab",
+    },
   },
   // Bindings from VS Code
   {
@@ -488,8 +467,8 @@
     "bindings": {
       "ctrl-[": "editor::Outdent",
       "ctrl-]": "editor::Indent",
-      "ctrl-shift-alt-up": ["editor::AddSelectionAbove", { "skip_soft_wrap": true }], // Insert Cursor Above
-      "ctrl-shift-alt-down": ["editor::AddSelectionBelow", { "skip_soft_wrap": true }], // Insert Cursor Below
+      "ctrl-alt-up": ["editor::AddSelectionAbove", { "skip_soft_wrap": true }], // Insert Cursor Above
+      "ctrl-alt-down": ["editor::AddSelectionBelow", { "skip_soft_wrap": true }], // Insert Cursor Below
       "ctrl-shift-k": "editor::DeleteLine",
       "alt-up": "editor::MoveLineUp",
       "alt-down": "editor::MoveLineDown",
@@ -500,10 +479,14 @@
       "ctrl-shift-l": "editor::SelectAllMatches", // Select all occurrences of current selection
       "ctrl-f2": "editor::SelectAllMatches", // Select all occurrences of current word
       "ctrl-d": ["editor::SelectNext", { "replace_newest": false }], // editor.action.addSelectionToNextFindMatch  / find_under_expand
+      "ctrl-f3": ["editor::SelectNext", { "replace_newest": false }], // editor.action.addSelectionToNextFindMatch  / find_under_expand
       "ctrl-k ctrl-d": ["editor::SelectNext", { "replace_newest": true }], // editor.action.moveSelectionToNextFindMatch  / find_under_expand_skip
+      "ctrl-shift-f3": ["editor::SelectPrevious", { "replace_newest": false }], // editor.action.addSelectionToNextFindMatch  / find_under_expand
       "ctrl-k ctrl-i": "editor::Hover",
       "ctrl-k ctrl-b": "editor::BlameHover",
+      "ctrl-k ctrl-f": "editor::FormatSelections",
       "ctrl-/": ["editor::ToggleComments", { "advance_downwards": false }],
+      "ctrl-k ctrl-c": ["editor::ToggleComments", { "advance_downwards": false }],
       "f8": ["editor::GoToDiagnostic", { "severity": { "min": "hint", "max": "error" } }],
       "shift-f8": ["editor::GoToPreviousDiagnostic", { "severity": { "min": "hint", "max": "error" } }],
       "f2": "editor::Rename",
@@ -535,32 +518,32 @@
       "ctrl-k p": "editor::CopyPath",
       "ctrl-\\": "pane::SplitRight",
       "alt-.": "editor::GoToHunk",
-      "alt-,": "editor::GoToPreviousHunk"
-    }
+      "alt-,": "editor::GoToPreviousHunk",
+    },
   },
   {
     "context": "Editor && extension == md",
     "use_key_equivalents": true,
     "bindings": {
       "ctrl-k v": "markdown::OpenPreviewToTheSide",
-      "ctrl-shift-v": "markdown::OpenPreview"
-    }
+      "ctrl-shift-v": "markdown::OpenPreview",
+    },
   },
   {
     "context": "Editor && extension == svg",
     "use_key_equivalents": true,
     "bindings": {
       "ctrl-k v": "svg::OpenPreviewToTheSide",
-      "ctrl-shift-v": "svg::OpenPreview"
-    }
+      "ctrl-shift-v": "svg::OpenPreview",
+    },
   },
   {
     "context": "Editor && mode == full",
     "use_key_equivalents": true,
     "bindings": {
       "ctrl-shift-o": "outline::Toggle",
-      "ctrl-g": "go_to_line::Toggle"
-    }
+      "ctrl-g": "go_to_line::Toggle",
+    },
   },
   {
     "context": "Workspace",
@@ -608,8 +591,8 @@
       "ctrl-alt-super-p": "settings_profile_selector::Toggle",
       "ctrl-t": "project_symbols::Toggle",
       "ctrl-p": "file_finder::Toggle",
-      "ctrl-tab": "tab_switcher::Toggle",
       "ctrl-shift-tab": ["tab_switcher::Toggle", { "select_last": true }],
+      "ctrl-tab": "tab_switcher::Toggle",
       "ctrl-e": "file_finder::Toggle",
       "f1": "command_palette::Toggle",
       "ctrl-shift-p": "command_palette::Toggle",
@@ -644,22 +627,22 @@
       // "foo-bar": ["task::Spawn", { "task_tag": "MyTag" }],
       "f5": "debugger::Rerun",
       "ctrl-f4": "workspace::CloseActiveDock",
-      "ctrl-w": "workspace::CloseActiveDock"
-    }
+      "ctrl-w": "workspace::CloseActiveDock",
+    },
   },
   {
     "context": "Workspace && debugger_running",
     "use_key_equivalents": true,
     "bindings": {
-      "f5": "zed::NoAction"
-    }
+      "f5": "zed::NoAction",
+    },
   },
   {
     "context": "Workspace && debugger_stopped",
     "use_key_equivalents": true,
     "bindings": {
-      "f5": "debugger::Continue"
-    }
+      "f5": "debugger::Continue",
+    },
   },
   {
     "context": "ApplicationMenu",
@@ -667,8 +650,8 @@
     "bindings": {
       "f10": "menu::Cancel",
       "left": "app_menu::ActivateMenuLeft",
-      "right": "app_menu::ActivateMenuRight"
-    }
+      "right": "app_menu::ActivateMenuRight",
+    },
   },
   // Bindings from Sublime Text
   {
@@ -685,8 +668,8 @@
       "ctrl-alt-left": "editor::MoveToPreviousSubwordStart",
       "ctrl-alt-right": "editor::MoveToNextSubwordEnd",
       "ctrl-shift-alt-left": "editor::SelectToPreviousSubwordStart",
-      "ctrl-shift-alt-right": "editor::SelectToNextSubwordEnd"
-    }
+      "ctrl-shift-alt-right": "editor::SelectToNextSubwordEnd",
+    },
   },
   // Bindings from Atom
   {
@@ -696,16 +679,16 @@
       "ctrl-k up": "pane::SplitUp",
       "ctrl-k down": "pane::SplitDown",
       "ctrl-k left": "pane::SplitLeft",
-      "ctrl-k right": "pane::SplitRight"
-    }
+      "ctrl-k right": "pane::SplitRight",
+    },
   },
   // Bindings that should be unified with bindings for more general actions
   {
     "context": "Editor && renaming",
     "use_key_equivalents": true,
     "bindings": {
-      "enter": "editor::ConfirmRename"
-    }
+      "enter": "editor::ConfirmRename",
+    },
   },
   {
     "context": "Editor && showing_completions",
@@ -713,22 +696,22 @@
     "bindings": {
       "enter": "editor::ConfirmCompletion",
       "shift-enter": "editor::ConfirmCompletionReplace",
-      "tab": "editor::ComposeCompletion"
-    }
+      "tab": "editor::ComposeCompletion",
+    },
   },
   {
     "context": "Editor && in_snippet && has_next_tabstop && !showing_completions",
     "use_key_equivalents": true,
     "bindings": {
-      "tab": "editor::NextSnippetTabstop"
-    }
+      "tab": "editor::NextSnippetTabstop",
+    },
   },
   {
     "context": "Editor && in_snippet && has_previous_tabstop && !showing_completions",
     "use_key_equivalents": true,
     "bindings": {
-      "shift-tab": "editor::PreviousSnippetTabstop"
-    }
+      "shift-tab": "editor::PreviousSnippetTabstop",
+    },
   },
   // Bindings for accepting edit predictions
   //
@@ -741,8 +724,9 @@
       "alt-tab": "editor::AcceptEditPrediction",
       "alt-l": "editor::AcceptEditPrediction",
       "tab": "editor::AcceptEditPrediction",
-      "alt-right": "editor::AcceptPartialEditPrediction"
-    }
+      "alt-right": "editor::AcceptNextWordEditPrediction",
+      "alt-down": "editor::AcceptNextLineEditPrediction",
+    },
   },
   {
     "context": "Editor && edit_prediction_conflict",
@@ -750,15 +734,16 @@
     "bindings": {
       "alt-tab": "editor::AcceptEditPrediction",
       "alt-l": "editor::AcceptEditPrediction",
-      "alt-right": "editor::AcceptPartialEditPrediction"
-    }
+      "alt-right": "editor::AcceptNextWordEditPrediction",
+      "alt-down": "editor::AcceptNextLineEditPrediction",
+    },
   },
   {
     "context": "Editor && showing_code_actions",
     "use_key_equivalents": true,
     "bindings": {
-      "enter": "editor::ConfirmCodeAction"
-    }
+      "enter": "editor::ConfirmCodeAction",
+    },
   },
   {
     "context": "Editor && (showing_code_actions || showing_completions)",
@@ -769,16 +754,16 @@
       "ctrl-n": "editor::ContextMenuNext",
       "down": "editor::ContextMenuNext",
       "pageup": "editor::ContextMenuFirst",
-      "pagedown": "editor::ContextMenuLast"
-    }
+      "pagedown": "editor::ContextMenuLast",
+    },
   },
   {
     "context": "Editor && showing_signature_help && !showing_completions",
     "use_key_equivalents": true,
     "bindings": {
       "up": "editor::SignatureHelpPrevious",
-      "down": "editor::SignatureHelpNext"
-    }
+      "down": "editor::SignatureHelpNext",
+    },
   },
   // Custom bindings
   {
@@ -786,15 +771,15 @@
     "bindings": {
       "ctrl-shift-alt-f": "workspace::FollowNextCollaborator",
       // Only available in debug builds: opens an element inspector for development.
-      "shift-alt-i": "dev::ToggleInspector"
-    }
+      "shift-alt-i": "dev::ToggleInspector",
+    },
   },
   {
     "context": "!Terminal",
     "use_key_equivalents": true,
     "bindings": {
-      "ctrl-shift-c": "collab_panel::ToggleFocus"
-    }
+      "ctrl-shift-c": "collab_panel::ToggleFocus",
+    },
   },
   {
     "context": "!ContextEditor > Editor && mode == full",
@@ -807,16 +792,18 @@
       "ctrl-f8": "editor::GoToHunk",
       "ctrl-shift-f8": "editor::GoToPreviousHunk",
       "ctrl-enter": "assistant::InlineAssist",
-      "ctrl-shift-;": "editor::ToggleInlayHints"
-    }
+      "ctrl-shift-;": "editor::ToggleInlayHints",
+    },
   },
   {
-    "context": "PromptEditor",
+    "context": "InlineAssistant",
     "use_key_equivalents": true,
     "bindings": {
       "ctrl-[": "agent::CyclePreviousInlineAssist",
-      "ctrl-]": "agent::CycleNextInlineAssist"
-    }
+      "ctrl-]": "agent::CycleNextInlineAssist",
+      "ctrl-shift-enter": "inline_assistant::ThumbsUpResult",
+      "ctrl-shift-delete": "inline_assistant::ThumbsDownResult",
+    },
   },
   {
     "context": "Prompt",
@@ -825,15 +812,15 @@
       "left": "menu::SelectPrevious",
       "right": "menu::SelectNext",
       "h": "menu::SelectPrevious",
-      "l": "menu::SelectNext"
-    }
+      "l": "menu::SelectNext",
+    },
   },
   {
     "context": "ProjectSearchBar && !in_replace",
     "use_key_equivalents": true,
     "bindings": {
-      "ctrl-enter": "project_search::SearchInNew"
-    }
+      "ctrl-enter": "project_search::SearchInNew",
+    },
   },
   {
     "context": "OutlinePanel && not_editing",
@@ -848,8 +835,8 @@
       "shift-down": "menu::SelectNext",
       "shift-up": "menu::SelectPrevious",
       "alt-enter": "editor::OpenExcerpts",
-      "ctrl-alt-enter": "editor::OpenExcerptsSplit"
-    }
+      "ctrl-alt-enter": "editor::OpenExcerptsSplit",
+    },
   },
   {
     "context": "ProjectPanel",
@@ -880,22 +867,24 @@
       "ctrl-k ctrl-shift-f": "project_panel::NewSearchInDirectory",
       "shift-down": "menu::SelectNext",
       "shift-up": "menu::SelectPrevious",
-      "escape": "menu::Cancel"
-    }
+      "escape": "menu::Cancel",
+    },
   },
   {
     "context": "ProjectPanel && not_editing",
     "use_key_equivalents": true,
     "bindings": {
-      "space": "project_panel::Open"
-    }
+      "space": "project_panel::Open",
+    },
   },
   {
     "context": "GitPanel && ChangesList",
     "use_key_equivalents": true,
     "bindings": {
-      "up": "menu::SelectPrevious",
-      "down": "menu::SelectNext",
+      "up": "git_panel::PreviousEntry",
+      "down": "git_panel::NextEntry",
+      "left": "git_panel::CollapseSelectedEntry",
+      "right": "git_panel::ExpandSelectedEntry",
       "enter": "menu::Confirm",
       "alt-y": "git::StageFile",
       "shift-alt-y": "git::UnstageFile",
@@ -909,15 +898,15 @@
       "backspace": ["git::RestoreFile", { "skip_prompt": false }],
       "shift-delete": ["git::RestoreFile", { "skip_prompt": false }],
       "ctrl-backspace": ["git::RestoreFile", { "skip_prompt": false }],
-      "ctrl-delete": ["git::RestoreFile", { "skip_prompt": false }]
-    }
+      "ctrl-delete": ["git::RestoreFile", { "skip_prompt": false }],
+    },
   },
   {
     "context": "GitPanel && CommitEditor",
     "use_key_equivalents": true,
     "bindings": {
-      "escape": "git::Cancel"
-    }
+      "escape": "git::Cancel",
+    },
   },
   {
     "context": "GitCommit > Editor",
@@ -927,8 +916,8 @@
       "enter": "editor::Newline",
       "ctrl-enter": "git::Commit",
       "ctrl-shift-enter": "git::Amend",
-      "alt-l": "git::GenerateCommitMessage"
-    }
+      "alt-l": "git::GenerateCommitMessage",
+    },
   },
   {
     "context": "GitPanel",
@@ -945,8 +934,8 @@
       "ctrl-space": "git::StageAll",
       "ctrl-shift-space": "git::UnstageAll",
       "ctrl-enter": "git::Commit",
-      "ctrl-shift-enter": "git::Amend"
-    }
+      "ctrl-shift-enter": "git::Amend",
+    },
   },
   {
     "context": "GitDiff > Editor",
@@ -955,15 +944,15 @@
       "ctrl-enter": "git::Commit",
       "ctrl-shift-enter": "git::Amend",
       "ctrl-space": "git::StageAll",
-      "ctrl-shift-space": "git::UnstageAll"
-    }
+      "ctrl-shift-space": "git::UnstageAll",
+    },
   },
   {
     "context": "AskPass > Editor",
     "use_key_equivalents": true,
     "bindings": {
-      "enter": "menu::Confirm"
-    }
+      "enter": "menu::Confirm",
+    },
   },
   {
     "context": "CommitEditor > Editor",
@@ -976,8 +965,8 @@
       "ctrl-enter": "git::Commit",
       "ctrl-shift-enter": "git::Amend",
       "alt-up": "git_panel::FocusChanges",
-      "alt-l": "git::GenerateCommitMessage"
-    }
+      "alt-l": "git::GenerateCommitMessage",
+    },
   },
   {
     "context": "DebugPanel",
@@ -985,8 +974,8 @@
     "bindings": {
       "ctrl-t": "debugger::ToggleThreadPicker",
       "ctrl-i": "debugger::ToggleSessionPicker",
-      "shift-alt-escape": "debugger::ToggleExpandItem"
-    }
+      "shift-alt-escape": "debugger::ToggleExpandItem",
+    },
   },
   {
     "context": "VariableList",
@@ -999,8 +988,8 @@
       "ctrl-alt-c": "variable_list::CopyVariableName",
       "delete": "variable_list::RemoveWatch",
       "backspace": "variable_list::RemoveWatch",
-      "alt-enter": "variable_list::AddWatch"
-    }
+      "alt-enter": "variable_list::AddWatch",
+    },
   },
   {
     "context": "BreakpointList",
@@ -1009,16 +998,16 @@
       "space": "debugger::ToggleEnableBreakpoint",
       "backspace": "debugger::UnsetBreakpoint",
       "left": "debugger::PreviousBreakpointProperty",
-      "right": "debugger::NextBreakpointProperty"
-    }
+      "right": "debugger::NextBreakpointProperty",
+    },
   },
   {
     "context": "CollabPanel && not_editing",
     "use_key_equivalents": true,
     "bindings": {
       "ctrl-backspace": "collab_panel::Remove",
-      "space": "menu::Confirm"
-    }
+      "space": "menu::Confirm",
+    },
   },
   {
     "context": "CollabPanel",
@@ -1026,22 +1015,22 @@
     "bindings": {
       "alt-up": "collab_panel::MoveChannelUp",
       "alt-down": "collab_panel::MoveChannelDown",
-      "alt-enter": "collab_panel::OpenSelectedChannelNotes"
-    }
+      "alt-enter": "collab_panel::OpenSelectedChannelNotes",
+    },
   },
   {
     "context": "(CollabPanel && editing) > Editor",
     "use_key_equivalents": true,
     "bindings": {
-      "space": "collab_panel::InsertSpace"
-    }
+      "space": "collab_panel::InsertSpace",
+    },
   },
   {
     "context": "ChannelModal",
     "use_key_equivalents": true,
     "bindings": {
-      "tab": "channel_modal::ToggleMode"
-    }
+      "tab": "channel_modal::ToggleMode",
+    },
   },
   {
     "context": "Picker > Editor",
@@ -1051,22 +1040,22 @@
       "up": "menu::SelectPrevious",
       "down": "menu::SelectNext",
       "tab": "picker::ConfirmCompletion",
-      "alt-enter": ["picker::ConfirmInput", { "secondary": false }]
-    }
+      "alt-enter": ["picker::ConfirmInput", { "secondary": false }],
+    },
   },
   {
     "context": "ChannelModal > Picker > Editor",
     "use_key_equivalents": true,
     "bindings": {
-      "tab": "channel_modal::ToggleMode"
-    }
+      "tab": "channel_modal::ToggleMode",
+    },
   },
   {
     "context": "ToolchainSelector",
     "use_key_equivalents": true,
     "bindings": {
-      "ctrl-shift-a": "toolchain::AddToolchain"
-    }
+      "ctrl-shift-a": "toolchain::AddToolchain",
+    },
   },
   {
     "context": "FileFinder || (FileFinder > Picker > Editor)",
@@ -1074,8 +1063,8 @@
     "bindings": {
       "ctrl-p": "file_finder::Toggle",
       "ctrl-shift-a": "file_finder::ToggleSplitMenu",
-      "ctrl-shift-i": "file_finder::ToggleFilterMenu"
-    }
+      "ctrl-shift-i": "file_finder::ToggleFilterMenu",
+    },
   },
   {
     "context": "FileFinder || (FileFinder > Picker > Editor) || (FileFinder > Picker > menu)",
@@ -1085,8 +1074,8 @@
       "ctrl-j": "pane::SplitDown",
       "ctrl-k": "pane::SplitUp",
       "ctrl-h": "pane::SplitLeft",
-      "ctrl-l": "pane::SplitRight"
-    }
+      "ctrl-l": "pane::SplitRight",
+    },
   },
   {
     "context": "TabSwitcher",
@@ -1095,16 +1084,16 @@
       "ctrl-shift-tab": "menu::SelectPrevious",
       "ctrl-up": "menu::SelectPrevious",
       "ctrl-down": "menu::SelectNext",
-      "ctrl-backspace": "tab_switcher::CloseSelectedItem"
-    }
+      "ctrl-backspace": "tab_switcher::CloseSelectedItem",
+    },
   },
   {
     "context": "StashList || (StashList > Picker > Editor)",
     "use_key_equivalents": true,
     "bindings": {
       "ctrl-shift-backspace": "stash_picker::DropStashItem",
-      "ctrl-shift-v": "stash_picker::ShowStashItem"
-    }
+      "ctrl-shift-v": "stash_picker::ShowStashItem",
+    },
   },
   {
     "context": "Terminal",
@@ -1128,6 +1117,8 @@
       "ctrl-e": ["terminal::SendKeystroke", "ctrl-e"],
       "ctrl-o": ["terminal::SendKeystroke", "ctrl-o"],
       "ctrl-w": ["terminal::SendKeystroke", "ctrl-w"],
+      "ctrl-q": ["terminal::SendKeystroke", "ctrl-q"],
+      "ctrl-r": ["terminal::SendKeystroke", "ctrl-r"],
       "ctrl-backspace": ["terminal::SendKeystroke", "ctrl-w"],
       "ctrl-shift-a": "editor::SelectAll",
       "ctrl-shift-f": "buffer_search::Deploy",
@@ -1149,21 +1140,21 @@
       "ctrl-shift-r": "terminal::RerunTask",
       "ctrl-alt-r": "terminal::RerunTask",
       "alt-t": "terminal::RerunTask",
-      "ctrl-shift-5": "pane::SplitRight"
-    }
+      "ctrl-shift-5": "pane::SplitRight",
+    },
   },
   {
     "context": "Terminal && selection",
     "bindings": {
-      "ctrl-c": "terminal::Copy"
-    }
+      "ctrl-c": "terminal::Copy",
+    },
   },
   {
     "context": "ZedPredictModal",
     "use_key_equivalents": true,
     "bindings": {
-      "escape": "menu::Cancel"
-    }
+      "escape": "menu::Cancel",
+    },
   },
   {
     "context": "ConfigureContextServerModal > Editor",

assets/keymaps/initial.json 🔗

@@ -10,12 +10,12 @@
     "context": "Workspace",
     "bindings": {
       // "shift shift": "file_finder::Toggle"
-    }
+    },
   },
   {
     "context": "Editor && vim_mode == insert",
     "bindings": {
       // "j k": "vim::NormalBefore"
-    }
-  }
+    },
+  },
 ]

assets/keymaps/linux/atom.json 🔗

@@ -4,15 +4,15 @@
     "bindings": {
       "ctrl-shift-f5": "workspace::Reload", // window:reload
       "ctrl-k ctrl-n": "workspace::ActivatePreviousPane", // window:focus-next-pane
-      "ctrl-k ctrl-p": "workspace::ActivateNextPane" // window:focus-previous-pane
-    }
+      "ctrl-k ctrl-p": "workspace::ActivateNextPane", // window:focus-previous-pane
+    },
   },
   {
     "context": "Editor",
     "bindings": {
       "ctrl-k ctrl-u": "editor::ConvertToUpperCase", // editor:upper-case
-      "ctrl-k ctrl-l": "editor::ConvertToLowerCase" // editor:lower-case
-    }
+      "ctrl-k ctrl-l": "editor::ConvertToLowerCase", // editor:lower-case
+    },
   },
   {
     "context": "Editor && mode == full",
@@ -32,8 +32,8 @@
       "ctrl-down": "editor::MoveLineDown", // editor:move-line-down
       "ctrl-\\": "workspace::ToggleLeftDock", // tree-view:toggle
       "ctrl-shift-m": "markdown::OpenPreviewToTheSide", // markdown-preview:toggle
-      "ctrl-r": "outline::Toggle" // symbols-view:toggle-project-symbols
-    }
+      "ctrl-r": "outline::Toggle", // symbols-view:toggle-project-symbols
+    },
   },
   {
     "context": "BufferSearchBar",
@@ -41,8 +41,8 @@
       "f3": ["editor::SelectNext", { "replace_newest": true }], // find-and-replace:find-next
       "shift-f3": ["editor::SelectPrevious", { "replace_newest": true }], //find-and-replace:find-previous
       "ctrl-f3": "search::SelectNextMatch", // find-and-replace:find-next-selected
-      "ctrl-shift-f3": "search::SelectPreviousMatch" // find-and-replace:find-previous-selected
-    }
+      "ctrl-shift-f3": "search::SelectPreviousMatch", // find-and-replace:find-previous-selected
+    },
   },
   {
     "context": "Workspace",
@@ -50,8 +50,8 @@
       "ctrl-\\": "workspace::ToggleLeftDock", // tree-view:toggle
       "ctrl-k ctrl-b": "workspace::ToggleLeftDock", // tree-view:toggle
       "ctrl-t": "file_finder::Toggle", // fuzzy-finder:toggle-file-finder
-      "ctrl-r": "project_symbols::Toggle" // symbols-view:toggle-project-symbols
-    }
+      "ctrl-r": "project_symbols::Toggle", // symbols-view:toggle-project-symbols
+    },
   },
   {
     "context": "Pane",
@@ -65,8 +65,8 @@
       "ctrl-6": ["pane::ActivateItem", 5], // tree-view:open-selected-entry-in-pane-6
       "ctrl-7": ["pane::ActivateItem", 6], // tree-view:open-selected-entry-in-pane-7
       "ctrl-8": ["pane::ActivateItem", 7], // tree-view:open-selected-entry-in-pane-8
-      "ctrl-9": ["pane::ActivateItem", 8] // tree-view:open-selected-entry-in-pane-9
-    }
+      "ctrl-9": ["pane::ActivateItem", 8], // tree-view:open-selected-entry-in-pane-9
+    },
   },
   {
     "context": "ProjectPanel",
@@ -75,8 +75,8 @@
       "backspace": ["project_panel::Trash", { "skip_prompt": false }],
       "ctrl-x": "project_panel::Cut", // tree-view:cut
       "ctrl-c": "project_panel::Copy", // tree-view:copy
-      "ctrl-v": "project_panel::Paste" // tree-view:paste
-    }
+      "ctrl-v": "project_panel::Paste", // tree-view:paste
+    },
   },
   {
     "context": "ProjectPanel && not_editing",
@@ -90,7 +90,7 @@
       "d": "project_panel::Duplicate", // tree-view:duplicate
       "home": "menu::SelectFirst", // core:move-to-top
       "end": "menu::SelectLast", // core:move-to-bottom
-      "shift-a": "project_panel::NewDirectory" // tree-view:add-folder
-    }
-  }
+      "shift-a": "project_panel::NewDirectory", // tree-view:add-folder
+    },
+  },
 ]

assets/keymaps/linux/cursor.json 🔗

@@ -8,8 +8,8 @@
       "ctrl-shift-i": "agent::ToggleFocus",
       "ctrl-l": "agent::ToggleFocus",
       "ctrl-shift-l": "agent::ToggleFocus",
-      "ctrl-shift-j": "agent::OpenSettings"
-    }
+      "ctrl-shift-j": "agent::OpenSettings",
+    },
   },
   {
     "context": "Editor && mode == full",
@@ -20,18 +20,18 @@
       "ctrl-shift-l": "agent::AddSelectionToThread", // In cursor uses "Ask" mode
       "ctrl-l": "agent::AddSelectionToThread", // In cursor uses "Agent" mode
       "ctrl-k": "assistant::InlineAssist",
-      "ctrl-shift-k": "assistant::InsertIntoEditor"
-    }
+      "ctrl-shift-k": "assistant::InsertIntoEditor",
+    },
   },
   {
-    "context": "InlineAssistEditor",
+    "context": "InlineAssistant > Editor",
     "use_key_equivalents": true,
     "bindings": {
-      "ctrl-shift-backspace": "editor::Cancel"
+      "ctrl-shift-backspace": "editor::Cancel",
       // "alt-enter": // Quick Question
       // "ctrl-shift-enter": // Full File Context
       // "ctrl-shift-k": // Toggle input focus (editor <> inline assist)
-    }
+    },
   },
   {
     "context": "AgentPanel || ContextEditor || (MessageEditor > Editor)",
@@ -47,7 +47,7 @@
       "ctrl-shift-backspace": "editor::Cancel",
       "ctrl-r": "agent::NewThread",
       "ctrl-shift-v": "editor::Paste",
-      "ctrl-shift-k": "assistant::InsertIntoEditor"
+      "ctrl-shift-k": "assistant::InsertIntoEditor",
       // "escape": "agent::ToggleFocus"
       ///// Enable when Zed supports multiple thread tabs
       // "ctrl-t": // new thread tab
@@ -56,28 +56,29 @@
       ///// Enable if Zed adds support for keyboard navigation of thread elements
       // "tab": // cycle to next message
       // "shift-tab": // cycle to previous message
-    }
+    },
   },
   {
     "context": "Editor && editor_agent_diff",
     "use_key_equivalents": true,
     "bindings": {
       "ctrl-enter": "agent::KeepAll",
-      "ctrl-backspace": "agent::RejectAll"
-    }
+      "ctrl-backspace": "agent::RejectAll",
+    },
   },
   {
     "context": "Editor && mode == full && edit_prediction",
     "use_key_equivalents": true,
     "bindings": {
-      "ctrl-right": "editor::AcceptPartialEditPrediction"
-    }
+      "ctrl-right": "editor::AcceptNextWordEditPrediction",
+      "ctrl-down": "editor::AcceptNextLineEditPrediction",
+    },
   },
   {
     "context": "Terminal",
     "use_key_equivalents": true,
     "bindings": {
-      "ctrl-k": "assistant::InlineAssist"
-    }
-  }
+      "ctrl-k": "assistant::InlineAssist",
+    },
+  },
 ]

assets/keymaps/linux/emacs.json 🔗

@@ -5,8 +5,8 @@
 [
   {
     "bindings": {
-      "ctrl-g": "menu::Cancel"
-    }
+      "ctrl-g": "menu::Cancel",
+    },
   },
   {
     // Workaround to avoid falling back to default bindings.
@@ -18,8 +18,8 @@
       "ctrl-g": null, // currently activates `go_to_line::Toggle` when there is nothing to cancel
       "ctrl-x": null, // currently activates `editor::Cut` if no following key is pressed for 1 second
       "ctrl-p": null, // currently activates `file_finder::Toggle` when the cursor is on the first character of the buffer
-      "ctrl-n": null // currently activates `workspace::NewFile` when the cursor is on the last character of the buffer
-    }
+      "ctrl-n": null, // currently activates `workspace::NewFile` when the cursor is on the last character of the buffer
+    },
   },
   {
     "context": "Editor",
@@ -82,8 +82,8 @@
       "ctrl-s": "buffer_search::Deploy", // isearch-forward
       "ctrl-r": "buffer_search::Deploy", // isearch-backward
       "alt-^": "editor::JoinLines", // join-line
-      "alt-q": "editor::Rewrap" // fill-paragraph
-    }
+      "alt-q": "editor::Rewrap", // fill-paragraph
+    },
   },
   {
     "context": "Editor && selection_mode", // region selection
@@ -119,22 +119,22 @@
       "alt->": "editor::SelectToEnd",
       "ctrl-home": "editor::SelectToBeginning",
       "ctrl-end": "editor::SelectToEnd",
-      "ctrl-g": "editor::Cancel"
-    }
+      "ctrl-g": "editor::Cancel",
+    },
   },
   {
     "context": "Editor && (showing_code_actions || showing_completions)",
     "bindings": {
       "ctrl-p": "editor::ContextMenuPrevious",
-      "ctrl-n": "editor::ContextMenuNext"
-    }
+      "ctrl-n": "editor::ContextMenuNext",
+    },
   },
   {
     "context": "Editor && showing_signature_help && !showing_completions",
     "bindings": {
       "ctrl-p": "editor::SignatureHelpPrevious",
-      "ctrl-n": "editor::SignatureHelpNext"
-    }
+      "ctrl-n": "editor::SignatureHelpNext",
+    },
   },
   // Example setting for using emacs-style tab
   // (i.e. indent the current line / selection or perform symbol completion depending on context)
@@ -164,8 +164,8 @@
       "ctrl-x ctrl-f": "file_finder::Toggle", // find-file
       "ctrl-x ctrl-s": "workspace::Save", // save-buffer
       "ctrl-x ctrl-w": "workspace::SaveAs", // write-file
-      "ctrl-x s": "workspace::SaveAll" // save-some-buffers
-    }
+      "ctrl-x s": "workspace::SaveAll", // save-some-buffers
+    },
   },
   {
     // Workaround to enable using native emacs from the Zed terminal.
@@ -185,22 +185,22 @@
       "ctrl-x ctrl-f": null, // find-file
       "ctrl-x ctrl-s": null, // save-buffer
       "ctrl-x ctrl-w": null, // write-file
-      "ctrl-x s": null // save-some-buffers
-    }
+      "ctrl-x s": null, // save-some-buffers
+    },
   },
   {
     "context": "BufferSearchBar > Editor",
     "bindings": {
       "ctrl-s": "search::SelectNextMatch",
       "ctrl-r": "search::SelectPreviousMatch",
-      "ctrl-g": "buffer_search::Dismiss"
-    }
+      "ctrl-g": "buffer_search::Dismiss",
+    },
   },
   {
     "context": "Pane",
     "bindings": {
       "ctrl-alt-left": "pane::GoBack",
-      "ctrl-alt-right": "pane::GoForward"
-    }
-  }
+      "ctrl-alt-right": "pane::GoForward",
+    },
+  },
 ]

assets/keymaps/linux/jetbrains.json 🔗

@@ -13,8 +13,8 @@
       "shift-f8": "debugger::StepOut",
       "f9": "debugger::Continue",
       "shift-f9": "debugger::Start",
-      "alt-shift-f9": "debugger::Start"
-    }
+      "alt-shift-f9": "debugger::Start",
+    },
   },
   {
     "context": "Editor",
@@ -62,28 +62,30 @@
       "ctrl-shift-end": "editor::SelectToEnd",
       "ctrl-f8": "editor::ToggleBreakpoint",
       "ctrl-shift-f8": "editor::EditLogBreakpoint",
-      "ctrl-shift-u": "editor::ToggleCase"
-    }
+      "ctrl-shift-u": "editor::ToggleCase",
+    },
   },
   {
     "context": "Editor && mode == full",
     "bindings": {
       "ctrl-f12": "outline::Toggle",
       "ctrl-r": ["buffer_search::Deploy", { "replace_enabled": true }],
+      "ctrl-e": "file_finder::Toggle",
       "ctrl-shift-n": "file_finder::Toggle",
+      "ctrl-alt-n": "file_finder::Toggle",
       "ctrl-g": "go_to_line::Toggle",
       "alt-enter": "editor::ToggleCodeActions",
       "ctrl-space": "editor::ShowCompletions",
       "ctrl-q": "editor::Hover",
       "ctrl-p": "editor::ShowSignatureHelp",
-      "ctrl-\\": "assistant::InlineAssist"
-    }
+      "ctrl-\\": "assistant::InlineAssist",
+    },
   },
   {
     "context": "BufferSearchBar",
     "bindings": {
-      "shift-enter": "search::SelectPreviousMatch"
-    }
+      "shift-enter": "search::SelectPreviousMatch",
+    },
   },
   {
     "context": "BufferSearchBar || ProjectSearchBar",
@@ -91,8 +93,8 @@
       "alt-c": "search::ToggleCaseSensitive",
       "alt-e": "search::ToggleSelection",
       "alt-x": "search::ToggleRegex",
-      "alt-w": "search::ToggleWholeWord"
-    }
+      "alt-w": "search::ToggleWholeWord",
+    },
   },
   {
     "context": "Workspace",
@@ -105,8 +107,8 @@
       "ctrl-e": "file_finder::Toggle",
       "ctrl-k": "git_panel::ToggleFocus", // bug: This should also focus commit editor
       "ctrl-shift-n": "file_finder::Toggle",
-      "ctrl-n": "project_symbols::Toggle",
       "ctrl-alt-n": "file_finder::Toggle",
+      "ctrl-n": "project_symbols::Toggle",
       "ctrl-shift-a": "command_palette::Toggle",
       "shift shift": "command_palette::Toggle",
       "ctrl-alt-shift-n": "project_symbols::Toggle",
@@ -114,8 +116,8 @@
       "alt-1": "project_panel::ToggleFocus",
       "alt-5": "debug_panel::ToggleFocus",
       "alt-6": "diagnostics::Deploy",
-      "alt-7": "outline_panel::ToggleFocus"
-    }
+      "alt-7": "outline_panel::ToggleFocus",
+    },
   },
   {
     "context": "Pane", // this is to override the default Pane mappings to switch tabs
@@ -129,15 +131,15 @@
       "alt-7": "outline_panel::ToggleFocus",
       "alt-8": null, // Services (bottom dock)
       "alt-9": null, // Git History (bottom dock)
-      "alt-0": "git_panel::ToggleFocus"
-    }
+      "alt-0": "git_panel::ToggleFocus",
+    },
   },
   {
     "context": "Workspace || Editor",
     "bindings": {
       "alt-f12": "terminal_panel::Toggle",
-      "ctrl-shift-k": "git::Push"
-    }
+      "ctrl-shift-k": "git::Push",
+    },
   },
   {
     "context": "Pane",
@@ -145,8 +147,8 @@
       "ctrl-alt-left": "pane::GoBack",
       "ctrl-alt-right": "pane::GoForward",
       "alt-left": "pane::ActivatePreviousItem",
-      "alt-right": "pane::ActivateNextItem"
-    }
+      "alt-right": "pane::ActivateNextItem",
+    },
   },
   {
     "context": "ProjectPanel",
@@ -156,8 +158,8 @@
       "backspace": ["project_panel::Trash", { "skip_prompt": false }],
       "delete": ["project_panel::Trash", { "skip_prompt": false }],
       "shift-delete": ["project_panel::Delete", { "skip_prompt": false }],
-      "shift-f6": "project_panel::Rename"
-    }
+      "shift-f6": "project_panel::Rename",
+    },
   },
   {
     "context": "Terminal",
@@ -167,8 +169,8 @@
       "ctrl-up": "terminal::ScrollLineUp",
       "ctrl-down": "terminal::ScrollLineDown",
       "shift-pageup": "terminal::ScrollPageUp",
-      "shift-pagedown": "terminal::ScrollPageDown"
-    }
+      "shift-pagedown": "terminal::ScrollPageDown",
+    },
   },
   { "context": "GitPanel", "bindings": { "alt-0": "workspace::CloseActiveDock" } },
   { "context": "ProjectPanel", "bindings": { "alt-1": "workspace::CloseActiveDock" } },
@@ -179,7 +181,7 @@
     "context": "Dock || Workspace || OutlinePanel || ProjectPanel || CollabPanel || (Editor && mode == auto_height)",
     "bindings": {
       "escape": "editor::ToggleFocus",
-      "shift-escape": "workspace::CloseActiveDock"
-    }
-  }
+      "shift-escape": "workspace::CloseActiveDock",
+    },
+  },
 ]

assets/keymaps/linux/sublime_text.json 🔗

@@ -22,8 +22,8 @@
       "ctrl-^": ["workspace::MoveItemToPane", { "destination": 5 }],
       "ctrl-&": ["workspace::MoveItemToPane", { "destination": 6 }],
       "ctrl-*": ["workspace::MoveItemToPane", { "destination": 7 }],
-      "ctrl-(": ["workspace::MoveItemToPane", { "destination": 8 }]
-    }
+      "ctrl-(": ["workspace::MoveItemToPane", { "destination": 8 }],
+    },
   },
   {
     "context": "Editor",
@@ -55,20 +55,20 @@
       "alt-right": "editor::MoveToNextSubwordEnd",
       "alt-left": "editor::MoveToPreviousSubwordStart",
       "alt-shift-right": "editor::SelectToNextSubwordEnd",
-      "alt-shift-left": "editor::SelectToPreviousSubwordStart"
-    }
+      "alt-shift-left": "editor::SelectToPreviousSubwordStart",
+    },
   },
   {
     "context": "Editor && mode == full",
     "bindings": {
-      "ctrl-r": "outline::Toggle"
-    }
+      "ctrl-r": "outline::Toggle",
+    },
   },
   {
     "context": "Editor && !agent_diff",
     "bindings": {
-      "ctrl-k ctrl-z": "git::Restore"
-    }
+      "ctrl-k ctrl-z": "git::Restore",
+    },
   },
   {
     "context": "Pane",
@@ -83,15 +83,15 @@
       "alt-6": ["pane::ActivateItem", 5],
       "alt-7": ["pane::ActivateItem", 6],
       "alt-8": ["pane::ActivateItem", 7],
-      "alt-9": "pane::ActivateLastItem"
-    }
+      "alt-9": "pane::ActivateLastItem",
+    },
   },
   {
     "context": "Workspace",
     "bindings": {
       "ctrl-k ctrl-b": "workspace::ToggleLeftDock",
       // "ctrl-0": "project_panel::ToggleFocus", // normally resets zoom
-      "shift-ctrl-r": "project_symbols::Toggle"
-    }
-  }
+      "shift-ctrl-r": "project_symbols::Toggle",
+    },
+  },
 ]

assets/keymaps/macos/atom.json 🔗

@@ -4,16 +4,16 @@
     "bindings": {
       "ctrl-alt-cmd-l": "workspace::Reload",
       "cmd-k cmd-p": "workspace::ActivatePreviousPane",
-      "cmd-k cmd-n": "workspace::ActivateNextPane"
-    }
+      "cmd-k cmd-n": "workspace::ActivateNextPane",
+    },
   },
   {
     "context": "Editor",
     "bindings": {
       "cmd-shift-backspace": "editor::DeleteToBeginningOfLine",
       "cmd-k cmd-u": "editor::ConvertToUpperCase",
-      "cmd-k cmd-l": "editor::ConvertToLowerCase"
-    }
+      "cmd-k cmd-l": "editor::ConvertToLowerCase",
+    },
   },
   {
     "context": "Editor && mode == full",
@@ -33,8 +33,8 @@
       "ctrl-cmd-down": "editor::MoveLineDown",
       "cmd-\\": "workspace::ToggleLeftDock",
       "ctrl-shift-m": "markdown::OpenPreviewToTheSide",
-      "cmd-r": "outline::Toggle"
-    }
+      "cmd-r": "outline::Toggle",
+    },
   },
   {
     "context": "BufferSearchBar",
@@ -42,8 +42,8 @@
       "cmd-g": ["editor::SelectNext", { "replace_newest": true }],
       "cmd-shift-g": ["editor::SelectPrevious", { "replace_newest": true }],
       "cmd-f3": "search::SelectNextMatch",
-      "cmd-shift-f3": "search::SelectPreviousMatch"
-    }
+      "cmd-shift-f3": "search::SelectPreviousMatch",
+    },
   },
   {
     "context": "Workspace",
@@ -51,8 +51,8 @@
       "cmd-\\": "workspace::ToggleLeftDock",
       "cmd-k cmd-b": "workspace::ToggleLeftDock",
       "cmd-t": "file_finder::Toggle",
-      "cmd-shift-r": "project_symbols::Toggle"
-    }
+      "cmd-shift-r": "project_symbols::Toggle",
+    },
   },
   {
     "context": "Pane",
@@ -67,8 +67,8 @@
       "cmd-6": ["pane::ActivateItem", 5],
       "cmd-7": ["pane::ActivateItem", 6],
       "cmd-8": ["pane::ActivateItem", 7],
-      "cmd-9": "pane::ActivateLastItem"
-    }
+      "cmd-9": "pane::ActivateLastItem",
+    },
   },
   {
     "context": "ProjectPanel",
@@ -77,8 +77,8 @@
       "backspace": ["project_panel::Trash", { "skip_prompt": false }],
       "cmd-x": "project_panel::Cut",
       "cmd-c": "project_panel::Copy",
-      "cmd-v": "project_panel::Paste"
-    }
+      "cmd-v": "project_panel::Paste",
+    },
   },
   {
     "context": "ProjectPanel && not_editing",
@@ -92,7 +92,7 @@
       "d": "project_panel::Duplicate",
       "home": "menu::SelectFirst",
       "end": "menu::SelectLast",
-      "shift-a": "project_panel::NewDirectory"
-    }
-  }
+      "shift-a": "project_panel::NewDirectory",
+    },
+  },
 ]

assets/keymaps/macos/cursor.json 🔗

@@ -8,8 +8,8 @@
       "cmd-shift-i": "agent::ToggleFocus",
       "cmd-l": "agent::ToggleFocus",
       "cmd-shift-l": "agent::ToggleFocus",
-      "cmd-shift-j": "agent::OpenSettings"
-    }
+      "cmd-shift-j": "agent::OpenSettings",
+    },
   },
   {
     "context": "Editor && mode == full",
@@ -20,19 +20,19 @@
       "cmd-shift-l": "agent::AddSelectionToThread", // In cursor uses "Ask" mode
       "cmd-l": "agent::AddSelectionToThread", // In cursor uses "Agent" mode
       "cmd-k": "assistant::InlineAssist",
-      "cmd-shift-k": "assistant::InsertIntoEditor"
-    }
+      "cmd-shift-k": "assistant::InsertIntoEditor",
+    },
   },
   {
-    "context": "InlineAssistEditor",
+    "context": "InlineAssistant > Editor",
     "use_key_equivalents": true,
     "bindings": {
       "cmd-shift-backspace": "editor::Cancel",
-      "cmd-enter": "menu::Confirm"
+      "cmd-enter": "menu::Confirm",
       // "alt-enter": // Quick Question
       // "cmd-shift-enter": // Full File Context
       // "cmd-shift-k": // Toggle input focus (editor <> inline assist)
-    }
+    },
   },
   {
     "context": "AgentPanel || ContextEditor || (MessageEditor > Editor)",
@@ -48,7 +48,7 @@
       "cmd-shift-backspace": "editor::Cancel",
       "cmd-r": "agent::NewThread",
       "cmd-shift-v": "editor::Paste",
-      "cmd-shift-k": "assistant::InsertIntoEditor"
+      "cmd-shift-k": "assistant::InsertIntoEditor",
       // "escape": "agent::ToggleFocus"
       ///// Enable when Zed supports multiple thread tabs
       // "cmd-t": // new thread tab
@@ -57,28 +57,29 @@
       ///// Enable if Zed adds support for keyboard navigation of thread elements
       // "tab": // cycle to next message
       // "shift-tab": // cycle to previous message
-    }
+    },
   },
   {
     "context": "Editor && editor_agent_diff",
     "use_key_equivalents": true,
     "bindings": {
       "cmd-enter": "agent::KeepAll",
-      "cmd-backspace": "agent::RejectAll"
-    }
+      "cmd-backspace": "agent::RejectAll",
+    },
   },
   {
     "context": "Editor && mode == full && edit_prediction",
     "use_key_equivalents": true,
     "bindings": {
-      "cmd-right": "editor::AcceptPartialEditPrediction"
-    }
+      "cmd-right": "editor::AcceptNextWordEditPrediction",
+      "cmd-down": "editor::AcceptNextLineEditPrediction",
+    },
   },
   {
     "context": "Terminal",
     "use_key_equivalents": true,
     "bindings": {
-      "cmd-k": "assistant::InlineAssist"
-    }
-  }
+      "cmd-k": "assistant::InlineAssist",
+    },
+  },
 ]

assets/keymaps/macos/emacs.json 🔗

@@ -6,8 +6,8 @@
   {
     "context": "!GitPanel",
     "bindings": {
-      "ctrl-g": "menu::Cancel"
-    }
+      "ctrl-g": "menu::Cancel",
+    },
   },
   {
     // Workaround to avoid falling back to default bindings.
@@ -15,8 +15,8 @@
     // NOTE: must be declared before the `Editor` override.
     "context": "Editor",
     "bindings": {
-      "ctrl-g": null // currently activates `go_to_line::Toggle` when there is nothing to cancel
-    }
+      "ctrl-g": null, // currently activates `go_to_line::Toggle` when there is nothing to cancel
+    },
   },
   {
     "context": "Editor",
@@ -79,8 +79,8 @@
       "ctrl-s": "buffer_search::Deploy", // isearch-forward
       "ctrl-r": "buffer_search::Deploy", // isearch-backward
       "alt-^": "editor::JoinLines", // join-line
-      "alt-q": "editor::Rewrap" // fill-paragraph
-    }
+      "alt-q": "editor::Rewrap", // fill-paragraph
+    },
   },
   {
     "context": "Editor && selection_mode", // region selection
@@ -116,22 +116,22 @@
       "alt->": "editor::SelectToEnd",
       "ctrl-home": "editor::SelectToBeginning",
       "ctrl-end": "editor::SelectToEnd",
-      "ctrl-g": "editor::Cancel"
-    }
+      "ctrl-g": "editor::Cancel",
+    },
   },
   {
     "context": "Editor && (showing_code_actions || showing_completions)",
     "bindings": {
       "ctrl-p": "editor::ContextMenuPrevious",
-      "ctrl-n": "editor::ContextMenuNext"
-    }
+      "ctrl-n": "editor::ContextMenuNext",
+    },
   },
   {
     "context": "Editor && showing_signature_help && !showing_completions",
     "bindings": {
       "ctrl-p": "editor::SignatureHelpPrevious",
-      "ctrl-n": "editor::SignatureHelpNext"
-    }
+      "ctrl-n": "editor::SignatureHelpNext",
+    },
   },
   // Example setting for using emacs-style tab
   // (i.e. indent the current line / selection or perform symbol completion depending on context)
@@ -161,8 +161,8 @@
       "ctrl-x ctrl-f": "file_finder::Toggle", // find-file
       "ctrl-x ctrl-s": "workspace::Save", // save-buffer
       "ctrl-x ctrl-w": "workspace::SaveAs", // write-file
-      "ctrl-x s": "workspace::SaveAll" // save-some-buffers
-    }
+      "ctrl-x s": "workspace::SaveAll", // save-some-buffers
+    },
   },
   {
     // Workaround to enable using native emacs from the Zed terminal.
@@ -182,22 +182,22 @@
       "ctrl-x ctrl-f": null, // find-file
       "ctrl-x ctrl-s": null, // save-buffer
       "ctrl-x ctrl-w": null, // write-file
-      "ctrl-x s": null // save-some-buffers
-    }
+      "ctrl-x s": null, // save-some-buffers
+    },
   },
   {
     "context": "BufferSearchBar > Editor",
     "bindings": {
       "ctrl-s": "search::SelectNextMatch",
       "ctrl-r": "search::SelectPreviousMatch",
-      "ctrl-g": "buffer_search::Dismiss"
-    }
+      "ctrl-g": "buffer_search::Dismiss",
+    },
   },
   {
     "context": "Pane",
     "bindings": {
       "ctrl-alt-left": "pane::GoBack",
-      "ctrl-alt-right": "pane::GoForward"
-    }
-  }
+      "ctrl-alt-right": "pane::GoForward",
+    },
+  },
 ]

assets/keymaps/macos/jetbrains.json 🔗

@@ -13,8 +13,8 @@
       "shift-f8": "debugger::StepOut",
       "f9": "debugger::Continue",
       "shift-f9": "debugger::Start",
-      "alt-shift-f9": "debugger::Start"
-    }
+      "alt-shift-f9": "debugger::Start",
+    },
   },
   {
     "context": "Editor",
@@ -60,28 +60,30 @@
       "cmd-shift-end": "editor::SelectToEnd",
       "ctrl-f8": "editor::ToggleBreakpoint",
       "ctrl-shift-f8": "editor::EditLogBreakpoint",
-      "cmd-shift-u": "editor::ToggleCase"
-    }
+      "cmd-shift-u": "editor::ToggleCase",
+    },
   },
   {
     "context": "Editor && mode == full",
     "bindings": {
       "cmd-f12": "outline::Toggle",
       "cmd-r": ["buffer_search::Deploy", { "replace_enabled": true }],
-      "cmd-shift-o": "file_finder::Toggle",
       "cmd-l": "go_to_line::Toggle",
+      "cmd-e": "file_finder::Toggle",
+      "cmd-shift-o": "file_finder::Toggle",
+      "cmd-shift-n": "file_finder::Toggle",
       "alt-enter": "editor::ToggleCodeActions",
       "ctrl-space": "editor::ShowCompletions",
       "cmd-j": "editor::Hover",
       "cmd-p": "editor::ShowSignatureHelp",
-      "cmd-\\": "assistant::InlineAssist"
-    }
+      "cmd-\\": "assistant::InlineAssist",
+    },
   },
   {
     "context": "BufferSearchBar",
     "bindings": {
-      "shift-enter": "search::SelectPreviousMatch"
-    }
+      "shift-enter": "search::SelectPreviousMatch",
+    },
   },
   {
     "context": "BufferSearchBar || ProjectSearchBar",
@@ -93,8 +95,8 @@
       "ctrl-alt-c": "search::ToggleCaseSensitive",
       "ctrl-alt-e": "search::ToggleSelection",
       "ctrl-alt-w": "search::ToggleWholeWord",
-      "ctrl-alt-x": "search::ToggleRegex"
-    }
+      "ctrl-alt-x": "search::ToggleRegex",
+    },
   },
   {
     "context": "Workspace",
@@ -116,8 +118,8 @@
       "cmd-1": "project_panel::ToggleFocus",
       "cmd-5": "debug_panel::ToggleFocus",
       "cmd-6": "diagnostics::Deploy",
-      "cmd-7": "outline_panel::ToggleFocus"
-    }
+      "cmd-7": "outline_panel::ToggleFocus",
+    },
   },
   {
     "context": "Pane", // this is to override the default Pane mappings to switch tabs
@@ -131,15 +133,15 @@
       "cmd-7": "outline_panel::ToggleFocus",
       "cmd-8": null, // Services (bottom dock)
       "cmd-9": null, // Git History (bottom dock)
-      "cmd-0": "git_panel::ToggleFocus"
-    }
+      "cmd-0": "git_panel::ToggleFocus",
+    },
   },
   {
     "context": "Workspace || Editor",
     "bindings": {
       "alt-f12": "terminal_panel::Toggle",
-      "cmd-shift-k": "git::Push"
-    }
+      "cmd-shift-k": "git::Push",
+    },
   },
   {
     "context": "Pane",
@@ -147,8 +149,8 @@
       "cmd-alt-left": "pane::GoBack",
       "cmd-alt-right": "pane::GoForward",
       "alt-left": "pane::ActivatePreviousItem",
-      "alt-right": "pane::ActivateNextItem"
-    }
+      "alt-right": "pane::ActivateNextItem",
+    },
   },
   {
     "context": "ProjectPanel",
@@ -159,8 +161,8 @@
       "backspace": ["project_panel::Trash", { "skip_prompt": false }],
       "delete": ["project_panel::Trash", { "skip_prompt": false }],
       "shift-delete": ["project_panel::Delete", { "skip_prompt": false }],
-      "shift-f6": "project_panel::Rename"
-    }
+      "shift-f6": "project_panel::Rename",
+    },
   },
   {
     "context": "Terminal",
@@ -170,8 +172,8 @@
       "cmd-up": "terminal::ScrollLineUp",
       "cmd-down": "terminal::ScrollLineDown",
       "shift-pageup": "terminal::ScrollPageUp",
-      "shift-pagedown": "terminal::ScrollPageDown"
-    }
+      "shift-pagedown": "terminal::ScrollPageDown",
+    },
   },
   { "context": "GitPanel", "bindings": { "cmd-0": "workspace::CloseActiveDock" } },
   { "context": "ProjectPanel", "bindings": { "cmd-1": "workspace::CloseActiveDock" } },
@@ -182,7 +184,7 @@
     "context": "Dock || Workspace || OutlinePanel || ProjectPanel || CollabPanel || (Editor && mode == auto_height)",
     "bindings": {
       "escape": "editor::ToggleFocus",
-      "shift-escape": "workspace::CloseActiveDock"
-    }
-  }
+      "shift-escape": "workspace::CloseActiveDock",
+    },
+  },
 ]

assets/keymaps/macos/sublime_text.json 🔗

@@ -22,8 +22,8 @@
       "ctrl-^": ["workspace::MoveItemToPane", { "destination": 5 }],
       "ctrl-&": ["workspace::MoveItemToPane", { "destination": 6 }],
       "ctrl-*": ["workspace::MoveItemToPane", { "destination": 7 }],
-      "ctrl-(": ["workspace::MoveItemToPane", { "destination": 8 }]
-    }
+      "ctrl-(": ["workspace::MoveItemToPane", { "destination": 8 }],
+    },
   },
   {
     "context": "Editor",
@@ -57,20 +57,20 @@
       "ctrl-right": "editor::MoveToNextSubwordEnd",
       "ctrl-left": "editor::MoveToPreviousSubwordStart",
       "ctrl-shift-right": "editor::SelectToNextSubwordEnd",
-      "ctrl-shift-left": "editor::SelectToPreviousSubwordStart"
-    }
+      "ctrl-shift-left": "editor::SelectToPreviousSubwordStart",
+    },
   },
   {
     "context": "Editor && mode == full",
     "bindings": {
-      "cmd-r": "outline::Toggle"
-    }
+      "cmd-r": "outline::Toggle",
+    },
   },
   {
     "context": "Editor && !agent_diff",
     "bindings": {
-      "cmd-k cmd-z": "git::Restore"
-    }
+      "cmd-k cmd-z": "git::Restore",
+    },
   },
   {
     "context": "Pane",
@@ -85,8 +85,8 @@
       "cmd-6": ["pane::ActivateItem", 5],
       "cmd-7": ["pane::ActivateItem", 6],
       "cmd-8": ["pane::ActivateItem", 7],
-      "cmd-9": "pane::ActivateLastItem"
-    }
+      "cmd-9": "pane::ActivateLastItem",
+    },
   },
   {
     "context": "Workspace",
@@ -95,7 +95,7 @@
       "cmd-t": "file_finder::Toggle",
       "shift-cmd-r": "project_symbols::Toggle",
       // Currently busted: https://github.com/zed-industries/feedback/issues/898
-      "ctrl-0": "project_panel::ToggleFocus"
-    }
-  }
+      "ctrl-0": "project_panel::ToggleFocus",
+    },
+  },
 ]

assets/keymaps/macos/textmate.json 🔗

@@ -2,8 +2,8 @@
   {
     "bindings": {
       "cmd-shift-o": "projects::OpenRecent",
-      "cmd-alt-tab": "project_panel::ToggleFocus"
-    }
+      "cmd-alt-tab": "project_panel::ToggleFocus",
+    },
   },
   {
     "context": "Editor && mode == full",
@@ -15,8 +15,8 @@
       "cmd-enter": "editor::NewlineBelow",
       "cmd-alt-enter": "editor::NewlineAbove",
       "cmd-shift-l": "editor::SelectLine",
-      "cmd-shift-t": "outline::Toggle"
-    }
+      "cmd-shift-t": "outline::Toggle",
+    },
   },
   {
     "context": "Editor",
@@ -41,30 +41,30 @@
       "ctrl-u": "editor::ConvertToUpperCase",
       "ctrl-shift-u": "editor::ConvertToLowerCase",
       "ctrl-alt-u": "editor::ConvertToUpperCamelCase",
-      "ctrl-_": "editor::ConvertToSnakeCase"
-    }
+      "ctrl-_": "editor::ConvertToSnakeCase",
+    },
   },
   {
     "context": "BufferSearchBar",
     "bindings": {
       "ctrl-s": "search::SelectNextMatch",
-      "ctrl-shift-s": "search::SelectPreviousMatch"
-    }
+      "ctrl-shift-s": "search::SelectPreviousMatch",
+    },
   },
   {
     "context": "Workspace",
     "bindings": {
       "cmd-alt-ctrl-d": "workspace::ToggleLeftDock",
       "cmd-t": "file_finder::Toggle",
-      "cmd-shift-t": "project_symbols::Toggle"
-    }
+      "cmd-shift-t": "project_symbols::Toggle",
+    },
   },
   {
     "context": "Pane",
     "bindings": {
       "alt-cmd-r": "search::ToggleRegex",
-      "ctrl-tab": "project_panel::ToggleFocus"
-    }
+      "ctrl-tab": "project_panel::ToggleFocus",
+    },
   },
   {
     "context": "ProjectPanel",
@@ -75,11 +75,11 @@
       "return": "project_panel::Rename",
       "cmd-c": "project_panel::Copy",
       "cmd-v": "project_panel::Paste",
-      "cmd-alt-c": "project_panel::CopyPath"
-    }
+      "cmd-alt-c": "project_panel::CopyPath",
+    },
   },
   {
     "context": "Dock",
-    "bindings": {}
-  }
+    "bindings": {},
+  },
 ]

assets/keymaps/storybook.json 🔗

@@ -27,7 +27,7 @@
       "backspace": "editor::Backspace",
       "delete": "editor::Delete",
       "left": "editor::MoveLeft",
-      "right": "editor::MoveRight"
-    }
-  }
+      "right": "editor::MoveRight",
+    },
+  },
 ]

assets/keymaps/vim.json 🔗

@@ -180,10 +180,9 @@
       "ctrl-w g shift-d": "editor::GoToTypeDefinitionSplit",
       "ctrl-w space": "editor::OpenExcerptsSplit",
       "ctrl-w g space": "editor::OpenExcerptsSplit",
-      "ctrl-6": "pane::AlternateFile",
       "ctrl-^": "pane::AlternateFile",
-      ".": "vim::Repeat"
-    }
+      ".": "vim::Repeat",
+    },
   },
   {
     "context": "vim_mode == normal || vim_mode == visual || vim_mode == operator",
@@ -224,8 +223,8 @@
       "] r": "vim::GoToNextReference",
       // tree-sitter related commands
       "[ x": "vim::SelectLargerSyntaxNode",
-      "] x": "vim::SelectSmallerSyntaxNode"
-    }
+      "] x": "vim::SelectSmallerSyntaxNode",
+    },
   },
   {
     "context": "vim_mode == normal",
@@ -262,16 +261,16 @@
       "[ d": "editor::GoToPreviousDiagnostic",
       "] c": "editor::GoToHunk",
       "[ c": "editor::GoToPreviousHunk",
-      "g c": "vim::PushToggleComments"
-    }
+      "g c": "vim::PushToggleComments",
+    },
   },
   {
     "context": "VimControl && VimCount",
     "bindings": {
       "0": ["vim::Number", 0],
       ":": "vim::CountCommand",
-      "%": "vim::GoToPercentage"
-    }
+      "%": "vim::GoToPercentage",
+    },
   },
   {
     "context": "vim_mode == visual",
@@ -323,8 +322,8 @@
       "g w": "vim::Rewrap",
       "g ?": "vim::ConvertToRot13",
       // "g ?": "vim::ConvertToRot47",
-      "\"": "vim::PushRegister"
-    }
+      "\"": "vim::PushRegister",
+    },
   },
   {
     "context": "vim_mode == helix_select",
@@ -344,8 +343,8 @@
       "ctrl-pageup": "pane::ActivatePreviousItem",
       "ctrl-pagedown": "pane::ActivateNextItem",
       ".": "vim::Repeat",
-      "alt-.": "vim::RepeatFind"
-    }
+      "alt-.": "vim::RepeatFind",
+    },
   },
   {
     "context": "vim_mode == insert",
@@ -375,8 +374,8 @@
       "ctrl-r": "vim::PushRegister",
       "insert": "vim::ToggleReplace",
       "ctrl-o": "vim::TemporaryNormal",
-      "ctrl-s": "editor::ShowSignatureHelp"
-    }
+      "ctrl-s": "editor::ShowSignatureHelp",
+    },
   },
   {
     "context": "showing_completions",
@@ -384,8 +383,8 @@
       "ctrl-d": "vim::ScrollDown",
       "ctrl-u": "vim::ScrollUp",
       "ctrl-e": "vim::LineDown",
-      "ctrl-y": "vim::LineUp"
-    }
+      "ctrl-y": "vim::LineUp",
+    },
   },
   {
     "context": "(vim_mode == normal || vim_mode == helix_normal) && !menu",
@@ -410,23 +409,31 @@
       "shift-s": "vim::SubstituteLine",
       "\"": "vim::PushRegister",
       "ctrl-pagedown": "pane::ActivateNextItem",
-      "ctrl-pageup": "pane::ActivatePreviousItem"
-    }
+      "ctrl-pageup": "pane::ActivatePreviousItem",
+    },
   },
   {
     "context": "VimControl && vim_mode == helix_normal && !menu",
     "bindings": {
+      "j": ["vim::Down", { "display_lines": true }],
+      "down": ["vim::Down", { "display_lines": true }],
+      "k": ["vim::Up", { "display_lines": true }],
+      "up": ["vim::Up", { "display_lines": true }],
+      "g j": "vim::Down",
+      "g down": "vim::Down",
+      "g k": "vim::Up",
+      "g up": "vim::Up",
       "escape": "vim::SwitchToHelixNormalMode",
       "i": "vim::HelixInsert",
       "a": "vim::HelixAppend",
-      "ctrl-[": "editor::Cancel"
-    }
+      "ctrl-[": "editor::Cancel",
+    },
   },
   {
     "context": "vim_mode == helix_select && !menu",
     "bindings": {
-      "escape": "vim::SwitchToHelixNormalMode"
-    }
+      "escape": "vim::SwitchToHelixNormalMode",
+    },
   },
   {
     "context": "(vim_mode == helix_normal || vim_mode == helix_select) && !menu",
@@ -446,9 +453,9 @@
       "shift-r": "editor::Paste",
       "`": "vim::ConvertToLowerCase",
       "alt-`": "vim::ConvertToUpperCase",
-      "insert": "vim::InsertBefore",
+      "insert": "vim::InsertBefore", // not a helix default
       "shift-u": "editor::Redo",
-      "ctrl-r": "vim::Redo",
+      "ctrl-r": "vim::Redo", // not a helix default
       "y": "vim::HelixYank",
       "p": "vim::HelixPaste",
       "shift-p": ["vim::HelixPaste", { "before": true }],
@@ -477,6 +484,7 @@
       "alt-p": "editor::SelectPreviousSyntaxNode",
       "alt-n": "editor::SelectNextSyntaxNode",
 
+      // Search
       "n": "vim::HelixSelectNext",
       "shift-n": "vim::HelixSelectPrevious",
 
@@ -484,27 +492,32 @@
       "g e": "vim::EndOfDocument",
       "g h": "vim::StartOfLine",
       "g l": "vim::EndOfLine",
-      "g s": "vim::FirstNonWhitespace", // "g s" default behavior is "space s"
+      "g s": "vim::FirstNonWhitespace",
       "g t": "vim::WindowTop",
       "g c": "vim::WindowMiddle",
       "g b": "vim::WindowBottom",
-      "g r": "editor::FindAllReferences", // zed specific
+      "g r": "editor::FindAllReferences",
       "g n": "pane::ActivateNextItem",
-      "shift-l": "pane::ActivateNextItem",
+      "shift-l": "pane::ActivateNextItem", // not a helix default
       "g p": "pane::ActivatePreviousItem",
-      "shift-h": "pane::ActivatePreviousItem",
-      "g .": "vim::HelixGotoLastModification", // go to last modification
+      "shift-h": "pane::ActivatePreviousItem", // not a helix default
+      "g .": "vim::HelixGotoLastModification",
+      "g o": "editor::ToggleSelectedDiffHunks", // Zed specific
+      "g shift-o": "git::ToggleStaged", // Zed specific
+      "g shift-r": "git::Restore", // Zed specific
+      "g u": "git::StageAndNext", // Zed specific
+      "g shift-u": "git::UnstageAndNext", // Zed specific
 
       // Window mode
+      "space w v": "pane::SplitDown",
+      "space w s": "pane::SplitRight",
       "space w h": "workspace::ActivatePaneLeft",
-      "space w l": "workspace::ActivatePaneRight",
-      "space w k": "workspace::ActivatePaneUp",
       "space w j": "workspace::ActivatePaneDown",
+      "space w k": "workspace::ActivatePaneUp",
+      "space w l": "workspace::ActivatePaneRight",
       "space w q": "pane::CloseActiveItem",
-      "space w s": "pane::SplitRight",
-      "space w r": "pane::SplitRight",
-      "space w v": "pane::SplitDown",
-      "space w d": "pane::SplitDown",
+      "space w r": "pane::SplitRight", // not a helix default
+      "space w d": "pane::SplitDown", // not a helix default
 
       // Space mode
       "space f": "file_finder::Toggle",
@@ -518,6 +531,7 @@
       "space c": "editor::ToggleComments",
       "space p": "editor::Paste",
       "space y": "editor::Copy",
+      "space /": "pane::DeploySearch",
 
       // Other
       ":": "command_palette::Toggle",
@@ -525,24 +539,22 @@
       "]": ["vim::PushHelixNext", { "around": true }],
       "[": ["vim::PushHelixPrevious", { "around": true }],
       "g q": "vim::PushRewrap",
-      "g w": "vim::PushRewrap"
-      // "tab": "pane::ActivateNextItem",
-      // "shift-tab": "pane::ActivatePrevItem",
-    }
+      "g w": "vim::PushRewrap", // not a helix default & clashes with helix `goto_word`
+    },
   },
   {
     "context": "vim_mode == insert && !(showing_code_actions || showing_completions)",
     "bindings": {
       "ctrl-p": "editor::ShowWordCompletions",
-      "ctrl-n": "editor::ShowWordCompletions"
-    }
+      "ctrl-n": "editor::ShowWordCompletions",
+    },
   },
   {
     "context": "(vim_mode == insert || vim_mode == normal) && showing_signature_help && !showing_completions",
     "bindings": {
       "ctrl-p": "editor::SignatureHelpPrevious",
-      "ctrl-n": "editor::SignatureHelpNext"
-    }
+      "ctrl-n": "editor::SignatureHelpNext",
+    },
   },
   {
     "context": "vim_mode == replace",
@@ -558,8 +570,8 @@
       "backspace": "vim::UndoReplace",
       "tab": "vim::Tab",
       "enter": "vim::Enter",
-      "insert": "vim::InsertBefore"
-    }
+      "insert": "vim::InsertBefore",
+    },
   },
   {
     "context": "vim_mode == waiting",
@@ -571,14 +583,14 @@
       "escape": "vim::ClearOperators",
       "ctrl-k": ["vim::PushDigraph", {}],
       "ctrl-v": ["vim::PushLiteral", {}],
-      "ctrl-q": ["vim::PushLiteral", {}]
-    }
+      "ctrl-q": ["vim::PushLiteral", {}],
+    },
   },
   {
     "context": "Editor && vim_mode == waiting && (vim_operator == ys || vim_operator == cs)",
     "bindings": {
-      "escape": "vim::SwitchToNormalMode"
-    }
+      "escape": "vim::SwitchToNormalMode",
+    },
   },
   {
     "context": "vim_mode == operator",
@@ -586,8 +598,8 @@
       "ctrl-c": "vim::ClearOperators",
       "ctrl-[": "vim::ClearOperators",
       "escape": "vim::ClearOperators",
-      "g c": "vim::Comment"
-    }
+      "g c": "vim::Comment",
+    },
   },
   {
     "context": "vim_operator == a || vim_operator == i || vim_operator == cs || vim_operator == helix_next || vim_operator == helix_previous",
@@ -624,14 +636,14 @@
       "shift-i": ["vim::IndentObj", { "include_below": true }],
       "f": "vim::Method",
       "c": "vim::Class",
-      "e": "vim::EntireFile"
-    }
+      "e": "vim::EntireFile",
+    },
   },
   {
     "context": "vim_operator == helix_m",
     "bindings": {
-      "m": "vim::Matching"
-    }
+      "m": "vim::Matching",
+    },
   },
   {
     "context": "vim_operator == helix_next",
@@ -648,8 +660,8 @@
       "x": "editor::SelectSmallerSyntaxNode",
       "d": "editor::GoToDiagnostic",
       "c": "editor::GoToHunk",
-      "space": "vim::InsertEmptyLineBelow"
-    }
+      "space": "vim::InsertEmptyLineBelow",
+    },
   },
   {
     "context": "vim_operator == helix_previous",
@@ -666,8 +678,8 @@
       "x": "editor::SelectLargerSyntaxNode",
       "d": "editor::GoToPreviousDiagnostic",
       "c": "editor::GoToPreviousHunk",
-      "space": "vim::InsertEmptyLineAbove"
-    }
+      "space": "vim::InsertEmptyLineAbove",
+    },
   },
   {
     "context": "vim_operator == c",
@@ -675,8 +687,8 @@
       "c": "vim::CurrentLine",
       "x": "vim::Exchange",
       "d": "editor::Rename", // zed specific
-      "s": ["vim::PushChangeSurrounds", {}]
-    }
+      "s": ["vim::PushChangeSurrounds", {}],
+    },
   },
   {
     "context": "vim_operator == d",
@@ -688,36 +700,36 @@
       "shift-o": "git::ToggleStaged",
       "p": "git::Restore", // "d p"
       "u": "git::StageAndNext", // "d u"
-      "shift-u": "git::UnstageAndNext" // "d shift-u"
-    }
+      "shift-u": "git::UnstageAndNext", // "d shift-u"
+    },
   },
   {
     "context": "vim_operator == gu",
     "bindings": {
       "g u": "vim::CurrentLine",
-      "u": "vim::CurrentLine"
-    }
+      "u": "vim::CurrentLine",
+    },
   },
   {
     "context": "vim_operator == gU",
     "bindings": {
       "g shift-u": "vim::CurrentLine",
-      "shift-u": "vim::CurrentLine"
-    }
+      "shift-u": "vim::CurrentLine",
+    },
   },
   {
     "context": "vim_operator == g~",
     "bindings": {
       "g ~": "vim::CurrentLine",
-      "~": "vim::CurrentLine"
-    }
+      "~": "vim::CurrentLine",
+    },
   },
   {
     "context": "vim_operator == g?",
     "bindings": {
       "g ?": "vim::CurrentLine",
-      "?": "vim::CurrentLine"
-    }
+      "?": "vim::CurrentLine",
+    },
   },
   {
     "context": "vim_operator == gq",
@@ -725,66 +737,66 @@
       "g q": "vim::CurrentLine",
       "q": "vim::CurrentLine",
       "g w": "vim::CurrentLine",
-      "w": "vim::CurrentLine"
-    }
+      "w": "vim::CurrentLine",
+    },
   },
   {
     "context": "vim_operator == y",
     "bindings": {
       "y": "vim::CurrentLine",
       "v": "vim::PushForcedMotion",
-      "s": ["vim::PushAddSurrounds", {}]
-    }
+      "s": ["vim::PushAddSurrounds", {}],
+    },
   },
   {
     "context": "vim_operator == ys",
     "bindings": {
-      "s": "vim::CurrentLine"
-    }
+      "s": "vim::CurrentLine",
+    },
   },
   {
     "context": "vim_operator == >",
     "bindings": {
-      ">": "vim::CurrentLine"
-    }
+      ">": "vim::CurrentLine",
+    },
   },
   {
     "context": "vim_operator == <",
     "bindings": {
-      "<": "vim::CurrentLine"
-    }
+      "<": "vim::CurrentLine",
+    },
   },
   {
     "context": "vim_operator == eq",
     "bindings": {
-      "=": "vim::CurrentLine"
-    }
+      "=": "vim::CurrentLine",
+    },
   },
   {
     "context": "vim_operator == sh",
     "bindings": {
-      "!": "vim::CurrentLine"
-    }
+      "!": "vim::CurrentLine",
+    },
   },
   {
     "context": "vim_operator == gc",
     "bindings": {
-      "c": "vim::CurrentLine"
-    }
+      "c": "vim::CurrentLine",
+    },
   },
   {
     "context": "vim_operator == gR",
     "bindings": {
       "r": "vim::CurrentLine",
-      "shift-r": "vim::CurrentLine"
-    }
+      "shift-r": "vim::CurrentLine",
+    },
   },
   {
     "context": "vim_operator == cx",
     "bindings": {
       "x": "vim::CurrentLine",
-      "c": "vim::ClearExchange"
-    }
+      "c": "vim::ClearExchange",
+    },
   },
   {
     "context": "vim_mode == literal",
@@ -826,15 +838,15 @@
       "tab": ["vim::Literal", ["tab", "\u0009"]],
       // zed extensions:
       "backspace": ["vim::Literal", ["backspace", "\u0008"]],
-      "delete": ["vim::Literal", ["delete", "\u007F"]]
-    }
+      "delete": ["vim::Literal", ["delete", "\u007F"]],
+    },
   },
   {
     "context": "BufferSearchBar && !in_replace",
     "bindings": {
       "enter": "vim::SearchSubmit",
-      "escape": "buffer_search::Dismiss"
-    }
+      "escape": "buffer_search::Dismiss",
+    },
   },
   {
     "context": "VimControl && !menu || !Editor && !Terminal",
@@ -895,15 +907,19 @@
       "ctrl-w ctrl-n": "workspace::NewFileSplitHorizontal",
       "ctrl-w n": "workspace::NewFileSplitHorizontal",
       "g t": "vim::GoToTab",
-      "g shift-t": "vim::GoToPreviousTab"
-    }
+      "g shift-t": "vim::GoToPreviousTab",
+    },
   },
   {
     "context": "!Editor && !Terminal",
     "bindings": {
       ":": "command_palette::Toggle",
-      "g /": "pane::DeploySearch"
-    }
+      "g /": "pane::DeploySearch",
+      "] b": "pane::ActivateNextItem",
+      "[ b": "pane::ActivatePreviousItem",
+      "] shift-b": "pane::ActivateLastItem",
+      "[ shift-b": ["pane::ActivateItem", 0],
+    },
   },
   {
     // netrw compatibility
@@ -953,17 +969,45 @@
       "6": ["vim::Number", 6],
       "7": ["vim::Number", 7],
       "8": ["vim::Number", 8],
-      "9": ["vim::Number", 9]
-    }
+      "9": ["vim::Number", 9],
+    },
   },
   {
     "context": "OutlinePanel && not_editing",
     "bindings": {
-      "j": "menu::SelectNext",
-      "k": "menu::SelectPrevious",
+      "h": "outline_panel::CollapseSelectedEntry",
+      "j": "vim::MenuSelectNext",
+      "k": "vim::MenuSelectPrevious",
+      "down": "vim::MenuSelectNext",
+      "up": "vim::MenuSelectPrevious",
+      "l": "outline_panel::ExpandSelectedEntry",
       "shift-g": "menu::SelectLast",
-      "g g": "menu::SelectFirst"
-    }
+      "g g": "menu::SelectFirst",
+      "-": "outline_panel::SelectParent",
+      "enter": "editor::ToggleFocus",
+      "/": "menu::Cancel",
+      "ctrl-u": "outline_panel::ScrollUp",
+      "ctrl-d": "outline_panel::ScrollDown",
+      "z t": "outline_panel::ScrollCursorTop",
+      "z z": "outline_panel::ScrollCursorCenter",
+      "z b": "outline_panel::ScrollCursorBottom",
+      "0": ["vim::Number", 0],
+      "1": ["vim::Number", 1],
+      "2": ["vim::Number", 2],
+      "3": ["vim::Number", 3],
+      "4": ["vim::Number", 4],
+      "5": ["vim::Number", 5],
+      "6": ["vim::Number", 6],
+      "7": ["vim::Number", 7],
+      "8": ["vim::Number", 8],
+      "9": ["vim::Number", 9],
+    },
+  },
+  {
+    "context": "OutlinePanel && editing",
+    "bindings": {
+      "enter": "menu::Cancel",
+    },
   },
   {
     "context": "GitPanel && ChangesList",
@@ -978,8 +1022,8 @@
       "x": "git::ToggleStaged",
       "shift-x": "git::StageAll",
       "g x": "git::StageRange",
-      "shift-u": "git::UnstageAll"
-    }
+      "shift-u": "git::UnstageAll",
+    },
   },
   {
     "context": "Editor && mode == auto_height && VimControl",
@@ -990,8 +1034,8 @@
       "#": null,
       "*": null,
       "n": null,
-      "shift-n": null
-    }
+      "shift-n": null,
+    },
   },
   {
     "context": "Picker > Editor",
@@ -1000,29 +1044,29 @@
       "ctrl-u": "editor::DeleteToBeginningOfLine",
       "ctrl-w": "editor::DeleteToPreviousWordStart",
       "ctrl-p": "menu::SelectPrevious",
-      "ctrl-n": "menu::SelectNext"
-    }
+      "ctrl-n": "menu::SelectNext",
+    },
   },
   {
     "context": "GitCommit > Editor && VimControl && vim_mode == normal",
     "bindings": {
       "ctrl-c": "menu::Cancel",
-      "escape": "menu::Cancel"
-    }
+      "escape": "menu::Cancel",
+    },
   },
   {
     "context": "Editor && edit_prediction",
     "bindings": {
       // This is identical to the binding in the base keymap, but the vim bindings above to
       // "vim::Tab" shadow it, so it needs to be bound again.
-      "tab": "editor::AcceptEditPrediction"
-    }
+      "tab": "editor::AcceptEditPrediction",
+    },
   },
   {
     "context": "MessageEditor > Editor && VimControl",
     "bindings": {
-      "enter": "agent::Chat"
-    }
+      "enter": "agent::Chat",
+    },
   },
   {
     "context": "os != macos && Editor && edit_prediction_conflict",
@@ -1030,8 +1074,8 @@
       // alt-l is provided as an alternative to tab/alt-tab. and will be displayed in the UI. This
       // is because alt-tab may not be available, as it is often used for window switching on Linux
       // and Windows.
-      "alt-l": "editor::AcceptEditPrediction"
-    }
+      "alt-l": "editor::AcceptEditPrediction",
+    },
   },
   {
     "context": "SettingsWindow > NavigationMenu && !search",
@@ -1041,7 +1085,16 @@
       "k": "settings_editor::FocusPreviousNavEntry",
       "j": "settings_editor::FocusNextNavEntry",
       "g g": "settings_editor::FocusFirstNavEntry",
-      "shift-g": "settings_editor::FocusLastNavEntry"
-    }
-  }
+      "shift-g": "settings_editor::FocusLastNavEntry",
+    },
+  },
+  {
+    "context": "MarkdownPreview",
+    "bindings": {
+      "ctrl-u": "markdown::ScrollPageUp",
+      "ctrl-d": "markdown::ScrollPageDown",
+      "ctrl-y": "markdown::ScrollUp",
+      "ctrl-e": "markdown::ScrollDown",
+    },
+  },
 ]

assets/prompts/content_prompt_v2.hbs 🔗

@@ -0,0 +1,40 @@
+{{#if language_name}}
+Here's a file of {{language_name}} that the user is going to ask you to make an edit to.
+{{else}}
+Here's a file of text that the user is going to ask you to make an edit to.
+{{/if}}
+
+The section you'll need to rewrite is marked with <rewrite_this></rewrite_this> tags.
+
+<document>
+{{{document_content}}}
+</document>
+
+{{#if is_truncated}}
+The context around the relevant section has been truncated (possibly in the middle of a line) for brevity.
+{{/if}}
+
+And here's the section to rewrite based on that prompt again for reference:
+
+<rewrite_this>
+{{{rewrite_section}}}
+</rewrite_this>
+
+{{#if diagnostic_errors}}
+Below are the diagnostic errors visible to the user.  If the user requests problems to be fixed, use this information, but do not try to fix these errors if the user hasn't asked you to.
+
+{{#each diagnostic_errors}}
+<diagnostic_error>
+    <line_number>{{line_number}}</line_number>
+    <error_message>{{error_message}}</error_message>
+    <code_content>{{code_content}}</code_content>
+</diagnostic_error>
+{{/each}}
+{{/if}}
+
+Only make changes that are necessary to fulfill the prompt, leave everything else as-is. All surrounding {{content_type}} will be preserved.
+
+Start at the indentation level in the original file in the rewritten {{content_type}}.
+
+IMPORTANT: You MUST use one of the provided tools to make the rewrite or to provide an explanation as to why the user's request cannot be fulfilled. You MUST NOT send back unstructured text. If you need to make a statement or ask a question you MUST use one of the tools to do so.
+It is an error if you try to make a change that cannot be made simply by editing the rewrite_section.

assets/settings/default.json 🔗

@@ -12,7 +12,7 @@
   "theme": {
     "mode": "system",
     "light": "One Light",
-    "dark": "One Dark"
+    "dark": "One Dark",
   },
   "icon_theme": "Zed (Default)",
   // The name of a base set of key bindings to use.
@@ -29,7 +29,7 @@
   // Features that can be globally enabled or disabled
   "features": {
     // Which edit prediction provider to use.
-    "edit_prediction_provider": "zed"
+    "edit_prediction_provider": "zed",
   },
   // The name of a font to use for rendering text in the editor
   // ".ZedMono" currently aliases to Lilex
@@ -69,7 +69,7 @@
   // The OpenType features to enable for text in the UI
   "ui_font_features": {
     // Disable ligatures:
-    "calt": false
+    "calt": false,
   },
   // The weight of the UI font in standard CSS units from 100 to 900.
   "ui_font_weight": 400,
@@ -87,7 +87,7 @@
     "border_size": 0.0,
     // Opacity of the inactive panes. 0 means transparent, 1 means opaque.
     // Values are clamped to the [0.0, 1.0] range.
-    "inactive_opacity": 1.0
+    "inactive_opacity": 1.0,
   },
   // Layout mode of the bottom dock. Defaults to "contained"
   //   choices: contained, full, left_aligned, right_aligned
@@ -103,12 +103,12 @@
     "left_padding": 0.2,
     // The relative width of the right padding of the central pane from the
     // workspace when the centered layout is used.
-    "right_padding": 0.2
+    "right_padding": 0.2,
   },
   // Image viewer settings
   "image_viewer": {
     // The unit for image file sizes: "binary" (KiB, MiB) or decimal (KB, MB)
-    "unit": "binary"
+    "unit": "binary",
   },
   // Determines the modifier to be used to add multiple cursors with the mouse. The open hover link mouse gestures will adapt such that it do not conflict with the multicursor modifier.
   //
@@ -296,7 +296,7 @@
     // When true, enables drag and drop text selection in buffer.
     "enabled": true,
     // The delay in milliseconds that must elapse before drag and drop is allowed. Otherwise, a new text selection is created.
-    "delay": 300
+    "delay": 300,
   },
   // What to do when go to definition yields no results.
   //
@@ -400,14 +400,14 @@
   // Visible characters used to render whitespace when show_whitespaces is enabled.
   "whitespace_map": {
     "space": "•",
-    "tab": "→"
+    "tab": "→",
   },
   // Settings related to calls in Zed
   "calls": {
     // Join calls with the microphone live by default
     "mute_on_join": false,
     // Share your project when you are the first to join a channel
-    "share_on_join": false
+    "share_on_join": false,
   },
   // Toolbar related settings
   "toolbar": {
@@ -420,7 +420,7 @@
     // Whether to show agent review buttons in the editor toolbar.
     "agent_review": true,
     // Whether to show code action buttons in the editor toolbar.
-    "code_actions": false
+    "code_actions": false,
   },
   // Whether to allow windows to tab together based on the user’s tabbing preference (macOS only).
   "use_system_window_tabs": false,
@@ -436,10 +436,12 @@
     "show_onboarding_banner": true,
     // Whether to show user picture in the titlebar.
     "show_user_picture": true,
+    // Whether to show the user menu in the titlebar.
+    "show_user_menu": true,
     // Whether to show the sign in button in the titlebar.
     "show_sign_in": true,
     // Whether to show the menus in the titlebar.
-    "show_menus": false
+    "show_menus": false,
   },
   "audio": {
     // Opt into the new audio system.
@@ -472,7 +474,7 @@
     // the future we will migrate by setting this to false
     //
     // You need to rejoin a call for this setting to apply
-    "experimental.legacy_audio_compatible": true
+    "experimental.legacy_audio_compatible": true,
   },
   // Scrollbar related settings
   "scrollbar": {
@@ -511,8 +513,8 @@
       // When false, forcefully disables the horizontal scrollbar. Otherwise, obey other settings.
       "horizontal": true,
       // When false, forcefully disables the vertical scrollbar. Otherwise, obey other settings.
-      "vertical": true
-    }
+      "vertical": true,
+    },
   },
   // Minimap related settings
   "minimap": {
@@ -560,7 +562,7 @@
     // 3. "gutter" or "none" to not highlight the current line in the minimap.
     "current_line_highlight": null,
     // Maximum number of columns to display in the minimap.
-    "max_width_columns": 80
+    "max_width_columns": 80,
   },
   // Enable middle-click paste on Linux.
   "middle_click_paste": true,
@@ -583,7 +585,7 @@
     // Whether to show fold buttons in the gutter.
     "folds": true,
     // Minimum number of characters to reserve space for in the gutter.
-    "min_line_number_digits": 4
+    "min_line_number_digits": 4,
   },
   "indent_guides": {
     // Whether to show indent guides in the editor.
@@ -604,7 +606,7 @@
     //
     // 1. "disabled"
     // 2. "indent_aware"
-    "background_coloring": "disabled"
+    "background_coloring": "disabled",
   },
   // Whether the editor will scroll beyond the last line.
   "scroll_beyond_last_line": "one_page",
@@ -623,7 +625,7 @@
   "fast_scroll_sensitivity": 4.0,
   "sticky_scroll": {
     // Whether to stick scopes to the top of the editor.
-    "enabled": false
+    "enabled": false,
   },
   "relative_line_numbers": "disabled",
   // If 'search_wrap' is disabled, search result do not wrap around the end of the file.
@@ -641,7 +643,7 @@
     // Whether to interpret the search query as a regular expression.
     "regex": false,
     // Whether to center the cursor on each search match when navigating.
-    "center_on_match": false
+    "center_on_match": false,
   },
   // When to populate a new search's query based on the text under the cursor.
   // This setting can take the following three values:
@@ -684,8 +686,8 @@
       "shift": false,
       "alt": false,
       "platform": false,
-      "function": false
-    }
+      "function": false,
+    },
   },
   // Whether to resize all the panels in a dock when resizing the dock.
   // Can be a combination of "left", "right" and "bottom".
@@ -733,7 +735,7 @@
       //    "always"
       // 5. Never show the scrollbar:
       //    "never"
-      "show": null
+      "show": null,
     },
     // Which files containing diagnostic errors/warnings to mark in the project panel.
     // This setting can take the following three values:
@@ -756,7 +758,7 @@
       //    "always"
       // 2. Never show indent guides:
       //    "never"
-      "show": "always"
+      "show": "always",
     },
     // Sort order for entries in the project panel.
     // This setting can take three values:
@@ -781,8 +783,8 @@
       // Whether to automatically open files after pasting or duplicating them.
       "on_paste": true,
       // Whether to automatically open files dropped from external sources.
-      "on_drop": true
-    }
+      "on_drop": true,
+    },
   },
   "outline_panel": {
     // Whether to show the outline panel button in the status bar
@@ -815,7 +817,7 @@
       //    "always"
       // 2. Never show indent guides:
       //    "never"
-      "show": "always"
+      "show": "always",
     },
     // Scrollbar-related settings
     "scrollbar": {
@@ -832,11 +834,11 @@
       //    "always"
       // 5. Never show the scrollbar:
       //    "never"
-      "show": null
+      "show": null,
     },
     // Default depth to expand outline items in the current file.
     // Set to 0 to collapse all items that have children, 1 or higher to collapse items at that depth or deeper.
-    "expand_outlines_with_depth": 100
+    "expand_outlines_with_depth": 100,
   },
   "collaboration_panel": {
     // Whether to show the collaboration panel button in the status bar.
@@ -844,7 +846,7 @@
     // Where to dock the collaboration panel. Can be 'left' or 'right'.
     "dock": "left",
     // Default width of the collaboration panel.
-    "default_width": 240
+    "default_width": 240,
   },
   "git_panel": {
     // Whether to show the git panel button in the status bar.
@@ -870,18 +872,22 @@
     //
     // Default: false
     "collapse_untracked_diff": false,
+    /// Whether to show entries with tree or flat view in the panel
+    ///
+    /// Default: false
+    "tree_view": false,
     "scrollbar": {
       // When to show the scrollbar in the git panel.
       //
       // Choices: always, auto, never, system
       // Default: inherits editor scrollbar settings
       // "show": null
-    }
+    },
   },
   "message_editor": {
     // Whether to automatically replace emoji shortcodes with emoji characters.
     // For example: typing `:wave:` gets replaced with `👋`.
-    "auto_replace_emoji_shortcode": true
+    "auto_replace_emoji_shortcode": true,
   },
   "notification_panel": {
     // Whether to show the notification panel button in the status bar.
@@ -889,9 +895,11 @@
     // Where to dock the notification panel. Can be 'left' or 'right'.
     "dock": "right",
     // Default width of the notification panel.
-    "default_width": 380
+    "default_width": 380,
   },
   "agent": {
+    // Whether the inline assistant should use streaming tools, when available
+    "inline_assistant_use_streaming_tools": true,
     // Whether the agent is enabled.
     "enabled": true,
     // What completion mode to start new threads in, if available. Can be 'normal' or 'burn'.
@@ -900,6 +908,8 @@
     "button": true,
     // Where to dock the agent panel. Can be 'left', 'right' or 'bottom'.
     "dock": "right",
+    // Where to dock the agents panel. Can be 'left' or 'right'.
+    "agents_panel_dock": "left",
     // Default width when the agent panel is docked to the left or right.
     "default_width": 640,
     // Default height when the agent panel is docked to the bottom.
@@ -911,7 +921,7 @@
       // The provider to use.
       "provider": "zed.dev",
       // The model to use.
-      "model": "claude-sonnet-4"
+      "model": "claude-sonnet-4",
     },
     // Additional parameters for language model requests. When making a request to a model, parameters will be taken
     // from the last entry in this list that matches the model's provider and name. In each entry, both provider
@@ -962,12 +972,14 @@
           "now": true,
           "find_path": true,
           "read_file": true,
+          "restore_file_from_disk": true,
+          "save_file": true,
           "open": true,
           "grep": true,
           "terminal": true,
           "thinking": true,
-          "web_search": true
-        }
+          "web_search": true,
+        },
       },
       "ask": {
         "name": "Ask",
@@ -984,14 +996,14 @@
           "open": true,
           "grep": true,
           "thinking": true,
-          "web_search": true
-        }
+          "web_search": true,
+        },
       },
       "minimal": {
         "name": "Minimal",
         "enable_all_context_servers": false,
-        "tools": {}
-      }
+        "tools": {},
+      },
     },
     // Where to show notifications when the agent has either completed
     // its response, or else needs confirmation before it can run a
@@ -1020,7 +1032,7 @@
     // Minimum number of lines to display in the agent message editor.
     //
     // Default: 4
-    "message_editor_min_lines": 4
+    "message_editor_min_lines": 4,
   },
   // Whether the screen sharing icon is shown in the os status bar.
   "show_call_status_icon": true,
@@ -1055,7 +1067,7 @@
     // Whether or not to show the navigation history buttons.
     "show_nav_history_buttons": true,
     // Whether or not to show the tab bar buttons.
-    "show_tab_bar_buttons": true
+    "show_tab_bar_buttons": true,
   },
   // Settings related to the editor's tabs
   "tabs": {
@@ -1094,19 +1106,28 @@
     //    "errors"
     // 3. Mark files with errors and warnings:
     //    "all"
-    "show_diagnostics": "off"
+    "show_diagnostics": "off",
   },
   // Settings related to preview tabs.
   "preview_tabs": {
     // Whether preview tabs should be enabled.
     // Preview tabs allow you to open files in preview mode, where they close automatically
-    // when you switch to another file unless you explicitly pin them.
+    // when you open another preview tab.
     // This is useful for quickly viewing files without cluttering your workspace.
     "enabled": true,
+    // Whether to open tabs in preview mode when opened from the project panel with a single click.
+    "enable_preview_from_project_panel": true,
     // Whether to open tabs in preview mode when selected from the file finder.
     "enable_preview_from_file_finder": false,
-    // Whether a preview tab gets replaced when code navigation is used to navigate away from the tab.
-    "enable_preview_from_code_navigation": false
+    // Whether to open tabs in preview mode when opened from a multibuffer.
+    "enable_preview_from_multibuffer": true,
+    // Whether to open tabs in preview mode when code navigation is used to open a multibuffer.
+    "enable_preview_multibuffer_from_code_navigation": false,
+    // Whether to open tabs in preview mode when code navigation is used to open a single file.
+    "enable_preview_file_from_code_navigation": true,
+    // Whether to keep tabs in preview mode when code navigation is used to navigate away from them.
+    // If `enable_preview_file_from_code_navigation` or `enable_preview_multibuffer_from_code_navigation` is also true, the new tab may replace the existing one.
+    "enable_keep_preview_on_code_navigation": false,
   },
   // Settings related to the file finder.
   "file_finder": {
@@ -1150,13 +1171,17 @@
     //   * "all": Use all gitignored files
     //   * "indexed": Use only the files Zed had indexed
     //   * "smart": Be smart and search for ignored when called from a gitignored worktree
-    "include_ignored": "smart"
+    "include_ignored": "smart",
   },
   // Whether or not to remove any trailing whitespace from lines of a buffer
   // before saving it.
   "remove_trailing_whitespace_on_save": true,
   // Whether to start a new line with a comment when a previous line is a comment as well.
   "extend_comment_on_newline": true,
+  // Whether to continue markdown lists when pressing enter.
+  "extend_list_on_newline": true,
+  // Whether to indent list items when pressing tab after a list marker.
+  "indent_list_on_tab": true,
   // Removes any lines containing only whitespace at the end of the file and
   // ensures just one newline at the end.
   "ensure_final_newline_on_save": true,
@@ -1221,7 +1246,7 @@
     // Send debug info like crash reports.
     "diagnostics": true,
     // Send anonymized usage data like what languages you're using Zed with.
-    "metrics": true
+    "metrics": true,
   },
   // Whether to disable all AI features in Zed.
   //
@@ -1255,7 +1280,7 @@
       "enabled": true,
       // Minimum time to wait before pulling diagnostics from the language server(s).
       // 0 turns the debounce off.
-      "debounce_ms": 50
+      "debounce_ms": 50,
     },
     // Settings for inline diagnostics
     "inline": {
@@ -1273,8 +1298,8 @@
       "min_column": 0,
       // The minimum severity of the diagnostics to show inline.
       // Inherits editor's diagnostics' max severity settings when `null`.
-      "max_severity": null
-    }
+      "max_severity": null,
+    },
   },
   // Files or globs of files that will be excluded by Zed entirely. They will be skipped during file
   // scans, file searches, and not be displayed in the project file tree. Takes precedence over `file_scan_inclusions`.
@@ -1288,7 +1313,7 @@
     "**/.DS_Store",
     "**/Thumbs.db",
     "**/.classpath",
-    "**/.settings"
+    "**/.settings",
   ],
   // Files or globs of files that will be included by Zed, even when ignored by git. This is useful
   // for files that are not tracked by git, but are still important to your project. Note that globs
@@ -1300,6 +1325,14 @@
   "hidden_files": ["**/.*"],
   // Git gutter behavior configuration.
   "git": {
+    // Global switch to enable or disable all git integration features.
+    // If set to true, disables all git integration features.
+    // If set to false, individual git integration features below will be independently enabled or disabled.
+    "disable_git": false,
+    // Whether to enable git status tracking.
+    "enable_status": true,
+    // Whether to enable git diff display.
+    "enable_diff": true,
     // Control whether the git gutter is shown. May take 2 values:
     // 1. Show the gutter
     //      "git_gutter": "tracked_files"
@@ -1323,14 +1356,14 @@
       // Whether or not to display the git commit summary on the same line.
       "show_commit_summary": false,
       // The minimum column number to show the inline blame information at
-      "min_column": 0
+      "min_column": 0,
     },
     "blame": {
-      "show_avatar": true
+      "show_avatar": true,
     },
     // Control which information is shown in the branch picker.
     "branch_picker": {
-      "show_author_name": true
+      "show_author_name": true,
     },
     // How git hunks are displayed visually in the editor.
     // This setting can take two values:
@@ -1342,7 +1375,7 @@
     "hunk_style": "staged_hollow",
     // Should the name or path be displayed first in the git view.
     // "path_style": "file_name_first" or "file_path_first"
-    "path_style": "file_name_first"
+    "path_style": "file_name_first",
   },
   // The list of custom Git hosting providers.
   "git_hosting_providers": [
@@ -1376,7 +1409,7 @@
       "**/secrets.yml",
       "**/.zed/settings.json", // zed project settings
       "/**/zed/settings.json", // zed user settings
-      "/**/zed/keymap.json"
+      "/**/zed/keymap.json",
     ],
     // When to show edit predictions previews in buffer.
     // This setting takes two possible values:
@@ -1394,15 +1427,16 @@
     "copilot": {
       "enterprise_uri": null,
       "proxy": null,
-      "proxy_no_verify": null
+      "proxy_no_verify": null,
     },
     "codestral": {
-      "model": null,
-      "max_tokens": null
+      "api_url": "https://codestral.mistral.ai",
+      "model": "codestral-latest",
+      "max_tokens": 150,
     },
     // Whether edit predictions are enabled when editing text threads in the agent panel.
     // This setting has no effect if globally disabled.
-    "enabled_in_text_threads": true
+    "enabled_in_text_threads": true,
   },
   // Settings specific to journaling
   "journal": {
@@ -1412,7 +1446,7 @@
     // May take 2 values:
     // 1. hour12
     // 2. hour24
-    "hour_format": "hour12"
+    "hour_format": "hour12",
   },
   // Status bar-related settings.
   "status_bar": {
@@ -1423,7 +1457,7 @@
     // Whether to show the cursor position button in the status bar.
     "cursor_position_button": true,
     // Whether to show active line endings button in the status bar.
-    "line_endings_button": false
+    "line_endings_button": false,
   },
   // Settings specific to the terminal
   "terminal": {
@@ -1544,8 +1578,8 @@
         // Preferred Conda manager to use when activating Conda environments.
         // Values: "auto", "conda", "mamba", "micromamba"
         // Default: "auto"
-        "conda_manager": "auto"
-      }
+        "conda_manager": "auto",
+      },
     },
     "toolbar": {
       // Whether to display the terminal title in its toolbar's breadcrumbs.
@@ -1553,7 +1587,7 @@
       //
       // The shell running in the terminal needs to be configured to emit the title.
       // Example: `echo -e "\e]2;New Title\007";`
-      "breadcrumbs": false
+      "breadcrumbs": false,
     },
     // Scrollbar-related settings
     "scrollbar": {
@@ -1570,7 +1604,7 @@
       //    "always"
       // 5. Never show the scrollbar:
       //    "never"
-      "show": null
+      "show": null,
     },
     // Set the terminal's font size. If this option is not included,
     // the terminal will default to matching the buffer's font size.
@@ -1633,30 +1667,26 @@
       // surrounding symbols or quotes
       [
         "(?x)",
-        "# optionally starts with 0-2 opening prefix symbols",
-        "[({\\[<]{0,2}",
-        "# which may be followed by an opening quote",
-        "(?<quote>[\"'`])?",
-        "# `path` is the shortest sequence of any non-space character",
-        "(?<link>(?<path>[^ ]+?",
-        "    # which may end with a line and optionally a column,",
-        "    (?<line_column>:+[0-9]+(:[0-9]+)?|:?\\([0-9]+([,:][0-9]+)?\\))?",
-        "))",
-        "# which must be followed by a matching quote",
-        "(?(<quote>)\\k<quote>)",
-        "# and optionally a single closing symbol",
-        "[)}\\]>]?",
-        "# if line/column matched, may be followed by a description",
-        "(?(<line_column>):[^ 0-9][^ ]*)?",
-        "# which may be followed by trailing punctuation",
-        "[.,:)}\\]>]*",
-        "# and always includes trailing whitespace or end of line",
-        "([ ]+|$)"
-      ]
+        "(?<path>",
+        "    (",
+        "        # multi-char path: first char (not opening delimiter or space)",
+        "        [^({\\[<\"'`\\ ]",
+        "        # middle chars: non-space, and colon/paren only if not followed by digit/paren",
+        "        ([^\\ :(]|[:(][^0-9()])*",
+        "        # last char: not closing delimiter or colon",
+        "        [^()}\\]>\"'`.,;:\\ ]",
+        "    |",
+        "        # single-char path: not delimiter, punctuation, or space",
+        "        [^(){}\\[\\]<>\"'`.,;:\\ ]",
+        "    )",
+        "    # optional line/column suffix (included in path for PathWithPosition::parse_str)",
+        "    (:+[0-9]+(:[0-9]+)?|:?\\([0-9]+([,:]?[0-9]+)?\\))?",
+        ")",
+      ],
     ],
     // Timeout for hover and Cmd-click path hyperlink discovery in milliseconds. Specifying a
     // timeout of `0` will disable path hyperlinking in terminal.
-    "path_hyperlink_timeout_ms": 1
+    "path_hyperlink_timeout_ms": 1,
   },
   "code_actions_on_format": {},
   // Settings related to running tasks.
@@ -1672,7 +1702,7 @@
     // * Zed task from history (e.g. one-off task was spawned before)
     //
     // Default: true
-    "prefer_lsp": true
+    "prefer_lsp": true,
   },
   // An object whose keys are language names, and whose values
   // are arrays of filenames or extensions of files that should
@@ -1687,9 +1717,14 @@
   // }
   //
   "file_types": {
-    "JSONC": ["**/.zed/**/*.json", "**/zed/**/*.json", "**/Zed/**/*.json", "**/.vscode/**/*.json", "tsconfig*.json"],
+    "JSONC": [
+      "**/.zed/*.json",
+      "**/.vscode/**/*.json",
+      "**/{zed,Zed}/{settings,keymap,tasks,debug}.json",
+      "tsconfig*.json",
+    ],
     "Markdown": [".rules", ".cursorrules", ".windsurfrules", ".clinerules"],
-    "Shell Script": [".env.*"]
+    "Shell Script": [".env.*"],
   },
   // Settings for which version of Node.js and NPM to use when installing
   // language servers and Copilot.
@@ -1705,14 +1740,14 @@
     // `path`, but not `npm_path`, Zed will assume that `npm` is located at
     // `${path}/../npm`.
     "path": null,
-    "npm_path": null
+    "npm_path": null,
   },
   // The extensions that Zed should automatically install on startup.
   //
   // If you don't want any of these extensions, add this field to your settings
   // and change the value to `false`.
   "auto_install_extensions": {
-    "html": true
+    "html": true,
   },
   // The capabilities granted to extensions.
   //
@@ -1720,7 +1755,7 @@
   "granted_extension_capabilities": [
     { "kind": "process:exec", "command": "*", "args": ["**"] },
     { "kind": "download_file", "host": "*", "path": ["**"] },
-    { "kind": "npm:install", "package": "*" }
+    { "kind": "npm:install", "package": "*" },
   ],
   // Controls how completions are processed for this language.
   "completions": {
@@ -1771,7 +1806,7 @@
     // 4. "replace_suffix"
     //   Behaves like `"replace"` if the text after the cursor is a suffix of the completion, and like
     //   `"insert"` otherwise.
-    "lsp_insert_mode": "replace_suffix"
+    "lsp_insert_mode": "replace_suffix",
   },
   // Different settings for specific languages.
   "languages": {
@@ -1779,113 +1814,116 @@
       "language_servers": ["astro-language-server", "..."],
       "prettier": {
         "allowed": true,
-        "plugins": ["prettier-plugin-astro"]
-      }
+        "plugins": ["prettier-plugin-astro"],
+      },
     },
     "Blade": {
       "prettier": {
-        "allowed": true
-      }
+        "allowed": true,
+      },
     },
     "C": {
       "format_on_save": "off",
       "use_on_type_format": false,
       "prettier": {
-        "allowed": false
-      }
+        "allowed": false,
+      },
     },
     "C++": {
       "format_on_save": "off",
       "use_on_type_format": false,
       "prettier": {
-        "allowed": false
-      }
+        "allowed": false,
+      },
+    },
+    "CSharp": {
+      "language_servers": ["roslyn", "!omnisharp", "..."],
     },
     "CSS": {
       "prettier": {
-        "allowed": true
-      }
+        "allowed": true,
+      },
     },
     "Dart": {
-      "tab_size": 2
+      "tab_size": 2,
     },
     "Diff": {
       "show_edit_predictions": false,
       "remove_trailing_whitespace_on_save": false,
-      "ensure_final_newline_on_save": false
+      "ensure_final_newline_on_save": false,
     },
     "Elixir": {
-      "language_servers": ["elixir-ls", "!expert", "!next-ls", "!lexical", "..."]
+      "language_servers": ["elixir-ls", "!expert", "!next-ls", "!lexical", "..."],
     },
     "Elm": {
-      "tab_size": 4
+      "tab_size": 4,
     },
     "Erlang": {
-      "language_servers": ["erlang-ls", "!elp", "..."]
+      "language_servers": ["erlang-ls", "!elp", "..."],
     },
     "Git Commit": {
       "allow_rewrap": "anywhere",
       "soft_wrap": "editor_width",
-      "preferred_line_length": 72
+      "preferred_line_length": 72,
     },
     "Go": {
       "hard_tabs": true,
       "code_actions_on_format": {
-        "source.organizeImports": true
+        "source.organizeImports": true,
       },
-      "debuggers": ["Delve"]
+      "debuggers": ["Delve"],
     },
     "GraphQL": {
       "prettier": {
-        "allowed": true
-      }
+        "allowed": true,
+      },
     },
     "HEEX": {
-      "language_servers": ["elixir-ls", "!expert", "!next-ls", "!lexical", "..."]
+      "language_servers": ["elixir-ls", "!expert", "!next-ls", "!lexical", "..."],
     },
     "HTML": {
       "prettier": {
-        "allowed": true
-      }
+        "allowed": true,
+      },
     },
     "HTML+ERB": {
-      "language_servers": ["herb", "!ruby-lsp", "..."]
+      "language_servers": ["herb", "!ruby-lsp", "..."],
     },
     "Java": {
       "prettier": {
         "allowed": true,
-        "plugins": ["prettier-plugin-java"]
-      }
+        "plugins": ["prettier-plugin-java"],
+      },
     },
     "JavaScript": {
       "language_servers": ["!typescript-language-server", "vtsls", "..."],
       "prettier": {
-        "allowed": true
-      }
+        "allowed": true,
+      },
     },
     "JSON": {
       "prettier": {
-        "allowed": true
-      }
+        "allowed": true,
+      },
     },
     "JSONC": {
       "prettier": {
-        "allowed": true
-      }
+        "allowed": true,
+      },
     },
     "JS+ERB": {
-      "language_servers": ["!ruby-lsp", "..."]
+      "language_servers": ["!ruby-lsp", "..."],
     },
     "Kotlin": {
-      "language_servers": ["!kotlin-language-server", "kotlin-lsp", "..."]
+      "language_servers": ["!kotlin-language-server", "kotlin-lsp", "..."],
     },
     "LaTeX": {
       "formatter": "language_server",
       "language_servers": ["texlab", "..."],
       "prettier": {
         "allowed": true,
-        "plugins": ["prettier-plugin-latex"]
-      }
+        "plugins": ["prettier-plugin-latex"],
+      },
     },
     "Markdown": {
       "format_on_save": "off",
@@ -1893,136 +1931,145 @@
       "remove_trailing_whitespace_on_save": false,
       "allow_rewrap": "anywhere",
       "soft_wrap": "editor_width",
+      "completions": {
+        "words": "disabled",
+      },
       "prettier": {
-        "allowed": true
-      }
+        "allowed": true,
+      },
     },
     "PHP": {
       "language_servers": ["phpactor", "!intelephense", "!phptools", "..."],
       "prettier": {
         "allowed": true,
         "plugins": ["@prettier/plugin-php"],
-        "parser": "php"
-      }
+        "parser": "php",
+      },
     },
     "Plain Text": {
       "allow_rewrap": "anywhere",
-      "soft_wrap": "editor_width"
+      "soft_wrap": "editor_width",
+      "completions": {
+        "words": "disabled",
+      },
+    },
+    "Proto": {
+      "language_servers": ["buf", "!protols", "!protobuf-language-server", "..."],
     },
     "Python": {
       "code_actions_on_format": {
-        "source.organizeImports.ruff": true
+        "source.organizeImports.ruff": true,
       },
       "formatter": {
         "language_server": {
-          "name": "ruff"
-        }
+          "name": "ruff",
+        },
       },
       "debuggers": ["Debugpy"],
-      "language_servers": ["basedpyright", "ruff", "!ty", "!pyrefly", "!pyright", "!pylsp", "..."]
+      "language_servers": ["basedpyright", "ruff", "!ty", "!pyrefly", "!pyright", "!pylsp", "..."],
     },
     "Ruby": {
-      "language_servers": ["solargraph", "!ruby-lsp", "!rubocop", "!sorbet", "!steep", "..."]
+      "language_servers": ["solargraph", "!ruby-lsp", "!rubocop", "!sorbet", "!steep", "..."],
     },
     "Rust": {
-      "debuggers": ["CodeLLDB"]
+      "debuggers": ["CodeLLDB"],
     },
     "SCSS": {
       "prettier": {
-        "allowed": true
-      }
+        "allowed": true,
+      },
     },
     "Starlark": {
-      "language_servers": ["starpls", "!buck2-lsp", "..."]
+      "language_servers": ["starpls", "!buck2-lsp", "..."],
     },
     "Svelte": {
       "language_servers": ["svelte-language-server", "..."],
       "prettier": {
         "allowed": true,
-        "plugins": ["prettier-plugin-svelte"]
-      }
+        "plugins": ["prettier-plugin-svelte"],
+      },
     },
     "TSX": {
       "language_servers": ["!typescript-language-server", "vtsls", "..."],
       "prettier": {
-        "allowed": true
-      }
+        "allowed": true,
+      },
     },
     "Twig": {
       "prettier": {
-        "allowed": true
-      }
+        "allowed": true,
+      },
     },
     "TypeScript": {
       "language_servers": ["!typescript-language-server", "vtsls", "..."],
       "prettier": {
-        "allowed": true
-      }
+        "allowed": true,
+      },
     },
     "SystemVerilog": {
       "format_on_save": "off",
       "language_servers": ["!slang", "..."],
-      "use_on_type_format": false
+      "use_on_type_format": false,
     },
     "Vue.js": {
       "language_servers": ["vue-language-server", "vtsls", "..."],
       "prettier": {
-        "allowed": true
-      }
+        "allowed": true,
+      },
     },
     "XML": {
       "prettier": {
         "allowed": true,
-        "plugins": ["@prettier/plugin-xml"]
-      }
+        "plugins": ["@prettier/plugin-xml"],
+      },
     },
     "YAML": {
       "prettier": {
-        "allowed": true
-      }
+        "allowed": true,
+      },
     },
     "YAML+ERB": {
-      "language_servers": ["!ruby-lsp", "..."]
+      "language_servers": ["!ruby-lsp", "..."],
     },
     "Zig": {
-      "language_servers": ["zls", "..."]
-    }
+      "language_servers": ["zls", "..."],
+    },
   },
   // Different settings for specific language models.
   "language_models": {
     "anthropic": {
-      "api_url": "https://api.anthropic.com"
+      "api_url": "https://api.anthropic.com",
     },
     "bedrock": {},
     "google": {
-      "api_url": "https://generativelanguage.googleapis.com"
+      "api_url": "https://generativelanguage.googleapis.com",
     },
     "ollama": {
-      "api_url": "http://localhost:11434"
+      "api_url": "http://localhost:11434",
     },
     "openai": {
-      "api_url": "https://api.openai.com/v1"
+      "api_url": "https://api.openai.com/v1",
     },
     "openai_compatible": {},
     "open_router": {
-      "api_url": "https://openrouter.ai/api/v1"
+      "api_url": "https://openrouter.ai/api/v1",
     },
     "lmstudio": {
-      "api_url": "http://localhost:1234/api/v0"
+      "api_url": "http://localhost:1234/api/v0",
     },
     "deepseek": {
-      "api_url": "https://api.deepseek.com/v1"
+      "api_url": "https://api.deepseek.com/v1",
     },
     "mistral": {
-      "api_url": "https://api.mistral.ai/v1"
+      "api_url": "https://api.mistral.ai/v1",
     },
     "vercel": {
-      "api_url": "https://api.v0.dev/v1"
+      "api_url": "https://api.v0.dev/v1",
     },
     "x_ai": {
-      "api_url": "https://api.x.ai/v1"
+      "api_url": "https://api.x.ai/v1",
     },
-    "zed.dev": {}
+    "zed.dev": {},
   },
   "session": {
     // Whether or not to restore unsaved buffers on restart.

assets/settings/initial_debug_tasks.json 🔗

@@ -8,7 +8,7 @@
     "adapter": "Debugpy",
     "program": "$ZED_FILE",
     "request": "launch",
-    "cwd": "$ZED_WORKTREE_ROOT"
+    "cwd": "$ZED_WORKTREE_ROOT",
   },
   {
     "label": "Debug active JavaScript file",
@@ -16,7 +16,7 @@
     "program": "$ZED_FILE",
     "request": "launch",
     "cwd": "$ZED_WORKTREE_ROOT",
-    "type": "pwa-node"
+    "type": "pwa-node",
   },
   {
     "label": "JavaScript debug terminal",
@@ -24,6 +24,6 @@
     "request": "launch",
     "cwd": "$ZED_WORKTREE_ROOT",
     "console": "integratedTerminal",
-    "type": "pwa-node"
-  }
+    "type": "pwa-node",
+  },
 ]

assets/settings/initial_server_settings.json 🔗

@@ -3,5 +3,5 @@
 // For a full list of overridable settings, and general information on settings,
 // see the documentation: https://zed.dev/docs/configuring-zed#settings-files
 {
-  "lsp": {}
+  "lsp": {},
 }

assets/settings/initial_tasks.json 🔗

@@ -47,8 +47,8 @@
     // Whether to show the task line in the output of the spawned task, defaults to `true`.
     "show_summary": true,
     // Whether to show the command line in the output of the spawned task, defaults to `true`.
-    "show_command": true
+    "show_command": true,
     // Represents the tags for inline runnable indicators, or spawning multiple tasks at once.
     // "tags": []
-  }
+  },
 ]

assets/themes/ayu/ayu.json 🔗

@@ -45,6 +45,7 @@
         "tab.inactive_background": "#1f2127ff",
         "tab.active_background": "#0d1016ff",
         "search.match_background": "#5ac2fe66",
+        "search.active_match_background": "#ea570166",
         "panel.background": "#1f2127ff",
         "panel.focused_border": "#5ac1feff",
         "pane.focused_border": null,
@@ -436,6 +437,7 @@
         "tab.inactive_background": "#ececedff",
         "tab.active_background": "#fcfcfcff",
         "search.match_background": "#3b9ee566",
+        "search.active_match_background": "#f88b3666",
         "panel.background": "#ececedff",
         "panel.focused_border": "#3b9ee5ff",
         "pane.focused_border": null,
@@ -827,6 +829,7 @@
         "tab.inactive_background": "#353944ff",
         "tab.active_background": "#242835ff",
         "search.match_background": "#73cffe66",
+        "search.active_match_background": "#fd722b66",
         "panel.background": "#353944ff",
         "panel.focused_border": null,
         "pane.focused_border": null,

assets/themes/gruvbox/gruvbox.json 🔗

@@ -46,6 +46,7 @@
         "tab.inactive_background": "#3a3735ff",
         "tab.active_background": "#282828ff",
         "search.match_background": "#83a59866",
+        "search.active_match_background": "#c09f3f66",
         "panel.background": "#3a3735ff",
         "panel.focused_border": "#83a598ff",
         "pane.focused_border": null,
@@ -70,33 +71,33 @@
         "editor.document_highlight.read_background": "#83a5981a",
         "editor.document_highlight.write_background": "#92847466",
         "terminal.background": "#282828ff",
-        "terminal.foreground": "#fbf1c7ff",
+        "terminal.foreground": "#ebdbb2ff",
         "terminal.bright_foreground": "#fbf1c7ff",
-        "terminal.dim_foreground": "#282828ff",
+        "terminal.dim_foreground": "#766b5dff",
         "terminal.ansi.black": "#282828ff",
-        "terminal.ansi.bright_black": "#73675eff",
+        "terminal.ansi.bright_black": "#928374ff",
         "terminal.ansi.dim_black": "#fbf1c7ff",
-        "terminal.ansi.red": "#fb4a35ff",
-        "terminal.ansi.bright_red": "#93201dff",
-        "terminal.ansi.dim_red": "#ffaa95ff",
-        "terminal.ansi.green": "#b7bb26ff",
-        "terminal.ansi.bright_green": "#605c1bff",
-        "terminal.ansi.dim_green": "#e0dc98ff",
-        "terminal.ansi.yellow": "#f9bd2fff",
-        "terminal.ansi.bright_yellow": "#91611bff",
-        "terminal.ansi.dim_yellow": "#fedc9bff",
-        "terminal.ansi.blue": "#83a598ff",
-        "terminal.ansi.bright_blue": "#414f4aff",
-        "terminal.ansi.dim_blue": "#c0d2cbff",
-        "terminal.ansi.magenta": "#d3869bff",
-        "terminal.ansi.bright_magenta": "#8e5868ff",
-        "terminal.ansi.dim_magenta": "#ff9ebbff",
-        "terminal.ansi.cyan": "#8ec07cff",
-        "terminal.ansi.bright_cyan": "#45603eff",
-        "terminal.ansi.dim_cyan": "#c7dfbdff",
-        "terminal.ansi.white": "#fbf1c7ff",
-        "terminal.ansi.bright_white": "#ffffffff",
-        "terminal.ansi.dim_white": "#b0a189ff",
+        "terminal.ansi.red": "#cc241dff",
+        "terminal.ansi.bright_red": "#fb4934ff",
+        "terminal.ansi.dim_red": "#8e1814ff",
+        "terminal.ansi.green": "#98971aff",
+        "terminal.ansi.bright_green": "#b8bb26ff",
+        "terminal.ansi.dim_green": "#6a6912ff",
+        "terminal.ansi.yellow": "#d79921ff",
+        "terminal.ansi.bright_yellow": "#fabd2fff",
+        "terminal.ansi.dim_yellow": "#966a17ff",
+        "terminal.ansi.blue": "#458588ff",
+        "terminal.ansi.bright_blue": "#83a598ff",
+        "terminal.ansi.dim_blue": "#305d5fff",
+        "terminal.ansi.magenta": "#b16286ff",
+        "terminal.ansi.bright_magenta": "#d3869bff",
+        "terminal.ansi.dim_magenta": "#7c455eff",
+        "terminal.ansi.cyan": "#689d6aff",
+        "terminal.ansi.bright_cyan": "#8ec07cff",
+        "terminal.ansi.dim_cyan": "#496e4aff",
+        "terminal.ansi.white": "#a89984ff",
+        "terminal.ansi.bright_white": "#fbf1c7ff",
+        "terminal.ansi.dim_white": "#766b5dff",
         "link_text.hover": "#83a598ff",
         "version_control.added": "#b7bb26ff",
         "version_control.modified": "#f9bd2fff",
@@ -452,6 +453,7 @@
         "tab.inactive_background": "#393634ff",
         "tab.active_background": "#1d2021ff",
         "search.match_background": "#83a59866",
+        "search.active_match_background": "#c9653666",
         "panel.background": "#393634ff",
         "panel.focused_border": "#83a598ff",
         "pane.focused_border": null,
@@ -476,33 +478,33 @@
         "editor.document_highlight.read_background": "#83a5981a",
         "editor.document_highlight.write_background": "#92847466",
         "terminal.background": "#1d2021ff",
-        "terminal.foreground": "#fbf1c7ff",
+        "terminal.foreground": "#ebdbb2ff",
         "terminal.bright_foreground": "#fbf1c7ff",
-        "terminal.dim_foreground": "#1d2021ff",
-        "terminal.ansi.black": "#1d2021ff",
-        "terminal.ansi.bright_black": "#73675eff",
+        "terminal.dim_foreground": "#766b5dff",
+        "terminal.ansi.black": "#282828ff",
+        "terminal.ansi.bright_black": "#928374ff",
         "terminal.ansi.dim_black": "#fbf1c7ff",
-        "terminal.ansi.red": "#fb4a35ff",
-        "terminal.ansi.bright_red": "#93201dff",
-        "terminal.ansi.dim_red": "#ffaa95ff",
-        "terminal.ansi.green": "#b7bb26ff",
-        "terminal.ansi.bright_green": "#605c1bff",
-        "terminal.ansi.dim_green": "#e0dc98ff",
-        "terminal.ansi.yellow": "#f9bd2fff",
-        "terminal.ansi.bright_yellow": "#91611bff",
-        "terminal.ansi.dim_yellow": "#fedc9bff",
-        "terminal.ansi.blue": "#83a598ff",
-        "terminal.ansi.bright_blue": "#414f4aff",
-        "terminal.ansi.dim_blue": "#c0d2cbff",
-        "terminal.ansi.magenta": "#d3869bff",
-        "terminal.ansi.bright_magenta": "#8e5868ff",
-        "terminal.ansi.dim_magenta": "#ff9ebbff",
-        "terminal.ansi.cyan": "#8ec07cff",
-        "terminal.ansi.bright_cyan": "#45603eff",
-        "terminal.ansi.dim_cyan": "#c7dfbdff",
-        "terminal.ansi.white": "#fbf1c7ff",
-        "terminal.ansi.bright_white": "#ffffffff",
-        "terminal.ansi.dim_white": "#b0a189ff",
+        "terminal.ansi.red": "#cc241dff",
+        "terminal.ansi.bright_red": "#fb4934ff",
+        "terminal.ansi.dim_red": "#8e1814ff",
+        "terminal.ansi.green": "#98971aff",
+        "terminal.ansi.bright_green": "#b8bb26ff",
+        "terminal.ansi.dim_green": "#6a6912ff",
+        "terminal.ansi.yellow": "#d79921ff",
+        "terminal.ansi.bright_yellow": "#fabd2fff",
+        "terminal.ansi.dim_yellow": "#966a17ff",
+        "terminal.ansi.blue": "#458588ff",
+        "terminal.ansi.bright_blue": "#83a598ff",
+        "terminal.ansi.dim_blue": "#305d5fff",
+        "terminal.ansi.magenta": "#b16286ff",
+        "terminal.ansi.bright_magenta": "#d3869bff",
+        "terminal.ansi.dim_magenta": "#7c455eff",
+        "terminal.ansi.cyan": "#689d6aff",
+        "terminal.ansi.bright_cyan": "#8ec07cff",
+        "terminal.ansi.dim_cyan": "#496e4aff",
+        "terminal.ansi.white": "#a89984ff",
+        "terminal.ansi.bright_white": "#fbf1c7ff",
+        "terminal.ansi.dim_white": "#766b5dff",
         "link_text.hover": "#83a598ff",
         "version_control.added": "#b7bb26ff",
         "version_control.modified": "#f9bd2fff",
@@ -858,6 +860,7 @@
         "tab.inactive_background": "#3b3735ff",
         "tab.active_background": "#32302fff",
         "search.match_background": "#83a59866",
+        "search.active_match_background": "#aea85166",
         "panel.background": "#3b3735ff",
         "panel.focused_border": null,
         "pane.focused_border": null,
@@ -882,33 +885,33 @@
         "editor.document_highlight.read_background": "#83a5981a",
         "editor.document_highlight.write_background": "#92847466",
         "terminal.background": "#32302fff",
-        "terminal.foreground": "#fbf1c7ff",
+        "terminal.foreground": "#ebdbb2ff",
         "terminal.bright_foreground": "#fbf1c7ff",
-        "terminal.dim_foreground": "#32302fff",
-        "terminal.ansi.black": "#32302fff",
-        "terminal.ansi.bright_black": "#73675eff",
+        "terminal.dim_foreground": "#766b5dff",
+        "terminal.ansi.black": "#282828ff",
+        "terminal.ansi.bright_black": "#928374ff",
         "terminal.ansi.dim_black": "#fbf1c7ff",
-        "terminal.ansi.red": "#fb4a35ff",
-        "terminal.ansi.bright_red": "#93201dff",
-        "terminal.ansi.dim_red": "#ffaa95ff",
-        "terminal.ansi.green": "#b7bb26ff",
-        "terminal.ansi.bright_green": "#605c1bff",
-        "terminal.ansi.dim_green": "#e0dc98ff",
-        "terminal.ansi.yellow": "#f9bd2fff",
-        "terminal.ansi.bright_yellow": "#91611bff",
-        "terminal.ansi.dim_yellow": "#fedc9bff",
-        "terminal.ansi.blue": "#83a598ff",
-        "terminal.ansi.bright_blue": "#414f4aff",
-        "terminal.ansi.dim_blue": "#c0d2cbff",
-        "terminal.ansi.magenta": "#d3869bff",
-        "terminal.ansi.bright_magenta": "#8e5868ff",
-        "terminal.ansi.dim_magenta": "#ff9ebbff",
-        "terminal.ansi.cyan": "#8ec07cff",
-        "terminal.ansi.bright_cyan": "#45603eff",
-        "terminal.ansi.dim_cyan": "#c7dfbdff",
-        "terminal.ansi.white": "#fbf1c7ff",
-        "terminal.ansi.bright_white": "#ffffffff",
-        "terminal.ansi.dim_white": "#b0a189ff",
+        "terminal.ansi.red": "#cc241dff",
+        "terminal.ansi.bright_red": "#fb4934ff",
+        "terminal.ansi.dim_red": "#8e1814ff",
+        "terminal.ansi.green": "#98971aff",
+        "terminal.ansi.bright_green": "#b8bb26ff",
+        "terminal.ansi.dim_green": "#6a6912ff",
+        "terminal.ansi.yellow": "#d79921ff",
+        "terminal.ansi.bright_yellow": "#fabd2fff",
+        "terminal.ansi.dim_yellow": "#966a17ff",
+        "terminal.ansi.blue": "#458588ff",
+        "terminal.ansi.bright_blue": "#83a598ff",
+        "terminal.ansi.dim_blue": "#305d5fff",
+        "terminal.ansi.magenta": "#b16286ff",
+        "terminal.ansi.bright_magenta": "#d3869bff",
+        "terminal.ansi.dim_magenta": "#7c455eff",
+        "terminal.ansi.cyan": "#689d6aff",
+        "terminal.ansi.bright_cyan": "#8ec07cff",
+        "terminal.ansi.dim_cyan": "#496e4aff",
+        "terminal.ansi.white": "#a89984ff",
+        "terminal.ansi.bright_white": "#fbf1c7ff",
+        "terminal.ansi.dim_white": "#766b5dff",
         "link_text.hover": "#83a598ff",
         "version_control.added": "#b7bb26ff",
         "version_control.modified": "#f9bd2fff",
@@ -1264,6 +1267,7 @@
         "tab.inactive_background": "#ecddb4ff",
         "tab.active_background": "#fbf1c7ff",
         "search.match_background": "#0b667866",
+        "search.active_match_background": "#ba2d1166",
         "panel.background": "#ecddb4ff",
         "panel.focused_border": null,
         "pane.focused_border": null,
@@ -1291,30 +1295,30 @@
         "terminal.foreground": "#282828ff",
         "terminal.bright_foreground": "#282828ff",
         "terminal.dim_foreground": "#fbf1c7ff",
-        "terminal.ansi.black": "#282828ff",
-        "terminal.ansi.bright_black": "#0b6678ff",
-        "terminal.ansi.dim_black": "#5f5650ff",
-        "terminal.ansi.red": "#9d0308ff",
-        "terminal.ansi.bright_red": "#db8b7aff",
-        "terminal.ansi.dim_red": "#4e1207ff",
-        "terminal.ansi.green": "#797410ff",
-        "terminal.ansi.bright_green": "#bfb787ff",
-        "terminal.ansi.dim_green": "#3e3a11ff",
-        "terminal.ansi.yellow": "#b57615ff",
-        "terminal.ansi.bright_yellow": "#e2b88bff",
-        "terminal.ansi.dim_yellow": "#5c3a12ff",
-        "terminal.ansi.blue": "#0b6678ff",
-        "terminal.ansi.bright_blue": "#8fb0baff",
-        "terminal.ansi.dim_blue": "#14333bff",
-        "terminal.ansi.magenta": "#8f3e71ff",
-        "terminal.ansi.bright_magenta": "#c76da0ff",
-        "terminal.ansi.dim_magenta": "#5c2848ff",
-        "terminal.ansi.cyan": "#437b59ff",
-        "terminal.ansi.bright_cyan": "#9fbca8ff",
-        "terminal.ansi.dim_cyan": "#253e2eff",
-        "terminal.ansi.white": "#fbf1c7ff",
-        "terminal.ansi.bright_white": "#ffffffff",
-        "terminal.ansi.dim_white": "#b0a189ff",
+        "terminal.ansi.black": "#fbf1c7ff",
+        "terminal.ansi.bright_black": "#928374ff",
+        "terminal.ansi.dim_black": "#7c6f64ff",
+        "terminal.ansi.red": "#cc241dff",
+        "terminal.ansi.bright_red": "#9d0006ff",
+        "terminal.ansi.dim_red": "#c31c16ff",
+        "terminal.ansi.green": "#98971aff",
+        "terminal.ansi.bright_green": "#79740eff",
+        "terminal.ansi.dim_green": "#929015ff",
+        "terminal.ansi.yellow": "#d79921ff",
+        "terminal.ansi.bright_yellow": "#b57614ff",
+        "terminal.ansi.dim_yellow": "#cf8e1aff",
+        "terminal.ansi.blue": "#458588ff",
+        "terminal.ansi.bright_blue": "#076678ff",
+        "terminal.ansi.dim_blue": "#356f77ff",
+        "terminal.ansi.magenta": "#b16286ff",
+        "terminal.ansi.bright_magenta": "#8f3f71ff",
+        "terminal.ansi.dim_magenta": "#a85580ff",
+        "terminal.ansi.cyan": "#689d6aff",
+        "terminal.ansi.bright_cyan": "#427b58ff",
+        "terminal.ansi.dim_cyan": "#5f9166ff",
+        "terminal.ansi.white": "#7c6f64ff",
+        "terminal.ansi.bright_white": "#282828ff",
+        "terminal.ansi.dim_white": "#282828ff",
         "link_text.hover": "#0b6678ff",
         "version_control.added": "#797410ff",
         "version_control.modified": "#b57615ff",
@@ -1670,6 +1674,7 @@
         "tab.inactive_background": "#ecddb5ff",
         "tab.active_background": "#f9f5d7ff",
         "search.match_background": "#0b667866",
+        "search.active_match_background": "#dc351466",
         "panel.background": "#ecddb5ff",
         "panel.focused_border": null,
         "pane.focused_border": null,
@@ -1697,30 +1702,30 @@
         "terminal.foreground": "#282828ff",
         "terminal.bright_foreground": "#282828ff",
         "terminal.dim_foreground": "#f9f5d7ff",
-        "terminal.ansi.black": "#282828ff",
-        "terminal.ansi.bright_black": "#73675eff",
-        "terminal.ansi.dim_black": "#f9f5d7ff",
-        "terminal.ansi.red": "#9d0308ff",
-        "terminal.ansi.bright_red": "#db8b7aff",
-        "terminal.ansi.dim_red": "#4e1207ff",
-        "terminal.ansi.green": "#797410ff",
-        "terminal.ansi.bright_green": "#bfb787ff",
-        "terminal.ansi.dim_green": "#3e3a11ff",
-        "terminal.ansi.yellow": "#b57615ff",
-        "terminal.ansi.bright_yellow": "#e2b88bff",
-        "terminal.ansi.dim_yellow": "#5c3a12ff",
-        "terminal.ansi.blue": "#0b6678ff",
-        "terminal.ansi.bright_blue": "#8fb0baff",
-        "terminal.ansi.dim_blue": "#14333bff",
-        "terminal.ansi.magenta": "#8f3e71ff",
-        "terminal.ansi.bright_magenta": "#c76da0ff",
-        "terminal.ansi.dim_magenta": "#5c2848ff",
-        "terminal.ansi.cyan": "#437b59ff",
-        "terminal.ansi.bright_cyan": "#9fbca8ff",
-        "terminal.ansi.dim_cyan": "#253e2eff",
-        "terminal.ansi.white": "#f9f5d7ff",
-        "terminal.ansi.bright_white": "#ffffffff",
-        "terminal.ansi.dim_white": "#b0a189ff",
+        "terminal.ansi.black": "#fbf1c7ff",
+        "terminal.ansi.bright_black": "#928374ff",
+        "terminal.ansi.dim_black": "#7c6f64ff",
+        "terminal.ansi.red": "#cc241dff",
+        "terminal.ansi.bright_red": "#9d0006ff",
+        "terminal.ansi.dim_red": "#c31c16ff",
+        "terminal.ansi.green": "#98971aff",
+        "terminal.ansi.bright_green": "#79740eff",
+        "terminal.ansi.dim_green": "#929015ff",
+        "terminal.ansi.yellow": "#d79921ff",
+        "terminal.ansi.bright_yellow": "#b57614ff",
+        "terminal.ansi.dim_yellow": "#cf8e1aff",
+        "terminal.ansi.blue": "#458588ff",
+        "terminal.ansi.bright_blue": "#076678ff",
+        "terminal.ansi.dim_blue": "#356f77ff",
+        "terminal.ansi.magenta": "#b16286ff",
+        "terminal.ansi.bright_magenta": "#8f3f71ff",
+        "terminal.ansi.dim_magenta": "#a85580ff",
+        "terminal.ansi.cyan": "#689d6aff",
+        "terminal.ansi.bright_cyan": "#427b58ff",
+        "terminal.ansi.dim_cyan": "#5f9166ff",
+        "terminal.ansi.white": "#7c6f64ff",
+        "terminal.ansi.bright_white": "#282828ff",
+        "terminal.ansi.dim_white": "#282828ff",
         "link_text.hover": "#0b6678ff",
         "version_control.added": "#797410ff",
         "version_control.modified": "#b57615ff",
@@ -2076,6 +2081,7 @@
         "tab.inactive_background": "#ecdcb3ff",
         "tab.active_background": "#f2e5bcff",
         "search.match_background": "#0b667866",
+        "search.active_match_background": "#d7331466",
         "panel.background": "#ecdcb3ff",
         "panel.focused_border": null,
         "pane.focused_border": null,
@@ -2103,30 +2109,30 @@
         "terminal.foreground": "#282828ff",
         "terminal.bright_foreground": "#282828ff",
         "terminal.dim_foreground": "#f2e5bcff",
-        "terminal.ansi.black": "#282828ff",
-        "terminal.ansi.bright_black": "#73675eff",
-        "terminal.ansi.dim_black": "#f2e5bcff",
-        "terminal.ansi.red": "#9d0308ff",
-        "terminal.ansi.bright_red": "#db8b7aff",
-        "terminal.ansi.dim_red": "#4e1207ff",
-        "terminal.ansi.green": "#797410ff",
-        "terminal.ansi.bright_green": "#bfb787ff",
-        "terminal.ansi.dim_green": "#3e3a11ff",
-        "terminal.ansi.yellow": "#b57615ff",
-        "terminal.ansi.bright_yellow": "#e2b88bff",
-        "terminal.ansi.dim_yellow": "#5c3a12ff",
-        "terminal.ansi.blue": "#0b6678ff",
-        "terminal.ansi.bright_blue": "#8fb0baff",
-        "terminal.ansi.dim_blue": "#14333bff",
-        "terminal.ansi.magenta": "#8f3e71ff",
-        "terminal.ansi.bright_magenta": "#c76da0ff",
-        "terminal.ansi.dim_magenta": "#5c2848ff",
-        "terminal.ansi.cyan": "#437b59ff",
-        "terminal.ansi.bright_cyan": "#9fbca8ff",
-        "terminal.ansi.dim_cyan": "#253e2eff",
-        "terminal.ansi.white": "#f2e5bcff",
-        "terminal.ansi.bright_white": "#ffffffff",
-        "terminal.ansi.dim_white": "#b0a189ff",
+        "terminal.ansi.black": "#fbf1c7ff",
+        "terminal.ansi.bright_black": "#928374ff",
+        "terminal.ansi.dim_black": "#7c6f64ff",
+        "terminal.ansi.red": "#cc241dff",
+        "terminal.ansi.bright_red": "#9d0006ff",
+        "terminal.ansi.dim_red": "#c31c16ff",
+        "terminal.ansi.green": "#98971aff",
+        "terminal.ansi.bright_green": "#79740eff",
+        "terminal.ansi.dim_green": "#929015ff",
+        "terminal.ansi.yellow": "#d79921ff",
+        "terminal.ansi.bright_yellow": "#b57614ff",
+        "terminal.ansi.dim_yellow": "#cf8e1aff",
+        "terminal.ansi.blue": "#458588ff",
+        "terminal.ansi.bright_blue": "#076678ff",
+        "terminal.ansi.dim_blue": "#356f77ff",
+        "terminal.ansi.magenta": "#b16286ff",
+        "terminal.ansi.bright_magenta": "#8f3f71ff",
+        "terminal.ansi.dim_magenta": "#a85580ff",
+        "terminal.ansi.cyan": "#689d6aff",
+        "terminal.ansi.bright_cyan": "#427b58ff",
+        "terminal.ansi.dim_cyan": "#5f9166ff",
+        "terminal.ansi.white": "#7c6f64ff",
+        "terminal.ansi.bright_white": "#282828ff",
+        "terminal.ansi.dim_white": "#282828ff",
         "link_text.hover": "#0b6678ff",
         "version_control.added": "#797410ff",
         "version_control.modified": "#b57615ff",

assets/themes/one/one.json 🔗

@@ -45,6 +45,7 @@
         "tab.inactive_background": "#2f343eff",
         "tab.active_background": "#282c33ff",
         "search.match_background": "#74ade866",
+        "search.active_match_background": "#e8af7466",
         "panel.background": "#2f343eff",
         "panel.focused_border": null,
         "pane.focused_border": null,
@@ -67,34 +68,34 @@
         "editor.active_wrap_guide": "#c8ccd41a",
         "editor.document_highlight.read_background": "#74ade81a",
         "editor.document_highlight.write_background": "#555a6366",
-        "terminal.background": "#282c33ff",
-        "terminal.foreground": "#dce0e5ff",
+        "terminal.background": "#282c34ff",
+        "terminal.foreground": "#abb2bfff",
         "terminal.bright_foreground": "#dce0e5ff",
-        "terminal.dim_foreground": "#282c33ff",
-        "terminal.ansi.black": "#282c33ff",
-        "terminal.ansi.bright_black": "#525561ff",
-        "terminal.ansi.dim_black": "#dce0e5ff",
-        "terminal.ansi.red": "#d07277ff",
-        "terminal.ansi.bright_red": "#673a3cff",
-        "terminal.ansi.dim_red": "#eab7b9ff",
-        "terminal.ansi.green": "#a1c181ff",
-        "terminal.ansi.bright_green": "#4d6140ff",
-        "terminal.ansi.dim_green": "#d1e0bfff",
-        "terminal.ansi.yellow": "#dec184ff",
-        "terminal.ansi.bright_yellow": "#e5c07bff",
-        "terminal.ansi.dim_yellow": "#f1dfc1ff",
-        "terminal.ansi.blue": "#74ade8ff",
-        "terminal.ansi.bright_blue": "#385378ff",
-        "terminal.ansi.dim_blue": "#bed5f4ff",
-        "terminal.ansi.magenta": "#b477cfff",
-        "terminal.ansi.bright_magenta": "#d6b4e4ff",
-        "terminal.ansi.dim_magenta": "#612a79ff",
-        "terminal.ansi.cyan": "#6eb4bfff",
-        "terminal.ansi.bright_cyan": "#3a565bff",
-        "terminal.ansi.dim_cyan": "#b9d9dfff",
-        "terminal.ansi.white": "#dce0e5ff",
+        "terminal.dim_foreground": "#636d83ff",
+        "terminal.ansi.black": "#282c34ff",
+        "terminal.ansi.bright_black": "#636d83ff",
+        "terminal.ansi.dim_black": "#3b3f4aff",
+        "terminal.ansi.red": "#e06c75ff",
+        "terminal.ansi.bright_red": "#EA858Bff",
+        "terminal.ansi.dim_red": "#a7545aff",
+        "terminal.ansi.green": "#98c379ff",
+        "terminal.ansi.bright_green": "#AAD581ff",
+        "terminal.ansi.dim_green": "#6d8f59ff",
+        "terminal.ansi.yellow": "#e5c07bff",
+        "terminal.ansi.bright_yellow": "#FFD885ff",
+        "terminal.ansi.dim_yellow": "#b8985bff",
+        "terminal.ansi.blue": "#61afefff",
+        "terminal.ansi.bright_blue": "#85C1FFff",
+        "terminal.ansi.dim_blue": "#457cadff",
+        "terminal.ansi.magenta": "#c678ddff",
+        "terminal.ansi.bright_magenta": "#D398EBff",
+        "terminal.ansi.dim_magenta": "#8d54a0ff",
+        "terminal.ansi.cyan": "#56b6c2ff",
+        "terminal.ansi.bright_cyan": "#6ED5DEff",
+        "terminal.ansi.dim_cyan": "#3c818aff",
+        "terminal.ansi.white": "#abb2bfff",
         "terminal.ansi.bright_white": "#fafafaff",
-        "terminal.ansi.dim_white": "#575d65ff",
+        "terminal.ansi.dim_white": "#8f969bff",
         "link_text.hover": "#74ade8ff",
         "version_control.added": "#27a657ff",
         "version_control.modified": "#d3b020ff",
@@ -448,6 +449,7 @@
         "tab.inactive_background": "#ebebecff",
         "tab.active_background": "#fafafaff",
         "search.match_background": "#5c79e266",
+        "search.active_match_background": "#d0a92366",
         "panel.background": "#ebebecff",
         "panel.focused_border": null,
         "pane.focused_border": null,
@@ -471,33 +473,33 @@
         "editor.document_highlight.read_background": "#5c78e225",
         "editor.document_highlight.write_background": "#a3a3a466",
         "terminal.background": "#fafafaff",
-        "terminal.foreground": "#242529ff",
-        "terminal.bright_foreground": "#242529ff",
-        "terminal.dim_foreground": "#fafafaff",
-        "terminal.ansi.black": "#242529ff",
-        "terminal.ansi.bright_black": "#747579ff",
-        "terminal.ansi.dim_black": "#97979aff",
-        "terminal.ansi.red": "#d36151ff",
-        "terminal.ansi.bright_red": "#f0b0a4ff",
-        "terminal.ansi.dim_red": "#6f312aff",
-        "terminal.ansi.green": "#669f59ff",
-        "terminal.ansi.bright_green": "#b2cfa9ff",
-        "terminal.ansi.dim_green": "#354d2eff",
-        "terminal.ansi.yellow": "#dec184ff",
-        "terminal.ansi.bright_yellow": "#826221ff",
-        "terminal.ansi.dim_yellow": "#786441ff",
-        "terminal.ansi.blue": "#5c78e2ff",
-        "terminal.ansi.bright_blue": "#b5baf2ff",
-        "terminal.ansi.dim_blue": "#2d3d75ff",
-        "terminal.ansi.magenta": "#984ea5ff",
-        "terminal.ansi.bright_magenta": "#cea6d3ff",
-        "terminal.ansi.dim_magenta": "#4b2a50ff",
-        "terminal.ansi.cyan": "#3a82b7ff",
-        "terminal.ansi.bright_cyan": "#a3bedaff",
-        "terminal.ansi.dim_cyan": "#254058ff",
-        "terminal.ansi.white": "#fafafaff",
+        "terminal.foreground": "#2a2c33ff",
+        "terminal.bright_foreground": "#2a2c33ff",
+        "terminal.dim_foreground": "#bbbbbbff",
+        "terminal.ansi.black": "#000000ff",
+        "terminal.ansi.bright_black": "#000000ff",
+        "terminal.ansi.dim_black": "#555555ff",
+        "terminal.ansi.red": "#de3e35ff",
+        "terminal.ansi.bright_red": "#de3e35ff",
+        "terminal.ansi.dim_red": "#9c2b26ff",
+        "terminal.ansi.green": "#3f953aff",
+        "terminal.ansi.bright_green": "#3f953aff",
+        "terminal.ansi.dim_green": "#2b6927ff",
+        "terminal.ansi.yellow": "#d2b67cff",
+        "terminal.ansi.bright_yellow": "#d2b67cff",
+        "terminal.ansi.dim_yellow": "#a48c5aff",
+        "terminal.ansi.blue": "#2f5af3ff",
+        "terminal.ansi.bright_blue": "#2f5af3ff",
+        "terminal.ansi.dim_blue": "#2140abff",
+        "terminal.ansi.magenta": "#950095ff",
+        "terminal.ansi.bright_magenta": "#a00095ff",
+        "terminal.ansi.dim_magenta": "#6a006aff",
+        "terminal.ansi.cyan": "#3f953aff",
+        "terminal.ansi.bright_cyan": "#3f953aff",
+        "terminal.ansi.dim_cyan": "#2b6927ff",
+        "terminal.ansi.white": "#bbbbbbff",
         "terminal.ansi.bright_white": "#ffffffff",
-        "terminal.ansi.dim_white": "#aaaaaaff",
+        "terminal.ansi.dim_white": "#888888ff",
         "link_text.hover": "#5c78e2ff",
         "version_control.added": "#27a657ff",
         "version_control.modified": "#d3b020ff",

clippy.toml 🔗

@@ -14,6 +14,7 @@ disallowed-methods = [
     { path = "std::process::Command::stderr", reason = "`smol::process::Command::from()` does not preserve stdio configuration", replacement = "smol::process::Command::stderr" },
     { path = "serde_json::from_reader", reason = "Parsing from a buffer is much slower than first reading the buffer into a Vec/String, see https://github.com/serde-rs/json/issues/160#issuecomment-253446892. Use `serde_json::from_slice` instead." },
     { path = "serde_json_lenient::from_reader", reason = "Parsing from a buffer is much slower than first reading the buffer into a Vec/String, see https://github.com/serde-rs/json/issues/160#issuecomment-253446892, Use `serde_json_lenient::from_slice` instead." },
+    { path = "cocoa::foundation::NSString::alloc", reason = "NSString must be autoreleased to avoid memory leaks. Use `ns_string()` helper instead." },
 ]
 disallowed-types = [
     # { path = "std::collections::HashMap", replacement = "collections::HashMap" },

crates/acp_thread/Cargo.toml 🔗

@@ -46,6 +46,7 @@ url.workspace = true
 util.workspace = true
 uuid.workspace = true
 watch.workspace = true
+urlencoding.workspace = true
 
 [dev-dependencies]
 env_logger.workspace = true

crates/acp_thread/src/acp_thread.rs 🔗

@@ -11,6 +11,7 @@ use language::language_settings::FormatOnSave;
 pub use mention::*;
 use project::lsp_store::{FormatTrigger, LspFormatTarget};
 use serde::{Deserialize, Serialize};
+use serde_json::to_string_pretty;
 use settings::Settings as _;
 use task::{Shell, ShellBuilder};
 pub use terminal::*;
@@ -43,6 +44,7 @@ pub struct UserMessage {
     pub content: ContentBlock,
     pub chunks: Vec<acp::ContentBlock>,
     pub checkpoint: Option<Checkpoint>,
+    pub indented: bool,
 }
 
 #[derive(Debug)]
@@ -73,6 +75,7 @@ impl UserMessage {
 #[derive(Debug, PartialEq)]
 pub struct AssistantMessage {
     pub chunks: Vec<AssistantMessageChunk>,
+    pub indented: bool,
 }
 
 impl AssistantMessage {
@@ -123,6 +126,14 @@ pub enum AgentThreadEntry {
 }
 
 impl AgentThreadEntry {
+    pub fn is_indented(&self) -> bool {
+        match self {
+            Self::UserMessage(message) => message.indented,
+            Self::AssistantMessage(message) => message.indented,
+            Self::ToolCall(_) => false,
+        }
+    }
+
     pub fn to_markdown(&self, cx: &App) -> String {
         match self {
             Self::UserMessage(message) => message.to_markdown(cx),
@@ -182,6 +193,7 @@ pub struct ToolCall {
     pub locations: Vec<acp::ToolCallLocation>,
     pub resolved_locations: Vec<Option<AgentLocation>>,
     pub raw_input: Option<serde_json::Value>,
+    pub raw_input_markdown: Option<Entity<Markdown>>,
     pub raw_output: Option<serde_json::Value>,
 }
 
@@ -201,17 +213,24 @@ impl ToolCall {
         };
         let mut content = Vec::with_capacity(tool_call.content.len());
         for item in tool_call.content {
-            content.push(ToolCallContent::from_acp(
+            if let Some(item) = ToolCallContent::from_acp(
                 item,
                 language_registry.clone(),
                 path_style,
                 terminals,
                 cx,
-            )?);
+            )? {
+                content.push(item);
+            }
         }
 
+        let raw_input_markdown = tool_call
+            .raw_input
+            .as_ref()
+            .and_then(|input| markdown_for_raw_output(input, &language_registry, cx));
+
         let result = Self {
-            id: tool_call.id,
+            id: tool_call.tool_call_id,
             label: cx
                 .new(|cx| Markdown::new(title.into(), Some(language_registry.clone()), None, cx)),
             kind: tool_call.kind,
@@ -220,6 +239,7 @@ impl ToolCall {
             resolved_locations: Vec::default(),
             status,
             raw_input: tool_call.raw_input,
+            raw_input_markdown,
             raw_output: tool_call.raw_output,
         };
         Ok(result)
@@ -241,6 +261,7 @@ impl ToolCall {
             locations,
             raw_input,
             raw_output,
+            ..
         } = fields;
 
         if let Some(kind) = kind {
@@ -262,21 +283,29 @@ impl ToolCall {
         }
 
         if let Some(content) = content {
-            let new_content_len = content.len();
+            let mut new_content_len = content.len();
             let mut content = content.into_iter();
 
             // Reuse existing content if we can
             for (old, new) in self.content.iter_mut().zip(content.by_ref()) {
-                old.update_from_acp(new, language_registry.clone(), path_style, terminals, cx)?;
+                let valid_content =
+                    old.update_from_acp(new, language_registry.clone(), path_style, terminals, cx)?;
+                if !valid_content {
+                    new_content_len -= 1;
+                }
             }
             for new in content {
-                self.content.push(ToolCallContent::from_acp(
+                if let Some(new) = ToolCallContent::from_acp(
                     new,
                     language_registry.clone(),
                     path_style,
                     terminals,
                     cx,
-                )?)
+                )? {
+                    self.content.push(new);
+                } else {
+                    new_content_len -= 1;
+                }
             }
             self.content.truncate(new_content_len);
         }
@@ -286,6 +315,7 @@ impl ToolCall {
         }
 
         if let Some(raw_input) = raw_input {
+            self.raw_input_markdown = markdown_for_raw_output(&raw_input, &language_registry, cx);
             self.raw_input = Some(raw_input);
         }
 
@@ -425,6 +455,7 @@ impl From<acp::ToolCallStatus> for ToolCallStatus {
             acp::ToolCallStatus::InProgress => Self::InProgress,
             acp::ToolCallStatus::Completed => Self::Completed,
             acp::ToolCallStatus::Failed => Self::Failed,
+            _ => Self::Pending,
         }
     }
 }
@@ -537,7 +568,7 @@ impl ContentBlock {
                 ..
             }) => Self::resource_link_md(&uri, path_style),
             acp::ContentBlock::Image(image) => Self::image_md(&image),
-            acp::ContentBlock::Audio(_) | acp::ContentBlock::Resource(_) => String::new(),
+            _ => String::new(),
         }
     }
 
@@ -591,15 +622,17 @@ impl ToolCallContent {
         path_style: PathStyle,
         terminals: &HashMap<acp::TerminalId, Entity<Terminal>>,
         cx: &mut App,
-    ) -> Result<Self> {
+    ) -> Result<Option<Self>> {
         match content {
-            acp::ToolCallContent::Content { content } => Ok(Self::ContentBlock(ContentBlock::new(
-                content,
-                &language_registry,
-                path_style,
-                cx,
-            ))),
-            acp::ToolCallContent::Diff { diff } => Ok(Self::Diff(cx.new(|cx| {
+            acp::ToolCallContent::Content(acp::Content { content, .. }) => {
+                Ok(Some(Self::ContentBlock(ContentBlock::new(
+                    content,
+                    &language_registry,
+                    path_style,
+                    cx,
+                ))))
+            }
+            acp::ToolCallContent::Diff(diff) => Ok(Some(Self::Diff(cx.new(|cx| {
                 Diff::finalized(
                     diff.path.to_string_lossy().into_owned(),
                     diff.old_text,
@@ -607,12 +640,13 @@ impl ToolCallContent {
                     language_registry,
                     cx,
                 )
-            }))),
-            acp::ToolCallContent::Terminal { terminal_id } => terminals
+            })))),
+            acp::ToolCallContent::Terminal(acp::Terminal { terminal_id, .. }) => terminals
                 .get(&terminal_id)
                 .cloned()
-                .map(Self::Terminal)
+                .map(|terminal| Some(Self::Terminal(terminal)))
                 .ok_or_else(|| anyhow::anyhow!("Terminal with id `{}` not found", terminal_id)),
+            _ => Ok(None),
         }
     }
 
@@ -623,9 +657,9 @@ impl ToolCallContent {
         path_style: PathStyle,
         terminals: &HashMap<acp::TerminalId, Entity<Terminal>>,
         cx: &mut App,
-    ) -> Result<()> {
+    ) -> Result<bool> {
         let needs_update = match (&self, &new) {
-            (Self::Diff(old_diff), acp::ToolCallContent::Diff { diff: new_diff }) => {
+            (Self::Diff(old_diff), acp::ToolCallContent::Diff(new_diff)) => {
                 old_diff.read(cx).needs_update(
                     new_diff.old_text.as_deref().unwrap_or(""),
                     &new_diff.new_text,
@@ -635,10 +669,14 @@ impl ToolCallContent {
             _ => true,
         };
 
-        if needs_update {
-            *self = Self::from_acp(new, language_registry, path_style, terminals, cx)?;
+        if let Some(update) = Self::from_acp(new, language_registry, path_style, terminals, cx)? {
+            if needs_update {
+                *self = update;
+            }
+            Ok(true)
+        } else {
+            Ok(false)
         }
-        Ok(())
     }
 
     pub fn to_markdown(&self, cx: &App) -> String {
@@ -660,7 +698,7 @@ pub enum ToolCallUpdate {
 impl ToolCallUpdate {
     fn id(&self) -> &acp::ToolCallId {
         match self {
-            Self::UpdateFields(update) => &update.id,
+            Self::UpdateFields(update) => &update.tool_call_id,
             Self::UpdateDiff(diff) => &diff.id,
             Self::UpdateTerminal(terminal) => &terminal.id,
         }
@@ -732,6 +770,7 @@ impl Plan {
                 acp::PlanEntryStatus::Completed => {
                     stats.completed += 1;
                 }
+                _ => {}
             }
         }
 
@@ -1154,6 +1193,7 @@ impl AcpThread {
                 current_mode_id,
                 ..
             }) => cx.emit(AcpThreadEvent::ModeUpdated(current_mode_id)),
+            _ => {}
         }
         Ok(())
     }
@@ -1163,6 +1203,16 @@ impl AcpThread {
         message_id: Option<UserMessageId>,
         chunk: acp::ContentBlock,
         cx: &mut Context<Self>,
+    ) {
+        self.push_user_content_block_with_indent(message_id, chunk, false, cx)
+    }
+
+    pub fn push_user_content_block_with_indent(
+        &mut self,
+        message_id: Option<UserMessageId>,
+        chunk: acp::ContentBlock,
+        indented: bool,
+        cx: &mut Context<Self>,
     ) {
         let language_registry = self.project.read(cx).languages().clone();
         let path_style = self.project.read(cx).path_style(cx);
@@ -1173,8 +1223,10 @@ impl AcpThread {
                 id,
                 content,
                 chunks,
+                indented: existing_indented,
                 ..
             }) = last_entry
+            && *existing_indented == indented
         {
             *id = message_id.or(id.take());
             content.append(chunk.clone(), &language_registry, path_style, cx);
@@ -1189,6 +1241,7 @@ impl AcpThread {
                     content,
                     chunks: vec![chunk],
                     checkpoint: None,
+                    indented,
                 }),
                 cx,
             );
@@ -1200,12 +1253,26 @@ impl AcpThread {
         chunk: acp::ContentBlock,
         is_thought: bool,
         cx: &mut Context<Self>,
+    ) {
+        self.push_assistant_content_block_with_indent(chunk, is_thought, false, cx)
+    }
+
+    pub fn push_assistant_content_block_with_indent(
+        &mut self,
+        chunk: acp::ContentBlock,
+        is_thought: bool,
+        indented: bool,
+        cx: &mut Context<Self>,
     ) {
         let language_registry = self.project.read(cx).languages().clone();
         let path_style = self.project.read(cx).path_style(cx);
         let entries_len = self.entries.len();
         if let Some(last_entry) = self.entries.last_mut()
-            && let AgentThreadEntry::AssistantMessage(AssistantMessage { chunks }) = last_entry
+            && let AgentThreadEntry::AssistantMessage(AssistantMessage {
+                chunks,
+                indented: existing_indented,
+            }) = last_entry
+            && *existing_indented == indented
         {
             let idx = entries_len - 1;
             cx.emit(AcpThreadEvent::EntryUpdated(idx));
@@ -1234,6 +1301,7 @@ impl AcpThread {
             self.push_entry(
                 AgentThreadEntry::AssistantMessage(AssistantMessage {
                     chunks: vec![chunk],
+                    indented,
                 }),
                 cx,
             );
@@ -1287,11 +1355,7 @@ impl AcpThread {
                     label: cx.new(|cx| Markdown::new("Tool call not found".into(), None, None, cx)),
                     kind: acp::ToolKind::Fetch,
                     content: vec![ToolCallContent::ContentBlock(ContentBlock::new(
-                        acp::ContentBlock::Text(acp::TextContent {
-                            text: "Tool call not found".to_string(),
-                            annotations: None,
-                            meta: None,
-                        }),
+                        "Tool call not found".into(),
                         &languages,
                         path_style,
                         cx,
@@ -1300,6 +1364,7 @@ impl AcpThread {
                     locations: Vec::new(),
                     resolved_locations: Vec::new(),
                     raw_input: None,
+                    raw_input_markdown: None,
                     raw_output: None,
                 };
                 self.push_entry(AgentThreadEntry::ToolCall(failed_tool_call), cx);
@@ -1315,7 +1380,7 @@ impl AcpThread {
                 let location_updated = update.fields.locations.is_some();
                 call.update_fields(update.fields, languages, path_style, &self.terminals, cx)?;
                 if location_updated {
-                    self.resolve_locations(update.id, cx);
+                    self.resolve_locations(update.tool_call_id, cx);
                 }
             }
             ToolCallUpdate::UpdateDiff(update) => {
@@ -1353,9 +1418,9 @@ impl AcpThread {
     ) -> Result<(), acp::Error> {
         let language_registry = self.project.read(cx).languages().clone();
         let path_style = self.project.read(cx).path_style(cx);
-        let id = update.id.clone();
+        let id = update.tool_call_id.clone();
 
-        let agent = self.connection().telemetry_id();
+        let agent_telemetry_id = self.connection().telemetry_id();
         let session = self.session_id();
         if let ToolCallStatus::Completed | ToolCallStatus::Failed = status {
             let status = if matches!(status, ToolCallStatus::Completed) {
@@ -1363,7 +1428,12 @@ impl AcpThread {
             } else {
                 "failed"
             };
-            telemetry::event!("Agent Tool Call Completed", agent, session, status);
+            telemetry::event!(
+                "Agent Tool Call Completed",
+                agent_telemetry_id,
+                session,
+                status
+            );
         }
 
         if let Some(ix) = self.index_for_tool_call(&id) {
@@ -1518,16 +1588,16 @@ impl AcpThread {
             // some tools would (incorrectly) continue to auto-accept.
             if let Some(allow_once_option) = options.iter().find_map(|option| {
                 if matches!(option.kind, acp::PermissionOptionKind::AllowOnce) {
-                    Some(option.id.clone())
+                    Some(option.option_id.clone())
                 } else {
                     None
                 }
             }) {
                 self.upsert_tool_call_inner(tool_call, ToolCallStatus::Pending, cx)?;
                 return Ok(async {
-                    acp::RequestPermissionOutcome::Selected {
-                        option_id: allow_once_option,
-                    }
+                    acp::RequestPermissionOutcome::Selected(acp::SelectedPermissionOutcome::new(
+                        allow_once_option,
+                    ))
                 }
                 .boxed());
             }
@@ -1543,7 +1613,9 @@ impl AcpThread {
 
         let fut = async {
             match rx.await {
-                Ok(option) => acp::RequestPermissionOutcome::Selected { option_id: option },
+                Ok(option) => acp::RequestPermissionOutcome::Selected(
+                    acp::SelectedPermissionOutcome::new(option),
+                ),
                 Err(oneshot::Canceled) => acp::RequestPermissionOutcome::Cancelled,
             }
         }
@@ -1570,6 +1642,7 @@ impl AcpThread {
             acp::PermissionOptionKind::AllowOnce | acp::PermissionOptionKind::AllowAlways => {
                 ToolCallStatus::InProgress
             }
+            _ => ToolCallStatus::InProgress,
         };
 
         let curr_status = mem::replace(&mut call.status, new_status);
@@ -1648,14 +1721,7 @@ impl AcpThread {
         message: &str,
         cx: &mut Context<Self>,
     ) -> BoxFuture<'static, Result<()>> {
-        self.send(
-            vec![acp::ContentBlock::Text(acp::TextContent {
-                text: message.to_string(),
-                annotations: None,
-                meta: None,
-            })],
-            cx,
-        )
+        self.send(vec![message.into()], cx)
     }
 
     pub fn send(
@@ -1669,11 +1735,7 @@ impl AcpThread {
             self.project.read(cx).path_style(cx),
             cx,
         );
-        let request = acp::PromptRequest {
-            prompt: message.clone(),
-            session_id: self.session_id.clone(),
-            meta: None,
-        };
+        let request = acp::PromptRequest::new(self.session_id.clone(), message.clone());
         let git_store = self.project.read(cx).git_store().clone();
 
         let message_id = if self.connection.truncate(&self.session_id, cx).is_some() {
@@ -1690,6 +1752,7 @@ impl AcpThread {
                         content: block,
                         chunks: message,
                         checkpoint: None,
+                        indented: false,
                     }),
                     cx,
                 );
@@ -1765,7 +1828,7 @@ impl AcpThread {
                             result,
                             Ok(Ok(acp::PromptResponse {
                                 stop_reason: acp::StopReason::Cancelled,
-                                meta: None,
+                                ..
                             }))
                         );
 
@@ -1781,7 +1844,7 @@ impl AcpThread {
                         // Handle refusal - distinguish between user prompt and tool call refusals
                         if let Ok(Ok(acp::PromptResponse {
                             stop_reason: acp::StopReason::Refusal,
-                            meta: _,
+                            ..
                         })) = result
                         {
                             if let Some((user_msg_ix, _)) = this.last_user_message() {
@@ -1930,37 +1993,42 @@ impl AcpThread {
     fn update_last_checkpoint(&mut self, cx: &mut Context<Self>) -> Task<Result<()>> {
         let git_store = self.project.read(cx).git_store().clone();
 
-        let old_checkpoint = if let Some((_, message)) = self.last_user_message() {
-            if let Some(checkpoint) = message.checkpoint.as_ref() {
-                checkpoint.git_checkpoint.clone()
-            } else {
-                return Task::ready(Ok(()));
-            }
-        } else {
+        let Some((_, message)) = self.last_user_message() else {
+            return Task::ready(Ok(()));
+        };
+        let Some(user_message_id) = message.id.clone() else {
+            return Task::ready(Ok(()));
+        };
+        let Some(checkpoint) = message.checkpoint.as_ref() else {
             return Task::ready(Ok(()));
         };
+        let old_checkpoint = checkpoint.git_checkpoint.clone();
 
         let new_checkpoint = git_store.update(cx, |git, cx| git.checkpoint(cx));
         cx.spawn(async move |this, cx| {
-            let new_checkpoint = new_checkpoint
+            let Some(new_checkpoint) = new_checkpoint
                 .await
                 .context("failed to get new checkpoint")
-                .log_err();
-            if let Some(new_checkpoint) = new_checkpoint {
-                let equal = git_store
-                    .update(cx, |git, cx| {
-                        git.compare_checkpoints(old_checkpoint.clone(), new_checkpoint, cx)
-                    })?
-                    .await
-                    .unwrap_or(true);
-                this.update(cx, |this, cx| {
-                    let (ix, message) = this.last_user_message().context("no user message")?;
-                    let checkpoint = message.checkpoint.as_mut().context("no checkpoint")?;
-                    checkpoint.show = !equal;
-                    cx.emit(AcpThreadEvent::EntryUpdated(ix));
-                    anyhow::Ok(())
-                })??;
-            }
+                .log_err()
+            else {
+                return Ok(());
+            };
+
+            let equal = git_store
+                .update(cx, |git, cx| {
+                    git.compare_checkpoints(old_checkpoint.clone(), new_checkpoint, cx)
+                })?
+                .await
+                .unwrap_or(true);
+
+            this.update(cx, |this, cx| {
+                if let Some((ix, message)) = this.user_message_mut(&user_message_id) {
+                    if let Some(checkpoint) = message.checkpoint.as_mut() {
+                        checkpoint.show = !equal;
+                        cx.emit(AcpThreadEvent::EntryUpdated(ix));
+                    }
+                }
+            })?;
 
             Ok(())
         })
@@ -2017,7 +2085,7 @@ impl AcpThread {
                         })?;
                     Ok(project.open_buffer(path, cx))
                 })
-                .map_err(|e| acp::Error::internal_error().with_data(e.to_string()))
+                .map_err(|e| acp::Error::internal_error().data(e.to_string()))
                 .flatten()?;
 
             let buffer = load.await?;
@@ -2050,7 +2118,7 @@ impl AcpThread {
             let start_position = Point::new(line, 0);
 
             if start_position > max_point {
-                return Err(acp::Error::invalid_params().with_data(format!(
+                return Err(acp::Error::invalid_params().data(format!(
                     "Attempting to read beyond the end of the file, line {}:{}",
                     max_point.row + 1,
                     max_point.column
@@ -2202,7 +2270,7 @@ impl AcpThread {
         let language_registry = project.read(cx).languages().clone();
         let is_windows = project.read(cx).path_style(cx).is_windows();
 
-        let terminal_id = acp::TerminalId(Uuid::new_v4().to_string().into());
+        let terminal_id = acp::TerminalId::new(Uuid::new_v4().to_string());
         let terminal_task = cx.spawn({
             let terminal_id = terminal_id.clone();
             async move |_this, cx| {
@@ -2360,8 +2428,10 @@ fn markdown_for_raw_output(
             )
         })),
         value => Some(cx.new(|cx| {
+            let pretty_json = to_string_pretty(value).unwrap_or_else(|_| value.to_string());
+
             Markdown::new(
-                format!("```json\n{}\n```", value).into(),
+                format!("```json\n{}\n```", pretty_json).into(),
                 Some(language_registry.clone()),
                 None,
                 cx,
@@ -2412,7 +2482,7 @@ mod tests {
             .await
             .unwrap();
 
-        let terminal_id = acp::TerminalId(uuid::Uuid::new_v4().to_string().into());
+        let terminal_id = acp::TerminalId::new(uuid::Uuid::new_v4().to_string());
 
         // Send Output BEFORE Created - should be buffered by acp_thread
         thread.update(cx, |thread, cx| {
@@ -2474,7 +2544,7 @@ mod tests {
             .await
             .unwrap();
 
-        let terminal_id = acp::TerminalId(uuid::Uuid::new_v4().to_string().into());
+        let terminal_id = acp::TerminalId::new(uuid::Uuid::new_v4().to_string());
 
         // Send Output BEFORE Created
         thread.update(cx, |thread, cx| {
@@ -2492,11 +2562,7 @@ mod tests {
             thread.on_terminal_provider_event(
                 TerminalProviderEvent::Exit {
                     terminal_id: terminal_id.clone(),
-                    status: acp::TerminalExitStatus {
-                        exit_code: Some(0),
-                        signal: None,
-                        meta: None,
-                    },
+                    status: acp::TerminalExitStatus::new().exit_code(0),
                 },
                 cx,
             );
@@ -2553,15 +2619,7 @@ mod tests {
 
         // Test creating a new user message
         thread.update(cx, |thread, cx| {
-            thread.push_user_content_block(
-                None,
-                acp::ContentBlock::Text(acp::TextContent {
-                    annotations: None,
-                    text: "Hello, ".to_string(),
-                    meta: None,
-                }),
-                cx,
-            );
+            thread.push_user_content_block(None, "Hello, ".into(), cx);
         });
 
         thread.update(cx, |thread, cx| {
@@ -2577,15 +2635,7 @@ mod tests {
         // Test appending to existing user message
         let message_1_id = UserMessageId::new();
         thread.update(cx, |thread, cx| {
-            thread.push_user_content_block(
-                Some(message_1_id.clone()),
-                acp::ContentBlock::Text(acp::TextContent {
-                    annotations: None,
-                    text: "world!".to_string(),
-                    meta: None,
-                }),
-                cx,
-            );
+            thread.push_user_content_block(Some(message_1_id.clone()), "world!".into(), cx);
         });
 
         thread.update(cx, |thread, cx| {
@@ -2600,26 +2650,14 @@ mod tests {
 
         // Test creating new user message after assistant message
         thread.update(cx, |thread, cx| {
-            thread.push_assistant_content_block(
-                acp::ContentBlock::Text(acp::TextContent {
-                    annotations: None,
-                    text: "Assistant response".to_string(),
-                    meta: None,
-                }),
-                false,
-                cx,
-            );
+            thread.push_assistant_content_block("Assistant response".into(), false, cx);
         });
 
         let message_2_id = UserMessageId::new();
         thread.update(cx, |thread, cx| {
             thread.push_user_content_block(
                 Some(message_2_id.clone()),
-                acp::ContentBlock::Text(acp::TextContent {
-                    annotations: None,
-                    text: "New user message".to_string(),
-                    meta: None,
-                }),
+                "New user message".into(),
                 cx,
             );
         });
@@ -2647,27 +2685,22 @@ mod tests {
                     thread.update(&mut cx, |thread, cx| {
                         thread
                             .handle_session_update(
-                                acp::SessionUpdate::AgentThoughtChunk(acp::ContentChunk {
-                                    content: "Thinking ".into(),
-                                    meta: None,
-                                }),
+                                acp::SessionUpdate::AgentThoughtChunk(acp::ContentChunk::new(
+                                    "Thinking ".into(),
+                                )),
                                 cx,
                             )
                             .unwrap();
                         thread
                             .handle_session_update(
-                                acp::SessionUpdate::AgentThoughtChunk(acp::ContentChunk {
-                                    content: "hard!".into(),
-                                    meta: None,
-                                }),
+                                acp::SessionUpdate::AgentThoughtChunk(acp::ContentChunk::new(
+                                    "hard!".into(),
+                                )),
                                 cx,
                             )
                             .unwrap();
                     })?;
-                    Ok(acp::PromptResponse {
-                        stop_reason: acp::StopReason::EndTurn,
-                        meta: None,
-                    })
+                    Ok(acp::PromptResponse::new(acp::StopReason::EndTurn))
                 }
                 .boxed_local()
             },
@@ -2735,10 +2768,7 @@ mod tests {
                         .unwrap()
                         .await
                         .unwrap();
-                    Ok(acp::PromptResponse {
-                        stop_reason: acp::StopReason::EndTurn,
-                        meta: None,
-                    })
+                    Ok(acp::PromptResponse::new(acp::StopReason::EndTurn))
                 }
                 .boxed_local()
             },
@@ -2960,7 +2990,7 @@ mod tests {
             .await
             .unwrap_err();
 
-        assert_eq!(err.code, acp::ErrorCode::RESOURCE_NOT_FOUND.code);
+        assert_eq!(err.code, acp::ErrorCode::ResourceNotFound);
     }
 
     #[gpui::test]
@@ -2969,7 +2999,7 @@ mod tests {
 
         let fs = FakeFs::new(cx.executor());
         let project = Project::test(fs, [], cx).await;
-        let id = acp::ToolCallId("test".into());
+        let id = acp::ToolCallId::new("test");
 
         let connection = Rc::new(FakeAgentConnection::new().on_user_message({
             let id = id.clone();
@@ -2979,26 +3009,17 @@ mod tests {
                     thread
                         .update(&mut cx, |thread, cx| {
                             thread.handle_session_update(
-                                acp::SessionUpdate::ToolCall(acp::ToolCall {
-                                    id: id.clone(),
-                                    title: "Label".into(),
-                                    kind: acp::ToolKind::Fetch,
-                                    status: acp::ToolCallStatus::InProgress,
-                                    content: vec![],
-                                    locations: vec![],
-                                    raw_input: None,
-                                    raw_output: None,
-                                    meta: None,
-                                }),
+                                acp::SessionUpdate::ToolCall(
+                                    acp::ToolCall::new(id.clone(), "Label")
+                                        .kind(acp::ToolKind::Fetch)
+                                        .status(acp::ToolCallStatus::InProgress),
+                                ),
                                 cx,
                             )
                         })
                         .unwrap()
                         .unwrap();
-                    Ok(acp::PromptResponse {
-                        stop_reason: acp::StopReason::EndTurn,
-                        meta: None,
-                    })
+                    Ok(acp::PromptResponse::new(acp::StopReason::EndTurn))
                 }
                 .boxed_local()
             }
@@ -3040,14 +3061,10 @@ mod tests {
         thread
             .update(cx, |thread, cx| {
                 thread.handle_session_update(
-                    acp::SessionUpdate::ToolCallUpdate(acp::ToolCallUpdate {
+                    acp::SessionUpdate::ToolCallUpdate(acp::ToolCallUpdate::new(
                         id,
-                        fields: acp::ToolCallUpdateFields {
-                            status: Some(acp::ToolCallStatus::Completed),
-                            ..Default::default()
-                        },
-                        meta: None,
-                    }),
+                        acp::ToolCallUpdateFields::new().status(acp::ToolCallStatus::Completed),
+                    )),
                     cx,
                 )
             })
@@ -3079,33 +3096,21 @@ mod tests {
                     thread
                         .update(&mut cx, |thread, cx| {
                             thread.handle_session_update(
-                                acp::SessionUpdate::ToolCall(acp::ToolCall {
-                                    id: acp::ToolCallId("test".into()),
-                                    title: "Label".into(),
-                                    kind: acp::ToolKind::Edit,
-                                    status: acp::ToolCallStatus::Completed,
-                                    content: vec![acp::ToolCallContent::Diff {
-                                        diff: acp::Diff {
-                                            path: "/test/test.txt".into(),
-                                            old_text: None,
-                                            new_text: "foo".into(),
-                                            meta: None,
-                                        },
-                                    }],
-                                    locations: vec![],
-                                    raw_input: None,
-                                    raw_output: None,
-                                    meta: None,
-                                }),
+                                acp::SessionUpdate::ToolCall(
+                                    acp::ToolCall::new("test", "Label")
+                                        .kind(acp::ToolKind::Edit)
+                                        .status(acp::ToolCallStatus::Completed)
+                                        .content(vec![acp::ToolCallContent::Diff(acp::Diff::new(
+                                            "/test/test.txt",
+                                            "foo",
+                                        ))]),
+                                ),
                                 cx,
                             )
                         })
                         .unwrap()
                         .unwrap();
-                    Ok(acp::PromptResponse {
-                        stop_reason: acp::StopReason::EndTurn,
-                        meta: None,
-                    })
+                    Ok(acp::PromptResponse::new(acp::StopReason::EndTurn))
                 }
                 .boxed_local()
             }
@@ -3158,18 +3163,14 @@ mod tests {
                     thread.update(&mut cx, |thread, cx| {
                         thread
                             .handle_session_update(
-                                acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk {
-                                    content: content.text.to_uppercase().into(),
-                                    meta: None,
-                                }),
+                                acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new(
+                                    content.text.to_uppercase().into(),
+                                )),
                                 cx,
                             )
                             .unwrap();
                     })?;
-                    Ok(acp::PromptResponse {
-                        stop_reason: acp::StopReason::EndTurn,
-                        meta: None,
-                    })
+                    Ok(acp::PromptResponse::new(acp::StopReason::EndTurn))
                 }
                 .boxed_local()
             }
@@ -3325,34 +3326,22 @@ mod tests {
                         thread.update(&mut cx, |thread, cx| {
                             thread
                                 .handle_session_update(
-                                    acp::SessionUpdate::ToolCall(acp::ToolCall {
-                                        id: acp::ToolCallId("tool1".into()),
-                                        title: "Test Tool".into(),
-                                        kind: acp::ToolKind::Fetch,
-                                        status: acp::ToolCallStatus::Completed,
-                                        content: vec![],
-                                        locations: vec![],
-                                        raw_input: Some(serde_json::json!({"query": "test"})),
-                                        raw_output: Some(
-                                            serde_json::json!({"result": "inappropriate content"}),
-                                        ),
-                                        meta: None,
-                                    }),
+                                    acp::SessionUpdate::ToolCall(
+                                        acp::ToolCall::new("tool1", "Test Tool")
+                                            .kind(acp::ToolKind::Fetch)
+                                            .status(acp::ToolCallStatus::Completed)
+                                            .raw_input(serde_json::json!({"query": "test"}))
+                                            .raw_output(serde_json::json!({"result": "inappropriate content"})),
+                                    ),
                                     cx,
                                 )
                                 .unwrap();
                         })?;
 
                         // Now return refusal because of the tool result
-                        Ok(acp::PromptResponse {
-                            stop_reason: acp::StopReason::Refusal,
-                            meta: None,
-                        })
+                        Ok(acp::PromptResponse::new(acp::StopReason::Refusal))
                     } else {
-                        Ok(acp::PromptResponse {
-                            stop_reason: acp::StopReason::EndTurn,
-                            meta: None,
-                        })
+                        Ok(acp::PromptResponse::new(acp::StopReason::EndTurn))
                     }
                 }
                 .boxed_local()
@@ -3380,16 +3369,7 @@ mod tests {
         });
 
         // Send a user message - this will trigger tool call and then refusal
-        let send_task = thread.update(cx, |thread, cx| {
-            thread.send(
-                vec![acp::ContentBlock::Text(acp::TextContent {
-                    text: "Hello".into(),
-                    annotations: None,
-                    meta: None,
-                })],
-                cx,
-            )
-        });
+        let send_task = thread.update(cx, |thread, cx| thread.send(vec!["Hello".into()], cx));
         cx.background_executor.spawn(send_task).detach();
         cx.run_until_parked();
 
@@ -3435,21 +3415,11 @@ mod tests {
             let refuse_next = refuse_next.clone();
             move |_request, _thread, _cx| {
                 if refuse_next.load(SeqCst) {
-                    async move {
-                        Ok(acp::PromptResponse {
-                            stop_reason: acp::StopReason::Refusal,
-                            meta: None,
-                        })
-                    }
-                    .boxed_local()
+                    async move { Ok(acp::PromptResponse::new(acp::StopReason::Refusal)) }
+                        .boxed_local()
                 } else {
-                    async move {
-                        Ok(acp::PromptResponse {
-                            stop_reason: acp::StopReason::EndTurn,
-                            meta: None,
-                        })
-                    }
-                    .boxed_local()
+                    async move { Ok(acp::PromptResponse::new(acp::StopReason::EndTurn)) }
+                        .boxed_local()
                 }
             }
         }));
@@ -3506,10 +3476,7 @@ mod tests {
                 let refuse_next = refuse_next.clone();
                 async move {
                     if refuse_next.load(SeqCst) {
-                        return Ok(acp::PromptResponse {
-                            stop_reason: acp::StopReason::Refusal,
-                            meta: None,
-                        });
+                        return Ok(acp::PromptResponse::new(acp::StopReason::Refusal));
                     }
 
                     let acp::ContentBlock::Text(content) = &request.prompt[0] else {
@@ -3518,18 +3485,14 @@ mod tests {
                     thread.update(&mut cx, |thread, cx| {
                         thread
                             .handle_session_update(
-                                acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk {
-                                    content: content.text.to_uppercase().into(),
-                                    meta: None,
-                                }),
+                                acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new(
+                                    content.text.to_uppercase().into(),
+                                )),
                                 cx,
                             )
                             .unwrap();
                     })?;
-                    Ok(acp::PromptResponse {
-                        stop_reason: acp::StopReason::EndTurn,
-                        meta: None,
-                    })
+                    Ok(acp::PromptResponse::new(acp::StopReason::EndTurn))
                 }
                 .boxed_local()
             }
@@ -3654,8 +3617,8 @@ mod tests {
     }
 
     impl AgentConnection for FakeAgentConnection {
-        fn telemetry_id(&self) -> &'static str {
-            "fake"
+        fn telemetry_id(&self) -> SharedString {
+            "fake".into()
         }
 
         fn auth_methods(&self) -> &[acp::AuthMethod] {
@@ -3668,13 +3631,12 @@ mod tests {
             _cwd: &Path,
             cx: &mut App,
         ) -> Task<gpui::Result<Entity<AcpThread>>> {
-            let session_id = acp::SessionId(
+            let session_id = acp::SessionId::new(
                 rand::rng()
                     .sample_iter(&distr::Alphanumeric)
                     .take(7)
                     .map(char::from)
-                    .collect::<String>()
-                    .into(),
+                    .collect::<String>(),
             );
             let action_log = cx.new(|_| ActionLog::new(project.clone()));
             let thread = cx.new(|cx| {

crates/acp_thread/src/connection.rs 🔗

@@ -20,7 +20,7 @@ impl UserMessageId {
 }
 
 pub trait AgentConnection {
-    fn telemetry_id(&self) -> &'static str;
+    fn telemetry_id(&self) -> SharedString;
 
     fn new_thread(
         self: Rc<Self>,
@@ -204,12 +204,21 @@ pub trait AgentModelSelector: 'static {
     }
 }
 
+/// Icon for a model in the model selector.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum AgentModelIcon {
+    /// A built-in icon from Zed's icon set.
+    Named(IconName),
+    /// Path to a custom SVG icon file.
+    Path(SharedString),
+}
+
 #[derive(Debug, Clone, PartialEq, Eq)]
 pub struct AgentModelInfo {
     pub id: acp::ModelId,
     pub name: SharedString,
     pub description: Option<SharedString>,
-    pub icon: Option<IconName>,
+    pub icon: Option<AgentModelIcon>,
 }
 
 impl From<acp::ModelInfo> for AgentModelInfo {
@@ -239,6 +248,10 @@ impl AgentModelList {
             AgentModelList::Grouped(groups) => groups.is_empty(),
         }
     }
+
+    pub fn is_flat(&self) -> bool {
+        matches!(self, AgentModelList::Flat(_))
+    }
 }
 
 #[cfg(feature = "test-support")]
@@ -322,8 +335,8 @@ mod test_support {
     }
 
     impl AgentConnection for StubAgentConnection {
-        fn telemetry_id(&self) -> &'static str {
-            "stub"
+        fn telemetry_id(&self) -> SharedString {
+            "stub".into()
         }
 
         fn auth_methods(&self) -> &[acp::AuthMethod] {
@@ -336,7 +349,7 @@ mod test_support {
             _cwd: &Path,
             cx: &mut gpui::App,
         ) -> Task<gpui::Result<Entity<AcpThread>>> {
-            let session_id = acp::SessionId(self.sessions.lock().len().to_string().into());
+            let session_id = acp::SessionId::new(self.sessions.lock().len().to_string());
             let action_log = cx.new(|_| ActionLog::new(project.clone()));
             let thread = cx.new(|cx| {
                 AcpThread::new(
@@ -345,12 +358,12 @@ mod test_support {
                     project,
                     action_log,
                     session_id.clone(),
-                    watch::Receiver::constant(acp::PromptCapabilities {
-                        image: true,
-                        audio: true,
-                        embedded_context: true,
-                        meta: None,
-                    }),
+                    watch::Receiver::constant(
+                        acp::PromptCapabilities::new()
+                            .image(true)
+                            .audio(true)
+                            .embedded_context(true),
+                    ),
                     cx,
                 )
             });
@@ -389,10 +402,7 @@ mod test_support {
                 response_tx.replace(tx);
                 cx.spawn(async move |_| {
                     let stop_reason = rx.await?;
-                    Ok(acp::PromptResponse {
-                        stop_reason,
-                        meta: None,
-                    })
+                    Ok(acp::PromptResponse::new(stop_reason))
                 })
             } else {
                 for update in self.next_prompt_updates.lock().drain(..) {
@@ -400,7 +410,7 @@ mod test_support {
                     let update = update.clone();
                     let permission_request = if let acp::SessionUpdate::ToolCall(tool_call) =
                         &update
-                        && let Some(options) = self.permission_requests.get(&tool_call.id)
+                        && let Some(options) = self.permission_requests.get(&tool_call.tool_call_id)
                     {
                         Some((tool_call.clone(), options.clone()))
                     } else {
@@ -429,10 +439,7 @@ mod test_support {
 
                 cx.spawn(async move |_| {
                     try_join_all(tasks).await?;
-                    Ok(acp::PromptResponse {
-                        stop_reason: acp::StopReason::EndTurn,
-                        meta: None,
-                    })
+                    Ok(acp::PromptResponse::new(acp::StopReason::EndTurn))
                 })
             }
         }

crates/acp_thread/src/diff.rs 🔗

@@ -158,7 +158,7 @@ impl Diff {
     }
 
     pub fn has_revealed_range(&self, cx: &App) -> bool {
-        self.multibuffer().read(cx).excerpt_paths().next().is_some()
+        self.multibuffer().read(cx).paths().next().is_some()
     }
 
     pub fn needs_update(&self, old_text: &str, new_text: &str, cx: &App) -> bool {

crates/acp_thread/src/mention.rs 🔗

@@ -4,12 +4,14 @@ use file_icons::FileIcons;
 use prompt_store::{PromptId, UserPromptId};
 use serde::{Deserialize, Serialize};
 use std::{
+    borrow::Cow,
     fmt,
     ops::RangeInclusive,
     path::{Path, PathBuf},
 };
 use ui::{App, IconName, SharedString};
 use url::Url;
+use urlencoding::decode;
 use util::paths::PathStyle;
 
 #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Hash)]
@@ -74,11 +76,13 @@ impl MentionUri {
         let path = url.path();
         match url.scheme() {
             "file" => {
-                let path = if path_style.is_windows() {
+                let normalized = if path_style.is_windows() {
                     path.trim_start_matches("/")
                 } else {
                     path
                 };
+                let decoded = decode(normalized).unwrap_or(Cow::Borrowed(normalized));
+                let path = decoded.as_ref();
 
                 if let Some(fragment) = url.fragment() {
                     let line_range = parse_line_range(fragment)?;
@@ -108,7 +112,7 @@ impl MentionUri {
                 if let Some(thread_id) = path.strip_prefix("/agent/thread/") {
                     let name = single_query_param(&url, "name")?.context("Missing thread name")?;
                     Ok(Self::Thread {
-                        id: acp::SessionId(thread_id.into()),
+                        id: acp::SessionId::new(thread_id),
                         name,
                     })
                 } else if let Some(path) = path.strip_prefix("/agent/text-thread/") {
@@ -406,6 +410,19 @@ mod tests {
         assert_eq!(parsed.to_uri().to_string(), selection_uri);
     }
 
+    #[test]
+    fn test_parse_file_uri_with_non_ascii() {
+        let file_uri = uri!("file:///path/to/%E6%97%A5%E6%9C%AC%E8%AA%9E.txt");
+        let parsed = MentionUri::parse(file_uri, PathStyle::local()).unwrap();
+        match &parsed {
+            MentionUri::File { abs_path } => {
+                assert_eq!(abs_path, Path::new(path!("/path/to/日本語.txt")));
+            }
+            _ => panic!("Expected File variant"),
+        }
+        assert_eq!(parsed.to_uri().to_string(), file_uri);
+    }
+
     #[test]
     fn test_parse_untitled_selection_uri() {
         let selection_uri = uri!("zed:///agent/untitled-buffer#L1:10");

crates/acp_thread/src/terminal.rs 🔗

@@ -75,11 +75,9 @@ impl Terminal {
 
                     let exit_status = exit_status.map(portable_pty::ExitStatus::from);
 
-                    acp::TerminalExitStatus {
-                        exit_code: exit_status.as_ref().map(|e| e.exit_code()),
-                        signal: exit_status.and_then(|e| e.signal().map(Into::into)),
-                        meta: None,
-                    }
+                    acp::TerminalExitStatus::new()
+                        .exit_code(exit_status.as_ref().map(|e| e.exit_code()))
+                        .signal(exit_status.and_then(|e| e.signal().map(ToOwned::to_owned)))
                 })
                 .shared(),
         }
@@ -103,25 +101,19 @@ impl Terminal {
         if let Some(output) = self.output.as_ref() {
             let exit_status = output.exit_status.map(portable_pty::ExitStatus::from);
 
-            acp::TerminalOutputResponse {
-                output: output.content.clone(),
-                truncated: output.original_content_len > output.content.len(),
-                exit_status: Some(acp::TerminalExitStatus {
-                    exit_code: exit_status.as_ref().map(|e| e.exit_code()),
-                    signal: exit_status.and_then(|e| e.signal().map(Into::into)),
-                    meta: None,
-                }),
-                meta: None,
-            }
+            acp::TerminalOutputResponse::new(
+                output.content.clone(),
+                output.original_content_len > output.content.len(),
+            )
+            .exit_status(
+                acp::TerminalExitStatus::new()
+                    .exit_code(exit_status.as_ref().map(|e| e.exit_code()))
+                    .signal(exit_status.and_then(|e| e.signal().map(ToOwned::to_owned))),
+            )
         } else {
             let (current_content, original_len) = self.truncated_output(cx);
-
-            acp::TerminalOutputResponse {
-                truncated: current_content.len() < original_len,
-                output: current_content,
-                exit_status: None,
-                meta: None,
-            }
+            let truncated = current_content.len() < original_len;
+            acp::TerminalOutputResponse::new(current_content, truncated)
         }
     }
 
@@ -195,8 +187,10 @@ pub async fn create_terminal_entity(
         Default::default()
     };
 
-    // Disables paging for `git` and hopefully other commands
+    // Disable pagers so agent/terminal commands don't hang behind interactive UIs
     env.insert("PAGER".into(), "".into());
+    // Override user core.pager (e.g. delta) which Git prefers over PAGER
+    env.insert("GIT_PAGER".into(), "cat".into());
     env.extend(env_vars);
 
     // Use remote shell or default system shell, as appropriate

crates/acp_tools/src/acp_tools.rs 🔗

@@ -371,13 +371,13 @@ impl AcpTools {
                                     syntax: cx.theme().syntax().clone(),
                                     code_block_overflow_x_scroll: true,
                                     code_block: StyleRefinement {
-                                        text: Some(TextStyleRefinement {
+                                        text: TextStyleRefinement {
                                             font_family: Some(
                                                 theme_settings.buffer_font.family.clone(),
                                             ),
                                             font_size: Some((base_size * 0.8).into()),
                                             ..Default::default()
-                                        }),
+                                        },
                                         ..Default::default()
                                     },
                                     ..Default::default()

crates/action_log/src/action_log.rs 🔗

@@ -6,7 +6,7 @@ use futures::{FutureExt, StreamExt, channel::mpsc};
 use gpui::{
     App, AppContext, AsyncApp, Context, Entity, SharedString, Subscription, Task, WeakEntity,
 };
-use language::{Anchor, Buffer, BufferEvent, DiskState, Point, ToPoint};
+use language::{Anchor, Buffer, BufferEvent, Point, ToPoint};
 use project::{Project, ProjectItem, lsp_store::OpenLspBufferHandle};
 use std::{cmp, ops::Range, sync::Arc};
 use text::{Edit, Patch, Rope};
@@ -150,7 +150,7 @@ impl ActionLog {
                 if buffer
                     .read(cx)
                     .file()
-                    .is_some_and(|file| file.disk_state() == DiskState::Deleted)
+                    .is_some_and(|file| file.disk_state().is_deleted())
                 {
                     // If the buffer had been edited by a tool, but it got
                     // deleted externally, we want to stop tracking it.
@@ -162,7 +162,7 @@ impl ActionLog {
                 if buffer
                     .read(cx)
                     .file()
-                    .is_some_and(|file| file.disk_state() != DiskState::Deleted)
+                    .is_some_and(|file| !file.disk_state().is_deleted())
                 {
                     // If the buffer had been deleted by a tool, but it got
                     // resurrected externally, we want to clear the edits we
@@ -768,7 +768,7 @@ impl ActionLog {
                 tracked.version != buffer.version
                     && buffer
                         .file()
-                        .is_some_and(|file| file.disk_state() != DiskState::Deleted)
+                        .is_some_and(|file| !file.disk_state().is_deleted())
             })
             .map(|(buffer, _)| buffer)
     }
@@ -776,7 +776,7 @@ impl ActionLog {
 
 #[derive(Clone)]
 pub struct ActionLogTelemetry {
-    pub agent_telemetry_id: &'static str,
+    pub agent_telemetry_id: SharedString,
     pub session_id: Arc<str>,
 }
 

crates/agent/Cargo.toml 🔗

@@ -83,6 +83,7 @@ ctor.workspace = true
 db = { workspace = true, "features" = ["test-support"] }
 editor = { workspace = true, "features" = ["test-support"] }
 env_logger.workspace = true
+eval_utils.workspace = true
 fs = { workspace = true, "features" = ["test-support"] }
 git = { workspace = true, "features" = ["test-support"] }
 gpui = { workspace = true, "features" = ["test-support"] }

crates/agent/src/agent.rs 🔗

@@ -5,12 +5,12 @@ mod legacy_thread;
 mod native_agent_server;
 pub mod outline;
 mod templates;
-mod thread;
-mod tools;
-
 #[cfg(test)]
 mod tests;
+mod thread;
+mod tools;
 
+use context_server::ContextServerId;
 pub use db::*;
 pub use history_store::*;
 pub use native_agent_server::NativeAgentServer;
@@ -18,11 +18,11 @@ pub use templates::*;
 pub use thread::*;
 pub use tools::*;
 
-use acp_thread::{AcpThread, AgentModelSelector};
+use acp_thread::{AcpThread, AgentModelSelector, UserMessageId};
 use agent_client_protocol as acp;
 use anyhow::{Context as _, Result, anyhow};
 use chrono::{DateTime, Utc};
-use collections::{HashSet, IndexMap};
+use collections::{HashMap, HashSet, IndexMap};
 use fs::Fs;
 use futures::channel::{mpsc, oneshot};
 use futures::future::Shared;
@@ -30,15 +30,15 @@ use futures::{StreamExt, future};
 use gpui::{
     App, AppContext, AsyncApp, Context, Entity, SharedString, Subscription, Task, WeakEntity,
 };
-use language_model::{LanguageModel, LanguageModelProvider, LanguageModelRegistry};
+use language_model::{IconOrSvg, LanguageModel, LanguageModelProvider, LanguageModelRegistry};
 use project::{Project, ProjectItem, ProjectPath, Worktree};
 use prompt_store::{
-    ProjectContext, PromptStore, RulesFileContext, UserRulesContext, WorktreeContext,
+    ProjectContext, PromptStore, RULES_FILE_NAMES, RulesFileContext, UserRulesContext,
+    WorktreeContext,
 };
 use serde::{Deserialize, Serialize};
 use settings::{LanguageModelSelection, update_settings_file};
 use std::any::Any;
-use std::collections::HashMap;
 use std::path::{Path, PathBuf};
 use std::rc::Rc;
 use std::sync::Arc;
@@ -51,18 +51,6 @@ pub struct ProjectSnapshot {
     pub timestamp: DateTime<Utc>,
 }
 
-const RULES_FILE_NAMES: [&str; 9] = [
-    ".rules",
-    ".cursorrules",
-    ".windsurfrules",
-    ".clinerules",
-    ".github/copilot-instructions.md",
-    "CLAUDE.md",
-    "AGENT.md",
-    "AGENTS.md",
-    "GEMINI.md",
-];
-
 pub struct RulesLoadingError {
     pub message: SharedString,
 }
@@ -105,7 +93,7 @@ impl LanguageModels {
     fn refresh_list(&mut self, cx: &App) {
         let providers = LanguageModelRegistry::global(cx)
             .read(cx)
-            .providers()
+            .visible_providers()
             .into_iter()
             .filter(|provider| provider.is_authenticated(cx))
             .collect::<Vec<_>>();
@@ -165,18 +153,21 @@ impl LanguageModels {
             id: Self::model_id(model),
             name: model.name().0,
             description: None,
-            icon: Some(provider.icon()),
+            icon: Some(match provider.icon() {
+                IconOrSvg::Svg(path) => acp_thread::AgentModelIcon::Path(path),
+                IconOrSvg::Icon(name) => acp_thread::AgentModelIcon::Named(name),
+            }),
         }
     }
 
     fn model_id(model: &Arc<dyn LanguageModel>) -> acp::ModelId {
-        acp::ModelId(format!("{}/{}", model.provider_id().0, model.id().0).into())
+        acp::ModelId::new(format!("{}/{}", model.provider_id().0, model.id().0))
     }
 
     fn authenticate_all_language_model_providers(cx: &mut App) -> Task<()> {
         let authenticate_all_providers = LanguageModelRegistry::global(cx)
             .read(cx)
-            .providers()
+            .visible_providers()
             .iter()
             .map(|provider| (provider.id(), provider.name(), provider.authenticate(cx)))
             .collect::<Vec<_>>();
@@ -263,12 +254,24 @@ impl NativeAgent {
             .await;
 
         cx.new(|cx| {
+            let context_server_store = project.read(cx).context_server_store();
+            let context_server_registry =
+                cx.new(|cx| ContextServerRegistry::new(context_server_store.clone(), cx));
+
             let mut subscriptions = vec![
                 cx.subscribe(&project, Self::handle_project_event),
                 cx.subscribe(
                     &LanguageModelRegistry::global(cx),
                     Self::handle_models_updated_event,
                 ),
+                cx.subscribe(
+                    &context_server_store,
+                    Self::handle_context_server_store_updated,
+                ),
+                cx.subscribe(
+                    &context_server_registry,
+                    Self::handle_context_server_registry_event,
+                ),
             ];
             if let Some(prompt_store) = prompt_store.as_ref() {
                 subscriptions.push(cx.subscribe(prompt_store, Self::handle_prompts_updated_event))
@@ -277,16 +280,14 @@ impl NativeAgent {
             let (project_context_needs_refresh_tx, project_context_needs_refresh_rx) =
                 watch::channel(());
             Self {
-                sessions: HashMap::new(),
+                sessions: HashMap::default(),
                 history,
                 project_context: cx.new(|_| project_context),
                 project_context_needs_refresh: project_context_needs_refresh_tx,
                 _maintain_project_context: cx.spawn(async move |this, cx| {
                     Self::maintain_project_context(this, project_context_needs_refresh_rx, cx).await
                 }),
-                context_server_registry: cx.new(|cx| {
-                    ContextServerRegistry::new(project.read(cx).context_server_store(), cx)
-                }),
+                context_server_registry,
                 templates,
                 models: LanguageModels::new(cx),
                 project,
@@ -355,6 +356,9 @@ impl NativeAgent {
                 pending_save: Task::ready(()),
             },
         );
+
+        self.update_available_commands(cx);
+
         acp_thread
     }
 
@@ -425,10 +429,7 @@ impl NativeAgent {
                 .into_iter()
                 .flat_map(|(contents, prompt_metadata)| match contents {
                     Ok(contents) => Some(UserRulesContext {
-                        uuid: match prompt_metadata.id {
-                            prompt_store::PromptId::User { uuid } => uuid,
-                            prompt_store::PromptId::EditWorkflow => return None,
-                        },
+                        uuid: prompt_metadata.id.as_user()?,
                         title: prompt_metadata.title.map(|title| title.to_string()),
                         contents,
                     }),
@@ -622,6 +623,99 @@ impl NativeAgent {
         }
     }
 
+    fn handle_context_server_store_updated(
+        &mut self,
+        _store: Entity<project::context_server_store::ContextServerStore>,
+        _event: &project::context_server_store::Event,
+        cx: &mut Context<Self>,
+    ) {
+        self.update_available_commands(cx);
+    }
+
+    fn handle_context_server_registry_event(
+        &mut self,
+        _registry: Entity<ContextServerRegistry>,
+        event: &ContextServerRegistryEvent,
+        cx: &mut Context<Self>,
+    ) {
+        match event {
+            ContextServerRegistryEvent::ToolsChanged => {}
+            ContextServerRegistryEvent::PromptsChanged => {
+                self.update_available_commands(cx);
+            }
+        }
+    }
+
+    fn update_available_commands(&self, cx: &mut Context<Self>) {
+        let available_commands = self.build_available_commands(cx);
+        for session in self.sessions.values() {
+            if let Some(acp_thread) = session.acp_thread.upgrade() {
+                acp_thread.update(cx, |thread, cx| {
+                    thread
+                        .handle_session_update(
+                            acp::SessionUpdate::AvailableCommandsUpdate(
+                                acp::AvailableCommandsUpdate::new(available_commands.clone()),
+                            ),
+                            cx,
+                        )
+                        .log_err();
+                });
+            }
+        }
+    }
+
+    fn build_available_commands(&self, cx: &App) -> Vec<acp::AvailableCommand> {
+        let registry = self.context_server_registry.read(cx);
+
+        let mut prompt_name_counts: HashMap<&str, usize> = HashMap::default();
+        for context_server_prompt in registry.prompts() {
+            *prompt_name_counts
+                .entry(context_server_prompt.prompt.name.as_str())
+                .or_insert(0) += 1;
+        }
+
+        registry
+            .prompts()
+            .flat_map(|context_server_prompt| {
+                let prompt = &context_server_prompt.prompt;
+
+                let should_prefix = prompt_name_counts
+                    .get(prompt.name.as_str())
+                    .copied()
+                    .unwrap_or(0)
+                    > 1;
+
+                let name = if should_prefix {
+                    format!("{}.{}", context_server_prompt.server_id, prompt.name)
+                } else {
+                    prompt.name.clone()
+                };
+
+                let mut command = acp::AvailableCommand::new(
+                    name,
+                    prompt.description.clone().unwrap_or_default(),
+                );
+
+                match prompt.arguments.as_deref() {
+                    Some([arg]) => {
+                        let hint = format!("<{}>", arg.name);
+
+                        command = command.input(acp::AvailableCommandInput::Unstructured(
+                            acp::UnstructuredCommandInput::new(hint),
+                        ));
+                    }
+                    Some([]) | None => {}
+                    Some(_) => {
+                        // skip >1 argument commands since we don't support them yet
+                        return None;
+                    }
+                }
+
+                Some(command)
+            })
+            .collect()
+    }
+
     pub fn load_thread(
         &mut self,
         id: acp::SessionId,
@@ -720,6 +814,102 @@ impl NativeAgent {
             history.update(cx, |history, cx| history.reload(cx)).ok();
         });
     }
+
+    fn send_mcp_prompt(
+        &self,
+        message_id: UserMessageId,
+        session_id: agent_client_protocol::SessionId,
+        prompt_name: String,
+        server_id: ContextServerId,
+        arguments: HashMap<String, String>,
+        original_content: Vec<acp::ContentBlock>,
+        cx: &mut Context<Self>,
+    ) -> Task<Result<acp::PromptResponse>> {
+        let server_store = self.context_server_registry.read(cx).server_store().clone();
+        let path_style = self.project.read(cx).path_style(cx);
+
+        cx.spawn(async move |this, cx| {
+            let prompt =
+                crate::get_prompt(&server_store, &server_id, &prompt_name, arguments, cx).await?;
+
+            let (acp_thread, thread) = this.update(cx, |this, _cx| {
+                let session = this
+                    .sessions
+                    .get(&session_id)
+                    .context("Failed to get session")?;
+                anyhow::Ok((session.acp_thread.clone(), session.thread.clone()))
+            })??;
+
+            let mut last_is_user = true;
+
+            thread.update(cx, |thread, cx| {
+                thread.push_acp_user_block(
+                    message_id,
+                    original_content.into_iter().skip(1),
+                    path_style,
+                    cx,
+                );
+            })?;
+
+            for message in prompt.messages {
+                let context_server::types::PromptMessage { role, content } = message;
+                let block = mcp_message_content_to_acp_content_block(content);
+
+                match role {
+                    context_server::types::Role::User => {
+                        let id = acp_thread::UserMessageId::new();
+
+                        acp_thread.update(cx, |acp_thread, cx| {
+                            acp_thread.push_user_content_block_with_indent(
+                                Some(id.clone()),
+                                block.clone(),
+                                true,
+                                cx,
+                            );
+                            anyhow::Ok(())
+                        })??;
+
+                        thread.update(cx, |thread, cx| {
+                            thread.push_acp_user_block(id, [block], path_style, cx);
+                            anyhow::Ok(())
+                        })??;
+                    }
+                    context_server::types::Role::Assistant => {
+                        acp_thread.update(cx, |acp_thread, cx| {
+                            acp_thread.push_assistant_content_block_with_indent(
+                                block.clone(),
+                                false,
+                                true,
+                                cx,
+                            );
+                            anyhow::Ok(())
+                        })??;
+
+                        thread.update(cx, |thread, cx| {
+                            thread.push_acp_agent_block(block, cx);
+                            anyhow::Ok(())
+                        })??;
+                    }
+                }
+
+                last_is_user = role == context_server::types::Role::User;
+            }
+
+            let response_stream = thread.update(cx, |thread, cx| {
+                if last_is_user {
+                    thread.send_existing(cx)
+                } else {
+                    // Resume if MCP prompt did not end with a user message
+                    thread.resume(cx)
+                }
+            })??;
+
+            cx.update(|cx| {
+                NativeAgentConnection::handle_thread_events(response_stream, acp_thread, cx)
+            })?
+            .await
+        })
+    }
 }
 
 /// Wrapper struct that implements the AgentConnection trait
@@ -789,28 +979,12 @@ impl NativeAgentConnection {
                             }
                             ThreadEvent::AgentText(text) => {
                                 acp_thread.update(cx, |thread, cx| {
-                                    thread.push_assistant_content_block(
-                                        acp::ContentBlock::Text(acp::TextContent {
-                                            text,
-                                            annotations: None,
-                                            meta: None,
-                                        }),
-                                        false,
-                                        cx,
-                                    )
+                                    thread.push_assistant_content_block(text.into(), false, cx)
                                 })?;
                             }
                             ThreadEvent::AgentThinking(text) => {
                                 acp_thread.update(cx, |thread, cx| {
-                                    thread.push_assistant_content_block(
-                                        acp::ContentBlock::Text(acp::TextContent {
-                                            text,
-                                            annotations: None,
-                                            meta: None,
-                                        }),
-                                        true,
-                                        cx,
-                                    )
+                                    thread.push_assistant_content_block(text.into(), true, cx)
                                 })?;
                             }
                             ThreadEvent::ToolCallAuthorization(ToolCallAuthorization {
@@ -824,8 +998,9 @@ impl NativeAgentConnection {
                                     )
                                 })??;
                                 cx.background_spawn(async move {
-                                    if let acp::RequestPermissionOutcome::Selected { option_id } =
-                                        outcome_task.await
+                                    if let acp::RequestPermissionOutcome::Selected(
+                                        acp::SelectedPermissionOutcome { option_id, .. },
+                                    ) = outcome_task.await
                                     {
                                         response
                                             .send(option_id)
@@ -852,10 +1027,7 @@ impl NativeAgentConnection {
                             }
                             ThreadEvent::Stop(stop_reason) => {
                                 log::debug!("Assistant message complete: {:?}", stop_reason);
-                                return Ok(acp::PromptResponse {
-                                    stop_reason,
-                                    meta: None,
-                                });
+                                return Ok(acp::PromptResponse::new(stop_reason));
                             }
                         }
                     }
@@ -867,14 +1039,44 @@ impl NativeAgentConnection {
             }
 
             log::debug!("Response stream completed");
-            anyhow::Ok(acp::PromptResponse {
-                stop_reason: acp::StopReason::EndTurn,
-                meta: None,
-            })
+            anyhow::Ok(acp::PromptResponse::new(acp::StopReason::EndTurn))
         })
     }
 }
 
+struct Command<'a> {
+    prompt_name: &'a str,
+    arg_value: &'a str,
+    explicit_server_id: Option<&'a str>,
+}
+
+impl<'a> Command<'a> {
+    fn parse(prompt: &'a [acp::ContentBlock]) -> Option<Self> {
+        let acp::ContentBlock::Text(text_content) = prompt.first()? else {
+            return None;
+        };
+        let text = text_content.text.trim();
+        let command = text.strip_prefix('/')?;
+        let (command, arg_value) = command
+            .split_once(char::is_whitespace)
+            .unwrap_or((command, ""));
+
+        if let Some((server_id, prompt_name)) = command.split_once('.') {
+            Some(Self {
+                prompt_name,
+                arg_value,
+                explicit_server_id: Some(server_id),
+            })
+        } else {
+            Some(Self {
+                prompt_name: command,
+                arg_value,
+                explicit_server_id: None,
+            })
+        }
+    }
+}
+
 struct NativeAgentModelSelector {
     session_id: acp::SessionId,
     connection: NativeAgentConnection,
@@ -968,8 +1170,8 @@ impl acp_thread::AgentModelSelector for NativeAgentModelSelector {
 }
 
 impl acp_thread::AgentConnection for NativeAgentConnection {
-    fn telemetry_id(&self) -> &'static str {
-        "zed"
+    fn telemetry_id(&self) -> SharedString {
+        "zed".into()
     }
 
     fn new_thread(
@@ -1040,6 +1242,47 @@ impl acp_thread::AgentConnection for NativeAgentConnection {
         let session_id = params.session_id.clone();
         log::info!("Received prompt request for session: {}", session_id);
         log::debug!("Prompt blocks count: {}", params.prompt.len());
+
+        if let Some(parsed_command) = Command::parse(&params.prompt) {
+            let registry = self.0.read(cx).context_server_registry.read(cx);
+
+            let explicit_server_id = parsed_command
+                .explicit_server_id
+                .map(|server_id| ContextServerId(server_id.into()));
+
+            if let Some(prompt) =
+                registry.find_prompt(explicit_server_id.as_ref(), parsed_command.prompt_name)
+            {
+                let arguments = if !parsed_command.arg_value.is_empty()
+                    && let Some(arg_name) = prompt
+                        .prompt
+                        .arguments
+                        .as_ref()
+                        .and_then(|args| args.first())
+                        .map(|arg| arg.name.clone())
+                {
+                    HashMap::from_iter([(arg_name, parsed_command.arg_value.to_string())])
+                } else {
+                    Default::default()
+                };
+
+                let prompt_name = prompt.prompt.name.clone();
+                let server_id = prompt.server_id.clone();
+
+                return self.0.update(cx, |agent, cx| {
+                    agent.send_mcp_prompt(
+                        id,
+                        session_id.clone(),
+                        prompt_name,
+                        server_id,
+                        arguments,
+                        params.prompt,
+                        cx,
+                    )
+                });
+            };
+        };
+
         let path_style = self.0.read(cx).project.read(cx).path_style(cx);
 
         self.run_turn(session_id, cx, move |thread, cx| {
@@ -1240,6 +1483,15 @@ impl TerminalHandle for AcpTerminalHandle {
         self.terminal
             .read_with(cx, |term, cx| term.current_output(cx))
     }
+
+    fn kill(&self, cx: &AsyncApp) -> Result<()> {
+        cx.update(|cx| {
+            self.terminal.update(cx, |terminal, cx| {
+                terminal.kill(cx);
+            });
+        })?;
+        Ok(())
+    }
 }
 
 #[cfg(test)]
@@ -1374,10 +1626,12 @@ mod internal_tests {
             IndexMap::from_iter([(
                 AgentModelGroupName("Fake".into()),
                 vec![AgentModelInfo {
-                    id: acp::ModelId("fake/fake".into()),
+                    id: acp::ModelId::new("fake/fake"),
                     name: "Fake".into(),
                     description: None,
-                    icon: Some(ui::IconName::ZedAssistant),
+                    icon: Some(acp_thread::AgentModelIcon::Named(
+                        ui::IconName::ZedAssistant
+                    )),
                 }]
             )])
         );
@@ -1435,7 +1689,7 @@ mod internal_tests {
 
         // Select a model
         let selector = connection.model_selector(&session_id).unwrap();
-        let model_id = acp::ModelId("fake/fake".into());
+        let model_id = acp::ModelId::new("fake/fake");
         cx.update(|cx| selector.select_model(model_id.clone(), cx))
             .await
             .unwrap();
@@ -1521,20 +1775,14 @@ mod internal_tests {
             thread.send(
                 vec![
                     "What does ".into(),
-                    acp::ContentBlock::ResourceLink(acp::ResourceLink {
-                        name: "b.md".into(),
-                        uri: MentionUri::File {
+                    acp::ContentBlock::ResourceLink(acp::ResourceLink::new(
+                        "b.md",
+                        MentionUri::File {
                             abs_path: path!("/a/b.md").into(),
                         }
                         .to_uri()
                         .to_string(),
-                        annotations: None,
-                        description: None,
-                        mime_type: None,
-                        size: None,
-                        title: None,
-                        meta: None,
-                    }),
+                    )),
                     " mean?".into(),
                 ],
                 cx,
@@ -1633,3 +1881,35 @@ mod internal_tests {
         });
     }
 }
+
+fn mcp_message_content_to_acp_content_block(
+    content: context_server::types::MessageContent,
+) -> acp::ContentBlock {
+    match content {
+        context_server::types::MessageContent::Text {
+            text,
+            annotations: _,
+        } => text.into(),
+        context_server::types::MessageContent::Image {
+            data,
+            mime_type,
+            annotations: _,
+        } => acp::ContentBlock::Image(acp::ImageContent::new(data, mime_type)),
+        context_server::types::MessageContent::Audio {
+            data,
+            mime_type,
+            annotations: _,
+        } => acp::ContentBlock::Audio(acp::AudioContent::new(data, mime_type)),
+        context_server::types::MessageContent::Resource {
+            resource,
+            annotations: _,
+        } => {
+            let mut link =
+                acp::ResourceLink::new(resource.uri.to_string(), resource.uri.to_string());
+            if let Some(mime_type) = resource.mime_type {
+                link = link.mime_type(mime_type);
+            }
+            acp::ContentBlock::ResourceLink(link)
+        }
+    }
+}

crates/agent/src/db.rs 🔗

@@ -366,7 +366,7 @@ impl ThreadsDatabase {
 
             for (id, summary, updated_at) in rows {
                 threads.push(DbThreadMetadata {
-                    id: acp::SessionId(id),
+                    id: acp::SessionId::new(id),
                     title: summary.into(),
                     updated_at: DateTime::parse_from_rfc3339(&updated_at)?.with_timezone(&Utc),
                 });

crates/agent/src/edit_agent/evals.rs 🔗

@@ -4,7 +4,7 @@ use crate::{
 };
 use Role::*;
 use client::{Client, UserStore};
-use collections::HashMap;
+use eval_utils::{EvalOutput, EvalOutputProcessor, OutcomeKind};
 use fs::FakeFs;
 use futures::{FutureExt, future::LocalBoxFuture};
 use gpui::{AppContext, TestAppContext, Timer};
@@ -20,16 +20,62 @@ use rand::prelude::*;
 use reqwest_client::ReqwestClient;
 use serde_json::json;
 use std::{
-    cmp::Reverse,
     fmt::{self, Display},
-    io::Write as _,
     path::Path,
     str::FromStr,
-    sync::mpsc,
     time::Duration,
 };
 use util::path;
 
+#[derive(Default, Clone, Debug)]
+struct EditAgentOutputProcessor {
+    mismatched_tag_threshold: f32,
+    cumulative_tags: usize,
+    cumulative_mismatched_tags: usize,
+    eval_outputs: Vec<EvalOutput<EditEvalMetadata>>,
+}
+
+fn mismatched_tag_threshold(mismatched_tag_threshold: f32) -> EditAgentOutputProcessor {
+    EditAgentOutputProcessor {
+        mismatched_tag_threshold,
+        cumulative_tags: 0,
+        cumulative_mismatched_tags: 0,
+        eval_outputs: Vec::new(),
+    }
+}
+
+#[derive(Clone, Debug)]
+struct EditEvalMetadata {
+    tags: usize,
+    mismatched_tags: usize,
+}
+
+impl EvalOutputProcessor for EditAgentOutputProcessor {
+    type Metadata = EditEvalMetadata;
+
+    fn process(&mut self, output: &EvalOutput<Self::Metadata>) {
+        if matches!(output.outcome, OutcomeKind::Passed | OutcomeKind::Failed) {
+            self.cumulative_mismatched_tags += output.metadata.mismatched_tags;
+            self.cumulative_tags += output.metadata.tags;
+            self.eval_outputs.push(output.clone());
+        }
+    }
+
+    fn assert(&mut self) {
+        let mismatched_tag_ratio =
+            self.cumulative_mismatched_tags as f32 / self.cumulative_tags as f32;
+        if mismatched_tag_ratio > self.mismatched_tag_threshold {
+            for eval_output in &self.eval_outputs {
+                println!("{}", eval_output.data);
+            }
+            panic!(
+                "Too many mismatched tags: {:?}",
+                self.cumulative_mismatched_tags
+            );
+        }
+    }
+}
+
 #[test]
 #[cfg_attr(not(feature = "unit-eval"), ignore)]
 fn eval_extract_handle_command_output() {
@@ -55,22 +101,19 @@ fn eval_extract_handle_command_output() {
         include_str!("evals/fixtures/extract_handle_command_output/possible-07.diff"),
     ];
     let edit_description = "Extract `handle_command_output` method from `run_git_blame`.";
-    eval(
-        100,
-        0.95,
-        0.05,
-        EvalInput::from_conversation(
+    eval_utils::eval(100, 0.95, mismatched_tag_threshold(0.05), move || {
+        run_eval(EvalInput::from_conversation(
             vec![
                 message(
                     User,
                     [text(formatdoc! {"
-                        Read the `{input_file_path}` file and extract a method in
-                        the final stanza of `run_git_blame` to deal with command failures,
-                        call it `handle_command_output` and take the std::process::Output as the only parameter.
-                        Do not document the method and do not add any comments.
+                            Read the `{input_file_path}` file and extract a method in
+                            the final stanza of `run_git_blame` to deal with command failures,
+                            call it `handle_command_output` and take the std::process::Output as the only parameter.
+                            Do not document the method and do not add any comments.
 
-                        Add it right next to `run_git_blame` and copy it verbatim from `run_git_blame`.
-                    "})],
+                            Add it right next to `run_git_blame` and copy it verbatim from `run_git_blame`.
+                        "})],
                 ),
                 message(
                     Assistant,
@@ -102,9 +145,9 @@ fn eval_extract_handle_command_output() {
                 ),
             ],
             Some(input_file_content.into()),
-            EvalAssertion::assert_diff_any(possible_diffs),
-        ),
-    );
+            EvalAssertion::assert_diff_any(possible_diffs.clone()),
+        ))
+    });
 }
 
 #[test]
@@ -122,18 +165,16 @@ fn eval_delete_run_git_blame() {
     let input_file_content = include_str!("evals/fixtures/delete_run_git_blame/before.rs");
     let output_file_content = include_str!("evals/fixtures/delete_run_git_blame/after.rs");
     let edit_description = "Delete the `run_git_blame` function.";
-    eval(
-        100,
-        0.95,
-        0.05,
-        EvalInput::from_conversation(
+
+    eval_utils::eval(100, 0.95, mismatched_tag_threshold(0.05), move || {
+        run_eval(EvalInput::from_conversation(
             vec![
                 message(
                     User,
                     [text(formatdoc! {"
-                        Read the `{input_file_path}` file and delete `run_git_blame`. Just that
-                        one function, not its usages.
-                    "})],
+                            Read the `{input_file_path}` file and delete `run_git_blame`. Just that
+                            one function, not its usages.
+                        "})],
                 ),
                 message(
                     Assistant,
@@ -166,8 +207,8 @@ fn eval_delete_run_git_blame() {
             ],
             Some(input_file_content.into()),
             EvalAssertion::assert_eq(output_file_content),
-        ),
-    );
+        ))
+    });
 }
 
 #[test]
@@ -185,18 +226,16 @@ fn eval_translate_doc_comments() {
     let input_file_path = "root/canvas.rs";
     let input_file_content = include_str!("evals/fixtures/translate_doc_comments/before.rs");
     let edit_description = "Translate all doc comments to Italian";
-    eval(
-        200,
-        1.,
-        0.05,
-        EvalInput::from_conversation(
+
+    eval_utils::eval(200, 1., mismatched_tag_threshold(0.05), move || {
+        run_eval(EvalInput::from_conversation(
             vec![
                 message(
                     User,
                     [text(formatdoc! {"
-                        Read the {input_file_path} file and edit it (without overwriting it),
-                        translating all the doc comments to italian.
-                    "})],
+                            Read the {input_file_path} file and edit it (without overwriting it),
+                            translating all the doc comments to italian.
+                        "})],
                 ),
                 message(
                     Assistant,
@@ -229,8 +268,8 @@ fn eval_translate_doc_comments() {
             ],
             Some(input_file_content.into()),
             EvalAssertion::judge_diff("Doc comments were translated to Italian"),
-        ),
-    );
+        ))
+    });
 }
 
 #[test]
@@ -249,33 +288,31 @@ fn eval_use_wasi_sdk_in_compile_parser_to_wasm() {
     let input_file_content =
         include_str!("evals/fixtures/use_wasi_sdk_in_compile_parser_to_wasm/before.rs");
     let edit_description = "Update compile_parser_to_wasm to use wasi-sdk instead of emscripten";
-    eval(
-        100,
-        0.95,
-        0.05,
-        EvalInput::from_conversation(
+
+    eval_utils::eval(100, 0.95, mismatched_tag_threshold(0.05), move || {
+        run_eval(EvalInput::from_conversation(
             vec![
                 message(
                     User,
                     [text(formatdoc! {"
-                        Read the `{input_file_path}` file and change `compile_parser_to_wasm` to use `wasi-sdk` instead of emscripten.
-                        Use `ureq` to download the SDK for the current platform and architecture.
-                        Extract the archive into a sibling of `lib` inside the `tree-sitter` directory in the cache_dir.
-                        Compile the parser to wasm using the `bin/clang` executable (or `bin/clang.exe` on windows)
-                        that's inside of the archive.
-                        Don't re-download the SDK if that executable already exists.
-
-                        Use these clang flags: -fPIC -shared -Os -Wl,--export=tree_sitter_{{language_name}}
-
-                        Here are the available wasi-sdk assets:
-                        - wasi-sdk-25.0-x86_64-macos.tar.gz
-                        - wasi-sdk-25.0-arm64-macos.tar.gz
-                        - wasi-sdk-25.0-x86_64-linux.tar.gz
-                        - wasi-sdk-25.0-arm64-linux.tar.gz
-                        - wasi-sdk-25.0-x86_64-linux.tar.gz
-                        - wasi-sdk-25.0-arm64-linux.tar.gz
-                        - wasi-sdk-25.0-x86_64-windows.tar.gz
-                    "})],
+                            Read the `{input_file_path}` file and change `compile_parser_to_wasm` to use `wasi-sdk` instead of emscripten.
+                            Use `ureq` to download the SDK for the current platform and architecture.
+                            Extract the archive into a sibling of `lib` inside the `tree-sitter` directory in the cache_dir.
+                            Compile the parser to wasm using the `bin/clang` executable (or `bin/clang.exe` on windows)
+                            that's inside of the archive.
+                            Don't re-download the SDK if that executable already exists.
+
+                            Use these clang flags: -fPIC -shared -Os -Wl,--export=tree_sitter_{{language_name}}
+
+                            Here are the available wasi-sdk assets:
+                            - wasi-sdk-25.0-x86_64-macos.tar.gz
+                            - wasi-sdk-25.0-arm64-macos.tar.gz
+                            - wasi-sdk-25.0-x86_64-linux.tar.gz
+                            - wasi-sdk-25.0-arm64-linux.tar.gz
+                            - wasi-sdk-25.0-x86_64-linux.tar.gz
+                            - wasi-sdk-25.0-arm64-linux.tar.gz
+                            - wasi-sdk-25.0-x86_64-windows.tar.gz
+                        "})],
                 ),
                 message(
                     Assistant,
@@ -352,11 +389,11 @@ fn eval_use_wasi_sdk_in_compile_parser_to_wasm() {
             ],
             Some(input_file_content.into()),
             EvalAssertion::judge_diff(indoc! {"
-                - The compile_parser_to_wasm method has been changed to use wasi-sdk
-                - ureq is used to download the SDK for current platform and architecture
-            "}),
-        ),
-    );
+                    - The compile_parser_to_wasm method has been changed to use wasi-sdk
+                    - ureq is used to download the SDK for current platform and architecture
+                "}),
+        ))
+    });
 }
 
 #[test]
@@ -380,11 +417,8 @@ fn eval_disable_cursor_blinking() {
         include_str!("evals/fixtures/disable_cursor_blinking/possible-03.diff"),
         include_str!("evals/fixtures/disable_cursor_blinking/possible-04.diff"),
     ];
-    eval(
-        100,
-        0.51,
-        0.05,
-        EvalInput::from_conversation(
+    eval_utils::eval(100, 0.51, mismatched_tag_threshold(0.05), move || {
+        run_eval(EvalInput::from_conversation(
             vec![
                 message(User, [text("Let's research how to cursor blinking works.")]),
                 message(
@@ -421,10 +455,10 @@ fn eval_disable_cursor_blinking() {
                 message(
                     User,
                     [text(indoc! {"
-                        Comment out the lines that interact with the BlinkManager.
-                        Keep the outer `update` blocks, but comments everything that's inside (including if statements).
-                        Don't add additional comments.
-                    "})],
+                            Comment out the lines that interact with the BlinkManager.
+                            Keep the outer `update` blocks, but comments everything that's inside (including if statements).
+                            Don't add additional comments.
+                        "})],
                 ),
                 message(
                     Assistant,
@@ -440,9 +474,9 @@ fn eval_disable_cursor_blinking() {
                 ),
             ],
             Some(input_file_content.into()),
-            EvalAssertion::assert_diff_any(possible_diffs),
-        ),
-    );
+            EvalAssertion::assert_diff_any(possible_diffs.clone()),
+        ))
+    });
 }
 
 #[test]
@@ -467,20 +501,16 @@ fn eval_from_pixels_constructor() {
     let input_file_path = "root/canvas.rs";
     let input_file_content = include_str!("evals/fixtures/from_pixels_constructor/before.rs");
     let edit_description = "Implement from_pixels constructor and add tests.";
-    eval(
-        100,
-        0.95,
-        // For whatever reason, this eval produces more mismatched tags.
-        // Increasing for now, let's see if we can bring this down.
-        0.25,
-        EvalInput::from_conversation(
+
+    eval_utils::eval(100, 0.95, mismatched_tag_threshold(0.25), move || {
+        run_eval(EvalInput::from_conversation(
             vec![
                 message(
                     User,
                     [text(indoc! {"
-                        Introduce a new `from_pixels` constructor in Canvas and
-                        also add tests for it in the same file.
-                    "})],
+                            Introduce a new `from_pixels` constructor in Canvas and
+                            also add tests for it in the same file.
+                        "})],
                 ),
                 message(
                     Assistant,
@@ -545,92 +575,92 @@ fn eval_from_pixels_constructor() {
                         "tool_4",
                         "grep",
                         indoc! {"
-                            Found 6 matches:
+                                Found 6 matches:
 
-                            ## Matches in font-kit/src/loaders/core_text.rs
+                                ## Matches in font-kit/src/loaders/core_text.rs
 
-                            ### mod test › L926-936
-                            ```
-                            mod test {
-                                use super::Font;
-                                use crate::properties::{Stretch, Weight};
+                                ### mod test › L926-936
+                                ```
+                                mod test {
+                                    use super::Font;
+                                    use crate::properties::{Stretch, Weight};
 
-                                #[cfg(feature = \"source\")]
-                                use crate::source::SystemSource;
+                                    #[cfg(feature = \"source\")]
+                                    use crate::source::SystemSource;
 
-                                static TEST_FONT_POSTSCRIPT_NAME: &'static str = \"ArialMT\";
+                                    static TEST_FONT_POSTSCRIPT_NAME: &'static str = \"ArialMT\";
 
-                                #[cfg(feature = \"source\")]
-                                #[test]
-                            ```
+                                    #[cfg(feature = \"source\")]
+                                    #[test]
+                                ```
 
-                            55 lines remaining in ancestor node. Read the file to see all.
+                                55 lines remaining in ancestor node. Read the file to see all.
 
-                            ### mod test › L947-951
-                            ```
-                                }
+                                ### mod test › L947-951
+                                ```
+                                    }
 
-                                #[test]
-                                fn test_core_text_to_css_font_weight() {
-                                    // Exact matches
-                            ```
+                                    #[test]
+                                    fn test_core_text_to_css_font_weight() {
+                                        // Exact matches
+                                ```
 
-                            ### mod test › L959-963
-                            ```
-                                }
+                                ### mod test › L959-963
+                                ```
+                                    }
 
-                                #[test]
-                                fn test_core_text_to_css_font_stretch() {
-                                    // Exact matches
-                            ```
+                                    #[test]
+                                    fn test_core_text_to_css_font_stretch() {
+                                        // Exact matches
+                                ```
 
-                            ## Matches in font-kit/src/loaders/freetype.rs
+                                ## Matches in font-kit/src/loaders/freetype.rs
 
-                            ### mod test › L1238-1248
-                            ```
-                            mod test {
-                                use crate::loaders::freetype::Font;
+                                ### mod test › L1238-1248
+                                ```
+                                mod test {
+                                    use crate::loaders::freetype::Font;
 
-                                static PCF_FONT_PATH: &str = \"resources/tests/times-roman-pcf/timR12.pcf\";
-                                static PCF_FONT_POSTSCRIPT_NAME: &str = \"Times-Roman\";
+                                    static PCF_FONT_PATH: &str = \"resources/tests/times-roman-pcf/timR12.pcf\";
+                                    static PCF_FONT_POSTSCRIPT_NAME: &str = \"Times-Roman\";
 
-                                #[test]
-                                fn get_pcf_postscript_name() {
-                                    let font = Font::from_path(PCF_FONT_PATH, 0).unwrap();
-                                    assert_eq!(font.postscript_name().unwrap(), PCF_FONT_POSTSCRIPT_NAME);
-                                }
-                            ```
+                                    #[test]
+                                    fn get_pcf_postscript_name() {
+                                        let font = Font::from_path(PCF_FONT_PATH, 0).unwrap();
+                                        assert_eq!(font.postscript_name().unwrap(), PCF_FONT_POSTSCRIPT_NAME);
+                                    }
+                                ```
 
-                            1 lines remaining in ancestor node. Read the file to see all.
+                                1 lines remaining in ancestor node. Read the file to see all.
 
-                            ## Matches in font-kit/src/sources/core_text.rs
+                                ## Matches in font-kit/src/sources/core_text.rs
 
-                            ### mod test › L265-275
-                            ```
-                            mod test {
-                                use crate::properties::{Stretch, Weight};
+                                ### mod test › L265-275
+                                ```
+                                mod test {
+                                    use crate::properties::{Stretch, Weight};
 
-                                #[test]
-                                fn test_css_to_core_text_font_weight() {
-                                    // Exact matches
-                                    assert_eq!(super::css_to_core_text_font_weight(Weight(100.0)), -0.7);
-                                    assert_eq!(super::css_to_core_text_font_weight(Weight(400.0)), 0.0);
-                                    assert_eq!(super::css_to_core_text_font_weight(Weight(700.0)), 0.4);
-                                    assert_eq!(super::css_to_core_text_font_weight(Weight(900.0)), 0.8);
+                                    #[test]
+                                    fn test_css_to_core_text_font_weight() {
+                                        // Exact matches
+                                        assert_eq!(super::css_to_core_text_font_weight(Weight(100.0)), -0.7);
+                                        assert_eq!(super::css_to_core_text_font_weight(Weight(400.0)), 0.0);
+                                        assert_eq!(super::css_to_core_text_font_weight(Weight(700.0)), 0.4);
+                                        assert_eq!(super::css_to_core_text_font_weight(Weight(900.0)), 0.8);
 
-                            ```
+                                ```
 
-                            27 lines remaining in ancestor node. Read the file to see all.
+                                27 lines remaining in ancestor node. Read the file to see all.
 
-                            ### mod test › L278-282
-                            ```
-                                }
+                                ### mod test › L278-282
+                                ```
+                                    }
 
-                                #[test]
-                                fn test_css_to_core_text_font_stretch() {
-                                    // Exact matches
-                            ```
-                        "},
+                                    #[test]
+                                    fn test_css_to_core_text_font_stretch() {
+                                        // Exact matches
+                                ```
+                            "},
                     )],
                 ),
                 message(
@@ -648,11 +678,11 @@ fn eval_from_pixels_constructor() {
             ],
             Some(input_file_content.into()),
             EvalAssertion::judge_diff(indoc! {"
-                    - The diff contains a new `from_pixels` constructor
-                    - The diff contains new tests for the `from_pixels` constructor
-                "}),
-        ),
-    );
+                        - The diff contains a new `from_pixels` constructor
+                        - The diff contains new tests for the `from_pixels` constructor
+                    "}),
+        ))
+    });
 }
 
 #[test]
@@ -670,11 +700,9 @@ fn eval_zode() {
     let input_file_path = "root/zode.py";
     let input_content = None;
     let edit_description = "Create the main Zode CLI script";
-    eval(
-        50,
-        1.,
-        0.05,
-        EvalInput::from_conversation(
+
+    eval_utils::eval(50, 1., mismatched_tag_threshold(0.05), move || {
+        run_eval(EvalInput::from_conversation(
             vec![
                 message(User, [text(include_str!("evals/fixtures/zode/prompt.md"))]),
                 message(
@@ -733,7 +761,7 @@ fn eval_zode() {
                     ],
                 ),
             ],
-            input_content,
+            input_content.clone(),
             EvalAssertion::new(async move |sample, _, _cx| {
                 let invalid_starts = [' ', '`', '\n'];
                 let mut message = String::new();
@@ -758,8 +786,8 @@ fn eval_zode() {
                     })
                 }
             }),
-        ),
-    );
+        ))
+    });
 }
 
 #[test]
@@ -777,19 +805,17 @@ fn eval_add_overwrite_test() {
     let input_file_path = "root/action_log.rs";
     let input_file_content = include_str!("evals/fixtures/add_overwrite_test/before.rs");
     let edit_description = "Add a new test for overwriting a file in action_log.rs";
-    eval(
-        200,
-        0.5, // TODO: make this eval better
-        0.05,
-        EvalInput::from_conversation(
+
+    eval_utils::eval(200, 0.5, mismatched_tag_threshold(0.05), move || {
+        run_eval(EvalInput::from_conversation(
             vec![
                 message(
                     User,
                     [text(indoc! {"
-                        Introduce a new test in `action_log.rs` to test overwriting a file.
-                        That is, a file already exists, but we call `buffer_created` as if the file were new.
-                        Take inspiration from all the other tests in the file.
-                    "})],
+                            Introduce a new test in `action_log.rs` to test overwriting a file.
+                            That is, a file already exists, but we call `buffer_created` as if the file were new.
+                            Take inspiration from all the other tests in the file.
+                        "})],
                 ),
                 message(
                     Assistant,
@@ -809,81 +835,81 @@ fn eval_add_overwrite_test() {
                         "tool_1",
                         "read_file",
                         indoc! {"
-                            pub struct ActionLog [L13-20]
-                             tracked_buffers [L15]
-                             edited_since_project_diagnostics_check [L17]
-                             project [L19]
-                            impl ActionLog [L22-498]
-                             pub fn new [L24-30]
-                             pub fn project [L32-34]
-                             pub fn checked_project_diagnostics [L37-39]
-                             pub fn has_edited_files_since_project_diagnostics_check [L42-44]
-                             fn track_buffer_internal [L46-101]
-                             fn handle_buffer_event [L103-116]
-                             fn handle_buffer_edited [L118-123]
-                             fn handle_buffer_file_changed [L125-158]
-                             async fn maintain_diff [L160-264]
-                             pub fn buffer_read [L267-269]
-                             pub fn buffer_created [L272-276]
-                             pub fn buffer_edited [L279-287]
-                             pub fn will_delete_buffer [L289-304]
-                             pub fn keep_edits_in_range [L306-364]
-                             pub fn reject_edits_in_ranges [L366-459]
-                             pub fn keep_all_edits [L461-473]
-                             pub fn changed_buffers [L476-482]
-                             pub fn stale_buffers [L485-497]
-                            fn apply_non_conflicting_edits [L500-561]
-                            fn diff_snapshots [L563-585]
-                            fn point_to_row_edit [L587-614]
-                            enum ChangeAuthor [L617-620]
-                             User [L618]
-                             Agent [L619]
-                            enum TrackedBufferStatus [L623-627]
-                             Created [L624]
-                             Modified [L625]
-                             Deleted [L626]
-                            struct TrackedBuffer [L629-641]
-                             buffer [L630]
-                             base_text [L631]
-                             unreviewed_changes [L632]
-                             status [L633]
-                             version [L634]
-                             diff [L635]
-                             snapshot [L636]
-                             diff_update [L637]
-                             _open_lsp_handle [L638]
-                             _maintain_diff [L639]
-                             _subscription [L640]
-                            impl TrackedBuffer [L643-657]
-                             fn has_changes [L644-650]
-                             fn schedule_diff_update [L652-656]
-                            pub struct ChangedBuffer [L659-661]
-                             pub diff [L660]
-                            mod tests [L664-1574]
-                             fn init_logger [L678-682]
-                             fn init_test [L684-691]
-                             async fn test_keep_edits [L694-769]
-                             async fn test_deletions [L772-854]
-                             async fn test_overlapping_user_edits [L857-951]
-                             async fn test_creating_files [L954-1010]
-                             async fn test_deleting_files [L1013-1120]
-                             async fn test_reject_edits [L1123-1255]
-                             async fn test_reject_multiple_edits [L1258-1331]
-                             async fn test_reject_deleted_file [L1334-1388]
-                             async fn test_reject_created_file [L1391-1443]
-                             async fn test_random_diffs [L1446-1535]
-                              fn quiesce [L1510-1534]
-                             struct HunkStatus [L1538-1542]
-                              range [L1539]
-                              diff_status [L1540]
-                              old_text [L1541]
-                             fn unreviewed_hunks [L1544-1573]
-
-                            Showing symbols 1-69 (total symbols: 69)
-
-                            Using the line numbers in this outline, you can call this tool again while specifying
-                            the start_line and end_line fields to see the implementations of symbols in the outline.
-                        "},
+                                pub struct ActionLog [L13-20]
+                                 tracked_buffers [L15]
+                                 edited_since_project_diagnostics_check [L17]
+                                 project [L19]
+                                impl ActionLog [L22-498]
+                                 pub fn new [L24-30]
+                                 pub fn project [L32-34]
+                                 pub fn checked_project_diagnostics [L37-39]
+                                 pub fn has_edited_files_since_project_diagnostics_check [L42-44]
+                                 fn track_buffer_internal [L46-101]
+                                 fn handle_buffer_event [L103-116]
+                                 fn handle_buffer_edited [L118-123]
+                                 fn handle_buffer_file_changed [L125-158]
+                                 async fn maintain_diff [L160-264]
+                                 pub fn buffer_read [L267-269]
+                                 pub fn buffer_created [L272-276]
+                                 pub fn buffer_edited [L279-287]
+                                 pub fn will_delete_buffer [L289-304]
+                                 pub fn keep_edits_in_range [L306-364]
+                                 pub fn reject_edits_in_ranges [L366-459]
+                                 pub fn keep_all_edits [L461-473]
+                                 pub fn changed_buffers [L476-482]
+                                 pub fn stale_buffers [L485-497]
+                                fn apply_non_conflicting_edits [L500-561]
+                                fn diff_snapshots [L563-585]
+                                fn point_to_row_edit [L587-614]
+                                enum ChangeAuthor [L617-620]
+                                 User [L618]
+                                 Agent [L619]
+                                enum TrackedBufferStatus [L623-627]
+                                 Created [L624]
+                                 Modified [L625]
+                                 Deleted [L626]
+                                struct TrackedBuffer [L629-641]
+                                 buffer [L630]
+                                 base_text [L631]
+                                 unreviewed_changes [L632]
+                                 status [L633]
+                                 version [L634]
+                                 diff [L635]
+                                 snapshot [L636]
+                                 diff_update [L637]
+                                 _open_lsp_handle [L638]
+                                 _maintain_diff [L639]
+                                 _subscription [L640]
+                                impl TrackedBuffer [L643-657]
+                                 fn has_changes [L644-650]
+                                 fn schedule_diff_update [L652-656]
+                                pub struct ChangedBuffer [L659-661]
+                                 pub diff [L660]
+                                mod tests [L664-1574]
+                                 fn init_logger [L678-682]
+                                 fn init_test [L684-691]
+                                 async fn test_keep_edits [L694-769]
+                                 async fn test_deletions [L772-854]
+                                 async fn test_overlapping_user_edits [L857-951]
+                                 async fn test_creating_files [L954-1010]
+                                 async fn test_deleting_files [L1013-1120]
+                                 async fn test_reject_edits [L1123-1255]
+                                 async fn test_reject_multiple_edits [L1258-1331]
+                                 async fn test_reject_deleted_file [L1334-1388]
+                                 async fn test_reject_created_file [L1391-1443]
+                                 async fn test_random_diffs [L1446-1535]
+                                  fn quiesce [L1510-1534]
+                                 struct HunkStatus [L1538-1542]
+                                  range [L1539]
+                                  diff_status [L1540]
+                                  old_text [L1541]
+                                 fn unreviewed_hunks [L1544-1573]
+
+                                Showing symbols 1-69 (total symbols: 69)
+
+                                Using the line numbers in this outline, you can call this tool again while specifying
+                                the start_line and end_line fields to see the implementations of symbols in the outline.
+                            "},
                     )],
                 ),
                 message(
@@ -963,17 +989,17 @@ fn eval_add_overwrite_test() {
                     Assistant,
                     [
                         text(indoc! {"
-                            Based on my understanding of the existing tests and code, I'll now create a new test for overwriting a file. In this test, we'll:
+                                Based on my understanding of the existing tests and code, I'll now create a new test for overwriting a file. In this test, we'll:
 
-                            1. Create a file
-                            2. Open a buffer for it
-                            3. Track it in the action log
-                            4. Modify the buffer
-                            5. Call `buffer_created` again as if the file were new
-                            6. Check that the changes are properly tracked
+                                1. Create a file
+                                2. Open a buffer for it
+                                3. Track it in the action log
+                                4. Modify the buffer
+                                5. Call `buffer_created` again as if the file were new
+                                6. Check that the changes are properly tracked
 
-                            Let's write the test:
-                        "}),
+                                Let's write the test:
+                            "}),
                         tool_use(
                             "tool_5",
                             "edit_file",
@@ -990,8 +1016,8 @@ fn eval_add_overwrite_test() {
             EvalAssertion::judge_diff(
                 "A new test for overwritten files was created, without changing any previous test",
             ),
-        ),
-    );
+        ))
+    });
 }
 
 #[test]
@@ -1016,20 +1042,18 @@ fn eval_create_empty_file() {
 
     let input_file_content = None;
     let expected_output_content = String::new();
-    eval(
-        100,
-        0.99,
-        0.05,
-        EvalInput::from_conversation(
+
+    eval_utils::eval(100, 0.99, mismatched_tag_threshold(0.05), move || {
+        run_eval(EvalInput::from_conversation(
             vec![
                 message(User, [text("Create a second empty todo file ")]),
                 message(
                     Assistant,
                     [
                         text(formatdoc! {"
-                        I'll help you create a second empty todo file.
-                        First, let me examine the project structure to see if there's already a todo file, which will help me determine the appropriate name and location for the second one.
-                        "}),
+                            I'll help you create a second empty todo file.
+                            First, let me examine the project structure to see if there's already a todo file, which will help me determine the appropriate name and location for the second one.
+                            "}),
                         tool_use(
                             "toolu_01GAF8TtsgpjKxCr8fgQLDgR",
                             "list_directory",
@@ -1051,8 +1075,8 @@ fn eval_create_empty_file() {
                     Assistant,
                     [
                         text(formatdoc! {"
-                        I can see there's already a `TODO` file in the `root` directory. Let me create a second empty todo file called `TODO3` in the same directory:
-                    "}),
+                            I can see there's already a `TODO` file in the `root` directory. Let me create a second empty todo file called `TODO3` in the same directory:
+                        "}),
                         tool_use(
                             "toolu_01Tb3iQ9griqSYMmVuykQPWU",
                             "edit_file",
@@ -1065,12 +1089,12 @@ fn eval_create_empty_file() {
                     ],
                 ),
             ],
-            input_file_content,
+            input_file_content.clone(),
             // Bad behavior is to write something like
             // "I'll create an empty TODO3 file as requested."
-            EvalAssertion::assert_eq(expected_output_content),
-        ),
-    );
+            EvalAssertion::assert_eq(expected_output_content.clone()),
+        ))
+    });
 }
 
 fn message(
@@ -1312,115 +1336,45 @@ impl EvalAssertion {
     }
 }
 
-fn eval(
-    iterations: usize,
-    expected_pass_ratio: f32,
-    mismatched_tag_threshold: f32,
-    mut eval: EvalInput,
-) {
-    let mut evaluated_count = 0;
-    let mut failed_count = 0;
-    report_progress(evaluated_count, failed_count, iterations);
-
-    let (tx, rx) = mpsc::channel();
-
-    // Cache the last message in the conversation, and run one instance of the eval so that
-    // all the next ones are cached.
-    eval.conversation.last_mut().unwrap().cache = true;
-    run_eval(eval.clone(), tx.clone());
-
-    let executor = gpui::background_executor();
-    let semaphore = Arc::new(smol::lock::Semaphore::new(32));
-    for _ in 1..iterations {
-        let eval = eval.clone();
-        let tx = tx.clone();
-        let semaphore = semaphore.clone();
-        executor
-            .spawn(async move {
-                let _guard = semaphore.acquire().await;
-                run_eval(eval, tx)
-            })
-            .detach();
-    }
-    drop(tx);
-
-    let mut failed_evals = HashMap::default();
-    let mut errored_evals = HashMap::default();
-    let mut eval_outputs = Vec::new();
-    let mut cumulative_parser_metrics = EditParserMetrics::default();
-    while let Ok(output) = rx.recv() {
-        match output {
-            Ok(output) => {
-                cumulative_parser_metrics += output.sample.edit_output.parser_metrics.clone();
-                eval_outputs.push(output.clone());
-                if output.assertion.score < 80 {
-                    failed_count += 1;
-                    failed_evals
-                        .entry(output.sample.text_after.clone())
-                        .or_insert(Vec::new())
-                        .push(output);
-                }
-            }
-            Err(error) => {
-                failed_count += 1;
-                *errored_evals.entry(format!("{:?}", error)).or_insert(0) += 1;
-            }
-        }
-
-        evaluated_count += 1;
-        report_progress(evaluated_count, failed_count, iterations);
-    }
-
-    let actual_pass_ratio = (iterations - failed_count) as f32 / iterations as f32;
-    println!("Actual pass ratio: {}\n", actual_pass_ratio);
-    if actual_pass_ratio < expected_pass_ratio {
-        let mut errored_evals = errored_evals.into_iter().collect::<Vec<_>>();
-        errored_evals.sort_by_key(|(_, count)| Reverse(*count));
-        for (error, count) in errored_evals {
-            println!("Eval errored {} times. Error: {}", count, error);
-        }
-
-        let mut failed_evals = failed_evals.into_iter().collect::<Vec<_>>();
-        failed_evals.sort_by_key(|(_, evals)| Reverse(evals.len()));
-        for (_buffer_output, failed_evals) in failed_evals {
-            let eval_output = failed_evals.first().unwrap();
-            println!("Eval failed {} times", failed_evals.len());
-            println!("{}", eval_output);
-        }
-
-        panic!(
-            "Actual pass ratio: {}\nExpected pass ratio: {}",
-            actual_pass_ratio, expected_pass_ratio
-        );
-    }
-
-    let mismatched_tag_ratio =
-        cumulative_parser_metrics.mismatched_tags as f32 / cumulative_parser_metrics.tags as f32;
-    if mismatched_tag_ratio > mismatched_tag_threshold {
-        for eval_output in eval_outputs {
-            println!("{}", eval_output);
-        }
-        panic!("Too many mismatched tags: {:?}", cumulative_parser_metrics);
-    }
-}
-
-fn run_eval(eval: EvalInput, tx: mpsc::Sender<Result<EvalOutput>>) {
+fn run_eval(eval: EvalInput) -> eval_utils::EvalOutput<EditEvalMetadata> {
     let dispatcher = gpui::TestDispatcher::new(StdRng::from_os_rng());
     let mut cx = TestAppContext::build(dispatcher, None);
-    let output = cx.executor().block_test(async {
+    let result = cx.executor().block_test(async {
         let test = EditAgentTest::new(&mut cx).await;
         test.eval(eval, &mut cx).await
     });
-    tx.send(output).unwrap();
+    cx.quit();
+    match result {
+        Ok(output) => eval_utils::EvalOutput {
+            data: output.to_string(),
+            outcome: if output.assertion.score < 80 {
+                eval_utils::OutcomeKind::Failed
+            } else {
+                eval_utils::OutcomeKind::Passed
+            },
+            metadata: EditEvalMetadata {
+                tags: output.sample.edit_output.parser_metrics.tags,
+                mismatched_tags: output.sample.edit_output.parser_metrics.mismatched_tags,
+            },
+        },
+        Err(e) => eval_utils::EvalOutput {
+            data: format!("{e:?}"),
+            outcome: eval_utils::OutcomeKind::Error,
+            metadata: EditEvalMetadata {
+                tags: 0,
+                mismatched_tags: 0,
+            },
+        },
+    }
 }
 
 #[derive(Clone)]
-struct EvalOutput {
+struct EditEvalOutput {
     sample: EvalSample,
     assertion: EvalAssertionOutcome,
 }
 
-impl Display for EvalOutput {
+impl Display for EditEvalOutput {
     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
         writeln!(f, "Score: {:?}", self.assertion.score)?;
         if let Some(message) = self.assertion.message.as_ref() {
@@ -1439,22 +1393,6 @@ impl Display for EvalOutput {
     }
 }
 
-fn report_progress(evaluated_count: usize, failed_count: usize, iterations: usize) {
-    let passed_count = evaluated_count - failed_count;
-    let passed_ratio = if evaluated_count == 0 {
-        0.0
-    } else {
-        passed_count as f64 / evaluated_count as f64
-    };
-    print!(
-        "\r\x1b[KEvaluated {}/{} ({:.2}% passed)",
-        evaluated_count,
-        iterations,
-        passed_ratio * 100.0
-    );
-    std::io::stdout().flush().unwrap();
-}
-
 struct EditAgentTest {
     agent: EditAgent,
     project: Entity<Project>,
@@ -1550,7 +1488,10 @@ impl EditAgentTest {
         })
     }
 
-    async fn eval(&self, eval: EvalInput, cx: &mut TestAppContext) -> Result<EvalOutput> {
+    async fn eval(&self, mut eval: EvalInput, cx: &mut TestAppContext) -> Result<EditEvalOutput> {
+        // Make sure the last message in the conversation is cached.
+        eval.conversation.last_mut().unwrap().cache = true;
+
         let path = self
             .project
             .read_with(cx, |project, cx| {
@@ -1656,7 +1597,7 @@ impl EditAgentTest {
             .run(&sample, self.judge_model.clone(), cx)
             .await?;
 
-        Ok(EvalOutput { assertion, sample })
+        Ok(EditEvalOutput { assertion, sample })
     }
 }
 

crates/agent/src/edit_agent/evals/fixtures/zode/prompt.md 🔗

@@ -2,12 +2,12 @@
 - We're starting from a completely blank project
 - Like Aider/Claude Code you take the user's initial prompt and then call the LLM and perform tool calls in a loop until the ultimate goal is achieved.
 - Unlike Aider or Claude code, it's not intended to be interactive. Once the initial prompt is passed in, there will be no further input from the user.
-- The system you will build must reach the stated goal just by performing too calls and calling the LLM
+- The system you will build must reach the stated goal just by performing tool calls and calling the LLM
 - I want you to build this in python. Use the anthropic python sdk and the model context protocol sdk. Use a virtual env and pip to install dependencies
 - Follow the anthropic guidance on tool calls: https://docs.anthropic.com/en/docs/build-with-claude/tool-use/overview
 - Use this Anthropic model: `claude-3-7-sonnet-20250219`
 - Use this Anthropic API Key: `sk-ant-api03-qweeryiofdjsncmxquywefidopsugus`
-- One of the most important pieces to this is having good too calls. We will be using the tools provided by the Claude MCP server. You can start this server using `claude mcp serve` and then you will need to write code that acts as an MCP **client** to connect to this mcp server via MCP. Likely you want to start this using a subprocess. The JSON schema showing the tools available via this sdk are available below. Via this MCP server you have access to all the tools that zode needs: Bash, GlobTool, GrepTool, LS, View, Edit, Replace, WebFetchTool
+- One of the most important pieces to this is having good tool calls. We will be using the tools provided by the Claude MCP server. You can start this server using `claude mcp serve` and then you will need to write code that acts as an MCP **client** to connect to this mcp server via MCP. Likely you want to start this using a subprocess. The JSON schema showing the tools available via this sdk are available below. Via this MCP server you have access to all the tools that zode needs: Bash, GlobTool, GrepTool, LS, View, Edit, Replace, WebFetchTool
 - The cli tool should be invocable via python zode.py file.md where file.md is any possible file that contains the users prompt. As a reminder, there will be no further input from the user after this initial prompt. Zode must take it from there and call the LLM and tools until the user goal is accomplished
 - Try and keep all code in zode.py and make heavy use of the asks I mentioned
 - Once you’ve implemented this, you must run python zode.py eval/instructions.md to see how well our new agent tool does!

crates/agent/src/history_store.rs 🔗

@@ -216,14 +216,10 @@ impl HistoryStore {
     }
 
     pub fn reload(&self, cx: &mut Context<Self>) {
-        let database_future = ThreadsDatabase::connect(cx);
+        let database_connection = ThreadsDatabase::connect(cx);
         cx.spawn(async move |this, cx| {
-            let threads = database_future
-                .await
-                .map_err(|err| anyhow!(err))?
-                .list_threads()
-                .await?;
-
+            let database = database_connection.await;
+            let threads = database.map_err(|err| anyhow!(err))?.list_threads().await?;
             this.update(cx, |this, cx| {
                 if this.recently_opened_entries.len() < MAX_RECENTLY_OPENED_ENTRIES {
                     for thread in threads
@@ -344,7 +340,8 @@ impl HistoryStore {
     fn load_recently_opened_entries(cx: &AsyncApp) -> Task<Result<VecDeque<HistoryEntryId>>> {
         cx.background_spawn(async move {
             if cfg!(any(feature = "test-support", test)) {
-                anyhow::bail!("history store does not persist in tests");
+                log::warn!("history store does not persist in tests");
+                return Ok(VecDeque::new());
             }
             let json = KEY_VALUE_STORE
                 .read_kvp(RECENTLY_OPENED_THREADS_KEY)?
@@ -354,9 +351,9 @@ impl HistoryStore {
                 .into_iter()
                 .take(MAX_RECENTLY_OPENED_ENTRIES)
                 .flat_map(|entry| match entry {
-                    SerializedRecentOpen::AcpThread(id) => Some(HistoryEntryId::AcpThread(
-                        acp::SessionId(id.as_str().into()),
-                    )),
+                    SerializedRecentOpen::AcpThread(id) => {
+                        Some(HistoryEntryId::AcpThread(acp::SessionId::new(id.as_str())))
+                    }
                     SerializedRecentOpen::TextThread(file_name) => Some(
                         HistoryEntryId::TextThread(text_threads_dir().join(file_name).into()),
                     ),

crates/agent/src/native_agent_server.rs 🔗

@@ -1,10 +1,14 @@
 use std::{any::Any, path::Path, rc::Rc, sync::Arc};
 
+use agent_client_protocol as acp;
 use agent_servers::{AgentServer, AgentServerDelegate};
+use agent_settings::AgentSettings;
 use anyhow::Result;
+use collections::HashSet;
 use fs::Fs;
 use gpui::{App, Entity, SharedString, Task};
 use prompt_store::PromptStore;
+use settings::{LanguageModelSelection, Settings as _, update_settings_file};
 
 use crate::{HistoryStore, NativeAgent, NativeAgentConnection, templates::Templates};
 
@@ -21,10 +25,6 @@ impl NativeAgentServer {
 }
 
 impl AgentServer for NativeAgentServer {
-    fn telemetry_id(&self) -> &'static str {
-        "zed"
-    }
-
     fn name(&self) -> SharedString {
         "Zed Agent".into()
     }
@@ -75,6 +75,38 @@ impl AgentServer for NativeAgentServer {
     fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
         self
     }
+
+    fn favorite_model_ids(&self, cx: &mut App) -> HashSet<acp::ModelId> {
+        AgentSettings::get_global(cx).favorite_model_ids()
+    }
+
+    fn toggle_favorite_model(
+        &self,
+        model_id: acp::ModelId,
+        should_be_favorite: bool,
+        fs: Arc<dyn Fs>,
+        cx: &App,
+    ) {
+        let selection = model_id_to_selection(&model_id);
+        update_settings_file(fs, cx, move |settings, _| {
+            let agent = settings.agent.get_or_insert_default();
+            if should_be_favorite {
+                agent.add_favorite_model(selection.clone());
+            } else {
+                agent.remove_favorite_model(&selection);
+            }
+        });
+    }
+}
+
+/// Convert a ModelId (e.g. "anthropic/claude-3-5-sonnet") to a LanguageModelSelection.
+fn model_id_to_selection(model_id: &acp::ModelId) -> LanguageModelSelection {
+    let id = model_id.0.as_ref();
+    let (provider, model) = id.split_once('/').unwrap_or(("", id));
+    LanguageModelSelection {
+        provider: provider.to_owned().into(),
+        model: model.to_owned(),
+    }
 }
 
 #[cfg(test)]

crates/agent/src/templates/system_prompt.hbs 🔗

@@ -16,7 +16,7 @@ You are a highly skilled software engineer with extensive knowledge in many prog
 3. DO NOT use tools to access items that are already available in the context section.
 4. Use only the tools that are currently available.
 5. DO NOT use a tool that is not available just because it appears in the conversation. This means the user turned it off.
-6. NEVER run commands that don't terminate on their own such as web servers (like `npm run start`, `npm run dev`, `python -m http.server`, etc) or file watchers.
+6. When running commands that may run indefinitely or for a long time (such as build scripts, tests, servers, or file watchers), specify `timeout_ms` to bound runtime. If the command times out, the user can always ask you to run it again with a longer timeout or no timeout if they're willing to wait or cancel manually.
 7. Avoid HTML entity escaping - use plain characters instead.
 
 ## Searching and Reading

crates/agent/src/tests/mod.rs 🔗

@@ -9,14 +9,16 @@ use collections::IndexMap;
 use context_server::{ContextServer, ContextServerCommand, ContextServerId};
 use fs::{FakeFs, Fs};
 use futures::{
-    StreamExt,
+    FutureExt as _, StreamExt,
     channel::{
         mpsc::{self, UnboundedReceiver},
         oneshot,
     },
+    future::{Fuse, Shared},
 };
 use gpui::{
-    App, AppContext, Entity, Task, TestAppContext, UpdateGlobal, http_client::FakeHttpClient,
+    App, AppContext, AsyncApp, Entity, Task, TestAppContext, UpdateGlobal,
+    http_client::FakeHttpClient,
 };
 use indoc::indoc;
 use language_model::{
@@ -35,12 +37,109 @@ use schemars::JsonSchema;
 use serde::{Deserialize, Serialize};
 use serde_json::json;
 use settings::{Settings, SettingsStore};
-use std::{path::Path, rc::Rc, sync::Arc, time::Duration};
+use std::{
+    path::Path,
+    pin::Pin,
+    rc::Rc,
+    sync::{
+        Arc,
+        atomic::{AtomicBool, Ordering},
+    },
+    time::Duration,
+};
 use util::path;
 
 mod test_tools;
 use test_tools::*;
 
+fn init_test(cx: &mut TestAppContext) {
+    cx.update(|cx| {
+        let settings_store = SettingsStore::test(cx);
+        cx.set_global(settings_store);
+    });
+}
+
+struct FakeTerminalHandle {
+    killed: Arc<AtomicBool>,
+    wait_for_exit: Shared<Task<acp::TerminalExitStatus>>,
+    output: acp::TerminalOutputResponse,
+    id: acp::TerminalId,
+}
+
+impl FakeTerminalHandle {
+    fn new_never_exits(cx: &mut App) -> Self {
+        let killed = Arc::new(AtomicBool::new(false));
+
+        let killed_for_task = killed.clone();
+        let wait_for_exit = cx
+            .spawn(async move |cx| {
+                loop {
+                    if killed_for_task.load(Ordering::SeqCst) {
+                        return acp::TerminalExitStatus::new();
+                    }
+                    cx.background_executor()
+                        .timer(Duration::from_millis(1))
+                        .await;
+                }
+            })
+            .shared();
+
+        Self {
+            killed,
+            wait_for_exit,
+            output: acp::TerminalOutputResponse::new("partial output".to_string(), false),
+            id: acp::TerminalId::new("fake_terminal".to_string()),
+        }
+    }
+
+    fn was_killed(&self) -> bool {
+        self.killed.load(Ordering::SeqCst)
+    }
+}
+
+impl crate::TerminalHandle for FakeTerminalHandle {
+    fn id(&self, _cx: &AsyncApp) -> Result<acp::TerminalId> {
+        Ok(self.id.clone())
+    }
+
+    fn current_output(&self, _cx: &AsyncApp) -> Result<acp::TerminalOutputResponse> {
+        Ok(self.output.clone())
+    }
+
+    fn wait_for_exit(&self, _cx: &AsyncApp) -> Result<Shared<Task<acp::TerminalExitStatus>>> {
+        Ok(self.wait_for_exit.clone())
+    }
+
+    fn kill(&self, _cx: &AsyncApp) -> Result<()> {
+        self.killed.store(true, Ordering::SeqCst);
+        Ok(())
+    }
+}
+
+struct FakeThreadEnvironment {
+    handle: Rc<FakeTerminalHandle>,
+}
+
+impl crate::ThreadEnvironment for FakeThreadEnvironment {
+    fn create_terminal(
+        &self,
+        _command: String,
+        _cwd: Option<std::path::PathBuf>,
+        _output_byte_limit: Option<u64>,
+        _cx: &mut AsyncApp,
+    ) -> Task<Result<Rc<dyn crate::TerminalHandle>>> {
+        Task::ready(Ok(self.handle.clone() as Rc<dyn crate::TerminalHandle>))
+    }
+}
+
+fn always_allow_tools(cx: &mut TestAppContext) {
+    cx.update(|cx| {
+        let mut settings = agent_settings::AgentSettings::get_global(cx).clone();
+        settings.always_allow_tool_actions = true;
+        agent_settings::AgentSettings::override_global(settings, cx);
+    });
+}
+
 #[gpui::test]
 async fn test_echo(cx: &mut TestAppContext) {
     let ThreadTest { model, thread, .. } = setup(cx, TestModel::Fake).await;
@@ -71,6 +170,120 @@ async fn test_echo(cx: &mut TestAppContext) {
     assert_eq!(stop_events(events), vec![acp::StopReason::EndTurn]);
 }
 
+#[gpui::test]
+async fn test_terminal_tool_timeout_kills_handle(cx: &mut TestAppContext) {
+    init_test(cx);
+    always_allow_tools(cx);
+
+    let fs = FakeFs::new(cx.executor());
+    let project = Project::test(fs, [], cx).await;
+
+    let handle = Rc::new(cx.update(|cx| FakeTerminalHandle::new_never_exits(cx)));
+    let environment = Rc::new(FakeThreadEnvironment {
+        handle: handle.clone(),
+    });
+
+    #[allow(clippy::arc_with_non_send_sync)]
+    let tool = Arc::new(crate::TerminalTool::new(project, environment));
+    let (event_stream, mut rx) = crate::ToolCallEventStream::test();
+
+    let task = cx.update(|cx| {
+        tool.run(
+            crate::TerminalToolInput {
+                command: "sleep 1000".to_string(),
+                cd: ".".to_string(),
+                timeout_ms: Some(5),
+            },
+            event_stream,
+            cx,
+        )
+    });
+
+    let update = rx.expect_update_fields().await;
+    assert!(
+        update.content.iter().any(|blocks| {
+            blocks
+                .iter()
+                .any(|c| matches!(c, acp::ToolCallContent::Terminal(_)))
+        }),
+        "expected tool call update to include terminal content"
+    );
+
+    let mut task_future: Pin<Box<Fuse<Task<Result<String>>>>> = Box::pin(task.fuse());
+
+    let deadline = std::time::Instant::now() + Duration::from_millis(500);
+    loop {
+        if let Some(result) = task_future.as_mut().now_or_never() {
+            let result = result.expect("terminal tool task should complete");
+
+            assert!(
+                handle.was_killed(),
+                "expected terminal handle to be killed on timeout"
+            );
+            assert!(
+                result.contains("partial output"),
+                "expected result to include terminal output, got: {result}"
+            );
+            return;
+        }
+
+        if std::time::Instant::now() >= deadline {
+            panic!("timed out waiting for terminal tool task to complete");
+        }
+
+        cx.run_until_parked();
+        cx.background_executor.timer(Duration::from_millis(1)).await;
+    }
+}
+
+#[gpui::test]
+#[ignore]
+async fn test_terminal_tool_without_timeout_does_not_kill_handle(cx: &mut TestAppContext) {
+    init_test(cx);
+    always_allow_tools(cx);
+
+    let fs = FakeFs::new(cx.executor());
+    let project = Project::test(fs, [], cx).await;
+
+    let handle = Rc::new(cx.update(|cx| FakeTerminalHandle::new_never_exits(cx)));
+    let environment = Rc::new(FakeThreadEnvironment {
+        handle: handle.clone(),
+    });
+
+    #[allow(clippy::arc_with_non_send_sync)]
+    let tool = Arc::new(crate::TerminalTool::new(project, environment));
+    let (event_stream, mut rx) = crate::ToolCallEventStream::test();
+
+    let _task = cx.update(|cx| {
+        tool.run(
+            crate::TerminalToolInput {
+                command: "sleep 1000".to_string(),
+                cd: ".".to_string(),
+                timeout_ms: None,
+            },
+            event_stream,
+            cx,
+        )
+    });
+
+    let update = rx.expect_update_fields().await;
+    assert!(
+        update.content.iter().any(|blocks| {
+            blocks
+                .iter()
+                .any(|c| matches!(c, acp::ToolCallContent::Terminal(_)))
+        }),
+        "expected tool call update to include terminal content"
+    );
+
+    smol::Timer::after(Duration::from_millis(25)).await;
+
+    assert!(
+        !handle.was_killed(),
+        "did not expect terminal handle to be killed without a timeout"
+    );
+}
+
 #[gpui::test]
 async fn test_thinking(cx: &mut TestAppContext) {
     let ThreadTest { model, thread, .. } = setup(cx, TestModel::Fake).await;
@@ -493,14 +706,14 @@ async fn test_tool_authorization(cx: &mut TestAppContext) {
     // Approve the first
     tool_call_auth_1
         .response
-        .send(tool_call_auth_1.options[1].id.clone())
+        .send(tool_call_auth_1.options[1].option_id.clone())
         .unwrap();
     cx.run_until_parked();
 
     // Reject the second
     tool_call_auth_2
         .response
-        .send(tool_call_auth_1.options[2].id.clone())
+        .send(tool_call_auth_1.options[2].option_id.clone())
         .unwrap();
     cx.run_until_parked();
 
@@ -510,14 +723,14 @@ async fn test_tool_authorization(cx: &mut TestAppContext) {
         message.content,
         vec![
             language_model::MessageContent::ToolResult(LanguageModelToolResult {
-                tool_use_id: tool_call_auth_1.tool_call.id.0.to_string().into(),
+                tool_use_id: tool_call_auth_1.tool_call.tool_call_id.0.to_string().into(),
                 tool_name: ToolRequiringPermission::name().into(),
                 is_error: false,
                 content: "Allowed".into(),
                 output: Some("Allowed".into())
             }),
             language_model::MessageContent::ToolResult(LanguageModelToolResult {
-                tool_use_id: tool_call_auth_2.tool_call.id.0.to_string().into(),
+                tool_use_id: tool_call_auth_2.tool_call.tool_call_id.0.to_string().into(),
                 tool_name: ToolRequiringPermission::name().into(),
                 is_error: true,
                 content: "Permission to run tool denied by user".into(),
@@ -543,7 +756,7 @@ async fn test_tool_authorization(cx: &mut TestAppContext) {
     let tool_call_auth_3 = next_tool_call_authorization(&mut events).await;
     tool_call_auth_3
         .response
-        .send(tool_call_auth_3.options[0].id.clone())
+        .send(tool_call_auth_3.options[0].option_id.clone())
         .unwrap();
     cx.run_until_parked();
     let completion = fake_model.pending_completions().pop().unwrap();
@@ -552,7 +765,7 @@ async fn test_tool_authorization(cx: &mut TestAppContext) {
         message.content,
         vec![language_model::MessageContent::ToolResult(
             LanguageModelToolResult {
-                tool_use_id: tool_call_auth_3.tool_call.id.0.to_string().into(),
+                tool_use_id: tool_call_auth_3.tool_call.tool_call_id.0.to_string().into(),
                 tool_name: ToolRequiringPermission::name().into(),
                 is_error: false,
                 content: "Allowed".into(),
@@ -1353,20 +1566,20 @@ async fn test_cancellation(cx: &mut TestAppContext) {
             ThreadEvent::ToolCall(tool_call) => {
                 assert_eq!(tool_call.title, expected_tools.remove(0));
                 if tool_call.title == "Echo" {
-                    echo_id = Some(tool_call.id);
+                    echo_id = Some(tool_call.tool_call_id);
                 }
             }
             ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::UpdateFields(
                 acp::ToolCallUpdate {
-                    id,
+                    tool_call_id,
                     fields:
                         acp::ToolCallUpdateFields {
                             status: Some(acp::ToolCallStatus::Completed),
                             ..
                         },
-                    meta: None,
+                    ..
                 },
-            )) if Some(&id) == echo_id.as_ref() => {
+            )) if Some(&tool_call_id) == echo_id.as_ref() => {
                 echo_completed = true;
             }
             _ => {}
@@ -1995,11 +2208,7 @@ async fn test_agent_connection(cx: &mut TestAppContext) {
         .update(|cx| {
             connection.prompt(
                 Some(acp_thread::UserMessageId::new()),
-                acp::PromptRequest {
-                    session_id: session_id.clone(),
-                    prompt: vec!["ghi".into()],
-                    meta: None,
-                },
+                acp::PromptRequest::new(session_id.clone(), vec!["ghi".into()]),
                 cx,
             )
         })
@@ -2056,68 +2265,50 @@ async fn test_tool_updates_to_completion(cx: &mut TestAppContext) {
     let tool_call = expect_tool_call(&mut events).await;
     assert_eq!(
         tool_call,
-        acp::ToolCall {
-            id: acp::ToolCallId("1".into()),
-            title: "Thinking".into(),
-            kind: acp::ToolKind::Think,
-            status: acp::ToolCallStatus::Pending,
-            content: vec![],
-            locations: vec![],
-            raw_input: Some(json!({})),
-            raw_output: None,
-            meta: Some(json!({ "tool_name": "thinking" })),
-        }
+        acp::ToolCall::new("1", "Thinking")
+            .kind(acp::ToolKind::Think)
+            .raw_input(json!({}))
+            .meta(acp::Meta::from_iter([(
+                "tool_name".into(),
+                "thinking".into()
+            )]))
     );
     let update = expect_tool_call_update_fields(&mut events).await;
     assert_eq!(
         update,
-        acp::ToolCallUpdate {
-            id: acp::ToolCallId("1".into()),
-            fields: acp::ToolCallUpdateFields {
-                title: Some("Thinking".into()),
-                kind: Some(acp::ToolKind::Think),
-                raw_input: Some(json!({ "content": "Thinking hard!" })),
-                ..Default::default()
-            },
-            meta: None,
-        }
+        acp::ToolCallUpdate::new(
+            "1",
+            acp::ToolCallUpdateFields::new()
+                .title("Thinking")
+                .kind(acp::ToolKind::Think)
+                .raw_input(json!({ "content": "Thinking hard!"}))
+        )
     );
     let update = expect_tool_call_update_fields(&mut events).await;
     assert_eq!(
         update,
-        acp::ToolCallUpdate {
-            id: acp::ToolCallId("1".into()),
-            fields: acp::ToolCallUpdateFields {
-                status: Some(acp::ToolCallStatus::InProgress),
-                ..Default::default()
-            },
-            meta: None,
-        }
+        acp::ToolCallUpdate::new(
+            "1",
+            acp::ToolCallUpdateFields::new().status(acp::ToolCallStatus::InProgress)
+        )
     );
     let update = expect_tool_call_update_fields(&mut events).await;
     assert_eq!(
         update,
-        acp::ToolCallUpdate {
-            id: acp::ToolCallId("1".into()),
-            fields: acp::ToolCallUpdateFields {
-                content: Some(vec!["Thinking hard!".into()]),
-                ..Default::default()
-            },
-            meta: None,
-        }
+        acp::ToolCallUpdate::new(
+            "1",
+            acp::ToolCallUpdateFields::new().content(vec!["Thinking hard!".into()])
+        )
     );
     let update = expect_tool_call_update_fields(&mut events).await;
     assert_eq!(
         update,
-        acp::ToolCallUpdate {
-            id: acp::ToolCallId("1".into()),
-            fields: acp::ToolCallUpdateFields {
-                status: Some(acp::ToolCallStatus::Completed),
-                raw_output: Some("Finished thinking.".into()),
-                ..Default::default()
-            },
-            meta: None,
-        }
+        acp::ToolCallUpdate::new(
+            "1",
+            acp::ToolCallUpdateFields::new()
+                .status(acp::ToolCallStatus::Completed)
+                .raw_output("Finished thinking.")
+        )
     );
 }
 
@@ -2618,3 +2809,181 @@ fn setup_context_server(
     cx.run_until_parked();
     mcp_tool_calls_rx
 }
+
+#[gpui::test]
+async fn test_tokens_before_message(cx: &mut TestAppContext) {
+    let ThreadTest { model, thread, .. } = setup(cx, TestModel::Fake).await;
+    let fake_model = model.as_fake();
+
+    // First message
+    let message_1_id = UserMessageId::new();
+    thread
+        .update(cx, |thread, cx| {
+            thread.send(message_1_id.clone(), ["First message"], cx)
+        })
+        .unwrap();
+    cx.run_until_parked();
+
+    // Before any response, tokens_before_message should return None for first message
+    thread.read_with(cx, |thread, _| {
+        assert_eq!(
+            thread.tokens_before_message(&message_1_id),
+            None,
+            "First message should have no tokens before it"
+        );
+    });
+
+    // Complete first message with usage
+    fake_model.send_last_completion_stream_text_chunk("Response 1");
+    fake_model.send_last_completion_stream_event(LanguageModelCompletionEvent::UsageUpdate(
+        language_model::TokenUsage {
+            input_tokens: 100,
+            output_tokens: 50,
+            cache_creation_input_tokens: 0,
+            cache_read_input_tokens: 0,
+        },
+    ));
+    fake_model.end_last_completion_stream();
+    cx.run_until_parked();
+
+    // First message still has no tokens before it
+    thread.read_with(cx, |thread, _| {
+        assert_eq!(
+            thread.tokens_before_message(&message_1_id),
+            None,
+            "First message should still have no tokens before it after response"
+        );
+    });
+
+    // Second message
+    let message_2_id = UserMessageId::new();
+    thread
+        .update(cx, |thread, cx| {
+            thread.send(message_2_id.clone(), ["Second message"], cx)
+        })
+        .unwrap();
+    cx.run_until_parked();
+
+    // Second message should have first message's input tokens before it
+    thread.read_with(cx, |thread, _| {
+        assert_eq!(
+            thread.tokens_before_message(&message_2_id),
+            Some(100),
+            "Second message should have 100 tokens before it (from first request)"
+        );
+    });
+
+    // Complete second message
+    fake_model.send_last_completion_stream_text_chunk("Response 2");
+    fake_model.send_last_completion_stream_event(LanguageModelCompletionEvent::UsageUpdate(
+        language_model::TokenUsage {
+            input_tokens: 250, // Total for this request (includes previous context)
+            output_tokens: 75,
+            cache_creation_input_tokens: 0,
+            cache_read_input_tokens: 0,
+        },
+    ));
+    fake_model.end_last_completion_stream();
+    cx.run_until_parked();
+
+    // Third message
+    let message_3_id = UserMessageId::new();
+    thread
+        .update(cx, |thread, cx| {
+            thread.send(message_3_id.clone(), ["Third message"], cx)
+        })
+        .unwrap();
+    cx.run_until_parked();
+
+    // Third message should have second message's input tokens (250) before it
+    thread.read_with(cx, |thread, _| {
+        assert_eq!(
+            thread.tokens_before_message(&message_3_id),
+            Some(250),
+            "Third message should have 250 tokens before it (from second request)"
+        );
+        // Second message should still have 100
+        assert_eq!(
+            thread.tokens_before_message(&message_2_id),
+            Some(100),
+            "Second message should still have 100 tokens before it"
+        );
+        // First message still has none
+        assert_eq!(
+            thread.tokens_before_message(&message_1_id),
+            None,
+            "First message should still have no tokens before it"
+        );
+    });
+}
+
+#[gpui::test]
+async fn test_tokens_before_message_after_truncate(cx: &mut TestAppContext) {
+    let ThreadTest { model, thread, .. } = setup(cx, TestModel::Fake).await;
+    let fake_model = model.as_fake();
+
+    // Set up three messages with responses
+    let message_1_id = UserMessageId::new();
+    thread
+        .update(cx, |thread, cx| {
+            thread.send(message_1_id.clone(), ["Message 1"], cx)
+        })
+        .unwrap();
+    cx.run_until_parked();
+    fake_model.send_last_completion_stream_text_chunk("Response 1");
+    fake_model.send_last_completion_stream_event(LanguageModelCompletionEvent::UsageUpdate(
+        language_model::TokenUsage {
+            input_tokens: 100,
+            output_tokens: 50,
+            cache_creation_input_tokens: 0,
+            cache_read_input_tokens: 0,
+        },
+    ));
+    fake_model.end_last_completion_stream();
+    cx.run_until_parked();
+
+    let message_2_id = UserMessageId::new();
+    thread
+        .update(cx, |thread, cx| {
+            thread.send(message_2_id.clone(), ["Message 2"], cx)
+        })
+        .unwrap();
+    cx.run_until_parked();
+    fake_model.send_last_completion_stream_text_chunk("Response 2");
+    fake_model.send_last_completion_stream_event(LanguageModelCompletionEvent::UsageUpdate(
+        language_model::TokenUsage {
+            input_tokens: 250,
+            output_tokens: 75,
+            cache_creation_input_tokens: 0,
+            cache_read_input_tokens: 0,
+        },
+    ));
+    fake_model.end_last_completion_stream();
+    cx.run_until_parked();
+
+    // Verify initial state
+    thread.read_with(cx, |thread, _| {
+        assert_eq!(thread.tokens_before_message(&message_2_id), Some(100));
+    });
+
+    // Truncate at message 2 (removes message 2 and everything after)
+    thread
+        .update(cx, |thread, cx| thread.truncate(message_2_id.clone(), cx))
+        .unwrap();
+    cx.run_until_parked();
+
+    // After truncation, message_2_id no longer exists, so lookup should return None
+    thread.read_with(cx, |thread, _| {
+        assert_eq!(
+            thread.tokens_before_message(&message_2_id),
+            None,
+            "After truncation, message 2 no longer exists"
+        );
+        // Message 1 still exists but has no tokens before it
+        assert_eq!(
+            thread.tokens_before_message(&message_1_id),
+            None,
+            "First message still has no tokens before it"
+        );
+    });
+}

crates/agent/src/thread.rs 🔗

@@ -2,7 +2,8 @@ use crate::{
     ContextServerRegistry, CopyPathTool, CreateDirectoryTool, DbLanguageModel, DbThread,
     DeletePathTool, DiagnosticsTool, EditFileTool, FetchTool, FindPathTool, GrepTool,
     ListDirectoryTool, MovePathTool, NowTool, OpenTool, ProjectSnapshot, ReadFileTool,
-    SystemPromptTemplate, Template, Templates, TerminalTool, ThinkingTool, WebSearchTool,
+    RestoreFileFromDiskTool, SaveFileTool, SystemPromptTemplate, Template, Templates, TerminalTool,
+    ThinkingTool, WebSearchTool,
 };
 use acp_thread::{MentionUri, UserMessageId};
 use action_log::ActionLog;
@@ -107,7 +108,13 @@ impl Message {
 
     pub fn to_request(&self) -> Vec<LanguageModelRequestMessage> {
         match self {
-            Message::User(message) => vec![message.to_request()],
+            Message::User(message) => {
+                if message.content.is_empty() {
+                    vec![]
+                } else {
+                    vec![message.to_request()]
+                }
+            }
             Message::Agent(message) => message.to_request(),
             Message::Resume => vec![LanguageModelRequestMessage {
                 role: Role::User,
@@ -530,6 +537,7 @@ pub trait TerminalHandle {
     fn id(&self, cx: &AsyncApp) -> Result<acp::TerminalId>;
     fn current_output(&self, cx: &AsyncApp) -> Result<acp::TerminalOutputResponse>;
     fn wait_for_exit(&self, cx: &AsyncApp) -> Result<Shared<Task<acp::TerminalExitStatus>>>;
+    fn kill(&self, cx: &AsyncApp) -> Result<()>;
 }
 
 pub trait ThreadEnvironment {
@@ -619,12 +627,9 @@ pub struct Thread {
 impl Thread {
     fn prompt_capabilities(model: Option<&dyn LanguageModel>) -> acp::PromptCapabilities {
         let image = model.map_or(true, |model| model.supports_images());
-        acp::PromptCapabilities {
-            meta: None,
-            image,
-            audio: false,
-            embedded_context: true,
-        }
+        acp::PromptCapabilities::new()
+            .image(image)
+            .embedded_context(true)
     }
 
     pub fn new(
@@ -640,7 +645,7 @@ impl Thread {
         let (prompt_capabilities_tx, prompt_capabilities_rx) =
             watch::channel(Self::prompt_capabilities(model.as_deref()));
         Self {
-            id: acp::SessionId(uuid::Uuid::new_v4().to_string().into()),
+            id: acp::SessionId::new(uuid::Uuid::new_v4().to_string()),
             prompt_id: PromptId::new(),
             updated_at: Utc::now(),
             title: None,
@@ -737,17 +742,11 @@ impl Thread {
         let Some(tool) = tool else {
             stream
                 .0
-                .unbounded_send(Ok(ThreadEvent::ToolCall(acp::ToolCall {
-                    meta: None,
-                    id: acp::ToolCallId(tool_use.id.to_string().into()),
-                    title: tool_use.name.to_string(),
-                    kind: acp::ToolKind::Other,
-                    status: acp::ToolCallStatus::Failed,
-                    content: Vec::new(),
-                    locations: Vec::new(),
-                    raw_input: Some(tool_use.input.clone()),
-                    raw_output: None,
-                })))
+                .unbounded_send(Ok(ThreadEvent::ToolCall(
+                    acp::ToolCall::new(tool_use.id.to_string(), tool_use.name.to_string())
+                        .status(acp::ToolCallStatus::Failed)
+                        .raw_input(tool_use.input.clone()),
+                )))
                 .ok();
             return;
         };
@@ -777,8 +776,8 @@ impl Thread {
 
         stream.update_tool_call_fields(
             &tool_use.id,
-            acp::ToolCallUpdateFields {
-                status: Some(
+            acp::ToolCallUpdateFields::new()
+                .status(
                     tool_result
                         .as_ref()
                         .map_or(acp::ToolCallStatus::Failed, |result| {
@@ -788,10 +787,8 @@ impl Thread {
                                 acp::ToolCallStatus::Completed
                             }
                         }),
-                ),
-                raw_output: output,
-                ..Default::default()
-            },
+                )
+                .raw_output(output),
         );
     }
 
@@ -1012,6 +1009,8 @@ impl Thread {
             self.project.clone(),
             self.action_log.clone(),
         ));
+        self.add_tool(SaveFileTool::new(self.project.clone()));
+        self.add_tool(RestoreFileFromDiskTool::new(self.project.clone()));
         self.add_tool(TerminalTool::new(self.project.clone(), environment));
         self.add_tool(ThinkingTool);
         self.add_tool(WebSearchTool);
@@ -1096,6 +1095,28 @@ impl Thread {
         })
     }
 
+    /// Get the total input token count as of the message before the given message.
+    ///
+    /// Returns `None` if:
+    /// - `target_id` is the first message (no previous message)
+    /// - The previous message hasn't received a response yet (no usage data)
+    /// - `target_id` is not found in the messages
+    pub fn tokens_before_message(&self, target_id: &UserMessageId) -> Option<u64> {
+        let mut previous_user_message_id: Option<&UserMessageId> = None;
+
+        for message in &self.messages {
+            if let Message::User(user_msg) = message {
+                if &user_msg.id == target_id {
+                    let prev_id = previous_user_message_id?;
+                    let usage = self.request_token_usage.get(prev_id)?;
+                    return Some(usage.input_tokens);
+                }
+                previous_user_message_id = Some(&user_msg.id);
+            }
+        }
+        None
+    }
+
     /// Look up the active profile and resolve its preferred model if one is configured.
     fn resolve_profile_model(
         profile_id: &AgentProfileId,
@@ -1148,20 +1169,64 @@ impl Thread {
     where
         T: Into<UserMessageContent>,
     {
+        let content = content.into_iter().map(Into::into).collect::<Vec<_>>();
+        log::debug!("Thread::send content: {:?}", content);
+
+        self.messages
+            .push(Message::User(UserMessage { id, content }));
+        cx.notify();
+
+        self.send_existing(cx)
+    }
+
+    pub fn send_existing(
+        &mut self,
+        cx: &mut Context<Self>,
+    ) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>> {
         let model = self.model().context("No language model configured")?;
 
         log::info!("Thread::send called with model: {}", model.name().0);
         self.advance_prompt_id();
 
-        let content = content.into_iter().map(Into::into).collect::<Vec<_>>();
-        log::debug!("Thread::send content: {:?}", content);
+        log::debug!("Total messages in thread: {}", self.messages.len());
+        self.run_turn(cx)
+    }
 
+    pub fn push_acp_user_block(
+        &mut self,
+        id: UserMessageId,
+        blocks: impl IntoIterator<Item = acp::ContentBlock>,
+        path_style: PathStyle,
+        cx: &mut Context<Self>,
+    ) {
+        let content = blocks
+            .into_iter()
+            .map(|block| UserMessageContent::from_content_block(block, path_style))
+            .collect::<Vec<_>>();
         self.messages
             .push(Message::User(UserMessage { id, content }));
         cx.notify();
+    }
 
-        log::debug!("Total messages in thread: {}", self.messages.len());
-        self.run_turn(cx)
+    pub fn push_acp_agent_block(&mut self, block: acp::ContentBlock, cx: &mut Context<Self>) {
+        let text = match block {
+            acp::ContentBlock::Text(text_content) => text_content.text,
+            acp::ContentBlock::Image(_) => "[image]".to_string(),
+            acp::ContentBlock::Audio(_) => "[audio]".to_string(),
+            acp::ContentBlock::ResourceLink(resource_link) => resource_link.uri,
+            acp::ContentBlock::Resource(resource) => match resource.resource {
+                acp::EmbeddedResourceResource::TextResourceContents(resource) => resource.uri,
+                acp::EmbeddedResourceResource::BlobResourceContents(resource) => resource.uri,
+                _ => "[resource]".to_string(),
+            },
+            _ => "[unknown]".to_string(),
+        };
+
+        self.messages.push(Message::Agent(AgentMessage {
+            content: vec![AgentMessageContent::Text(text)],
+            ..Default::default()
+        }));
+        cx.notify();
     }
 
     #[cfg(feature = "eval")]
@@ -1274,15 +1339,13 @@ impl Thread {
 
                 event_stream.update_tool_call_fields(
                     &tool_result.tool_use_id,
-                    acp::ToolCallUpdateFields {
-                        status: Some(if tool_result.is_error {
+                    acp::ToolCallUpdateFields::new()
+                        .status(if tool_result.is_error {
                             acp::ToolCallStatus::Failed
                         } else {
                             acp::ToolCallStatus::Completed
-                        }),
-                        raw_output: tool_result.output.clone(),
-                        ..Default::default()
-                    },
+                        })
+                        .raw_output(tool_result.output.clone()),
                 );
                 this.update(cx, |this, _cx| {
                     this.pending_message()
@@ -1560,12 +1623,10 @@ impl Thread {
         } else {
             event_stream.update_tool_call_fields(
                 &tool_use.id,
-                acp::ToolCallUpdateFields {
-                    title: Some(title.into()),
-                    kind: Some(kind),
-                    raw_input: Some(tool_use.input.clone()),
-                    ..Default::default()
-                },
+                acp::ToolCallUpdateFields::new()
+                    .title(title.as_str())
+                    .kind(kind)
+                    .raw_input(tool_use.input.clone()),
             );
         }
 
@@ -1587,10 +1648,9 @@ impl Thread {
         let fs = self.project.read(cx).fs().clone();
         let tool_event_stream =
             ToolCallEventStream::new(tool_use.id.clone(), event_stream.clone(), Some(fs));
-        tool_event_stream.update_fields(acp::ToolCallUpdateFields {
-            status: Some(acp::ToolCallStatus::InProgress),
-            ..Default::default()
-        });
+        tool_event_stream.update_fields(
+            acp::ToolCallUpdateFields::new().status(acp::ToolCallStatus::InProgress),
+        );
         let supports_images = self.model().is_some_and(|model| model.supports_images());
         let tool_result = tool.run(tool_use.input, tool_event_stream, cx);
         log::debug!("Running tool {}", tool_use.name);
@@ -1665,6 +1725,10 @@ impl Thread {
         self.pending_summary_generation.is_some()
     }
 
+    pub fn is_generating_title(&self) -> bool {
+        self.pending_title_generation.is_some()
+    }
+
     pub fn summary(&mut self, cx: &mut Context<Self>) -> Shared<Task<Option<SharedString>>> {
         if let Some(summary) = self.summary.as_ref() {
             return Task::ready(Some(summary.clone())).shared();
@@ -1732,7 +1796,7 @@ impl Thread {
         task
     }
 
-    fn generate_title(&mut self, cx: &mut Context<Self>) {
+    pub fn generate_title(&mut self, cx: &mut Context<Self>) {
         let Some(model) = self.summarization_model.clone() else {
             return;
         };
@@ -1981,6 +2045,12 @@ impl Thread {
         self.running_turn.as_ref()?.tools.get(name).cloned()
     }
 
+    pub fn has_tool(&self, name: &str) -> bool {
+        self.running_turn
+            .as_ref()
+            .is_some_and(|turn| turn.tools.contains_key(name))
+    }
+
     fn build_request_messages(
         &self,
         available_tools: Vec<SharedString>,
@@ -2381,19 +2451,13 @@ impl ThreadEventStream {
         kind: acp::ToolKind,
         input: serde_json::Value,
     ) -> acp::ToolCall {
-        acp::ToolCall {
-            meta: Some(serde_json::json!({
-                "tool_name": tool_name
-            })),
-            id: acp::ToolCallId(id.to_string().into()),
-            title,
-            kind,
-            status: acp::ToolCallStatus::Pending,
-            content: vec![],
-            locations: vec![],
-            raw_input: Some(input),
-            raw_output: None,
-        }
+        acp::ToolCall::new(id.to_string(), title)
+            .kind(kind)
+            .raw_input(input)
+            .meta(acp::Meta::from_iter([(
+                "tool_name".into(),
+                tool_name.into(),
+            )]))
     }
 
     fn update_tool_call_fields(
@@ -2403,12 +2467,7 @@ impl ThreadEventStream {
     ) {
         self.0
             .unbounded_send(Ok(ThreadEvent::ToolCallUpdate(
-                acp::ToolCallUpdate {
-                    meta: None,
-                    id: acp::ToolCallId(tool_use_id.to_string().into()),
-                    fields,
-                }
-                .into(),
+                acp::ToolCallUpdate::new(tool_use_id.to_string(), fields).into(),
             )))
             .ok();
     }
@@ -2471,7 +2530,7 @@ impl ToolCallEventStream {
             .0
             .unbounded_send(Ok(ThreadEvent::ToolCallUpdate(
                 acp_thread::ToolCallUpdateDiff {
-                    id: acp::ToolCallId(self.tool_use_id.to_string().into()),
+                    id: acp::ToolCallId::new(self.tool_use_id.to_string()),
                     diff,
                 }
                 .into(),
@@ -2489,33 +2548,26 @@ impl ToolCallEventStream {
             .0
             .unbounded_send(Ok(ThreadEvent::ToolCallAuthorization(
                 ToolCallAuthorization {
-                    tool_call: acp::ToolCallUpdate {
-                        meta: None,
-                        id: acp::ToolCallId(self.tool_use_id.to_string().into()),
-                        fields: acp::ToolCallUpdateFields {
-                            title: Some(title.into()),
-                            ..Default::default()
-                        },
-                    },
+                    tool_call: acp::ToolCallUpdate::new(
+                        self.tool_use_id.to_string(),
+                        acp::ToolCallUpdateFields::new().title(title.into()),
+                    ),
                     options: vec![
-                        acp::PermissionOption {
-                            id: acp::PermissionOptionId("always_allow".into()),
-                            name: "Always Allow".into(),
-                            kind: acp::PermissionOptionKind::AllowAlways,
-                            meta: None,
-                        },
-                        acp::PermissionOption {
-                            id: acp::PermissionOptionId("allow".into()),
-                            name: "Allow".into(),
-                            kind: acp::PermissionOptionKind::AllowOnce,
-                            meta: None,
-                        },
-                        acp::PermissionOption {
-                            id: acp::PermissionOptionId("deny".into()),
-                            name: "Deny".into(),
-                            kind: acp::PermissionOptionKind::RejectOnce,
-                            meta: None,
-                        },
+                        acp::PermissionOption::new(
+                            acp::PermissionOptionId::new("always_allow"),
+                            "Always Allow",
+                            acp::PermissionOptionKind::AllowAlways,
+                        ),
+                        acp::PermissionOption::new(
+                            acp::PermissionOptionId::new("allow"),
+                            "Allow",
+                            acp::PermissionOptionKind::AllowOnce,
+                        ),
+                        acp::PermissionOption::new(
+                            acp::PermissionOptionId::new("deny"),
+                            "Deny",
+                            acp::PermissionOptionKind::RejectOnce,
+                        ),
                     ],
                     response: response_tx,
                 },
@@ -2660,7 +2712,15 @@ impl UserMessageContent {
                     // TODO
                     Self::Text("[blob]".to_string())
                 }
+                other => {
+                    log::warn!("Unexpected content type: {:?}", other);
+                    Self::Text("[unknown]".to_string())
+                }
             },
+            other => {
+                log::warn!("Unexpected content type: {:?}", other);
+                Self::Text("[unknown]".to_string())
+            }
         }
     }
 }
@@ -2668,32 +2728,15 @@ impl UserMessageContent {
 impl From<UserMessageContent> for acp::ContentBlock {
     fn from(content: UserMessageContent) -> Self {
         match content {
-            UserMessageContent::Text(text) => acp::ContentBlock::Text(acp::TextContent {
-                text,
-                annotations: None,
-                meta: None,
-            }),
-            UserMessageContent::Image(image) => acp::ContentBlock::Image(acp::ImageContent {
-                data: image.source.to_string(),
-                mime_type: "image/png".to_string(),
-                meta: None,
-                annotations: None,
-                uri: None,
-            }),
-            UserMessageContent::Mention { uri, content } => {
-                acp::ContentBlock::Resource(acp::EmbeddedResource {
-                    meta: None,
-                    resource: acp::EmbeddedResourceResource::TextResourceContents(
-                        acp::TextResourceContents {
-                            meta: None,
-                            mime_type: None,
-                            text: content,
-                            uri: uri.to_uri().to_string(),
-                        },
-                    ),
-                    annotations: None,
-                })
+            UserMessageContent::Text(text) => text.into(),
+            UserMessageContent::Image(image) => {
+                acp::ContentBlock::Image(acp::ImageContent::new(image.source, "image/png"))
             }
+            UserMessageContent::Mention { uri, content } => acp::ContentBlock::Resource(
+                acp::EmbeddedResource::new(acp::EmbeddedResourceResource::TextResourceContents(
+                    acp::TextResourceContents::new(content, uri.to_uri().to_string()),
+                )),
+            ),
         }
     }
 }
@@ -2701,7 +2744,6 @@ impl From<UserMessageContent> for acp::ContentBlock {
 fn convert_image(image_content: acp::ImageContent) -> LanguageModelImage {
     LanguageModelImage {
         source: image_content.data.into(),
-        // TODO: make this optional?
-        size: gpui::Size::new(0.into(), 0.into()),
+        size: None,
     }
 }

crates/agent/src/tools.rs 🔗

@@ -12,6 +12,9 @@ mod move_path_tool;
 mod now_tool;
 mod open_tool;
 mod read_file_tool;
+mod restore_file_from_disk_tool;
+mod save_file_tool;
+
 mod terminal_tool;
 mod thinking_tool;
 mod web_search_tool;
@@ -33,6 +36,9 @@ pub use move_path_tool::*;
 pub use now_tool::*;
 pub use open_tool::*;
 pub use read_file_tool::*;
+pub use restore_file_from_disk_tool::*;
+pub use save_file_tool::*;
+
 pub use terminal_tool::*;
 pub use thinking_tool::*;
 pub use web_search_tool::*;
@@ -88,6 +94,8 @@ tools! {
     NowTool,
     OpenTool,
     ReadFileTool,
+    RestoreFileFromDiskTool,
+    SaveFileTool,
     TerminalTool,
     ThinkingTool,
     WebSearchTool,

crates/agent/src/tools/context_server_registry.rs 🔗

@@ -2,12 +2,24 @@ use crate::{AgentToolOutput, AnyAgentTool, ToolCallEventStream};
 use agent_client_protocol::ToolKind;
 use anyhow::{Result, anyhow, bail};
 use collections::{BTreeMap, HashMap};
-use context_server::ContextServerId;
-use gpui::{App, Context, Entity, SharedString, Task};
+use context_server::{ContextServerId, client::NotificationSubscription};
+use gpui::{App, AppContext, AsyncApp, Context, Entity, EventEmitter, SharedString, Task};
 use project::context_server_store::{ContextServerStatus, ContextServerStore};
 use std::sync::Arc;
 use util::ResultExt;
 
+pub struct ContextServerPrompt {
+    pub server_id: ContextServerId,
+    pub prompt: context_server::types::Prompt,
+}
+
+pub enum ContextServerRegistryEvent {
+    ToolsChanged,
+    PromptsChanged,
+}
+
+impl EventEmitter<ContextServerRegistryEvent> for ContextServerRegistry {}
+
 pub struct ContextServerRegistry {
     server_store: Entity<ContextServerStore>,
     registered_servers: HashMap<ContextServerId, RegisteredContextServer>,
@@ -16,7 +28,10 @@ pub struct ContextServerRegistry {
 
 struct RegisteredContextServer {
     tools: BTreeMap<SharedString, Arc<dyn AnyAgentTool>>,
+    prompts: BTreeMap<SharedString, ContextServerPrompt>,
     load_tools: Task<Result<()>>,
+    load_prompts: Task<Result<()>>,
+    _tools_updated_subscription: Option<NotificationSubscription>,
 }
 
 impl ContextServerRegistry {
@@ -28,6 +43,7 @@ impl ContextServerRegistry {
         };
         for server in server_store.read(cx).running_servers() {
             this.reload_tools_for_server(server.id(), cx);
+            this.reload_prompts_for_server(server.id(), cx);
         }
         this
     }
@@ -56,6 +72,88 @@ impl ContextServerRegistry {
             .map(|(id, server)| (id, &server.tools))
     }
 
+    pub fn prompts(&self) -> impl Iterator<Item = &ContextServerPrompt> {
+        self.registered_servers
+            .values()
+            .flat_map(|server| server.prompts.values())
+    }
+
+    pub fn find_prompt(
+        &self,
+        server_id: Option<&ContextServerId>,
+        name: &str,
+    ) -> Option<&ContextServerPrompt> {
+        if let Some(server_id) = server_id {
+            self.registered_servers
+                .get(server_id)
+                .and_then(|server| server.prompts.get(name))
+        } else {
+            self.registered_servers
+                .values()
+                .find_map(|server| server.prompts.get(name))
+        }
+    }
+
+    pub fn server_store(&self) -> &Entity<ContextServerStore> {
+        &self.server_store
+    }
+
+    fn get_or_register_server(
+        &mut self,
+        server_id: &ContextServerId,
+        cx: &mut Context<Self>,
+    ) -> &mut RegisteredContextServer {
+        self.registered_servers
+            .entry(server_id.clone())
+            .or_insert_with(|| Self::init_registered_server(server_id, &self.server_store, cx))
+    }
+
+    fn init_registered_server(
+        server_id: &ContextServerId,
+        server_store: &Entity<ContextServerStore>,
+        cx: &mut Context<Self>,
+    ) -> RegisteredContextServer {
+        let tools_updated_subscription = server_store
+            .read(cx)
+            .get_running_server(server_id)
+            .and_then(|server| {
+                let client = server.client()?;
+
+                if !client.capable(context_server::protocol::ServerCapability::Tools) {
+                    return None;
+                }
+
+                let server_id = server.id();
+                let this = cx.entity().downgrade();
+
+                Some(client.on_notification(
+                    "notifications/tools/list_changed",
+                    Box::new(move |_params, cx: AsyncApp| {
+                        let server_id = server_id.clone();
+                        let this = this.clone();
+                        cx.spawn(async move |cx| {
+                            this.update(cx, |this, cx| {
+                                log::info!(
+                                    "Received tools/list_changed notification for server {}",
+                                    server_id
+                                );
+                                this.reload_tools_for_server(server_id, cx);
+                            })
+                        })
+                        .detach();
+                    }),
+                ))
+            });
+
+        RegisteredContextServer {
+            tools: BTreeMap::default(),
+            prompts: BTreeMap::default(),
+            load_tools: Task::ready(Ok(())),
+            load_prompts: Task::ready(Ok(())),
+            _tools_updated_subscription: tools_updated_subscription,
+        }
+    }
+
     fn reload_tools_for_server(&mut self, server_id: ContextServerId, cx: &mut Context<Self>) {
         let Some(server) = self.server_store.read(cx).get_running_server(&server_id) else {
             return;
@@ -63,17 +161,12 @@ impl ContextServerRegistry {
         let Some(client) = server.client() else {
             return;
         };
+
         if !client.capable(context_server::protocol::ServerCapability::Tools) {
             return;
         }
 
-        let registered_server =
-            self.registered_servers
-                .entry(server_id.clone())
-                .or_insert(RegisteredContextServer {
-                    tools: BTreeMap::default(),
-                    load_tools: Task::ready(Ok(())),
-                });
+        let registered_server = self.get_or_register_server(&server_id, cx);
         registered_server.load_tools = cx.spawn(async move |this, cx| {
             let response = client
                 .request::<context_server::types::requests::ListTools>(())
@@ -94,6 +187,49 @@ impl ContextServerRegistry {
                         ));
                         registered_server.tools.insert(tool.name(), tool);
                     }
+                    cx.emit(ContextServerRegistryEvent::ToolsChanged);
+                    cx.notify();
+                }
+            })
+        });
+    }
+
+    fn reload_prompts_for_server(&mut self, server_id: ContextServerId, cx: &mut Context<Self>) {
+        let Some(server) = self.server_store.read(cx).get_running_server(&server_id) else {
+            return;
+        };
+        let Some(client) = server.client() else {
+            return;
+        };
+        if !client.capable(context_server::protocol::ServerCapability::Prompts) {
+            return;
+        }
+
+        let registered_server = self.get_or_register_server(&server_id, cx);
+
+        registered_server.load_prompts = cx.spawn(async move |this, cx| {
+            let response = client
+                .request::<context_server::types::requests::PromptsList>(())
+                .await;
+
+            this.update(cx, |this, cx| {
+                let Some(registered_server) = this.registered_servers.get_mut(&server_id) else {
+                    return;
+                };
+
+                registered_server.prompts.clear();
+                if let Some(response) = response.log_err() {
+                    for prompt in response.prompts {
+                        let name: SharedString = prompt.name.clone().into();
+                        registered_server.prompts.insert(
+                            name,
+                            ContextServerPrompt {
+                                server_id: server_id.clone(),
+                                prompt,
+                            },
+                        );
+                    }
+                    cx.emit(ContextServerRegistryEvent::PromptsChanged);
                     cx.notify();
                 }
             })
@@ -112,9 +248,17 @@ impl ContextServerRegistry {
                     ContextServerStatus::Starting => {}
                     ContextServerStatus::Running => {
                         self.reload_tools_for_server(server_id.clone(), cx);
+                        self.reload_prompts_for_server(server_id.clone(), cx);
                     }
                     ContextServerStatus::Stopped | ContextServerStatus::Error(_) => {
-                        self.registered_servers.remove(server_id);
+                        if let Some(registered_server) = self.registered_servers.remove(server_id) {
+                            if !registered_server.tools.is_empty() {
+                                cx.emit(ContextServerRegistryEvent::ToolsChanged);
+                            }
+                            if !registered_server.prompts.is_empty() {
+                                cx.emit(ContextServerRegistryEvent::PromptsChanged);
+                            }
+                        }
                         cx.notify();
                     }
                 }
@@ -251,3 +395,39 @@ impl AnyAgentTool for ContextServerTool {
         Ok(())
     }
 }
+
+pub fn get_prompt(
+    server_store: &Entity<ContextServerStore>,
+    server_id: &ContextServerId,
+    prompt_name: &str,
+    arguments: HashMap<String, String>,
+    cx: &mut AsyncApp,
+) -> Task<Result<context_server::types::PromptsGetResponse>> {
+    let server = match cx.update(|cx| server_store.read(cx).get_running_server(server_id)) {
+        Ok(server) => server,
+        Err(error) => return Task::ready(Err(error)),
+    };
+    let Some(server) = server else {
+        return Task::ready(Err(anyhow::anyhow!("Context server not found")));
+    };
+
+    let Some(protocol) = server.client() else {
+        return Task::ready(Err(anyhow::anyhow!("Context server not initialized")));
+    };
+
+    let prompt_name = prompt_name.to_string();
+
+    cx.background_spawn(async move {
+        let response = protocol
+            .request::<context_server::types::requests::PromptsGet>(
+                context_server::types::PromptsGetParams {
+                    name: prompt_name,
+                    arguments: (!arguments.is_empty()).then(|| arguments),
+                    meta: None,
+                },
+            )
+            .await?;
+
+        Ok(response)
+    })
+}

crates/agent/src/tools/edit_file_tool.rs 🔗

@@ -273,14 +273,9 @@ impl AgentTool for EditFileTool {
         };
         let abs_path = project.read(cx).absolute_path(&project_path, cx);
         if let Some(abs_path) = abs_path.clone() {
-            event_stream.update_fields(ToolCallUpdateFields {
-                locations: Some(vec![acp::ToolCallLocation {
-                    path: abs_path,
-                    line: None,
-                    meta: None,
-                }]),
-                ..Default::default()
-            });
+            event_stream.update_fields(
+                ToolCallUpdateFields::new().locations(vec![acp::ToolCallLocation::new(abs_path)]),
+            );
         }
 
         let authorize = self.authorize(&input, &event_stream, cx);
@@ -311,20 +306,39 @@ impl AgentTool for EditFileTool {
 
             // Check if the file has been modified since the agent last read it
             if let Some(abs_path) = abs_path.as_ref() {
-                let (last_read_mtime, current_mtime, is_dirty) = self.thread.update(cx, |thread, cx| {
+                let (last_read_mtime, current_mtime, is_dirty, has_save_tool, has_restore_tool) = self.thread.update(cx, |thread, cx| {
                     let last_read = thread.file_read_times.get(abs_path).copied();
                     let current = buffer.read(cx).file().and_then(|file| file.disk_state().mtime());
                     let dirty = buffer.read(cx).is_dirty();
-                    (last_read, current, dirty)
+                    let has_save = thread.has_tool("save_file");
+                    let has_restore = thread.has_tool("restore_file_from_disk");
+                    (last_read, current, dirty, has_save, has_restore)
                 })?;
 
                 // Check for unsaved changes first - these indicate modifications we don't know about
                 if is_dirty {
-                    anyhow::bail!(
-                        "This file cannot be written to because it has unsaved changes. \
-                         Please end the current conversation immediately by telling the user you want to write to this file (mention its path explicitly) but you can't write to it because it has unsaved changes. \
-                         Ask the user to save that buffer's changes and to inform you when it's ok to proceed."
-                    );
+                    let message = match (has_save_tool, has_restore_tool) {
+                        (true, true) => {
+                            "This file has unsaved changes. Ask the user whether they want to keep or discard those changes. \
+                             If they want to keep them, ask for confirmation then use the save_file tool to save the file, then retry this edit. \
+                             If they want to discard them, ask for confirmation then use the restore_file_from_disk tool to restore the on-disk contents, then retry this edit."
+                        }
+                        (true, false) => {
+                            "This file has unsaved changes. Ask the user whether they want to keep or discard those changes. \
+                             If they want to keep them, ask for confirmation then use the save_file tool to save the file, then retry this edit. \
+                             If they want to discard them, ask the user to manually revert the file, then inform you when it's ok to proceed."
+                        }
+                        (false, true) => {
+                            "This file has unsaved changes. Ask the user whether they want to keep or discard those changes. \
+                             If they want to keep them, ask the user to manually save the file, then inform you when it's ok to proceed. \
+                             If they want to discard them, ask for confirmation then use the restore_file_from_disk tool to restore the on-disk contents, then retry this edit."
+                        }
+                        (false, false) => {
+                            "This file has unsaved changes. Ask the user whether they want to keep or discard those changes, \
+                             then ask them to save or revert the file manually and inform you when it's ok to proceed."
+                        }
+                    };
+                    anyhow::bail!("{}", message);
                 }
 
                 // Check if the file was modified on disk since we last read it
@@ -389,10 +403,7 @@ impl AgentTool for EditFileTool {
                                 range.start.to_point(&buffer.snapshot()).row
                             }).ok();
                             if let Some(abs_path) = abs_path.clone() {
-                                event_stream.update_fields(ToolCallUpdateFields {
-                                    locations: Some(vec![ToolCallLocation { path: abs_path, line, meta: None }]),
-                                    ..Default::default()
-                                });
+                                event_stream.update_fields(ToolCallUpdateFields::new().locations(vec![ToolCallLocation::new(abs_path).line(line)]));
                             }
                             emitted_location = true;
                         }
@@ -2210,9 +2221,21 @@ mod tests {
         assert!(result.is_err(), "Edit should fail when buffer is dirty");
         let error_msg = result.unwrap_err().to_string();
         assert!(
-            error_msg.contains("cannot be written to because it has unsaved changes"),
+            error_msg.contains("This file has unsaved changes."),
             "Error should mention unsaved changes, got: {}",
             error_msg
         );
+        assert!(
+            error_msg.contains("keep or discard"),
+            "Error should ask whether to keep or discard changes, got: {}",
+            error_msg
+        );
+        // Since save_file and restore_file_from_disk tools aren't added to the thread,
+        // the error message should ask the user to manually save or revert
+        assert!(
+            error_msg.contains("save or revert the file manually"),
+            "Error should ask user to manually save or revert when tools aren't available, got: {}",
+            error_msg
+        );
     }
 }

crates/agent/src/tools/find_path_tool.rs 🔗

@@ -118,33 +118,29 @@ impl AgentTool for FindPathTool {
             let paginated_matches: &[PathBuf] = &matches[cmp::min(input.offset, matches.len())
                 ..cmp::min(input.offset + RESULTS_PER_PAGE, matches.len())];
 
-            event_stream.update_fields(acp::ToolCallUpdateFields {
-                title: Some(if paginated_matches.is_empty() {
-                    "No matches".into()
-                } else if paginated_matches.len() == 1 {
-                    "1 match".into()
-                } else {
-                    format!("{} matches", paginated_matches.len())
-                }),
-                content: Some(
-                    paginated_matches
-                        .iter()
-                        .map(|path| acp::ToolCallContent::Content {
-                            content: acp::ContentBlock::ResourceLink(acp::ResourceLink {
-                                uri: format!("file://{}", path.display()),
-                                name: path.to_string_lossy().into(),
-                                annotations: None,
-                                description: None,
-                                mime_type: None,
-                                size: None,
-                                title: None,
-                                meta: None,
-                            }),
-                        })
-                        .collect(),
-                ),
-                ..Default::default()
-            });
+            event_stream.update_fields(
+                acp::ToolCallUpdateFields::new()
+                    .title(if paginated_matches.is_empty() {
+                        "No matches".into()
+                    } else if paginated_matches.len() == 1 {
+                        "1 match".into()
+                    } else {
+                        format!("{} matches", paginated_matches.len())
+                    })
+                    .content(
+                        paginated_matches
+                            .iter()
+                            .map(|path| {
+                                acp::ToolCallContent::Content(acp::Content::new(
+                                    acp::ContentBlock::ResourceLink(acp::ResourceLink::new(
+                                        path.to_string_lossy(),
+                                        format!("file://{}", path.display()),
+                                    )),
+                                ))
+                            })
+                            .collect::<Vec<_>>(),
+                    ),
+            );
 
             Ok(FindPathToolOutput {
                 offset: input.offset,

crates/agent/src/tools/grep_tool.rs 🔗

@@ -322,7 +322,6 @@ mod tests {
 
     use super::*;
     use gpui::{TestAppContext, UpdateGlobal};
-    use language::{Language, LanguageConfig, LanguageMatcher};
     use project::{FakeFs, Project};
     use serde_json::json;
     use settings::SettingsStore;
@@ -564,7 +563,7 @@ mod tests {
         let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
 
         project.update(cx, |project, _cx| {
-            project.languages().add(rust_lang().into())
+            project.languages().add(language::rust_lang())
         });
 
         project
@@ -793,22 +792,6 @@ mod tests {
         });
     }
 
-    fn rust_lang() -> Language {
-        Language::new(
-            LanguageConfig {
-                name: "Rust".into(),
-                matcher: LanguageMatcher {
-                    path_suffixes: vec!["rs".to_string()],
-                    ..Default::default()
-                },
-                ..Default::default()
-            },
-            Some(tree_sitter_rust::LANGUAGE.into()),
-        )
-        .with_outline_query(include_str!("../../../languages/src/rust/outline.scm"))
-        .unwrap()
-    }
-
     #[gpui::test]
     async fn test_grep_security_boundaries(cx: &mut TestAppContext) {
         init_test(cx);

crates/agent/src/tools/read_file_tool.rs 🔗

@@ -153,14 +153,10 @@ impl AgentTool for ReadFileTool {
 
         let file_path = input.path.clone();
 
-        event_stream.update_fields(ToolCallUpdateFields {
-            locations: Some(vec![acp::ToolCallLocation {
-                path: abs_path.clone(),
-                line: input.start_line.map(|line| line.saturating_sub(1)),
-                meta: None,
-            }]),
-            ..Default::default()
-        });
+        event_stream.update_fields(ToolCallUpdateFields::new().locations(vec![
+                acp::ToolCallLocation::new(&abs_path)
+                    .line(input.start_line.map(|line| line.saturating_sub(1))),
+            ]));
 
         if image_store::is_image_file(&self.project, &project_path, cx) {
             return cx.spawn(async move |cx| {
@@ -289,12 +285,9 @@ impl AgentTool for ReadFileTool {
                         text,
                     }
                     .to_string();
-                    event_stream.update_fields(ToolCallUpdateFields {
-                        content: Some(vec![acp::ToolCallContent::Content {
-                            content: markdown.into(),
-                        }]),
-                        ..Default::default()
-                    })
+                    event_stream.update_fields(ToolCallUpdateFields::new().content(vec![
+                        acp::ToolCallContent::Content(acp::Content::new(markdown)),
+                    ]));
                 }
             })?;
 
@@ -308,7 +301,6 @@ mod test {
     use super::*;
     use crate::{ContextServerRegistry, Templates, Thread};
     use gpui::{AppContext, TestAppContext, UpdateGlobal as _};
-    use language::{Language, LanguageConfig, LanguageMatcher, tree_sitter_rust};
     use language_model::fake_provider::FakeLanguageModel;
     use project::{FakeFs, Project};
     use prompt_store::ProjectContext;
@@ -412,7 +404,7 @@ mod test {
         .await;
         let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
         let language_registry = project.read_with(cx, |project, _| project.languages().clone());
-        language_registry.add(Arc::new(rust_lang()));
+        language_registry.add(language::rust_lang());
         let action_log = cx.new(|_| ActionLog::new(project.clone()));
         let context_server_registry =
             cx.new(|cx| ContextServerRegistry::new(project.read(cx).context_server_store(), cx));
@@ -602,49 +594,6 @@ mod test {
         });
     }
 
-    fn rust_lang() -> Language {
-        Language::new(
-            LanguageConfig {
-                name: "Rust".into(),
-                matcher: LanguageMatcher {
-                    path_suffixes: vec!["rs".to_string()],
-                    ..Default::default()
-                },
-                ..Default::default()
-            },
-            Some(tree_sitter_rust::LANGUAGE.into()),
-        )
-        .with_outline_query(
-            r#"
-            (line_comment) @annotation
-
-            (struct_item
-                "struct" @context
-                name: (_) @name) @item
-            (enum_item
-                "enum" @context
-                name: (_) @name) @item
-            (enum_variant
-                name: (_) @name) @item
-            (field_declaration
-                name: (_) @name) @item
-            (impl_item
-                "impl" @context
-                trait: (_)? @name
-                "for"? @context
-                type: (_) @name
-                body: (_ "{" (_)* "}")) @item
-            (function_item
-                "fn" @context
-                name: (_) @name) @item
-            (mod_item
-                "mod" @context
-                name: (_) @name) @item
-            "#,
-        )
-        .unwrap()
-    }
-
     #[gpui::test]
     async fn test_read_file_security(cx: &mut TestAppContext) {
         init_test(cx);

crates/agent/src/tools/restore_file_from_disk_tool.rs 🔗

@@ -0,0 +1,352 @@
+use agent_client_protocol as acp;
+use anyhow::Result;
+use collections::FxHashSet;
+use gpui::{App, Entity, SharedString, Task};
+use language::Buffer;
+use project::Project;
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+use std::path::PathBuf;
+use std::sync::Arc;
+
+use crate::{AgentTool, ToolCallEventStream};
+
+/// Discards unsaved changes in open buffers by reloading file contents from disk.
+///
+/// Use this tool when:
+/// - You attempted to edit files but they have unsaved changes the user does not want to keep.
+/// - You want to reset files to the on-disk state before retrying an edit.
+///
+/// Only use this tool after asking the user for permission, because it will discard unsaved changes.
+#[derive(Debug, Serialize, Deserialize, JsonSchema)]
+pub struct RestoreFileFromDiskToolInput {
+    /// The paths of the files to restore from disk.
+    pub paths: Vec<PathBuf>,
+}
+
+pub struct RestoreFileFromDiskTool {
+    project: Entity<Project>,
+}
+
+impl RestoreFileFromDiskTool {
+    pub fn new(project: Entity<Project>) -> Self {
+        Self { project }
+    }
+}
+
+impl AgentTool for RestoreFileFromDiskTool {
+    type Input = RestoreFileFromDiskToolInput;
+    type Output = String;
+
+    fn name() -> &'static str {
+        "restore_file_from_disk"
+    }
+
+    fn kind() -> acp::ToolKind {
+        acp::ToolKind::Other
+    }
+
+    fn initial_title(
+        &self,
+        input: Result<Self::Input, serde_json::Value>,
+        _cx: &mut App,
+    ) -> SharedString {
+        match input {
+            Ok(input) if input.paths.len() == 1 => "Restore file from disk".into(),
+            Ok(input) => format!("Restore {} files from disk", input.paths.len()).into(),
+            Err(_) => "Restore files from disk".into(),
+        }
+    }
+
+    fn run(
+        self: Arc<Self>,
+        input: Self::Input,
+        _event_stream: ToolCallEventStream,
+        cx: &mut App,
+    ) -> Task<Result<String>> {
+        let project = self.project.clone();
+        let input_paths = input.paths;
+
+        cx.spawn(async move |cx| {
+            let mut buffers_to_reload: FxHashSet<Entity<Buffer>> = FxHashSet::default();
+
+            let mut restored_paths: Vec<PathBuf> = Vec::new();
+            let mut clean_paths: Vec<PathBuf> = Vec::new();
+            let mut not_found_paths: Vec<PathBuf> = Vec::new();
+            let mut open_errors: Vec<(PathBuf, String)> = Vec::new();
+            let mut dirty_check_errors: Vec<(PathBuf, String)> = Vec::new();
+            let mut reload_errors: Vec<String> = Vec::new();
+
+            for path in input_paths {
+                let project_path =
+                    project.read_with(cx, |project, cx| project.find_project_path(&path, cx));
+
+                let project_path = match project_path {
+                    Ok(Some(project_path)) => project_path,
+                    Ok(None) => {
+                        not_found_paths.push(path);
+                        continue;
+                    }
+                    Err(error) => {
+                        open_errors.push((path, error.to_string()));
+                        continue;
+                    }
+                };
+
+                let open_buffer_task =
+                    project.update(cx, |project, cx| project.open_buffer(project_path, cx));
+
+                let buffer = match open_buffer_task {
+                    Ok(task) => match task.await {
+                        Ok(buffer) => buffer,
+                        Err(error) => {
+                            open_errors.push((path, error.to_string()));
+                            continue;
+                        }
+                    },
+                    Err(error) => {
+                        open_errors.push((path, error.to_string()));
+                        continue;
+                    }
+                };
+
+                let is_dirty = match buffer.read_with(cx, |buffer, _| buffer.is_dirty()) {
+                    Ok(is_dirty) => is_dirty,
+                    Err(error) => {
+                        dirty_check_errors.push((path, error.to_string()));
+                        continue;
+                    }
+                };
+
+                if is_dirty {
+                    buffers_to_reload.insert(buffer);
+                    restored_paths.push(path);
+                } else {
+                    clean_paths.push(path);
+                }
+            }
+
+            if !buffers_to_reload.is_empty() {
+                let reload_task = project.update(cx, |project, cx| {
+                    project.reload_buffers(buffers_to_reload, true, cx)
+                });
+
+                match reload_task {
+                    Ok(task) => {
+                        if let Err(error) = task.await {
+                            reload_errors.push(error.to_string());
+                        }
+                    }
+                    Err(error) => {
+                        reload_errors.push(error.to_string());
+                    }
+                }
+            }
+
+            let mut lines: Vec<String> = Vec::new();
+
+            if !restored_paths.is_empty() {
+                lines.push(format!("Restored {} file(s).", restored_paths.len()));
+            }
+            if !clean_paths.is_empty() {
+                lines.push(format!("{} clean.", clean_paths.len()));
+            }
+
+            if !not_found_paths.is_empty() {
+                lines.push(format!("Not found ({}):", not_found_paths.len()));
+                for path in &not_found_paths {
+                    lines.push(format!("- {}", path.display()));
+                }
+            }
+            if !open_errors.is_empty() {
+                lines.push(format!("Open failed ({}):", open_errors.len()));
+                for (path, error) in &open_errors {
+                    lines.push(format!("- {}: {}", path.display(), error));
+                }
+            }
+            if !dirty_check_errors.is_empty() {
+                lines.push(format!(
+                    "Dirty check failed ({}):",
+                    dirty_check_errors.len()
+                ));
+                for (path, error) in &dirty_check_errors {
+                    lines.push(format!("- {}: {}", path.display(), error));
+                }
+            }
+            if !reload_errors.is_empty() {
+                lines.push(format!("Reload failed ({}):", reload_errors.len()));
+                for error in &reload_errors {
+                    lines.push(format!("- {}", error));
+                }
+            }
+
+            if lines.is_empty() {
+                Ok("No paths provided.".to_string())
+            } else {
+                Ok(lines.join("\n"))
+            }
+        })
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use fs::Fs;
+    use gpui::TestAppContext;
+    use language::LineEnding;
+    use project::FakeFs;
+    use serde_json::json;
+    use settings::SettingsStore;
+    use util::path;
+
+    fn init_test(cx: &mut TestAppContext) {
+        cx.update(|cx| {
+            let settings_store = SettingsStore::test(cx);
+            cx.set_global(settings_store);
+        });
+    }
+
+    #[gpui::test]
+    async fn test_restore_file_from_disk_output_and_effects(cx: &mut TestAppContext) {
+        init_test(cx);
+
+        let fs = FakeFs::new(cx.executor());
+        fs.insert_tree(
+            "/root",
+            json!({
+                "dirty.txt": "on disk: dirty\n",
+                "clean.txt": "on disk: clean\n",
+            }),
+        )
+        .await;
+
+        let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
+        let tool = Arc::new(RestoreFileFromDiskTool::new(project.clone()));
+
+        // Make dirty.txt dirty in-memory by saving different content into the buffer without saving to disk.
+        let dirty_project_path = project.read_with(cx, |project, cx| {
+            project
+                .find_project_path("root/dirty.txt", cx)
+                .expect("dirty.txt should exist in project")
+        });
+
+        let dirty_buffer = project
+            .update(cx, |project, cx| {
+                project.open_buffer(dirty_project_path, cx)
+            })
+            .await
+            .unwrap();
+        dirty_buffer.update(cx, |buffer, cx| {
+            buffer.edit([(0..buffer.len(), "in memory: dirty\n")], None, cx);
+        });
+        assert!(
+            dirty_buffer.read_with(cx, |buffer, _| buffer.is_dirty()),
+            "dirty.txt buffer should be dirty before restore"
+        );
+
+        // Ensure clean.txt is opened but remains clean.
+        let clean_project_path = project.read_with(cx, |project, cx| {
+            project
+                .find_project_path("root/clean.txt", cx)
+                .expect("clean.txt should exist in project")
+        });
+
+        let clean_buffer = project
+            .update(cx, |project, cx| {
+                project.open_buffer(clean_project_path, cx)
+            })
+            .await
+            .unwrap();
+        assert!(
+            !clean_buffer.read_with(cx, |buffer, _| buffer.is_dirty()),
+            "clean.txt buffer should start clean"
+        );
+
+        let output = cx
+            .update(|cx| {
+                tool.clone().run(
+                    RestoreFileFromDiskToolInput {
+                        paths: vec![
+                            PathBuf::from("root/dirty.txt"),
+                            PathBuf::from("root/clean.txt"),
+                        ],
+                    },
+                    ToolCallEventStream::test().0,
+                    cx,
+                )
+            })
+            .await
+            .unwrap();
+
+        // Output should mention restored + clean.
+        assert!(
+            output.contains("Restored 1 file(s)."),
+            "expected restored count line, got:\n{output}"
+        );
+        assert!(
+            output.contains("1 clean."),
+            "expected clean count line, got:\n{output}"
+        );
+
+        // Effect: dirty buffer should be restored back to disk content and become clean.
+        let dirty_text = dirty_buffer.read_with(cx, |buffer, _| buffer.text());
+        assert_eq!(
+            dirty_text, "on disk: dirty\n",
+            "dirty.txt buffer should be restored to disk contents"
+        );
+        assert!(
+            !dirty_buffer.read_with(cx, |buffer, _| buffer.is_dirty()),
+            "dirty.txt buffer should not be dirty after restore"
+        );
+
+        // Disk contents should be unchanged (restore-from-disk should not write).
+        let disk_dirty = fs.load(path!("/root/dirty.txt").as_ref()).await.unwrap();
+        assert_eq!(disk_dirty, "on disk: dirty\n");
+
+        // Sanity: clean buffer should remain clean and unchanged.
+        let clean_text = clean_buffer.read_with(cx, |buffer, _| buffer.text());
+        assert_eq!(clean_text, "on disk: clean\n");
+        assert!(
+            !clean_buffer.read_with(cx, |buffer, _| buffer.is_dirty()),
+            "clean.txt buffer should remain clean"
+        );
+
+        // Test empty paths case.
+        let output = cx
+            .update(|cx| {
+                tool.clone().run(
+                    RestoreFileFromDiskToolInput { paths: vec![] },
+                    ToolCallEventStream::test().0,
+                    cx,
+                )
+            })
+            .await
+            .unwrap();
+        assert_eq!(output, "No paths provided.");
+
+        // Test not-found path case (path outside the project root).
+        let output = cx
+            .update(|cx| {
+                tool.clone().run(
+                    RestoreFileFromDiskToolInput {
+                        paths: vec![PathBuf::from("nonexistent/path.txt")],
+                    },
+                    ToolCallEventStream::test().0,
+                    cx,
+                )
+            })
+            .await
+            .unwrap();
+        assert!(
+            output.contains("Not found (1):"),
+            "expected not-found header line, got:\n{output}"
+        );
+        assert!(
+            output.contains("- nonexistent/path.txt"),
+            "expected not-found path bullet, got:\n{output}"
+        );
+
+        let _ = LineEnding::Unix; // keep import used if the buffer edit API changes
+    }
+}

crates/agent/src/tools/save_file_tool.rs 🔗

@@ -0,0 +1,351 @@
+use agent_client_protocol as acp;
+use anyhow::Result;
+use collections::FxHashSet;
+use gpui::{App, Entity, SharedString, Task};
+use language::Buffer;
+use project::Project;
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+use std::path::PathBuf;
+use std::sync::Arc;
+
+use crate::{AgentTool, ToolCallEventStream};
+
+/// Saves files that have unsaved changes.
+///
+/// Use this tool when you need to edit files but they have unsaved changes that must be saved first.
+/// Only use this tool after asking the user for permission to save their unsaved changes.
+#[derive(Debug, Serialize, Deserialize, JsonSchema)]
+pub struct SaveFileToolInput {
+    /// The paths of the files to save.
+    pub paths: Vec<PathBuf>,
+}
+
+pub struct SaveFileTool {
+    project: Entity<Project>,
+}
+
+impl SaveFileTool {
+    pub fn new(project: Entity<Project>) -> Self {
+        Self { project }
+    }
+}
+
+impl AgentTool for SaveFileTool {
+    type Input = SaveFileToolInput;
+    type Output = String;
+
+    fn name() -> &'static str {
+        "save_file"
+    }
+
+    fn kind() -> acp::ToolKind {
+        acp::ToolKind::Other
+    }
+
+    fn initial_title(
+        &self,
+        input: Result<Self::Input, serde_json::Value>,
+        _cx: &mut App,
+    ) -> SharedString {
+        match input {
+            Ok(input) if input.paths.len() == 1 => "Save file".into(),
+            Ok(input) => format!("Save {} files", input.paths.len()).into(),
+            Err(_) => "Save files".into(),
+        }
+    }
+
+    fn run(
+        self: Arc<Self>,
+        input: Self::Input,
+        _event_stream: ToolCallEventStream,
+        cx: &mut App,
+    ) -> Task<Result<String>> {
+        let project = self.project.clone();
+        let input_paths = input.paths;
+
+        cx.spawn(async move |cx| {
+            let mut buffers_to_save: FxHashSet<Entity<Buffer>> = FxHashSet::default();
+
+            let mut saved_paths: Vec<PathBuf> = Vec::new();
+            let mut clean_paths: Vec<PathBuf> = Vec::new();
+            let mut not_found_paths: Vec<PathBuf> = Vec::new();
+            let mut open_errors: Vec<(PathBuf, String)> = Vec::new();
+            let mut dirty_check_errors: Vec<(PathBuf, String)> = Vec::new();
+            let mut save_errors: Vec<(String, String)> = Vec::new();
+
+            for path in input_paths {
+                let project_path =
+                    project.read_with(cx, |project, cx| project.find_project_path(&path, cx));
+
+                let project_path = match project_path {
+                    Ok(Some(project_path)) => project_path,
+                    Ok(None) => {
+                        not_found_paths.push(path);
+                        continue;
+                    }
+                    Err(error) => {
+                        open_errors.push((path, error.to_string()));
+                        continue;
+                    }
+                };
+
+                let open_buffer_task =
+                    project.update(cx, |project, cx| project.open_buffer(project_path, cx));
+
+                let buffer = match open_buffer_task {
+                    Ok(task) => match task.await {
+                        Ok(buffer) => buffer,
+                        Err(error) => {
+                            open_errors.push((path, error.to_string()));
+                            continue;
+                        }
+                    },
+                    Err(error) => {
+                        open_errors.push((path, error.to_string()));
+                        continue;
+                    }
+                };
+
+                let is_dirty = match buffer.read_with(cx, |buffer, _| buffer.is_dirty()) {
+                    Ok(is_dirty) => is_dirty,
+                    Err(error) => {
+                        dirty_check_errors.push((path, error.to_string()));
+                        continue;
+                    }
+                };
+
+                if is_dirty {
+                    buffers_to_save.insert(buffer);
+                    saved_paths.push(path);
+                } else {
+                    clean_paths.push(path);
+                }
+            }
+
+            // Save each buffer individually since there's no batch save API.
+            for buffer in buffers_to_save {
+                let path_for_buffer = match buffer.read_with(cx, |buffer, _| {
+                    buffer
+                        .file()
+                        .map(|file| file.path().to_rel_path_buf())
+                        .map(|path| path.as_rel_path().as_unix_str().to_owned())
+                }) {
+                    Ok(path) => path.unwrap_or_else(|| "<unknown>".to_string()),
+                    Err(error) => {
+                        save_errors.push(("<unknown>".to_string(), error.to_string()));
+                        continue;
+                    }
+                };
+
+                let save_task = project.update(cx, |project, cx| project.save_buffer(buffer, cx));
+
+                match save_task {
+                    Ok(task) => {
+                        if let Err(error) = task.await {
+                            save_errors.push((path_for_buffer, error.to_string()));
+                        }
+                    }
+                    Err(error) => {
+                        save_errors.push((path_for_buffer, error.to_string()));
+                    }
+                }
+            }
+
+            let mut lines: Vec<String> = Vec::new();
+
+            if !saved_paths.is_empty() {
+                lines.push(format!("Saved {} file(s).", saved_paths.len()));
+            }
+            if !clean_paths.is_empty() {
+                lines.push(format!("{} clean.", clean_paths.len()));
+            }
+
+            if !not_found_paths.is_empty() {
+                lines.push(format!("Not found ({}):", not_found_paths.len()));
+                for path in &not_found_paths {
+                    lines.push(format!("- {}", path.display()));
+                }
+            }
+            if !open_errors.is_empty() {
+                lines.push(format!("Open failed ({}):", open_errors.len()));
+                for (path, error) in &open_errors {
+                    lines.push(format!("- {}: {}", path.display(), error));
+                }
+            }
+            if !dirty_check_errors.is_empty() {
+                lines.push(format!(
+                    "Dirty check failed ({}):",
+                    dirty_check_errors.len()
+                ));
+                for (path, error) in &dirty_check_errors {
+                    lines.push(format!("- {}: {}", path.display(), error));
+                }
+            }
+            if !save_errors.is_empty() {
+                lines.push(format!("Save failed ({}):", save_errors.len()));
+                for (path, error) in &save_errors {
+                    lines.push(format!("- {}: {}", path, error));
+                }
+            }
+
+            if lines.is_empty() {
+                Ok("No paths provided.".to_string())
+            } else {
+                Ok(lines.join("\n"))
+            }
+        })
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use fs::Fs;
+    use gpui::TestAppContext;
+    use project::FakeFs;
+    use serde_json::json;
+    use settings::SettingsStore;
+    use util::path;
+
+    fn init_test(cx: &mut TestAppContext) {
+        cx.update(|cx| {
+            let settings_store = SettingsStore::test(cx);
+            cx.set_global(settings_store);
+        });
+    }
+
+    #[gpui::test]
+    async fn test_save_file_output_and_effects(cx: &mut TestAppContext) {
+        init_test(cx);
+
+        let fs = FakeFs::new(cx.executor());
+        fs.insert_tree(
+            "/root",
+            json!({
+                "dirty.txt": "on disk: dirty\n",
+                "clean.txt": "on disk: clean\n",
+            }),
+        )
+        .await;
+
+        let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
+        let tool = Arc::new(SaveFileTool::new(project.clone()));
+
+        // Make dirty.txt dirty in-memory.
+        let dirty_project_path = project.read_with(cx, |project, cx| {
+            project
+                .find_project_path("root/dirty.txt", cx)
+                .expect("dirty.txt should exist in project")
+        });
+
+        let dirty_buffer = project
+            .update(cx, |project, cx| {
+                project.open_buffer(dirty_project_path, cx)
+            })
+            .await
+            .unwrap();
+        dirty_buffer.update(cx, |buffer, cx| {
+            buffer.edit([(0..buffer.len(), "in memory: dirty\n")], None, cx);
+        });
+        assert!(
+            dirty_buffer.read_with(cx, |buffer, _| buffer.is_dirty()),
+            "dirty.txt buffer should be dirty before save"
+        );
+
+        // Ensure clean.txt is opened but remains clean.
+        let clean_project_path = project.read_with(cx, |project, cx| {
+            project
+                .find_project_path("root/clean.txt", cx)
+                .expect("clean.txt should exist in project")
+        });
+
+        let clean_buffer = project
+            .update(cx, |project, cx| {
+                project.open_buffer(clean_project_path, cx)
+            })
+            .await
+            .unwrap();
+        assert!(
+            !clean_buffer.read_with(cx, |buffer, _| buffer.is_dirty()),
+            "clean.txt buffer should start clean"
+        );
+
+        let output = cx
+            .update(|cx| {
+                tool.clone().run(
+                    SaveFileToolInput {
+                        paths: vec![
+                            PathBuf::from("root/dirty.txt"),
+                            PathBuf::from("root/clean.txt"),
+                        ],
+                    },
+                    ToolCallEventStream::test().0,
+                    cx,
+                )
+            })
+            .await
+            .unwrap();
+
+        // Output should mention saved + clean.
+        assert!(
+            output.contains("Saved 1 file(s)."),
+            "expected saved count line, got:\n{output}"
+        );
+        assert!(
+            output.contains("1 clean."),
+            "expected clean count line, got:\n{output}"
+        );
+
+        // Effect: dirty buffer should now be clean and disk should have new content.
+        assert!(
+            !dirty_buffer.read_with(cx, |buffer, _| buffer.is_dirty()),
+            "dirty.txt buffer should not be dirty after save"
+        );
+
+        let disk_dirty = fs.load(path!("/root/dirty.txt").as_ref()).await.unwrap();
+        assert_eq!(
+            disk_dirty, "in memory: dirty\n",
+            "dirty.txt disk content should be updated"
+        );
+
+        // Sanity: clean buffer should remain clean and disk unchanged.
+        let disk_clean = fs.load(path!("/root/clean.txt").as_ref()).await.unwrap();
+        assert_eq!(disk_clean, "on disk: clean\n");
+
+        // Test empty paths case.
+        let output = cx
+            .update(|cx| {
+                tool.clone().run(
+                    SaveFileToolInput { paths: vec![] },
+                    ToolCallEventStream::test().0,
+                    cx,
+                )
+            })
+            .await
+            .unwrap();
+        assert_eq!(output, "No paths provided.");
+
+        // Test not-found path case.
+        let output = cx
+            .update(|cx| {
+                tool.clone().run(
+                    SaveFileToolInput {
+                        paths: vec![PathBuf::from("nonexistent/path.txt")],
+                    },
+                    ToolCallEventStream::test().0,
+                    cx,
+                )
+            })
+            .await
+            .unwrap();
+        assert!(
+            output.contains("Not found (1):"),
+            "expected not-found header line, got:\n{output}"
+        );
+        assert!(
+            output.contains("- nonexistent/path.txt"),
+            "expected not-found path bullet, got:\n{output}"
+        );
+    }
+}

crates/agent/src/tools/terminal_tool.rs 🔗

@@ -1,6 +1,7 @@
 use agent_client_protocol as acp;
 use anyhow::Result;
-use gpui::{App, Entity, SharedString, Task};
+use futures::FutureExt as _;
+use gpui::{App, AppContext, Entity, SharedString, Task};
 use project::Project;
 use schemars::JsonSchema;
 use serde::{Deserialize, Serialize};
@@ -8,6 +9,7 @@ use std::{
     path::{Path, PathBuf},
     rc::Rc,
     sync::Arc,
+    time::Duration,
 };
 use util::markdown::MarkdownInlineCode;
 
@@ -25,13 +27,17 @@ const COMMAND_OUTPUT_LIMIT: u64 = 16 * 1024;
 ///
 /// Do not use this tool for commands that run indefinitely, such as servers (like `npm run start`, `npm run dev`, `python -m http.server`, etc) or file watchers that don't terminate on their own.
 ///
+/// For potentially long-running commands, prefer specifying `timeout_ms` to bound runtime and prevent indefinite hangs.
+///
 /// Remember that each invocation of this tool will spawn a new shell process, so you can't rely on any state from previous invocations.
 #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
 pub struct TerminalToolInput {
     /// The one-liner command to execute.
-    command: String,
+    pub command: String,
     /// Working directory for the command. This must be one of the root directories of the project.
-    cd: String,
+    pub cd: String,
+    /// Optional maximum runtime (in milliseconds). If exceeded, the running terminal task is killed.
+    pub timeout_ms: Option<u64>,
 }
 
 pub struct TerminalTool {
@@ -112,12 +118,30 @@ impl AgentTool for TerminalTool {
                 .await?;
 
             let terminal_id = terminal.id(cx)?;
-            event_stream.update_fields(acp::ToolCallUpdateFields {
-                content: Some(vec![acp::ToolCallContent::Terminal { terminal_id }]),
-                ..Default::default()
-            });
+            event_stream.update_fields(acp::ToolCallUpdateFields::new().content(vec![
+                acp::ToolCallContent::Terminal(acp::Terminal::new(terminal_id)),
+            ]));
+
+            let timeout = input.timeout_ms.map(Duration::from_millis);
+
+            let exit_status = match timeout {
+                Some(timeout) => {
+                    let wait_for_exit = terminal.wait_for_exit(cx)?;
+                    let timeout_task = cx.background_spawn(async move {
+                        smol::Timer::after(timeout).await;
+                    });
+
+                    futures::select! {
+                        status = wait_for_exit.clone().fuse() => status,
+                        _ = timeout_task.fuse() => {
+                            terminal.kill(cx)?;
+                            wait_for_exit.await
+                        }
+                    }
+                }
+                None => terminal.wait_for_exit(cx)?.await,
+            };
 
-            let exit_status = terminal.wait_for_exit(cx)?.await;
             let output = terminal.current_output(cx)?;
 
             Ok(process_content(output, &input.command, exit_status))

crates/agent/src/tools/thinking_tool.rs 🔗

@@ -43,10 +43,8 @@ impl AgentTool for ThinkingTool {
         event_stream: ToolCallEventStream,
         _cx: &mut App,
     ) -> Task<Result<String>> {
-        event_stream.update_fields(acp::ToolCallUpdateFields {
-            content: Some(vec![input.content.into()]),
-            ..Default::default()
-        });
+        event_stream
+            .update_fields(acp::ToolCallUpdateFields::new().content(vec![input.content.into()]));
         Task::ready(Ok("Finished thinking.".to_string()))
     }
 }

crates/agent/src/tools/web_search_tool.rs 🔗

@@ -76,10 +76,8 @@ impl AgentTool for WebSearchTool {
             let response = match search_task.await {
                 Ok(response) => response,
                 Err(err) => {
-                    event_stream.update_fields(acp::ToolCallUpdateFields {
-                        title: Some("Web Search Failed".to_string()),
-                        ..Default::default()
-                    });
+                    event_stream
+                        .update_fields(acp::ToolCallUpdateFields::new().title("Web Search Failed"));
                     return Err(err);
                 }
             };
@@ -107,26 +105,23 @@ fn emit_update(response: &WebSearchResponse, event_stream: &ToolCallEventStream)
     } else {
         format!("{} results", response.results.len())
     };
-    event_stream.update_fields(acp::ToolCallUpdateFields {
-        title: Some(format!("Searched the web: {result_text}")),
-        content: Some(
-            response
-                .results
-                .iter()
-                .map(|result| acp::ToolCallContent::Content {
-                    content: acp::ContentBlock::ResourceLink(acp::ResourceLink {
-                        name: result.title.clone(),
-                        uri: result.url.clone(),
-                        title: Some(result.title.clone()),
-                        description: Some(result.text.clone()),
-                        mime_type: None,
-                        annotations: None,
-                        size: None,
-                        meta: None,
-                    }),
-                })
-                .collect(),
-        ),
-        ..Default::default()
-    });
+    event_stream.update_fields(
+        acp::ToolCallUpdateFields::new()
+            .title(format!("Searched the web: {result_text}"))
+            .content(
+                response
+                    .results
+                    .iter()
+                    .map(|result| {
+                        acp::ToolCallContent::Content(acp::Content::new(
+                            acp::ContentBlock::ResourceLink(
+                                acp::ResourceLink::new(result.title.clone(), result.url.clone())
+                                    .title(result.title.clone())
+                                    .description(result.text.clone()),
+                            ),
+                        ))
+                    })
+                    .collect::<Vec<_>>(),
+            ),
+    );
 }

crates/agent_servers/src/acp.rs 🔗

@@ -9,6 +9,8 @@ use futures::io::BufReader;
 use project::Project;
 use project::agent_server_store::AgentServerCommand;
 use serde::Deserialize;
+use settings::Settings as _;
+use task::ShellBuilder;
 use util::ResultExt as _;
 
 use std::path::PathBuf;
@@ -21,7 +23,7 @@ use gpui::{App, AppContext as _, AsyncApp, Entity, SharedString, Task, WeakEntit
 
 use acp_thread::{AcpThread, AuthRequired, LoadError, TerminalProviderEvent};
 use terminal::TerminalBuilder;
-use terminal::terminal_settings::{AlternateScroll, CursorShape};
+use terminal::terminal_settings::{AlternateScroll, CursorShape, TerminalSettings};
 
 #[derive(Debug, Error)]
 #[error("Unsupported version")]
@@ -29,7 +31,7 @@ pub struct UnsupportedVersion;
 
 pub struct AcpConnection {
     server_name: SharedString,
-    telemetry_id: &'static str,
+    telemetry_id: SharedString,
     connection: Rc<acp::ClientSideConnection>,
     sessions: Rc<RefCell<HashMap<acp::SessionId, AcpSession>>>,
     auth_methods: Vec<acp::AuthMethod>,
@@ -54,7 +56,6 @@ pub struct AcpSession {
 
 pub async fn connect(
     server_name: SharedString,
-    telemetry_id: &'static str,
     command: AgentServerCommand,
     root_dir: &Path,
     default_mode: Option<acp::SessionModeId>,
@@ -64,7 +65,6 @@ pub async fn connect(
 ) -> Result<Rc<dyn AgentConnection>> {
     let conn = AcpConnection::stdio(
         server_name,
-        telemetry_id,
         command.clone(),
         root_dir,
         default_mode,
@@ -76,12 +76,11 @@ pub async fn connect(
     Ok(Rc::new(conn) as _)
 }
 
-const MINIMUM_SUPPORTED_VERSION: acp::ProtocolVersion = acp::V1;
+const MINIMUM_SUPPORTED_VERSION: acp::ProtocolVersion = acp::ProtocolVersion::V1;
 
 impl AcpConnection {
     pub async fn stdio(
         server_name: SharedString,
-        telemetry_id: &'static str,
         command: AgentServerCommand,
         root_dir: &Path,
         default_mode: Option<acp::SessionModeId>,
@@ -89,9 +88,11 @@ impl AcpConnection {
         is_remote: bool,
         cx: &mut AsyncApp,
     ) -> Result<Self> {
-        let mut child = util::command::new_smol_command(&command.path);
+        let shell = cx.update(|cx| TerminalSettings::get(None, cx).shell.clone())?;
+        let builder = ShellBuilder::new(&shell, cfg!(windows)).non_interactive();
+        let mut child =
+            builder.build_command(Some(command.path.display().to_string()), &command.args);
         child
-            .args(command.args.iter().map(|arg| arg.as_str()))
             .envs(command.env.iter().flatten())
             .stdin(std::process::Stdio::piped())
             .stdout(std::process::Stdio::piped())
@@ -174,34 +175,38 @@ impl AcpConnection {
         })?;
 
         let response = connection
-            .initialize(acp::InitializeRequest {
-                protocol_version: acp::VERSION,
-                client_capabilities: acp::ClientCapabilities {
-                    fs: acp::FileSystemCapability {
-                        read_text_file: true,
-                        write_text_file: true,
-                        meta: None,
-                    },
-                    terminal: true,
-                    meta: Some(serde_json::json!({
-                        // Experimental: Allow for rendering terminal output from the agents
-                        "terminal_output": true,
-                        "terminal-auth": true,
-                    })),
-                },
-                client_info: Some(acp::Implementation {
-                    name: "zed".to_owned(),
-                    title: release_channel.map(|c| c.to_owned()),
-                    version,
-                }),
-                meta: None,
-            })
+            .initialize(
+                acp::InitializeRequest::new(acp::ProtocolVersion::V1)
+                    .client_capabilities(
+                        acp::ClientCapabilities::new()
+                            .fs(acp::FileSystemCapability::new()
+                                .read_text_file(true)
+                                .write_text_file(true))
+                            .terminal(true)
+                            // Experimental: Allow for rendering terminal output from the agents
+                            .meta(acp::Meta::from_iter([
+                                ("terminal_output".into(), true.into()),
+                                ("terminal-auth".into(), true.into()),
+                            ])),
+                    )
+                    .client_info(
+                        acp::Implementation::new("zed", version)
+                            .title(release_channel.map(ToOwned::to_owned)),
+                    ),
+            )
             .await?;
 
         if response.protocol_version < MINIMUM_SUPPORTED_VERSION {
             return Err(UnsupportedVersion.into());
         }
 
+        let telemetry_id = response
+            .agent_info
+            // Use the one the agent provides if we have one
+            .map(|info| info.name.into())
+            // Otherwise, just use the name
+            .unwrap_or_else(|| server_name.clone());
+
         Ok(Self {
             auth_methods: response.auth_methods,
             root_dir: root_dir.to_owned(),
@@ -236,8 +241,8 @@ impl Drop for AcpConnection {
 }
 
 impl AgentConnection for AcpConnection {
-    fn telemetry_id(&self) -> &'static str {
-        self.telemetry_id
+    fn telemetry_id(&self) -> SharedString {
+        self.telemetry_id.clone()
     }
 
     fn new_thread(
@@ -253,14 +258,13 @@ impl AgentConnection for AcpConnection {
         let default_model = self.default_model.clone();
         let cwd = cwd.to_path_buf();
         let context_server_store = project.read(cx).context_server_store().read(cx);
-        let mcp_servers =
-            if project.read(cx).is_local() {
-                context_server_store
-                    .configured_server_ids()
-                    .iter()
-                    .filter_map(|id| {
-                        let configuration = context_server_store.configuration_for_server(id)?;
-                        match &*configuration {
+        let mcp_servers = if project.read(cx).is_local() {
+            context_server_store
+                .configured_server_ids()
+                .iter()
+                .filter_map(|id| {
+                    let configuration = context_server_store.configuration_for_server(id)?;
+                    match &*configuration {
                         project::context_server_store::ContextServerConfiguration::Custom {
                             command,
                             ..
@@ -268,53 +272,47 @@ impl AgentConnection for AcpConnection {
                         | project::context_server_store::ContextServerConfiguration::Extension {
                             command,
                             ..
-                        } => Some(acp::McpServer::Stdio {
-                            name: id.0.to_string(),
-                            command: command.path.clone(),
-                            args: command.args.clone(),
-                            env: if let Some(env) = command.env.as_ref() {
-                                env.iter()
-                                    .map(|(name, value)| acp::EnvVariable {
-                                        name: name.clone(),
-                                        value: value.clone(),
-                                        meta: None,
-                                    })
-                                    .collect()
-                            } else {
-                                vec![]
-                            },
-                        }),
+                        } => Some(acp::McpServer::Stdio(
+                            acp::McpServerStdio::new(id.0.to_string(), &command.path)
+                                .args(command.args.clone())
+                                .env(if let Some(env) = command.env.as_ref() {
+                                    env.iter()
+                                        .map(|(name, value)| acp::EnvVariable::new(name, value))
+                                        .collect()
+                                } else {
+                                    vec![]
+                                }),
+                        )),
                         project::context_server_store::ContextServerConfiguration::Http {
                             url,
                             headers,
-                        } => Some(acp::McpServer::Http {
-                            name: id.0.to_string(),
-                            url: url.to_string(),
-                            headers: headers.iter().map(|(name, value)| acp::HttpHeader {
-                                name: name.clone(),
-                                value: value.clone(),
-                                meta: None,
-                            }).collect(),
-                        }),
+                        } => Some(acp::McpServer::Http(
+                            acp::McpServerHttp::new(id.0.to_string(), url.to_string()).headers(
+                                headers
+                                    .iter()
+                                    .map(|(name, value)| acp::HttpHeader::new(name, value))
+                                    .collect(),
+                            ),
+                        )),
                     }
-                    })
-                    .collect()
-            } else {
-                // In SSH projects, the external agent is running on the remote
-                // machine, and currently we only run MCP servers on the local
-                // machine. So don't pass any MCP servers to the agent in that case.
-                Vec::new()
-            };
+                })
+                .collect()
+        } else {
+            // In SSH projects, the external agent is running on the remote
+            // machine, and currently we only run MCP servers on the local
+            // machine. So don't pass any MCP servers to the agent in that case.
+            Vec::new()
+        };
 
         cx.spawn(async move |cx| {
             let response = conn
-                .new_session(acp::NewSessionRequest { mcp_servers, cwd, meta: None })
+                .new_session(acp::NewSessionRequest::new(cwd).mcp_servers(mcp_servers))
                 .await
                 .map_err(|err| {
-                    if err.code == acp::ErrorCode::AUTH_REQUIRED.code {
+                    if err.code == acp::ErrorCode::AuthRequired {
                         let mut error = AuthRequired::new();
 
-                        if err.message != acp::ErrorCode::AUTH_REQUIRED.message {
+                        if err.message != acp::ErrorCode::AuthRequired.to_string() {
                             error = error.with_description(err.message);
                         }
 
@@ -341,11 +339,7 @@ impl AgentConnection for AcpConnection {
                             let modes = modes.clone();
                             let conn = conn.clone();
                             async move |_| {
-                                let result = conn.set_session_mode(acp::SetSessionModeRequest {
-                                    session_id,
-                                    mode_id: default_mode,
-                                    meta: None,
-                                })
+                                let result = conn.set_session_mode(acp::SetSessionModeRequest::new(session_id, default_mode))
                                 .await.log_err();
 
                                 if result.is_none() {
@@ -388,11 +382,7 @@ impl AgentConnection for AcpConnection {
                             let models = models.clone();
                             let conn = conn.clone();
                             async move |_| {
-                                let result = conn.set_session_model(acp::SetSessionModelRequest {
-                                    session_id,
-                                    model_id: default_model,
-                                    meta: None,
-                                })
+                                let result = conn.set_session_model(acp::SetSessionModelRequest::new(session_id, default_model))
                                 .await.log_err();
 
                                 if result.is_none() {
@@ -456,12 +446,8 @@ impl AgentConnection for AcpConnection {
     fn authenticate(&self, method_id: acp::AuthMethodId, cx: &mut App) -> Task<Result<()>> {
         let conn = self.connection.clone();
         cx.foreground_executor().spawn(async move {
-            conn.authenticate(acp::AuthenticateRequest {
-                method_id: method_id.clone(),
-                meta: None,
-            })
-            .await?;
-
+            conn.authenticate(acp::AuthenticateRequest::new(method_id))
+                .await?;
             Ok(())
         })
     }
@@ -488,11 +474,11 @@ impl AgentConnection for AcpConnection {
             match result {
                 Ok(response) => Ok(response),
                 Err(err) => {
-                    if err.code == acp::ErrorCode::AUTH_REQUIRED.code {
+                    if err.code == acp::ErrorCode::AuthRequired {
                         return Err(anyhow!(acp::Error::auth_required()));
                     }
 
-                    if err.code != ErrorCode::INTERNAL_ERROR.code {
+                    if err.code != ErrorCode::InternalError {
                         anyhow::bail!(err)
                     }
 
@@ -515,10 +501,7 @@ impl AgentConnection for AcpConnection {
                                 && (details.contains("This operation was aborted")
                                     || details.contains("The user aborted a request"))
                             {
-                                Ok(acp::PromptResponse {
-                                    stop_reason: acp::StopReason::Cancelled,
-                                    meta: None,
-                                })
+                                Ok(acp::PromptResponse::new(acp::StopReason::Cancelled))
                             } else {
                                 Err(anyhow!(details))
                             }
@@ -535,10 +518,7 @@ impl AgentConnection for AcpConnection {
             session.suppress_abort_err = true;
         }
         let conn = self.connection.clone();
-        let params = acp::CancelNotification {
-            session_id: session_id.clone(),
-            meta: None,
-        };
+        let params = acp::CancelNotification::new(session_id.clone());
         cx.foreground_executor()
             .spawn(async move { conn.cancel(params).await })
             .detach();
@@ -619,11 +599,7 @@ impl acp_thread::AgentSessionModes for AcpSessionModes {
         let state = self.state.clone();
         cx.foreground_executor().spawn(async move {
             let result = connection
-                .set_session_mode(acp::SetSessionModeRequest {
-                    session_id,
-                    mode_id,
-                    meta: None,
-                })
+                .set_session_mode(acp::SetSessionModeRequest::new(session_id, mode_id))
                 .await;
 
             if result.is_err() {
@@ -682,11 +658,7 @@ impl acp_thread::AgentModelSelector for AcpModelSelector {
         let state = self.state.clone();
         cx.foreground_executor().spawn(async move {
             let result = connection
-                .set_session_model(acp::SetSessionModelRequest {
-                    session_id,
-                    model_id,
-                    meta: None,
-                })
+                .set_session_model(acp::SetSessionModelRequest::new(session_id, model_id))
                 .await;
 
             if result.is_err() {
@@ -748,10 +720,7 @@ impl acp::Client for ClientDelegate {
 
         let outcome = task.await;
 
-        Ok(acp::RequestPermissionResponse {
-            outcome,
-            meta: None,
-        })
+        Ok(acp::RequestPermissionResponse::new(outcome))
     }
 
     async fn write_text_file(
@@ -783,10 +752,7 @@ impl acp::Client for ClientDelegate {
 
         let content = task.await?;
 
-        Ok(acp::ReadTextFileResponse {
-            content,
-            meta: None,
-        })
+        Ok(acp::ReadTextFileResponse::new(content))
     }
 
     async fn session_notification(
@@ -821,7 +787,7 @@ impl acp::Client for ClientDelegate {
                 if let Some(terminal_info) = meta.get("terminal_info") {
                     if let Some(id_str) = terminal_info.get("terminal_id").and_then(|v| v.as_str())
                     {
-                        let terminal_id = acp::TerminalId(id_str.into());
+                        let terminal_id = acp::TerminalId::new(id_str);
                         let cwd = terminal_info
                             .get("cwd")
                             .and_then(|v| v.as_str().map(PathBuf::from));
@@ -837,7 +803,7 @@ impl acp::Client for ClientDelegate {
                             let lower = cx.new(|cx| builder.subscribe(cx));
                             thread.on_terminal_provider_event(
                                 TerminalProviderEvent::Created {
-                                    terminal_id: terminal_id.clone(),
+                                    terminal_id,
                                     label: tc.title.clone(),
                                     cwd,
                                     output_byte_limit: None,
@@ -862,15 +828,12 @@ impl acp::Client for ClientDelegate {
             if let Some(meta) = &tcu.meta {
                 if let Some(term_out) = meta.get("terminal_output") {
                     if let Some(id_str) = term_out.get("terminal_id").and_then(|v| v.as_str()) {
-                        let terminal_id = acp::TerminalId(id_str.into());
+                        let terminal_id = acp::TerminalId::new(id_str);
                         if let Some(s) = term_out.get("data").and_then(|v| v.as_str()) {
                             let data = s.as_bytes().to_vec();
                             let _ = session.thread.update(&mut self.cx.clone(), |thread, cx| {
                                 thread.on_terminal_provider_event(
-                                    TerminalProviderEvent::Output {
-                                        terminal_id: terminal_id.clone(),
-                                        data,
-                                    },
+                                    TerminalProviderEvent::Output { terminal_id, data },
                                     cx,
                                 );
                             });
@@ -881,21 +844,24 @@ impl acp::Client for ClientDelegate {
                 // terminal_exit
                 if let Some(term_exit) = meta.get("terminal_exit") {
                     if let Some(id_str) = term_exit.get("terminal_id").and_then(|v| v.as_str()) {
-                        let terminal_id = acp::TerminalId(id_str.into());
-                        let status = acp::TerminalExitStatus {
-                            exit_code: term_exit
-                                .get("exit_code")
-                                .and_then(|v| v.as_u64())
-                                .map(|i| i as u32),
-                            signal: term_exit
-                                .get("signal")
-                                .and_then(|v| v.as_str().map(|s| s.to_string())),
-                            meta: None,
-                        };
+                        let terminal_id = acp::TerminalId::new(id_str);
+                        let status = acp::TerminalExitStatus::new()
+                            .exit_code(
+                                term_exit
+                                    .get("exit_code")
+                                    .and_then(|v| v.as_u64())
+                                    .map(|i| i as u32),
+                            )
+                            .signal(
+                                term_exit
+                                    .get("signal")
+                                    .and_then(|v| v.as_str().map(|s| s.to_string())),
+                            );
+
                         let _ = session.thread.update(&mut self.cx.clone(), |thread, cx| {
                             thread.on_terminal_provider_event(
                                 TerminalProviderEvent::Exit {
-                                    terminal_id: terminal_id.clone(),
+                                    terminal_id,
                                     status,
                                 },
                                 cx,
@@ -932,7 +898,7 @@ impl acp::Client for ClientDelegate {
         // Register with renderer
         let terminal_entity = thread.update(&mut self.cx.clone(), |thread, cx| {
             thread.register_terminal_created(
-                acp::TerminalId(uuid::Uuid::new_v4().to_string().into()),
+                acp::TerminalId::new(uuid::Uuid::new_v4().to_string()),
                 format!("{} {}", args.command, args.args.join(" ")),
                 args.cwd.clone(),
                 args.output_byte_limit,
@@ -942,10 +908,7 @@ impl acp::Client for ClientDelegate {
         })?;
         let terminal_id =
             terminal_entity.read_with(&self.cx, |terminal, _| terminal.id().clone())?;
-        Ok(acp::CreateTerminalResponse {
-            terminal_id,
-            meta: None,
-        })
+        Ok(acp::CreateTerminalResponse::new(terminal_id))
     }
 
     async fn kill_terminal_command(
@@ -1006,10 +969,7 @@ impl acp::Client for ClientDelegate {
             })??
             .await;
 
-        Ok(acp::WaitForTerminalExitResponse {
-            exit_status,
-            meta: None,
-        })
+        Ok(acp::WaitForTerminalExitResponse::new(exit_status))
     }
 }
 

crates/agent_servers/src/agent_servers.rs 🔗

@@ -4,6 +4,8 @@ mod codex;
 mod custom;
 mod gemini;
 
+use collections::HashSet;
+
 #[cfg(any(test, feature = "test-support"))]
 pub mod e2e_tests;
 
@@ -56,10 +58,19 @@ impl AgentServerDelegate {
 pub trait AgentServer: Send {
     fn logo(&self) -> ui::IconName;
     fn name(&self) -> SharedString;
-    fn telemetry_id(&self) -> &'static str;
+    fn connect(
+        &self,
+        root_dir: Option<&Path>,
+        delegate: AgentServerDelegate,
+        cx: &mut App,
+    ) -> Task<Result<(Rc<dyn AgentConnection>, Option<task::SpawnInTerminal>)>>;
+
+    fn into_any(self: Rc<Self>) -> Rc<dyn Any>;
+
     fn default_mode(&self, _cx: &mut App) -> Option<agent_client_protocol::SessionModeId> {
         None
     }
+
     fn set_default_mode(
         &self,
         _mode_id: Option<agent_client_protocol::SessionModeId>,
@@ -80,14 +91,18 @@ pub trait AgentServer: Send {
     ) {
     }
 
-    fn connect(
-        &self,
-        root_dir: Option<&Path>,
-        delegate: AgentServerDelegate,
-        cx: &mut App,
-    ) -> Task<Result<(Rc<dyn AgentConnection>, Option<task::SpawnInTerminal>)>>;
+    fn favorite_model_ids(&self, _cx: &mut App) -> HashSet<agent_client_protocol::ModelId> {
+        HashSet::default()
+    }
 
-    fn into_any(self: Rc<Self>) -> Rc<dyn Any>;
+    fn toggle_favorite_model(
+        &self,
+        _model_id: agent_client_protocol::ModelId,
+        _should_be_favorite: bool,
+        _fs: Arc<dyn Fs>,
+        _cx: &App,
+    ) {
+    }
 }
 
 impl dyn AgentServer {

crates/agent_servers/src/claude.rs 🔗

@@ -1,4 +1,5 @@
 use agent_client_protocol as acp;
+use collections::HashSet;
 use fs::Fs;
 use settings::{SettingsStore, update_settings_file};
 use std::path::Path;
@@ -22,10 +23,6 @@ pub struct AgentServerLoginCommand {
 }
 
 impl AgentServer for ClaudeCode {
-    fn telemetry_id(&self) -> &'static str {
-        "claude-code"
-    }
-
     fn name(&self) -> SharedString {
         "Claude Code".into()
     }
@@ -41,7 +38,7 @@ impl AgentServer for ClaudeCode {
 
         settings
             .as_ref()
-            .and_then(|s| s.default_mode.clone().map(|m| acp::SessionModeId(m.into())))
+            .and_then(|s| s.default_mode.clone().map(acp::SessionModeId::new))
     }
 
     fn set_default_mode(&self, mode_id: Option<acp::SessionModeId>, fs: Arc<dyn Fs>, cx: &mut App) {
@@ -62,7 +59,7 @@ impl AgentServer for ClaudeCode {
 
         settings
             .as_ref()
-            .and_then(|s| s.default_model.clone().map(|m| acp::ModelId(m.into())))
+            .and_then(|s| s.default_model.clone().map(acp::ModelId::new))
     }
 
     fn set_default_model(&self, model_id: Option<acp::ModelId>, fs: Arc<dyn Fs>, cx: &mut App) {
@@ -76,6 +73,48 @@ impl AgentServer for ClaudeCode {
         });
     }
 
+    fn favorite_model_ids(&self, cx: &mut App) -> HashSet<acp::ModelId> {
+        let settings = cx.read_global(|settings: &SettingsStore, _| {
+            settings.get::<AllAgentServersSettings>(None).claude.clone()
+        });
+
+        settings
+            .as_ref()
+            .map(|s| {
+                s.favorite_models
+                    .iter()
+                    .map(|id| acp::ModelId::new(id.clone()))
+                    .collect()
+            })
+            .unwrap_or_default()
+    }
+
+    fn toggle_favorite_model(
+        &self,
+        model_id: acp::ModelId,
+        should_be_favorite: bool,
+        fs: Arc<dyn Fs>,
+        cx: &App,
+    ) {
+        update_settings_file(fs, cx, move |settings, _| {
+            let favorite_models = &mut settings
+                .agent_servers
+                .get_or_insert_default()
+                .claude
+                .get_or_insert_default()
+                .favorite_models;
+
+            let model_id_str = model_id.to_string();
+            if should_be_favorite {
+                if !favorite_models.contains(&model_id_str) {
+                    favorite_models.push(model_id_str);
+                }
+            } else {
+                favorite_models.retain(|id| id != &model_id_str);
+            }
+        });
+    }
+
     fn connect(
         &self,
         root_dir: Option<&Path>,
@@ -83,7 +122,6 @@ impl AgentServer for ClaudeCode {
         cx: &mut App,
     ) -> Task<Result<(Rc<dyn AgentConnection>, Option<task::SpawnInTerminal>)>> {
         let name = self.name();
-        let telemetry_id = self.telemetry_id();
         let root_dir = root_dir.map(|root_dir| root_dir.to_string_lossy().into_owned());
         let is_remote = delegate.project.read(cx).is_via_remote_server();
         let store = delegate.store.downgrade();
@@ -108,7 +146,6 @@ impl AgentServer for ClaudeCode {
                 .await?;
             let connection = crate::acp::connect(
                 name,
-                telemetry_id,
                 command,
                 root_dir.as_ref(),
                 default_mode,

crates/agent_servers/src/codex.rs 🔗

@@ -5,6 +5,7 @@ use std::{any::Any, path::Path};
 use acp_thread::AgentConnection;
 use agent_client_protocol as acp;
 use anyhow::{Context as _, Result};
+use collections::HashSet;
 use fs::Fs;
 use gpui::{App, AppContext as _, SharedString, Task};
 use project::agent_server_store::{AllAgentServersSettings, CODEX_NAME};
@@ -23,10 +24,6 @@ pub(crate) mod tests {
 }
 
 impl AgentServer for Codex {
-    fn telemetry_id(&self) -> &'static str {
-        "codex"
-    }
-
     fn name(&self) -> SharedString {
         "Codex".into()
     }
@@ -42,7 +39,7 @@ impl AgentServer for Codex {
 
         settings
             .as_ref()
-            .and_then(|s| s.default_mode.clone().map(|m| acp::SessionModeId(m.into())))
+            .and_then(|s| s.default_mode.clone().map(acp::SessionModeId::new))
     }
 
     fn set_default_mode(&self, mode_id: Option<acp::SessionModeId>, fs: Arc<dyn Fs>, cx: &mut App) {
@@ -63,7 +60,7 @@ impl AgentServer for Codex {
 
         settings
             .as_ref()
-            .and_then(|s| s.default_model.clone().map(|m| acp::ModelId(m.into())))
+            .and_then(|s| s.default_model.clone().map(acp::ModelId::new))
     }
 
     fn set_default_model(&self, model_id: Option<acp::ModelId>, fs: Arc<dyn Fs>, cx: &mut App) {
@@ -77,6 +74,48 @@ impl AgentServer for Codex {
         });
     }
 
+    fn favorite_model_ids(&self, cx: &mut App) -> HashSet<acp::ModelId> {
+        let settings = cx.read_global(|settings: &SettingsStore, _| {
+            settings.get::<AllAgentServersSettings>(None).codex.clone()
+        });
+
+        settings
+            .as_ref()
+            .map(|s| {
+                s.favorite_models
+                    .iter()
+                    .map(|id| acp::ModelId::new(id.clone()))
+                    .collect()
+            })
+            .unwrap_or_default()
+    }
+
+    fn toggle_favorite_model(
+        &self,
+        model_id: acp::ModelId,
+        should_be_favorite: bool,
+        fs: Arc<dyn Fs>,
+        cx: &App,
+    ) {
+        update_settings_file(fs, cx, move |settings, _| {
+            let favorite_models = &mut settings
+                .agent_servers
+                .get_or_insert_default()
+                .codex
+                .get_or_insert_default()
+                .favorite_models;
+
+            let model_id_str = model_id.to_string();
+            if should_be_favorite {
+                if !favorite_models.contains(&model_id_str) {
+                    favorite_models.push(model_id_str);
+                }
+            } else {
+                favorite_models.retain(|id| id != &model_id_str);
+            }
+        });
+    }
+
     fn connect(
         &self,
         root_dir: Option<&Path>,
@@ -84,7 +123,6 @@ impl AgentServer for Codex {
         cx: &mut App,
     ) -> Task<Result<(Rc<dyn AgentConnection>, Option<task::SpawnInTerminal>)>> {
         let name = self.name();
-        let telemetry_id = self.telemetry_id();
         let root_dir = root_dir.map(|root_dir| root_dir.to_string_lossy().into_owned());
         let is_remote = delegate.project.read(cx).is_via_remote_server();
         let store = delegate.store.downgrade();
@@ -110,7 +148,6 @@ impl AgentServer for Codex {
 
             let connection = crate::acp::connect(
                 name,
-                telemetry_id,
                 command,
                 root_dir.as_ref(),
                 default_mode,

crates/agent_servers/src/custom.rs 🔗

@@ -1,7 +1,8 @@
-use crate::{AgentServerDelegate, load_proxy_env};
+use crate::{AgentServer, AgentServerDelegate, load_proxy_env};
 use acp_thread::AgentConnection;
 use agent_client_protocol as acp;
 use anyhow::{Context as _, Result};
+use collections::HashSet;
 use fs::Fs;
 use gpui::{App, AppContext as _, SharedString, Task};
 use project::agent_server_store::{AllAgentServersSettings, ExternalAgentServerName};
@@ -20,11 +21,7 @@ impl CustomAgentServer {
     }
 }
 
-impl crate::AgentServer for CustomAgentServer {
-    fn telemetry_id(&self) -> &'static str {
-        "custom"
-    }
-
+impl AgentServer for CustomAgentServer {
     fn name(&self) -> SharedString {
         self.name.clone()
     }
@@ -44,7 +41,7 @@ impl crate::AgentServer for CustomAgentServer {
 
         settings
             .as_ref()
-            .and_then(|s| s.default_mode().map(|m| acp::SessionModeId(m.into())))
+            .and_then(|s| s.default_mode().map(acp::SessionModeId::new))
     }
 
     fn set_default_mode(&self, mode_id: Option<acp::SessionModeId>, fs: Arc<dyn Fs>, cx: &mut App) {
@@ -58,6 +55,7 @@ impl crate::AgentServer for CustomAgentServer {
                 .or_insert_with(|| settings::CustomAgentServerSettings::Extension {
                     default_model: None,
                     default_mode: None,
+                    favorite_models: Vec::new(),
                 });
 
             match settings {
@@ -80,7 +78,7 @@ impl crate::AgentServer for CustomAgentServer {
 
         settings
             .as_ref()
-            .and_then(|s| s.default_model().map(|m| acp::ModelId(m.into())))
+            .and_then(|s| s.default_model().map(acp::ModelId::new))
     }
 
     fn set_default_model(&self, model_id: Option<acp::ModelId>, fs: Arc<dyn Fs>, cx: &mut App) {
@@ -94,6 +92,7 @@ impl crate::AgentServer for CustomAgentServer {
                 .or_insert_with(|| settings::CustomAgentServerSettings::Extension {
                     default_model: None,
                     default_mode: None,
+                    favorite_models: Vec::new(),
                 });
 
             match settings {
@@ -105,6 +104,66 @@ impl crate::AgentServer for CustomAgentServer {
         });
     }
 
+    fn favorite_model_ids(&self, cx: &mut App) -> HashSet<acp::ModelId> {
+        let settings = cx.read_global(|settings: &SettingsStore, _| {
+            settings
+                .get::<AllAgentServersSettings>(None)
+                .custom
+                .get(&self.name())
+                .cloned()
+        });
+
+        settings
+            .as_ref()
+            .map(|s| {
+                s.favorite_models()
+                    .iter()
+                    .map(|id| acp::ModelId::new(id.clone()))
+                    .collect()
+            })
+            .unwrap_or_default()
+    }
+
+    fn toggle_favorite_model(
+        &self,
+        model_id: acp::ModelId,
+        should_be_favorite: bool,
+        fs: Arc<dyn Fs>,
+        cx: &App,
+    ) {
+        let name = self.name();
+        update_settings_file(fs, cx, move |settings, _| {
+            let settings = settings
+                .agent_servers
+                .get_or_insert_default()
+                .custom
+                .entry(name.clone())
+                .or_insert_with(|| settings::CustomAgentServerSettings::Extension {
+                    default_model: None,
+                    default_mode: None,
+                    favorite_models: Vec::new(),
+                });
+
+            let favorite_models = match settings {
+                settings::CustomAgentServerSettings::Custom {
+                    favorite_models, ..
+                }
+                | settings::CustomAgentServerSettings::Extension {
+                    favorite_models, ..
+                } => favorite_models,
+            };
+
+            let model_id_str = model_id.to_string();
+            if should_be_favorite {
+                if !favorite_models.contains(&model_id_str) {
+                    favorite_models.push(model_id_str);
+                }
+            } else {
+                favorite_models.retain(|id| id != &model_id_str);
+            }
+        });
+    }
+
     fn connect(
         &self,
         root_dir: Option<&Path>,
@@ -112,14 +171,12 @@ impl crate::AgentServer for CustomAgentServer {
         cx: &mut App,
     ) -> Task<Result<(Rc<dyn AgentConnection>, Option<task::SpawnInTerminal>)>> {
         let name = self.name();
-        let telemetry_id = self.telemetry_id();
         let root_dir = root_dir.map(|root_dir| root_dir.to_string_lossy().into_owned());
         let is_remote = delegate.project.read(cx).is_via_remote_server();
         let default_mode = self.default_mode(cx);
         let default_model = self.default_model(cx);
         let store = delegate.store.downgrade();
         let extra_env = load_proxy_env(cx);
-
         cx.spawn(async move |cx| {
             let (command, root_dir, login) = store
                 .update(cx, |store, cx| {
@@ -139,7 +196,6 @@ impl crate::AgentServer for CustomAgentServer {
                 .await?;
             let connection = crate::acp::connect(
                 name,
-                telemetry_id,
                 command,
                 root_dir.as_ref(),
                 default_mode,

crates/agent_servers/src/e2e_tests.rs 🔗

@@ -82,26 +82,9 @@ where
         .update(cx, |thread, cx| {
             thread.send(
                 vec![
-                    acp::ContentBlock::Text(acp::TextContent {
-                        text: "Read the file ".into(),
-                        annotations: None,
-                        meta: None,
-                    }),
-                    acp::ContentBlock::ResourceLink(acp::ResourceLink {
-                        uri: "foo.rs".into(),
-                        name: "foo.rs".into(),
-                        annotations: None,
-                        description: None,
-                        mime_type: None,
-                        size: None,
-                        title: None,
-                        meta: None,
-                    }),
-                    acp::ContentBlock::Text(acp::TextContent {
-                        text: " and tell me what the content of the println! is".into(),
-                        annotations: None,
-                        meta: None,
-                    }),
+                    "Read the file ".into(),
+                    acp::ContentBlock::ResourceLink(acp::ResourceLink::new("foo.rs", "foo.rs")),
+                    " and tell me what the content of the println! is".into(),
                 ],
                 cx,
             )
@@ -429,7 +412,7 @@ macro_rules! common_e2e_tests {
             async fn tool_call_with_permission(cx: &mut ::gpui::TestAppContext) {
                 $crate::e2e_tests::test_tool_call_with_permission(
                     $server,
-                    ::agent_client_protocol::PermissionOptionId($allow_option_id.into()),
+                    ::agent_client_protocol::PermissionOptionId::new($allow_option_id),
                     cx,
                 )
                 .await;
@@ -477,6 +460,7 @@ pub async fn init_test(cx: &mut TestAppContext) -> Arc<FakeFs> {
                     ignore_system_version: None,
                     default_mode: None,
                     default_model: None,
+                    favorite_models: vec![],
                 }),
                 gemini: Some(crate::gemini::tests::local_command().into()),
                 codex: Some(BuiltinAgentServerSettings {
@@ -486,6 +470,7 @@ pub async fn init_test(cx: &mut TestAppContext) -> Arc<FakeFs> {
                     ignore_system_version: None,
                     default_mode: None,
                     default_model: None,
+                    favorite_models: vec![],
                 }),
                 custom: collections::HashMap::default(),
             },

crates/agent_servers/src/gemini.rs 🔗

@@ -12,10 +12,6 @@ use project::agent_server_store::GEMINI_NAME;
 pub struct Gemini;
 
 impl AgentServer for Gemini {
-    fn telemetry_id(&self) -> &'static str {
-        "gemini-cli"
-    }
-
     fn name(&self) -> SharedString {
         "Gemini CLI".into()
     }
@@ -31,7 +27,6 @@ impl AgentServer for Gemini {
         cx: &mut App,
     ) -> Task<Result<(Rc<dyn AgentConnection>, Option<task::SpawnInTerminal>)>> {
         let name = self.name();
-        let telemetry_id = self.telemetry_id();
         let root_dir = root_dir.map(|root_dir| root_dir.to_string_lossy().into_owned());
         let is_remote = delegate.project.read(cx).is_via_remote_server();
         let store = delegate.store.downgrade();
@@ -66,7 +61,6 @@ impl AgentServer for Gemini {
 
             let connection = crate::acp::connect(
                 name,
-                telemetry_id,
                 command,
                 root_dir.as_ref(),
                 default_mode,

crates/agent_settings/Cargo.toml 🔗

@@ -12,6 +12,7 @@ workspace = true
 path = "src/agent_settings.rs"
 
 [dependencies]
+agent-client-protocol.workspace = true
 anyhow.workspace = true
 cloud_llm_client.workspace = true
 collections.workspace = true

crates/agent_settings/src/agent_settings.rs 🔗

@@ -2,14 +2,15 @@ mod agent_profile;
 
 use std::sync::Arc;
 
-use collections::IndexMap;
+use agent_client_protocol::ModelId;
+use collections::{HashSet, IndexMap};
 use gpui::{App, Pixels, px};
 use language_model::LanguageModel;
 use project::DisableAiSettings;
 use schemars::JsonSchema;
 use serde::{Deserialize, Serialize};
 use settings::{
-    DefaultAgentView, DockPosition, LanguageModelParameters, LanguageModelSelection,
+    DefaultAgentView, DockPosition, DockSide, LanguageModelParameters, LanguageModelSelection,
     NotifyWhenAgentWaiting, RegisterSetting, Settings,
 };
 
@@ -24,13 +25,16 @@ pub struct AgentSettings {
     pub enabled: bool,
     pub button: bool,
     pub dock: DockPosition,
+    pub agents_panel_dock: DockSide,
     pub default_width: Pixels,
     pub default_height: Pixels,
     pub default_model: Option<LanguageModelSelection>,
     pub inline_assistant_model: Option<LanguageModelSelection>,
+    pub inline_assistant_use_streaming_tools: bool,
     pub commit_message_model: Option<LanguageModelSelection>,
     pub thread_summary_model: Option<LanguageModelSelection>,
     pub inline_alternatives: Vec<LanguageModelSelection>,
+    pub favorite_models: Vec<LanguageModelSelection>,
     pub default_profile: AgentProfileId,
     pub default_view: DefaultAgentView,
     pub profiles: IndexMap<AgentProfileId, AgentProfileSettings>,
@@ -94,6 +98,13 @@ impl AgentSettings {
     pub fn set_message_editor_max_lines(&self) -> usize {
         self.message_editor_min_lines * 2
     }
+
+    pub fn favorite_model_ids(&self) -> HashSet<ModelId> {
+        self.favorite_models
+            .iter()
+            .map(|sel| ModelId::new(format!("{}/{}", sel.provider.0, sel.model)))
+            .collect()
+    }
 }
 
 #[derive(Clone, Copy, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Default)]
@@ -151,13 +162,18 @@ impl Settings for AgentSettings {
             enabled: agent.enabled.unwrap(),
             button: agent.button.unwrap(),
             dock: agent.dock.unwrap(),
+            agents_panel_dock: agent.agents_panel_dock.unwrap(),
             default_width: px(agent.default_width.unwrap()),
             default_height: px(agent.default_height.unwrap()),
             default_model: Some(agent.default_model.unwrap()),
             inline_assistant_model: agent.inline_assistant_model,
+            inline_assistant_use_streaming_tools: agent
+                .inline_assistant_use_streaming_tools
+                .unwrap_or(true),
             commit_message_model: agent.commit_message_model,
             thread_summary_model: agent.thread_summary_model,
             inline_alternatives: agent.inline_alternatives.unwrap_or_default(),
+            favorite_models: agent.favorite_models,
             default_profile: AgentProfileId(agent.default_profile.unwrap()),
             default_view: agent.default_view.unwrap(),
             profiles: agent

crates/agent_ui/Cargo.toml 🔗

@@ -13,7 +13,8 @@ path = "src/agent_ui.rs"
 doctest = false
 
 [features]
-test-support = ["gpui/test-support", "language/test-support"]
+test-support = ["assistant_text_thread/test-support", "eval_utils", "gpui/test-support", "language/test-support", "reqwest_client", "workspace/test-support", "agent/test-support"]
+unit-eval = []
 
 [dependencies]
 acp_thread.workspace = true
@@ -39,6 +40,7 @@ component.workspace = true
 context_server.workspace = true
 db.workspace = true
 editor.workspace = true
+eval_utils = { workspace = true, optional = true }
 extension.workspace = true
 extension_host.workspace = true
 feature_flags.workspace = true
@@ -47,6 +49,7 @@ fs.workspace = true
 futures.workspace = true
 fuzzy.workspace = true
 gpui.workspace = true
+gpui_tokio.workspace = true
 html_to_markdown.workspace = true
 http_client.workspace = true
 indoc.workspace = true
@@ -69,6 +72,7 @@ postage.workspace = true
 project.workspace = true
 prompt_store.workspace = true
 proto.workspace = true
+rand.workspace = true
 release_channel.workspace = true
 rope.workspace = true
 rules_library.workspace = true
@@ -82,7 +86,6 @@ smol.workspace = true
 streaming_diff.workspace = true
 task.workspace = true
 telemetry.workspace = true
-telemetry_events.workspace = true
 terminal.workspace = true
 terminal_view.workspace = true
 text.workspace = true
@@ -93,19 +96,23 @@ ui.workspace = true
 ui_input.workspace = true
 url.workspace = true
 util.workspace = true
+uuid.workspace = true
 watch.workspace = true
 workspace.workspace = true
 zed_actions.workspace = true
 image.workspace = true
 async-fs.workspace = true
+reqwest_client = { workspace = true, optional = true }
 
 [dev-dependencies]
 acp_thread = { workspace = true, features = ["test-support"] }
 agent = { workspace = true, features = ["test-support"] }
 assistant_text_thread = { workspace = true, features = ["test-support"] }
 buffer_diff = { workspace = true, features = ["test-support"] }
+clock.workspace = true
 db = { workspace = true, features = ["test-support"] }
 editor = { workspace = true, features = ["test-support"] }
+eval_utils.workspace = true
 gpui = { workspace = true, "features" = ["test-support"] }
 indoc.workspace = true
 language = { workspace = true, "features" = ["test-support"] }
@@ -114,6 +121,6 @@ language_model = { workspace = true, "features" = ["test-support"] }
 pretty_assertions.workspace = true
 project = { workspace = true, features = ["test-support"] }
 semver.workspace = true
-rand.workspace = true
+reqwest_client.workspace = true
 tree-sitter-md.workspace = true
 unindent.workspace = true

crates/agent_ui/src/acp/entry_view_state.rs 🔗

@@ -22,7 +22,7 @@ use crate::acp::message_editor::{MessageEditor, MessageEditorEvent};
 
 pub struct EntryViewState {
     workspace: WeakEntity<Workspace>,
-    project: Entity<Project>,
+    project: WeakEntity<Project>,
     history_store: Entity<HistoryStore>,
     prompt_store: Option<Entity<PromptStore>>,
     entries: Vec<Entry>,
@@ -34,7 +34,7 @@ pub struct EntryViewState {
 impl EntryViewState {
     pub fn new(
         workspace: WeakEntity<Workspace>,
-        project: Entity<Project>,
+        project: WeakEntity<Project>,
         history_store: Entity<HistoryStore>,
         prompt_store: Option<Entity<PromptStore>>,
         prompt_capabilities: Rc<RefCell<acp::PromptCapabilities>>,
@@ -328,7 +328,7 @@ impl Entry {
 
 fn create_terminal(
     workspace: WeakEntity<Workspace>,
-    project: Entity<Project>,
+    project: WeakEntity<Project>,
     terminal: Entity<acp_thread::Terminal>,
     window: &mut Window,
     cx: &mut App,
@@ -336,9 +336,9 @@ fn create_terminal(
     cx.new(|cx| {
         let mut view = TerminalView::new(
             terminal.read(cx).inner().clone(),
-            workspace.clone(),
+            workspace,
             None,
-            project.downgrade(),
+            project,
             window,
             cx,
         );
@@ -432,24 +432,11 @@ mod tests {
         let (workspace, cx) =
             cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
 
-        let tool_call = acp::ToolCall {
-            id: acp::ToolCallId("tool".into()),
-            title: "Tool call".into(),
-            kind: acp::ToolKind::Other,
-            status: acp::ToolCallStatus::InProgress,
-            content: vec![acp::ToolCallContent::Diff {
-                diff: acp::Diff {
-                    path: "/project/hello.txt".into(),
-                    old_text: Some("hi world".into()),
-                    new_text: "hello world".into(),
-                    meta: None,
-                },
-            }],
-            locations: vec![],
-            raw_input: None,
-            raw_output: None,
-            meta: None,
-        };
+        let tool_call = acp::ToolCall::new("tool", "Tool call")
+            .status(acp::ToolCallStatus::InProgress)
+            .content(vec![acp::ToolCallContent::Diff(
+                acp::Diff::new("/project/hello.txt", "hello world").old_text("hi world"),
+            )]);
         let connection = Rc::new(StubAgentConnection::new());
         let thread = cx
             .update(|_, cx| {
@@ -471,7 +458,7 @@ mod tests {
         let view_state = cx.new(|_cx| {
             EntryViewState::new(
                 workspace.downgrade(),
-                project.clone(),
+                project.downgrade(),
                 history_store,
                 None,
                 Default::default(),

crates/agent_ui/src/acp/message_editor.rs 🔗

@@ -21,8 +21,8 @@ use editor::{
 };
 use futures::{FutureExt as _, future::join_all};
 use gpui::{
-    AppContext, Context, Entity, EventEmitter, FocusHandle, Focusable, ImageFormat, KeyContext,
-    SharedString, Subscription, Task, TextStyle, WeakEntity,
+    AppContext, ClipboardEntry, Context, Entity, EventEmitter, FocusHandle, Focusable, ImageFormat,
+    KeyContext, SharedString, Subscription, Task, TextStyle, WeakEntity,
 };
 use language::{Buffer, Language, language_settings::InlayHintKind};
 use project::{CompletionIntent, InlayHint, InlayHintLabel, InlayId, Project, Worktree};
@@ -31,15 +31,14 @@ use rope::Point;
 use settings::Settings;
 use std::{cell::RefCell, fmt::Write, rc::Rc, sync::Arc};
 use theme::ThemeSettings;
-use ui::prelude::*;
+use ui::{ContextMenu, prelude::*};
 use util::{ResultExt, debug_panic};
 use workspace::{CollaboratorId, Workspace};
-use zed_actions::agent::Chat;
+use zed_actions::agent::{Chat, PasteRaw};
 
 pub struct MessageEditor {
     mention_set: Entity<MentionSet>,
     editor: Entity<Editor>,
-    project: Entity<Project>,
     workspace: WeakEntity<Workspace>,
     prompt_capabilities: Rc<RefCell<acp::PromptCapabilities>>,
     available_commands: Rc<RefCell<Vec<acp::AvailableCommand>>>,
@@ -98,7 +97,7 @@ impl PromptCompletionProviderDelegate for Entity<MessageEditor> {
 impl MessageEditor {
     pub fn new(
         workspace: WeakEntity<Workspace>,
-        project: Entity<Project>,
+        project: WeakEntity<Project>,
         history_store: Entity<HistoryStore>,
         prompt_store: Option<Entity<PromptStore>>,
         prompt_capabilities: Rc<RefCell<acp::PromptCapabilities>>,
@@ -124,6 +123,7 @@ impl MessageEditor {
             let mut editor = Editor::new(mode, buffer, None, window, cx);
             editor.set_placeholder_text(placeholder, window, cx);
             editor.set_show_indent_guides(false, cx);
+            editor.set_show_completions_on_input(Some(true));
             editor.set_soft_wrap();
             editor.set_use_modal_editing(true);
             editor.set_context_menu_options(ContextMenuOptions {
@@ -132,15 +132,25 @@ impl MessageEditor {
                 placement: Some(ContextMenuPlacement::Above),
             });
             editor.register_addon(MessageEditorAddon::new());
+
+            editor.set_custom_context_menu(|editor, _point, window, cx| {
+                let has_selection = editor.has_non_empty_selection(&editor.display_snapshot(cx));
+
+                Some(ContextMenu::build(window, cx, |menu, _, _| {
+                    menu.action("Cut", Box::new(editor::actions::Cut))
+                        .action_disabled_when(
+                            !has_selection,
+                            "Copy",
+                            Box::new(editor::actions::Copy),
+                        )
+                        .action("Paste", Box::new(editor::actions::Paste))
+                }))
+            });
+
             editor
         });
-        let mention_set = cx.new(|_cx| {
-            MentionSet::new(
-                project.downgrade(),
-                history_store.clone(),
-                prompt_store.clone(),
-            )
-        });
+        let mention_set =
+            cx.new(|_cx| MentionSet::new(project, history_store.clone(), prompt_store.clone()));
         let completion_provider = Rc::new(PromptCompletionProvider::new(
             cx.entity(),
             editor.downgrade(),
@@ -198,7 +208,6 @@ impl MessageEditor {
 
         Self {
             editor,
-            project,
             mention_set,
             workspace,
             prompt_capabilities,
@@ -225,8 +234,13 @@ impl MessageEditor {
             .iter()
             .find(|command| command.name == command_name)?;
 
-        let acp::AvailableCommandInput::Unstructured { mut hint } =
-            available_command.input.clone()?;
+        let acp::AvailableCommandInput::Unstructured(acp::UnstructuredCommandInput {
+            mut hint,
+            ..
+        }) = available_command.input.clone()?
+        else {
+            return None;
+        };
 
         let mut hint_pos = MultiBufferOffset(parsed_command.source_range.end) + 1usize;
         if hint_pos > snapshot.len() {
@@ -403,34 +417,27 @@ impl MessageEditor {
                             } => {
                                 all_tracked_buffers.extend(tracked_buffers.iter().cloned());
                                 if supports_embedded_context {
-                                    acp::ContentBlock::Resource(acp::EmbeddedResource {
-                                        annotations: None,
-                                        resource:
-                                            acp::EmbeddedResourceResource::TextResourceContents(
-                                                acp::TextResourceContents {
-                                                    mime_type: None,
-                                                    text: content.clone(),
-                                                    uri: uri.to_uri().to_string(),
-                                                    meta: None,
-                                                },
+                                    acp::ContentBlock::Resource(acp::EmbeddedResource::new(
+                                        acp::EmbeddedResourceResource::TextResourceContents(
+                                            acp::TextResourceContents::new(
+                                                content.clone(),
+                                                uri.to_uri().to_string(),
                                             ),
-                                        meta: None,
-                                    })
+                                        ),
+                                    ))
                                 } else {
-                                    acp::ContentBlock::ResourceLink(acp::ResourceLink {
-                                        name: uri.name(),
-                                        uri: uri.to_uri().to_string(),
-                                        annotations: None,
-                                        description: None,
-                                        mime_type: None,
-                                        size: None,
-                                        title: None,
-                                        meta: None,
-                                    })
+                                    acp::ContentBlock::ResourceLink(acp::ResourceLink::new(
+                                        uri.name(),
+                                        uri.to_uri().to_string(),
+                                    ))
                                 }
                             }
-                            Mention::Image(mention_image) => {
-                                let uri = match uri {
+                            Mention::Image(mention_image) => acp::ContentBlock::Image(
+                                acp::ImageContent::new(
+                                    mention_image.data.clone(),
+                                    mention_image.format.mime_type(),
+                                )
+                                .uri(match uri {
                                     MentionUri::File { .. } => Some(uri.to_uri().to_string()),
                                     MentionUri::PastedImage => None,
                                     other => {
@@ -440,25 +447,11 @@ impl MessageEditor {
                                         );
                                         None
                                     }
-                                };
-                                acp::ContentBlock::Image(acp::ImageContent {
-                                    annotations: None,
-                                    data: mention_image.data.to_string(),
-                                    mime_type: mention_image.format.mime_type().into(),
-                                    uri,
-                                    meta: None,
-                                })
-                            }
-                            Mention::Link => acp::ContentBlock::ResourceLink(acp::ResourceLink {
-                                name: uri.name(),
-                                uri: uri.to_uri().to_string(),
-                                annotations: None,
-                                description: None,
-                                mime_type: None,
-                                size: None,
-                                title: None,
-                                meta: None,
-                            }),
+                                }),
+                            ),
+                            Mention::Link => acp::ContentBlock::ResourceLink(
+                                acp::ResourceLink::new(uri.name(), uri.to_uri().to_string()),
+                            ),
                         };
                         chunks.push(chunk);
                         ix = crease_range.end.0;
@@ -565,6 +558,142 @@ impl MessageEditor {
     }
 
     fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
+        let Some(workspace) = self.workspace.upgrade() else {
+            return;
+        };
+        let editor_clipboard_selections = cx
+            .read_from_clipboard()
+            .and_then(|item| item.entries().first().cloned())
+            .and_then(|entry| match entry {
+                ClipboardEntry::String(text) => {
+                    text.metadata_json::<Vec<editor::ClipboardSelection>>()
+                }
+                _ => None,
+            });
+
+        // Insert creases for pasted clipboard selections that:
+        // 1. Contain exactly one selection
+        // 2. Have an associated file path
+        // 3. Span multiple lines (not single-line selections)
+        // 4. Belong to a file that exists in the current project
+        let should_insert_creases = util::maybe!({
+            let selections = editor_clipboard_selections.as_ref()?;
+            if selections.len() > 1 {
+                return Some(false);
+            }
+            let selection = selections.first()?;
+            let file_path = selection.file_path.as_ref()?;
+            let line_range = selection.line_range.as_ref()?;
+
+            if line_range.start() == line_range.end() {
+                return Some(false);
+            }
+
+            Some(
+                workspace
+                    .read(cx)
+                    .project()
+                    .read(cx)
+                    .project_path_for_absolute_path(file_path, cx)
+                    .is_some(),
+            )
+        })
+        .unwrap_or(false);
+
+        if should_insert_creases && let Some(selections) = editor_clipboard_selections {
+            cx.stop_propagation();
+            let insertion_target = self
+                .editor
+                .read(cx)
+                .selections
+                .newest_anchor()
+                .start
+                .text_anchor;
+
+            let project = workspace.read(cx).project().clone();
+            for selection in selections {
+                if let (Some(file_path), Some(line_range)) =
+                    (selection.file_path, selection.line_range)
+                {
+                    let crease_text =
+                        acp_thread::selection_name(Some(file_path.as_ref()), &line_range);
+
+                    let mention_uri = MentionUri::Selection {
+                        abs_path: Some(file_path.clone()),
+                        line_range: line_range.clone(),
+                    };
+
+                    let mention_text = mention_uri.as_link().to_string();
+                    let (excerpt_id, text_anchor, content_len) =
+                        self.editor.update(cx, |editor, cx| {
+                            let buffer = editor.buffer().read(cx);
+                            let snapshot = buffer.snapshot(cx);
+                            let (excerpt_id, _, buffer_snapshot) = snapshot.as_singleton().unwrap();
+                            let text_anchor = insertion_target.bias_left(&buffer_snapshot);
+
+                            editor.insert(&mention_text, window, cx);
+                            editor.insert(" ", window, cx);
+
+                            (*excerpt_id, text_anchor, mention_text.len())
+                        });
+
+                    let Some((crease_id, tx)) = insert_crease_for_mention(
+                        excerpt_id,
+                        text_anchor,
+                        content_len,
+                        crease_text.into(),
+                        mention_uri.icon_path(cx),
+                        None,
+                        self.editor.clone(),
+                        window,
+                        cx,
+                    ) else {
+                        continue;
+                    };
+                    drop(tx);
+
+                    let mention_task = cx
+                        .spawn({
+                            let project = project.clone();
+                            async move |_, cx| {
+                                let project_path = project
+                                    .update(cx, |project, cx| {
+                                        project.project_path_for_absolute_path(&file_path, cx)
+                                    })
+                                    .map_err(|e| e.to_string())?
+                                    .ok_or_else(|| "project path not found".to_string())?;
+
+                                let buffer = project
+                                    .update(cx, |project, cx| project.open_buffer(project_path, cx))
+                                    .map_err(|e| e.to_string())?
+                                    .await
+                                    .map_err(|e| e.to_string())?;
+
+                                buffer
+                                    .update(cx, |buffer, cx| {
+                                        let start = Point::new(*line_range.start(), 0)
+                                            .min(buffer.max_point());
+                                        let end = Point::new(*line_range.end() + 1, 0)
+                                            .min(buffer.max_point());
+                                        let content = buffer.text_for_range(start..end).collect();
+                                        Mention::Text {
+                                            content,
+                                            tracked_buffers: vec![cx.entity()],
+                                        }
+                                    })
+                                    .map_err(|e| e.to_string())
+                            }
+                        })
+                        .shared();
+
+                    self.mention_set.update(cx, |mention_set, _cx| {
+                        mention_set.insert_mention(crease_id, mention_uri.clone(), mention_task)
+                    });
+                }
+            }
+            return;
+        }
+
         if self.prompt_capabilities.borrow().image
             && let Some(task) =
                 paste_images_as_context(self.editor.clone(), self.mention_set.clone(), window, cx)
@@ -573,6 +702,13 @@ impl MessageEditor {
         }
     }
 
+    fn paste_raw(&mut self, _: &PasteRaw, window: &mut Window, cx: &mut Context<Self>) {
+        let editor = self.editor.clone();
+        window.defer(cx, move |window, cx| {
+            editor.update(cx, |editor, cx| editor.paste(&Paste, window, cx));
+        });
+    }
+
     pub fn insert_dragged_files(
         &mut self,
         paths: Vec<project::ProjectPath>,
@@ -583,17 +719,18 @@ impl MessageEditor {
         let Some(workspace) = self.workspace.upgrade() else {
             return;
         };
-        let path_style = self.project.read(cx).path_style(cx);
+        let project = workspace.read(cx).project().clone();
+        let path_style = project.read(cx).path_style(cx);
         let buffer = self.editor.read(cx).buffer().clone();
         let Some(buffer) = buffer.read(cx).as_singleton() else {
             return;
         };
         let mut tasks = Vec::new();
         for path in paths {
-            let Some(entry) = self.project.read(cx).entry_for_path(&path, cx) else {
+            let Some(entry) = project.read(cx).entry_for_path(&path, cx) else {
                 continue;
             };
-            let Some(worktree) = self.project.read(cx).worktree_for_id(path.worktree_id, cx) else {
+            let Some(worktree) = project.read(cx).worktree_for_id(path.worktree_id, cx) else {
                 continue;
             };
             let abs_path = worktree.read(cx).absolutize(&path.path);
@@ -701,9 +838,13 @@ impl MessageEditor {
         window: &mut Window,
         cx: &mut Context<Self>,
     ) {
+        let Some(workspace) = self.workspace.upgrade() else {
+            return;
+        };
+
         self.clear(window, cx);
 
-        let path_style = self.project.read(cx).path_style(cx);
+        let path_style = workspace.read(cx).project().read(cx).path_style(cx);
         let mut text = String::new();
         let mut mentions = Vec::new();
 
@@ -746,8 +887,7 @@ impl MessageEditor {
                     uri,
                     data,
                     mime_type,
-                    annotations: _,
-                    meta: _,
+                    ..
                 }) => {
                     let mention_uri = if let Some(uri) = uri {
                         MentionUri::parse(&uri, path_style)
@@ -773,7 +913,7 @@ impl MessageEditor {
                         }),
                     ));
                 }
-                acp::ContentBlock::Audio(_) | acp::ContentBlock::Resource(_) => {}
+                _ => {}
             }
         }
 
@@ -846,6 +986,7 @@ impl Render for MessageEditor {
             .on_action(cx.listener(Self::chat))
             .on_action(cx.listener(Self::chat_with_follow))
             .on_action(cx.listener(Self::cancel))
+            .on_action(cx.listener(Self::paste_raw))
             .capture_action(cx.listener(Self::paste))
             .flex_1()
             .child({
@@ -947,7 +1088,7 @@ mod tests {
             cx.new(|cx| {
                 MessageEditor::new(
                     workspace.downgrade(),
-                    project.clone(),
+                    project.downgrade(),
                     history_store.clone(),
                     None,
                     Default::default(),
@@ -1058,7 +1199,7 @@ mod tests {
             cx.new(|cx| {
                 MessageEditor::new(
                     workspace_handle.clone(),
-                    project.clone(),
+                    project.downgrade(),
                     history_store.clone(),
                     None,
                     prompt_capabilities.clone(),
@@ -1092,12 +1233,7 @@ mod tests {
         assert!(error_message.contains("Available commands: none"));
 
         // Now simulate Claude providing its list of available commands (which doesn't include file)
-        available_commands.replace(vec![acp::AvailableCommand {
-            name: "help".to_string(),
-            description: "Get help".to_string(),
-            input: None,
-            meta: None,
-        }]);
+        available_commands.replace(vec![acp::AvailableCommand::new("help", "Get help")]);
 
         // Test that unsupported slash commands trigger an error when we have a list of available commands
         editor.update_in(cx, |editor, window, cx| {
@@ -1211,20 +1347,12 @@ mod tests {
         let history_store = cx.new(|cx| HistoryStore::new(text_thread_store, cx));
         let prompt_capabilities = Rc::new(RefCell::new(acp::PromptCapabilities::default()));
         let available_commands = Rc::new(RefCell::new(vec![
-            acp::AvailableCommand {
-                name: "quick-math".to_string(),
-                description: "2 + 2 = 4 - 1 = 3".to_string(),
-                input: None,
-                meta: None,
-            },
-            acp::AvailableCommand {
-                name: "say-hello".to_string(),
-                description: "Say hello to whoever you want".to_string(),
-                input: Some(acp::AvailableCommandInput::Unstructured {
-                    hint: "<name>".to_string(),
-                }),
-                meta: None,
-            },
+            acp::AvailableCommand::new("quick-math", "2 + 2 = 4 - 1 = 3"),
+            acp::AvailableCommand::new("say-hello", "Say hello to whoever you want").input(
+                acp::AvailableCommandInput::Unstructured(acp::UnstructuredCommandInput::new(
+                    "<name>",
+                )),
+            ),
         ]));
 
         let editor = workspace.update_in(&mut cx, |workspace, window, cx| {
@@ -1232,7 +1360,7 @@ mod tests {
             let message_editor = cx.new(|cx| {
                 MessageEditor::new(
                     workspace_handle,
-                    project.clone(),
+                    project.downgrade(),
                     history_store.clone(),
                     None,
                     prompt_capabilities.clone(),
@@ -1257,7 +1385,7 @@ mod tests {
                     cx,
                 );
             });
-            message_editor.read(cx).focus_handle(cx).focus(window);
+            message_editor.read(cx).focus_handle(cx).focus(window, cx);
             message_editor.read(cx).editor().clone()
         });
 
@@ -1454,7 +1582,7 @@ mod tests {
             let message_editor = cx.new(|cx| {
                 MessageEditor::new(
                     workspace_handle,
-                    project.clone(),
+                    project.downgrade(),
                     history_store.clone(),
                     None,
                     prompt_capabilities.clone(),
@@ -1479,7 +1607,7 @@ mod tests {
                     cx,
                 );
             });
-            message_editor.read(cx).focus_handle(cx).focus(window);
+            message_editor.read(cx).focus_handle(cx).focus(window, cx);
             let editor = message_editor.read(cx).editor().clone();
             (message_editor, editor)
         });
@@ -1504,12 +1632,12 @@ mod tests {
             editor.set_text("", window, cx);
         });
 
-        prompt_capabilities.replace(acp::PromptCapabilities {
-            image: true,
-            audio: true,
-            embedded_context: true,
-            meta: None,
-        });
+        prompt_capabilities.replace(
+            acp::PromptCapabilities::new()
+                .image(true)
+                .audio(true)
+                .embedded_context(true),
+        );
 
         cx.simulate_input("Lorem ");
 
@@ -1945,7 +2073,7 @@ mod tests {
             cx.new(|cx| {
                 let editor = MessageEditor::new(
                     workspace.downgrade(),
-                    project.clone(),
+                    project.downgrade(),
                     history_store.clone(),
                     None,
                     Default::default(),
@@ -1960,11 +2088,9 @@ mod tests {
                     cx,
                 );
                 // Enable embedded context so files are actually included
-                editor.prompt_capabilities.replace(acp::PromptCapabilities {
-                    embedded_context: true,
-                    meta: None,
-                    ..Default::default()
-                });
+                editor
+                    .prompt_capabilities
+                    .replace(acp::PromptCapabilities::new().embedded_context(true));
                 editor
             })
         });
@@ -2043,7 +2169,7 @@ mod tests {
 
         // Create a thread metadata to insert as summary
         let thread_metadata = agent::DbThreadMetadata {
-            id: acp::SessionId("thread-123".into()),
+            id: acp::SessionId::new("thread-123"),
             title: "Previous Conversation".into(),
             updated_at: chrono::Utc::now(),
         };
@@ -2052,7 +2178,7 @@ mod tests {
             cx.new(|cx| {
                 let mut editor = MessageEditor::new(
                     workspace.downgrade(),
-                    project.clone(),
+                    project.downgrade(),
                     history_store.clone(),
                     None,
                     Default::default(),
@@ -2121,7 +2247,7 @@ mod tests {
             cx.new(|cx| {
                 MessageEditor::new(
                     workspace.downgrade(),
-                    project.clone(),
+                    project.downgrade(),
                     history_store.clone(),
                     None,
                     Default::default(),
@@ -2150,14 +2276,7 @@ mod tests {
             .await
             .unwrap();
 
-        assert_eq!(
-            content,
-            vec![acp::ContentBlock::Text(acp::TextContent {
-                text: "してhello world".into(),
-                annotations: None,
-                meta: None
-            })]
-        );
+        assert_eq!(content, vec!["してhello world".into()]);
     }
 
     #[gpui::test]
@@ -2191,7 +2310,7 @@ mod tests {
             let message_editor = cx.new(|cx| {
                 MessageEditor::new(
                     workspace_handle,
-                    project.clone(),
+                    project.downgrade(),
                     history_store.clone(),
                     None,
                     Default::default(),
@@ -2216,7 +2335,7 @@ mod tests {
                     cx,
                 );
             });
-            message_editor.read(cx).focus_handle(cx).focus(window);
+            message_editor.read(cx).focus_handle(cx).focus(window, cx);
             let editor = message_editor.read(cx).editor().clone();
             (message_editor, editor)
         });
@@ -2236,38 +2355,24 @@ mod tests {
             .0;
 
         let main_rs_uri = if cfg!(windows) {
-            "file:///C:/project/src/main.rs".to_string()
+            "file:///C:/project/src/main.rs"
         } else {
-            "file:///project/src/main.rs".to_string()
+            "file:///project/src/main.rs"
         };
 
         // When embedded context is `false` we should get a resource link
         pretty_assertions::assert_eq!(
             content,
             vec![
-                acp::ContentBlock::Text(acp::TextContent {
-                    text: "What is in ".to_string(),
-                    annotations: None,
-                    meta: None
-                }),
-                acp::ContentBlock::ResourceLink(acp::ResourceLink {
-                    uri: main_rs_uri.clone(),
-                    name: "main.rs".to_string(),
-                    annotations: None,
-                    meta: None,
-                    description: None,
-                    mime_type: None,
-                    size: None,
-                    title: None,
-                })
+                "What is in ".into(),
+                acp::ContentBlock::ResourceLink(acp::ResourceLink::new("main.rs", main_rs_uri))
             ]
         );
 
         message_editor.update(cx, |editor, _cx| {
-            editor.prompt_capabilities.replace(acp::PromptCapabilities {
-                embedded_context: true,
-                ..Default::default()
-            })
+            editor
+                .prompt_capabilities
+                .replace(acp::PromptCapabilities::new().embedded_context(true))
         });
 
         let content = message_editor
@@ -2280,23 +2385,12 @@ mod tests {
         pretty_assertions::assert_eq!(
             content,
             vec![
-                acp::ContentBlock::Text(acp::TextContent {
-                    text: "What is in ".to_string(),
-                    annotations: None,
-                    meta: None
-                }),
-                acp::ContentBlock::Resource(acp::EmbeddedResource {
-                    resource: acp::EmbeddedResourceResource::TextResourceContents(
-                        acp::TextResourceContents {
-                            text: file_content.to_string(),
-                            uri: main_rs_uri,
-                            mime_type: None,
-                            meta: None
-                        }
-                    ),
-                    annotations: None,
-                    meta: None
-                })
+                "What is in ".into(),
+                acp::ContentBlock::Resource(acp::EmbeddedResource::new(
+                    acp::EmbeddedResourceResource::TextResourceContents(
+                        acp::TextResourceContents::new(file_content, main_rs_uri)
+                    )
+                ))
             ]
         );
     }
@@ -2374,7 +2468,7 @@ mod tests {
             let message_editor = cx.new(|cx| {
                 MessageEditor::new(
                     workspace_handle,
-                    project.clone(),
+                    project.downgrade(),
                     history_store.clone(),
                     None,
                     Default::default(),

crates/agent_ui/src/acp/mode_selector.rs 🔗

@@ -161,7 +161,7 @@ impl Render for ModeSelector {
             .map(|mode| mode.name.clone())
             .unwrap_or_else(|| "Unknown".into());
 
-        let this = cx.entity();
+        let this = cx.weak_entity();
 
         let icon = if self.menu_handle.is_deployed() {
             IconName::ChevronUp
@@ -188,25 +188,25 @@ impl Render for ModeSelector {
                             .gap_1()
                             .child(
                                 h_flex()
-                                    .pb_1()
                                     .gap_2()
                                     .justify_between()
-                                    .border_b_1()
-                                    .border_color(cx.theme().colors().border_variant)
-                                    .child(Label::new("Cycle Through Modes"))
+                                    .child(Label::new("Toggle Mode Menu"))
                                     .child(KeyBinding::for_action_in(
-                                        &CycleModeSelector,
+                                        &ToggleProfileSelector,
                                         &focus_handle,
                                         cx,
                                     )),
                             )
                             .child(
                                 h_flex()
+                                    .pb_1()
                                     .gap_2()
                                     .justify_between()
-                                    .child(Label::new("Toggle Mode Menu"))
+                                    .border_b_1()
+                                    .border_color(cx.theme().colors().border_variant)
+                                    .child(Label::new("Cycle Through Modes"))
                                     .child(KeyBinding::for_action_in(
-                                        &ToggleProfileSelector,
+                                        &CycleModeSelector,
                                         &focus_handle,
                                         cx,
                                     )),
@@ -222,7 +222,8 @@ impl Render for ModeSelector {
                 y: px(-2.0),
             })
             .menu(move |window, cx| {
-                Some(this.update(cx, |this, cx| this.build_context_menu(window, cx)))
+                this.update(cx, |this, cx| this.build_context_menu(window, cx))
+                    .ok()
             })
     }
 }

crates/agent_ui/src/acp/model_selector.rs 🔗

@@ -1,25 +1,26 @@
 use std::{cmp::Reverse, rc::Rc, sync::Arc};
 
-use acp_thread::{AgentModelInfo, AgentModelList, AgentModelSelector};
+use acp_thread::{AgentModelIcon, AgentModelInfo, AgentModelList, AgentModelSelector};
+use agent_client_protocol::ModelId;
 use agent_servers::AgentServer;
 use anyhow::Result;
-use collections::IndexMap;
+use collections::{HashSet, IndexMap};
 use fs::Fs;
 use futures::FutureExt;
 use fuzzy::{StringMatchCandidate, match_strings};
 use gpui::{
-    Action, AsyncWindowContext, BackgroundExecutor, DismissEvent, FocusHandle, Task, WeakEntity,
+    Action, AsyncWindowContext, BackgroundExecutor, DismissEvent, FocusHandle, Subscription, Task,
+    WeakEntity,
 };
+use itertools::Itertools;
 use ordered_float::OrderedFloat;
 use picker::{Picker, PickerDelegate};
-use ui::{
-    DocumentationAside, DocumentationEdge, DocumentationSide, IntoElement, KeyBinding, ListItem,
-    ListItemSpacing, prelude::*,
-};
+use settings::SettingsStore;
+use ui::{DocumentationAside, DocumentationEdge, DocumentationSide, IntoElement, prelude::*};
 use util::ResultExt;
 use zed_actions::agent::OpenSettings;
 
-use crate::ui::HoldForDefault;
+use crate::ui::{HoldForDefault, ModelSelectorFooter, ModelSelectorHeader, ModelSelectorListItem};
 
 pub type AcpModelSelector = Picker<AcpModelPickerDelegate>;
 
@@ -41,7 +42,7 @@ pub fn acp_model_selector(
 
 enum AcpModelPickerEntry {
     Separator(SharedString),
-    Model(AgentModelInfo),
+    Model(AgentModelInfo, bool),
 }
 
 pub struct AcpModelPickerDelegate {
@@ -53,7 +54,9 @@ pub struct AcpModelPickerDelegate {
     selected_index: usize,
     selected_description: Option<(usize, SharedString, bool)>,
     selected_model: Option<AgentModelInfo>,
+    favorites: HashSet<ModelId>,
     _refresh_models_task: Task<()>,
+    _settings_subscription: Subscription,
     focus_handle: FocusHandle,
 }
 
@@ -101,6 +104,19 @@ impl AcpModelPickerDelegate {
             })
         };
 
+        let agent_server_for_subscription = agent_server.clone();
+        let settings_subscription =
+            cx.observe_global_in::<SettingsStore>(window, move |picker, window, cx| {
+                // Only refresh if the favorites actually changed to avoid redundant work
+                // when other settings are modified (e.g., user editing settings.json)
+                let new_favorites = agent_server_for_subscription.favorite_model_ids(cx);
+                if new_favorites != picker.delegate.favorites {
+                    picker.delegate.favorites = new_favorites;
+                    picker.refresh(window, cx);
+                }
+            });
+        let favorites = agent_server.favorite_model_ids(cx);
+
         Self {
             selector,
             agent_server,
@@ -110,7 +126,9 @@ impl AcpModelPickerDelegate {
             selected_model: None,
             selected_index: 0,
             selected_description: None,
+            favorites,
             _refresh_models_task: refresh_models_task,
+            _settings_subscription: settings_subscription,
             focus_handle,
         }
     }
@@ -118,6 +136,64 @@ impl AcpModelPickerDelegate {
     pub fn active_model(&self) -> Option<&AgentModelInfo> {
         self.selected_model.as_ref()
     }
+
+    pub fn favorites_count(&self) -> usize {
+        self.favorites.len()
+    }
+
+    pub fn cycle_favorite_models(&mut self, window: &mut Window, cx: &mut Context<Picker<Self>>) {
+        if self.favorites.is_empty() {
+            return;
+        }
+
+        let Some(models) = &self.models else {
+            return;
+        };
+
+        let all_models: Vec<&AgentModelInfo> = match models {
+            AgentModelList::Flat(list) => list.iter().collect(),
+            AgentModelList::Grouped(index_map) => index_map.values().flatten().collect(),
+        };
+
+        let favorite_models: Vec<_> = all_models
+            .into_iter()
+            .filter(|model| self.favorites.contains(&model.id))
+            .unique_by(|model| &model.id)
+            .collect();
+
+        if favorite_models.is_empty() {
+            return;
+        }
+
+        let current_id = self.selected_model.as_ref().map(|m| &m.id);
+
+        let current_index_in_favorites = current_id
+            .and_then(|id| favorite_models.iter().position(|m| &m.id == id))
+            .unwrap_or(usize::MAX);
+
+        let next_index = if current_index_in_favorites == usize::MAX {
+            0
+        } else {
+            (current_index_in_favorites + 1) % favorite_models.len()
+        };
+
+        let next_model = favorite_models[next_index].clone();
+
+        self.selector
+            .select_model(next_model.id.clone(), cx)
+            .detach_and_log_err(cx);
+
+        self.selected_model = Some(next_model);
+
+        // Keep the picker selection aligned with the newly-selected model
+        if let Some(new_index) = self.filtered_entries.iter().position(|entry| {
+            matches!(entry, AcpModelPickerEntry::Model(model_info, _) if self.selected_model.as_ref().is_some_and(|selected| model_info.id == selected.id))
+        }) {
+            self.set_selected_index(new_index, window, cx);
+        } else {
+            cx.notify();
+        }
+    }
 }
 
 impl PickerDelegate for AcpModelPickerDelegate {
@@ -143,7 +219,7 @@ impl PickerDelegate for AcpModelPickerDelegate {
         _cx: &mut Context<Picker<Self>>,
     ) -> bool {
         match self.filtered_entries.get(ix) {
-            Some(AcpModelPickerEntry::Model(_)) => true,
+            Some(AcpModelPickerEntry::Model(_, _)) => true,
             Some(AcpModelPickerEntry::Separator(_)) | None => false,
         }
     }
@@ -158,6 +234,8 @@ impl PickerDelegate for AcpModelPickerDelegate {
         window: &mut Window,
         cx: &mut Context<Picker<Self>>,
     ) -> Task<()> {
+        let favorites = self.favorites.clone();
+
         cx.spawn_in(window, async move |this, cx| {
             let filtered_models = match this
                 .read_with(cx, |this, cx| {
@@ -174,7 +252,7 @@ impl PickerDelegate for AcpModelPickerDelegate {
 
             this.update_in(cx, |this, window, cx| {
                 this.delegate.filtered_entries =
-                    info_list_to_picker_entries(filtered_models).collect();
+                    info_list_to_picker_entries(filtered_models, &favorites);
                 // Finds the currently selected model in the list
                 let new_index = this
                     .delegate
@@ -182,7 +260,7 @@ impl PickerDelegate for AcpModelPickerDelegate {
                     .as_ref()
                     .and_then(|selected| {
                         this.delegate.filtered_entries.iter().position(|entry| {
-                            if let AcpModelPickerEntry::Model(model_info) = entry {
+                            if let AcpModelPickerEntry::Model(model_info, _) = entry {
                                 model_info.id == selected.id
                             } else {
                                 false
@@ -198,7 +276,7 @@ impl PickerDelegate for AcpModelPickerDelegate {
     }
 
     fn confirm(&mut self, _secondary: bool, window: &mut Window, cx: &mut Context<Picker<Self>>) {
-        if let Some(AcpModelPickerEntry::Model(model_info)) =
+        if let Some(AcpModelPickerEntry::Model(model_info, _)) =
             self.filtered_entries.get(self.selected_index)
         {
             if window.modifiers().secondary() {
@@ -241,75 +319,57 @@ impl PickerDelegate for AcpModelPickerDelegate {
         cx: &mut Context<Picker<Self>>,
     ) -> Option<Self::ListItem> {
         match self.filtered_entries.get(ix)? {
-            AcpModelPickerEntry::Separator(title) => Some(
-                div()
-                    .px_2()
-                    .pb_1()
-                    .when(ix > 1, |this| {
-                        this.mt_1()
-                            .pt_2()
-                            .border_t_1()
-                            .border_color(cx.theme().colors().border_variant)
-                    })
-                    .child(
-                        Label::new(title)
-                            .size(LabelSize::XSmall)
-                            .color(Color::Muted),
-                    )
-                    .into_any_element(),
-            ),
-            AcpModelPickerEntry::Model(model_info) => {
+            AcpModelPickerEntry::Separator(title) => {
+                Some(ModelSelectorHeader::new(title, ix > 1).into_any_element())
+            }
+            AcpModelPickerEntry::Model(model_info, is_favorite) => {
                 let is_selected = Some(model_info) == self.selected_model.as_ref();
                 let default_model = self.agent_server.default_model(cx);
                 let is_default = default_model.as_ref() == Some(&model_info.id);
 
-                let model_icon_color = if is_selected {
-                    Color::Accent
-                } else {
-                    Color::Muted
+                let is_favorite = *is_favorite;
+                let handle_action_click = {
+                    let model_id = model_info.id.clone();
+                    let fs = self.fs.clone();
+                    let agent_server = self.agent_server.clone();
+
+                    cx.listener(move |_, _, _, cx| {
+                        agent_server.toggle_favorite_model(
+                            model_id.clone(),
+                            !is_favorite,
+                            fs.clone(),
+                            cx,
+                        );
+                    })
                 };
 
                 Some(
                     div()
                         .id(("model-picker-menu-child", ix))
                         .when_some(model_info.description.clone(), |this, description| {
-                            this
-                                .on_hover(cx.listener(move |menu, hovered, _, cx| {
-                                    if *hovered {
-                                        menu.delegate.selected_description = Some((ix, description.clone(), is_default));
-                                    } else if matches!(menu.delegate.selected_description, Some((id, _, _)) if id == ix) {
-                                        menu.delegate.selected_description = None;
-                                    }
-                                    cx.notify();
-                                }))
+                            this.on_hover(cx.listener(move |menu, hovered, _, cx| {
+                                if *hovered {
+                                    menu.delegate.selected_description =
+                                        Some((ix, description.clone(), is_default));
+                                } else if matches!(menu.delegate.selected_description, Some((id, _, _)) if id == ix) {
+                                    menu.delegate.selected_description = None;
+                                }
+                                cx.notify();
+                            }))
                         })
                         .child(
-                            ListItem::new(ix)
-                                .inset(true)
-                                .spacing(ListItemSpacing::Sparse)
-                                .toggle_state(selected)
-                                .child(
-                                    h_flex()
-                                        .w_full()
-                                        .gap_1p5()
-                                        .when_some(model_info.icon, |this, icon| {
-                                            this.child(
-                                                Icon::new(icon)
-                                                    .color(model_icon_color)
-                                                    .size(IconSize::Small)
-                                            )
-                                        })
-                                        .child(Label::new(model_info.name.clone()).truncate()),
-                                )
-                                .end_slot(div().pr_3().when(is_selected, |this| {
-                                    this.child(
-                                        Icon::new(IconName::Check)
-                                            .color(Color::Accent)
-                                            .size(IconSize::Small),
-                                    )
-                                })),
+                            ModelSelectorListItem::new(ix, model_info.name.clone())
+                                .map(|this| match &model_info.icon {
+                                    Some(AgentModelIcon::Path(path)) => this.icon_path(path.clone()),
+                                    Some(AgentModelIcon::Named(icon)) => this.icon(*icon),
+                                    None => this,
+                                })
+                                .is_selected(is_selected)
+                                .is_focused(selected)
+                                .is_favorite(is_favorite)
+                                .on_toggle_favorite(handle_action_click),
                         )
-                        .into_any_element()
+                        .into_any_element(),
                 )
             }
         }
@@ -343,7 +403,7 @@ impl PickerDelegate for AcpModelPickerDelegate {
     fn render_footer(
         &self,
         _window: &mut Window,
-        cx: &mut Context<Picker<Self>>,
+        _cx: &mut Context<Picker<Self>>,
     ) -> Option<AnyElement> {
         let focus_handle = self.focus_handle.clone();
 
@@ -351,43 +411,57 @@ impl PickerDelegate for AcpModelPickerDelegate {
             return None;
         }
 
-        Some(
-            h_flex()
-                .w_full()
-                .p_1p5()
-                .border_t_1()
-                .border_color(cx.theme().colors().border_variant)
-                .child(
-                    Button::new("configure", "Configure")
-                        .full_width()
-                        .style(ButtonStyle::Outlined)
-                        .key_binding(
-                            KeyBinding::for_action_in(&OpenSettings, &focus_handle, cx)
-                                .map(|kb| kb.size(rems_from_px(12.))),
-                        )
-                        .on_click(|_, window, cx| {
-                            window.dispatch_action(OpenSettings.boxed_clone(), cx);
-                        }),
-                )
-                .into_any(),
-        )
+        Some(ModelSelectorFooter::new(OpenSettings.boxed_clone(), focus_handle).into_any_element())
     }
 }
 
 fn info_list_to_picker_entries(
     model_list: AgentModelList,
-) -> impl Iterator<Item = AcpModelPickerEntry> {
+    favorites: &HashSet<ModelId>,
+) -> Vec<AcpModelPickerEntry> {
+    let mut entries = Vec::new();
+
+    let all_models: Vec<_> = match &model_list {
+        AgentModelList::Flat(list) => list.iter().collect(),
+        AgentModelList::Grouped(index_map) => index_map.values().flatten().collect(),
+    };
+
+    let favorite_models: Vec<_> = all_models
+        .iter()
+        .filter(|m| favorites.contains(&m.id))
+        .unique_by(|m| &m.id)
+        .collect();
+
+    let has_favorites = !favorite_models.is_empty();
+    if has_favorites {
+        entries.push(AcpModelPickerEntry::Separator("Favorite".into()));
+        for model in favorite_models {
+            entries.push(AcpModelPickerEntry::Model((*model).clone(), true));
+        }
+    }
+
     match model_list {
         AgentModelList::Flat(list) => {
-            itertools::Either::Left(list.into_iter().map(AcpModelPickerEntry::Model))
+            if has_favorites {
+                entries.push(AcpModelPickerEntry::Separator("All".into()));
+            }
+            for model in list {
+                let is_favorite = favorites.contains(&model.id);
+                entries.push(AcpModelPickerEntry::Model(model, is_favorite));
+            }
         }
         AgentModelList::Grouped(index_map) => {
-            itertools::Either::Right(index_map.into_iter().flat_map(|(group_name, models)| {
-                std::iter::once(AcpModelPickerEntry::Separator(group_name.0))
-                    .chain(models.into_iter().map(AcpModelPickerEntry::Model))
-            }))
+            for (group_name, models) in index_map {
+                entries.push(AcpModelPickerEntry::Separator(group_name.0));
+                for model in models {
+                    let is_favorite = favorites.contains(&model.id);
+                    entries.push(AcpModelPickerEntry::Model(model, is_favorite));
+                }
+            }
         }
     }
+
+    entries
 }
 
 async fn fuzzy_search(
@@ -403,9 +477,7 @@ async fn fuzzy_search(
         let candidates = model_list
             .iter()
             .enumerate()
-            .map(|(ix, model)| {
-                StringMatchCandidate::new(ix, &format!("{}/{}", model.id, model.name))
-            })
+            .map(|(ix, model)| StringMatchCandidate::new(ix, model.name.as_ref()))
             .collect::<Vec<_>>();
         let mut matches = match_strings(
             &candidates,
@@ -464,7 +536,7 @@ mod tests {
                     models
                         .into_iter()
                         .map(|model| acp_thread::AgentModelInfo {
-                            id: acp::ModelId(model.to_string().into()),
+                            id: acp::ModelId::new(model.to_string()),
                             name: model.to_string().into(),
                             description: None,
                             icon: None,
@@ -511,6 +583,33 @@ mod tests {
         }
     }
 
+    fn create_favorites(models: Vec<&str>) -> HashSet<ModelId> {
+        models
+            .into_iter()
+            .map(|m| ModelId::new(m.to_string()))
+            .collect()
+    }
+
+    fn get_entry_model_ids(entries: &[AcpModelPickerEntry]) -> Vec<&str> {
+        entries
+            .iter()
+            .filter_map(|entry| match entry {
+                AcpModelPickerEntry::Model(info, _) => Some(info.id.0.as_ref()),
+                _ => None,
+            })
+            .collect()
+    }
+
+    fn get_entry_labels(entries: &[AcpModelPickerEntry]) -> Vec<&str> {
+        entries
+            .iter()
+            .map(|entry| match entry {
+                AcpModelPickerEntry::Model(info, _) => info.id.0.as_ref(),
+                AcpModelPickerEntry::Separator(s) => &s,
+            })
+            .collect()
+    }
+
     #[gpui::test]
     async fn test_fuzzy_match(cx: &mut TestAppContext) {
         let models = create_model_list(vec![
@@ -550,4 +649,185 @@ mod tests {
             ],
         );
     }
+
+    #[gpui::test]
+    fn test_favorites_section_appears_when_favorites_exist(_cx: &mut TestAppContext) {
+        let models = create_model_list(vec![
+            ("zed", vec!["zed/claude", "zed/gemini"]),
+            ("openai", vec!["openai/gpt-5"]),
+        ]);
+        let favorites = create_favorites(vec!["zed/gemini"]);
+
+        let entries = info_list_to_picker_entries(models, &favorites);
+
+        assert!(matches!(
+            entries.first(),
+            Some(AcpModelPickerEntry::Separator(s)) if s == "Favorite"
+        ));
+
+        let model_ids = get_entry_model_ids(&entries);
+        assert_eq!(model_ids[0], "zed/gemini");
+    }
+
+    #[gpui::test]
+    fn test_no_favorites_section_when_no_favorites(_cx: &mut TestAppContext) {
+        let models = create_model_list(vec![("zed", vec!["zed/claude", "zed/gemini"])]);
+        let favorites = create_favorites(vec![]);
+
+        let entries = info_list_to_picker_entries(models, &favorites);
+
+        assert!(matches!(
+            entries.first(),
+            Some(AcpModelPickerEntry::Separator(s)) if s == "zed"
+        ));
+    }
+
+    #[gpui::test]
+    fn test_models_have_correct_actions(_cx: &mut TestAppContext) {
+        let models = create_model_list(vec![
+            ("zed", vec!["zed/claude", "zed/gemini"]),
+            ("openai", vec!["openai/gpt-5"]),
+        ]);
+        let favorites = create_favorites(vec!["zed/claude"]);
+
+        let entries = info_list_to_picker_entries(models, &favorites);
+
+        for entry in &entries {
+            if let AcpModelPickerEntry::Model(info, is_favorite) = entry {
+                if info.id.0.as_ref() == "zed/claude" {
+                    assert!(is_favorite, "zed/claude should be a favorite");
+                } else {
+                    assert!(!is_favorite, "{} should not be a favorite", info.id.0);
+                }
+            }
+        }
+    }
+
+    #[gpui::test]
+    fn test_favorites_appear_in_both_sections(_cx: &mut TestAppContext) {
+        let models = create_model_list(vec![
+            ("zed", vec!["zed/claude", "zed/gemini"]),
+            ("openai", vec!["openai/gpt-5", "openai/gpt-4"]),
+        ]);
+        let favorites = create_favorites(vec!["zed/gemini", "openai/gpt-5"]);
+
+        let entries = info_list_to_picker_entries(models, &favorites);
+        let model_ids = get_entry_model_ids(&entries);
+
+        assert_eq!(model_ids[0], "zed/gemini");
+        assert_eq!(model_ids[1], "openai/gpt-5");
+
+        assert!(model_ids[2..].contains(&"zed/gemini"));
+        assert!(model_ids[2..].contains(&"openai/gpt-5"));
+    }
+
+    #[gpui::test]
+    fn test_favorites_are_not_duplicated_when_repeated_in_other_sections(_cx: &mut TestAppContext) {
+        let models = create_model_list(vec![
+            ("Recommended", vec!["zed/claude", "anthropic/claude"]),
+            ("Zed", vec!["zed/claude", "zed/gpt-5"]),
+            ("Antropic", vec!["anthropic/claude"]),
+            ("OpenAI", vec!["openai/gpt-5"]),
+        ]);
+
+        let favorites = create_favorites(vec!["zed/claude"]);
+
+        let entries = info_list_to_picker_entries(models, &favorites);
+        let labels = get_entry_labels(&entries);
+
+        assert_eq!(
+            labels,
+            vec![
+                "Favorite",
+                "zed/claude",
+                "Recommended",
+                "zed/claude",
+                "anthropic/claude",
+                "Zed",
+                "zed/claude",
+                "zed/gpt-5",
+                "Antropic",
+                "anthropic/claude",
+                "OpenAI",
+                "openai/gpt-5"
+            ]
+        );
+    }
+
+    #[gpui::test]
+    fn test_flat_model_list_with_favorites(_cx: &mut TestAppContext) {
+        let models = AgentModelList::Flat(vec![
+            acp_thread::AgentModelInfo {
+                id: acp::ModelId::new("zed/claude".to_string()),
+                name: "Claude".into(),
+                description: None,
+                icon: None,
+            },
+            acp_thread::AgentModelInfo {
+                id: acp::ModelId::new("zed/gemini".to_string()),
+                name: "Gemini".into(),
+                description: None,
+                icon: None,
+            },
+        ]);
+        let favorites = create_favorites(vec!["zed/gemini"]);
+
+        let entries = info_list_to_picker_entries(models, &favorites);
+
+        assert!(matches!(
+            entries.first(),
+            Some(AcpModelPickerEntry::Separator(s)) if s == "Favorite"
+        ));
+
+        assert!(entries.iter().any(|e| matches!(
+            e,
+            AcpModelPickerEntry::Separator(s) if s == "All"
+        )));
+    }
+
+    #[gpui::test]
+    fn test_favorites_count_returns_correct_count(_cx: &mut TestAppContext) {
+        let empty_favorites: HashSet<ModelId> = HashSet::default();
+        assert_eq!(empty_favorites.len(), 0);
+
+        let one_favorite = create_favorites(vec!["model-a"]);
+        assert_eq!(one_favorite.len(), 1);
+
+        let multiple_favorites = create_favorites(vec!["model-a", "model-b", "model-c"]);
+        assert_eq!(multiple_favorites.len(), 3);
+
+        let with_duplicates = create_favorites(vec!["model-a", "model-a", "model-b"]);
+        assert_eq!(with_duplicates.len(), 2);
+    }
+
+    #[gpui::test]
+    fn test_is_favorite_flag_set_correctly_in_entries(_cx: &mut TestAppContext) {
+        let models = AgentModelList::Flat(vec![
+            acp_thread::AgentModelInfo {
+                id: acp::ModelId::new("favorite-model".to_string()),
+                name: "Favorite".into(),
+                description: None,
+                icon: None,
+            },
+            acp_thread::AgentModelInfo {
+                id: acp::ModelId::new("regular-model".to_string()),
+                name: "Regular".into(),
+                description: None,
+                icon: None,
+            },
+        ]);
+        let favorites = create_favorites(vec!["favorite-model"]);
+
+        let entries = info_list_to_picker_entries(models, &favorites);
+
+        for entry in &entries {
+            if let AcpModelPickerEntry::Model(info, is_favorite) = entry {
+                if info.id.0.as_ref() == "favorite-model" {
+                    assert!(*is_favorite, "favorite-model should have is_favorite=true");
+                } else if info.id.0.as_ref() == "regular-model" {
+                    assert!(!*is_favorite, "regular-model should have is_favorite=false");
+                }
+            }
+        }
+    }
 }

crates/agent_ui/src/acp/model_selector_popover.rs 🔗

@@ -1,18 +1,14 @@
 use std::rc::Rc;
 use std::sync::Arc;
 
-use acp_thread::{AgentModelInfo, AgentModelSelector};
-use agent_servers::AgentServer;
+use acp_thread::{AgentModelIcon, AgentModelInfo, AgentModelSelector};
 use fs::Fs;
 use gpui::{Entity, FocusHandle};
 use picker::popover_menu::PickerPopoverMenu;
-use ui::{
-    ButtonLike, Context, IntoElement, PopoverMenuHandle, SharedString, TintColor, Tooltip, Window,
-    prelude::*,
-};
-use zed_actions::agent::ToggleModelSelector;
+use ui::{ButtonLike, PopoverMenuHandle, TintColor, Tooltip, prelude::*};
 
 use crate::acp::{AcpModelSelector, model_selector::acp_model_selector};
+use crate::ui::ModelSelectorTooltip;
 
 pub struct AcpModelSelectorPopover {
     selector: Entity<AcpModelSelector>,
@@ -23,7 +19,7 @@ pub struct AcpModelSelectorPopover {
 impl AcpModelSelectorPopover {
     pub(crate) fn new(
         selector: Rc<dyn AgentModelSelector>,
-        agent_server: Rc<dyn AgentServer>,
+        agent_server: Rc<dyn agent_servers::AgentServer>,
         fs: Arc<dyn Fs>,
         menu_handle: PopoverMenuHandle<AcpModelSelector>,
         focus_handle: FocusHandle,
@@ -54,17 +50,24 @@ impl AcpModelSelectorPopover {
     pub fn active_model<'a>(&self, cx: &'a App) -> Option<&'a AgentModelInfo> {
         self.selector.read(cx).delegate.active_model()
     }
+
+    pub fn cycle_favorite_models(&self, window: &mut Window, cx: &mut Context<Self>) {
+        self.selector.update(cx, |selector, cx| {
+            selector.delegate.cycle_favorite_models(window, cx);
+        });
+    }
 }
 
 impl Render for AcpModelSelectorPopover {
     fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
-        let model = self.selector.read(cx).delegate.active_model();
+        let selector = self.selector.read(cx);
+        let model = selector.delegate.active_model();
         let model_name = model
             .as_ref()
             .map(|model| model.name.clone())
             .unwrap_or_else(|| SharedString::from("Select a Model"));
 
-        let model_icon = model.as_ref().and_then(|model| model.icon);
+        let model_icon = model.as_ref().and_then(|model| model.icon.clone());
 
         let focus_handle = self.focus_handle.clone();
 
@@ -74,12 +77,29 @@ impl Render for AcpModelSelectorPopover {
             (Color::Muted, IconName::ChevronDown)
         };
 
+        let show_cycle_row = selector.delegate.favorites_count() > 1;
+
+        let tooltip = Tooltip::element({
+            move |_, _cx| {
+                ModelSelectorTooltip::new(focus_handle.clone())
+                    .show_cycle_row(show_cycle_row)
+                    .into_any_element()
+            }
+        });
+
         PickerPopoverMenu::new(
             self.selector.clone(),
             ButtonLike::new("active-model")
                 .selected_style(ButtonStyle::Tinted(TintColor::Accent))
                 .when_some(model_icon, |this, icon| {
-                    this.child(Icon::new(icon).color(color).size(IconSize::XSmall))
+                    this.child(
+                        match icon {
+                            AgentModelIcon::Path(path) => Icon::from_external_svg(path),
+                            AgentModelIcon::Named(icon_name) => Icon::new(icon_name),
+                        }
+                        .color(color)
+                        .size(IconSize::XSmall),
+                    )
                 })
                 .child(
                     Label::new(model_name)
@@ -88,9 +108,7 @@ impl Render for AcpModelSelectorPopover {
                         .ml_0p5(),
                 )
                 .child(Icon::new(icon).color(Color::Muted).size(IconSize::XSmall)),
-            move |_window, cx| {
-                Tooltip::for_action_in("Change Model", &ToggleModelSelector, &focus_handle, cx)
-            },
+            tooltip,
             gpui::Corner::BottomRight,
             cx,
         )

crates/agent_ui/src/acp/thread_history.rs 🔗

@@ -1,7 +1,7 @@
 use crate::acp::AcpThreadView;
 use crate::{AgentPanel, RemoveHistory, RemoveSelectedThread};
 use agent::{HistoryEntry, HistoryStore};
-use chrono::{Datelike as _, Local, NaiveDate, TimeDelta};
+use chrono::{Datelike as _, Local, NaiveDate, TimeDelta, Utc};
 use editor::{Editor, EditorEvent};
 use fuzzy::StringMatchCandidate;
 use gpui::{
@@ -402,7 +402,22 @@ impl AcpThreadHistory {
         let selected = ix == self.selected_index;
         let hovered = Some(ix) == self.hovered_index;
         let timestamp = entry.updated_at().timestamp();
-        let thread_timestamp = format.format_timestamp(timestamp, self.local_timezone);
+
+        let display_text = match format {
+            EntryTimeFormat::DateAndTime => {
+                let entry_time = entry.updated_at();
+                let now = Utc::now();
+                let duration = now.signed_duration_since(entry_time);
+                let days = duration.num_days();
+
+                format!("{}d", days)
+            }
+            EntryTimeFormat::TimeOnly => format.format_timestamp(timestamp, self.local_timezone),
+        };
+
+        let title = entry.title().clone();
+        let full_date =
+            EntryTimeFormat::DateAndTime.format_timestamp(timestamp, self.local_timezone);
 
         h_flex()
             .w_full()
@@ -423,11 +438,14 @@ impl AcpThreadHistory {
                                     .truncate(),
                             )
                             .child(
-                                Label::new(thread_timestamp)
+                                Label::new(display_text)
                                     .color(Color::Muted)
                                     .size(LabelSize::XSmall),
                             ),
                     )
+                    .tooltip(move |_, cx| {
+                        Tooltip::with_meta(title.clone(), None, full_date.clone(), cx)
+                    })
                     .on_hover(cx.listener(move |this, is_hovered, _window, cx| {
                         if *is_hovered {
                             this.hovered_index = Some(ix);

crates/agent_ui/src/acp/thread_view.rs 🔗

@@ -34,7 +34,7 @@ use language::Buffer;
 
 use language_model::LanguageModelRegistry;
 use markdown::{HeadingLevelStyles, Markdown, MarkdownElement, MarkdownStyle};
-use project::{Project, ProjectEntryId};
+use project::{AgentServerStore, ExternalAgentServerName, Project, ProjectEntryId};
 use prompt_store::{PromptId, PromptStore};
 use rope::Point;
 use settings::{NotifyWhenAgentWaiting, Settings as _, SettingsStore};
@@ -47,8 +47,9 @@ use terminal_view::terminal_panel::TerminalPanel;
 use text::Anchor;
 use theme::{AgentFontSize, ThemeSettings};
 use ui::{
-    Callout, CommonAnimationExt, Disclosure, Divider, DividerColor, ElevationIndex, KeyBinding,
-    PopoverMenuHandle, SpinnerLabel, TintColor, Tooltip, WithScrollbar, prelude::*,
+    Callout, CommonAnimationExt, ContextMenu, ContextMenuEntry, Disclosure, Divider, DividerColor,
+    ElevationIndex, KeyBinding, PopoverMenuHandle, SpinnerLabel, TintColor, Tooltip, WithScrollbar,
+    prelude::*, right_click_menu,
 };
 use util::{ResultExt, size::format_file_size, time::duration_alt_display};
 use workspace::{CollaboratorId, NewTerminal, Workspace};
@@ -63,14 +64,11 @@ use crate::acp::message_editor::{MessageEditor, MessageEditorEvent};
 use crate::agent_diff::AgentDiff;
 use crate::profile_selector::{ProfileProvider, ProfileSelector};
 
-use crate::ui::{
-    AgentNotification, AgentNotificationEvent, BurnModeTooltip, UnavailableEditingTooltip,
-    UsageCallout,
-};
+use crate::ui::{AgentNotification, AgentNotificationEvent, BurnModeTooltip, UsageCallout};
 use crate::{
     AgentDiffPane, AgentPanel, AllowAlways, AllowOnce, ContinueThread, ContinueWithBurnMode,
-    CycleModeSelector, ExpandMessageEditor, Follow, KeepAll, NewThread, OpenAgentDiff, OpenHistory,
-    RejectAll, RejectOnce, ToggleBurnMode, ToggleProfileSelector,
+    CycleFavoriteModels, CycleModeSelector, ExpandMessageEditor, Follow, KeepAll, NewThread,
+    OpenAgentDiff, OpenHistory, RejectAll, RejectOnce, ToggleBurnMode, ToggleProfileSelector,
 };
 
 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
@@ -100,7 +98,7 @@ impl ThreadError {
         {
             Self::ModelRequestLimitReached(error.plan)
         } else if let Some(acp_error) = error.downcast_ref::<acp::Error>()
-            && acp_error.code == acp::ErrorCode::AUTH_REQUIRED.code
+            && acp_error.code == acp::ErrorCode::AuthRequired
         {
             Self::AuthenticationRequired(acp_error.message.clone().into())
         } else {
@@ -170,7 +168,7 @@ impl ThreadFeedbackState {
             }
         }
         let session_id = thread.read(cx).session_id().clone();
-        let agent = thread.read(cx).connection().telemetry_id();
+        let agent_telemetry_id = thread.read(cx).connection().telemetry_id();
         let task = telemetry.thread_data(&session_id, cx);
         let rating = match feedback {
             ThreadFeedback::Positive => "positive",
@@ -180,7 +178,7 @@ impl ThreadFeedbackState {
             let thread = task.await?;
             telemetry::event!(
                 "Agent Thread Rated",
-                agent = agent,
+                agent = agent_telemetry_id,
                 session_id = session_id,
                 rating = rating,
                 thread = thread
@@ -207,13 +205,13 @@ impl ThreadFeedbackState {
         self.comments_editor.take();
 
         let session_id = thread.read(cx).session_id().clone();
-        let agent = thread.read(cx).connection().telemetry_id();
+        let agent_telemetry_id = thread.read(cx).connection().telemetry_id();
         let task = telemetry.thread_data(&session_id, cx);
         cx.background_spawn(async move {
             let thread = task.await?;
             telemetry::event!(
                 "Agent Thread Feedback Comments",
-                agent = agent,
+                agent = agent_telemetry_id,
                 session_id = session_id,
                 comments = comments,
                 thread = thread
@@ -256,13 +254,14 @@ impl ThreadFeedbackState {
             editor
         });
 
-        editor.read(cx).focus_handle(cx).focus(window);
+        editor.read(cx).focus_handle(cx).focus(window, cx);
         editor
     }
 }
 
 pub struct AcpThreadView {
     agent: Rc<dyn AgentServer>,
+    agent_server_store: Entity<AgentServerStore>,
     workspace: WeakEntity<Workspace>,
     project: Entity<Project>,
     thread_state: ThreadState,
@@ -279,6 +278,7 @@ pub struct AcpThreadView {
     thread_retry_status: Option<RetryStatus>,
     thread_error: Option<ThreadError>,
     thread_error_markdown: Option<Entity<Markdown>>,
+    token_limit_callout_dismissed: bool,
     thread_feedback: ThreadFeedbackState,
     list_state: ListState,
     auth_task: Option<Task<()>>,
@@ -333,18 +333,25 @@ impl AcpThreadView {
         project: Entity<Project>,
         history_store: Entity<HistoryStore>,
         prompt_store: Option<Entity<PromptStore>>,
+        track_load_event: bool,
         window: &mut Window,
         cx: &mut Context<Self>,
     ) -> Self {
         let prompt_capabilities = Rc::new(RefCell::new(acp::PromptCapabilities::default()));
         let available_commands = Rc::new(RefCell::new(vec![]));
 
-        let placeholder = placeholder_text(agent.name().as_ref(), false);
+        let agent_server_store = project.read(cx).agent_server_store().clone();
+        let agent_display_name = agent_server_store
+            .read(cx)
+            .agent_display_name(&ExternalAgentServerName(agent.name()))
+            .unwrap_or_else(|| agent.name());
+
+        let placeholder = placeholder_text(agent_display_name.as_ref(), false);
 
         let message_editor = cx.new(|cx| {
             let mut editor = MessageEditor::new(
                 workspace.clone(),
-                project.clone(),
+                project.downgrade(),
                 history_store.clone(),
                 prompt_store.clone(),
                 prompt_capabilities.clone(),
@@ -369,7 +376,7 @@ impl AcpThreadView {
         let entry_view_state = cx.new(|_| {
             EntryViewState::new(
                 workspace.clone(),
-                project.clone(),
+                project.downgrade(),
                 history_store.clone(),
                 prompt_store.clone(),
                 prompt_capabilities.clone(),
@@ -378,7 +385,6 @@ impl AcpThreadView {
             )
         });
 
-        let agent_server_store = project.read(cx).agent_server_store().clone();
         let subscriptions = [
             cx.observe_global_in::<SettingsStore>(window, Self::agent_ui_font_size_changed),
             cx.observe_global_in::<AgentFontSize>(window, Self::agent_ui_font_size_changed),
@@ -391,11 +397,24 @@ impl AcpThreadView {
             ),
         ];
 
-        let show_codex_windows_warning = crate::ExternalAgent::parse_built_in(agent.as_ref())
-            == Some(crate::ExternalAgent::Codex);
+        cx.on_release(|this, cx| {
+            for window in this.notifications.drain(..) {
+                window
+                    .update(cx, |_, window, _| {
+                        window.remove_window();
+                    })
+                    .ok();
+            }
+        })
+        .detach();
+
+        let show_codex_windows_warning = cfg!(windows)
+            && project.read(cx).is_local()
+            && agent.clone().downcast::<agent_servers::Codex>().is_some();
 
         Self {
             agent: agent.clone(),
+            agent_server_store,
             workspace: workspace.clone(),
             project: project.clone(),
             entry_view_state,
@@ -404,6 +423,7 @@ impl AcpThreadView {
                 resume_thread.clone(),
                 workspace.clone(),
                 project.clone(),
+                track_load_event,
                 window,
                 cx,
             ),
@@ -411,13 +431,13 @@ impl AcpThreadView {
             message_editor,
             model_selector: None,
             profile_selector: None,
-
             notifications: Vec::new(),
             notification_subscriptions: HashMap::default(),
             list_state: list_state,
             thread_retry_status: None,
             thread_error: None,
             thread_error_markdown: None,
+            token_limit_callout_dismissed: false,
             thread_feedback: Default::default(),
             auth_task: None,
             expanded_tool_calls: HashSet::default(),
@@ -448,6 +468,7 @@ impl AcpThreadView {
             self.resume_thread_metadata.clone(),
             self.workspace.clone(),
             self.project.clone(),
+            true,
             window,
             cx,
         );
@@ -461,6 +482,7 @@ impl AcpThreadView {
         resume_thread: Option<DbThreadMetadata>,
         workspace: WeakEntity<Workspace>,
         project: Entity<Project>,
+        track_load_event: bool,
         window: &mut Window,
         cx: &mut Context<Self>,
     ) -> ThreadState {
@@ -498,17 +520,7 @@ impl AcpThreadView {
             Some(new_version_available_tx),
         );
 
-        let agent_name = agent.name();
-        let timeout = cx.background_executor().timer(Duration::from_secs(30));
-        let connect_task = smol::future::or(
-            agent.connect(root_dir.as_deref(), delegate, cx),
-            async move {
-                timeout.await;
-                Err(anyhow::Error::new(LoadError::Other(
-                    format!("{agent_name} is unable to initialize after 30 seconds.").into(),
-                )))
-            },
-        );
+        let connect_task = agent.connect(root_dir.as_deref(), delegate, cx);
         let load_task = cx.spawn_in(window, async move |this, cx| {
             let connection = match connect_task.await {
                 Ok((connection, login)) => {
@@ -529,6 +541,10 @@ impl AcpThreadView {
                 }
             };
 
+            if track_load_event {
+                telemetry::event!("Agent Thread Started", agent = connection.telemetry_id());
+            }
+
             let result = if let Some(native_agent) = connection
                 .clone()
                 .downcast::<agent::NativeAgentConnection>()
@@ -675,7 +691,7 @@ impl AcpThreadView {
                             })
                         });
 
-                        this.message_editor.focus_handle(cx).focus(window);
+                        this.message_editor.focus_handle(cx).focus(window, cx);
 
                         cx.notify();
                     }
@@ -694,7 +710,7 @@ impl AcpThreadView {
                         this.new_server_version_available = Some(new_version.into());
                         cx.notify();
                     })
-                    .log_err();
+                    .ok();
                 }
             }
         })
@@ -730,7 +746,7 @@ impl AcpThreadView {
         cx: &mut App,
     ) {
         let agent_name = agent.name();
-        let (configuration_view, subscription) = if let Some(provider_id) = err.provider_id {
+        let (configuration_view, subscription) = if let Some(provider_id) = &err.provider_id {
             let registry = LanguageModelRegistry::global(cx);
 
             let sub = window.subscribe(&registry, cx, {
@@ -772,12 +788,11 @@ impl AcpThreadView {
                 configuration_view,
                 description: err
                     .description
-                    .clone()
                     .map(|desc| cx.new(|cx| Markdown::new(desc.into(), None, None, cx))),
                 _subscription: subscription,
             };
             if this.message_editor.focus_handle(cx).is_focused(window) {
-                this.focus_handle.focus(window)
+                this.focus_handle.focus(window, cx)
             }
             cx.notify();
         })
@@ -797,7 +812,7 @@ impl AcpThreadView {
                 ThreadState::LoadError(LoadError::Other(format!("{:#}", err).into()))
         }
         if self.message_editor.focus_handle(cx).is_focused(window) {
-            self.focus_handle.focus(window)
+            self.focus_handle.focus(window, cx)
         }
         cx.notify();
     }
@@ -1081,10 +1096,7 @@ impl AcpThreadView {
                 window.defer(cx, |window, cx| {
                     Self::handle_auth_required(
                         this,
-                        AuthRequired {
-                            description: None,
-                            provider_id: None,
-                        },
+                        AuthRequired::new(),
                         agent,
                         connection,
                         window,
@@ -1143,8 +1155,8 @@ impl AcpThreadView {
         let Some(thread) = self.thread() else {
             return;
         };
-        let agent_telemetry_id = self.agent.telemetry_id();
         let session_id = thread.read(cx).session_id().clone();
+        let agent_telemetry_id = thread.read(cx).connection().telemetry_id();
         let thread = thread.downgrade();
         if self.should_be_following {
             self.workspace
@@ -1263,7 +1275,7 @@ impl AcpThreadView {
                 }
             })
         };
-        self.focus_handle(cx).focus(window);
+        self.focus_handle(cx).focus(window, cx);
         cx.notify();
     }
 
@@ -1315,11 +1327,11 @@ impl AcpThreadView {
                 .await?;
             this.update_in(cx, |this, window, cx| {
                 this.send_impl(message_editor, window, cx);
-                this.focus_handle(cx).focus(window);
+                this.focus_handle(cx).focus(window, cx);
             })?;
             anyhow::Ok(())
         })
-        .detach();
+        .detach_and_log_err(cx);
     }
 
     fn open_edited_buffer(
@@ -1383,6 +1395,7 @@ impl AcpThreadView {
     fn clear_thread_error(&mut self, cx: &mut Context<Self>) {
         self.thread_error = None;
         self.thread_error_markdown = None;
+        self.token_limit_callout_dismissed = true;
         cx.notify();
     }
 
@@ -1458,7 +1471,7 @@ impl AcpThreadView {
                 self.thread_retry_status.take();
                 self.thread_state = ThreadState::LoadError(error.clone());
                 if self.message_editor.focus_handle(cx).is_focused(window) {
-                    self.focus_handle.focus(window)
+                    self.focus_handle.focus(window, cx)
                 }
             }
             AcpThreadEvent::TitleUpdated => {
@@ -1486,24 +1499,20 @@ impl AcpThreadView {
                     .iter()
                     .any(|method| method.id.0.as_ref() == "claude-login")
                 {
-                    available_commands.push(acp::AvailableCommand {
-                        name: "login".to_owned(),
-                        description: "Authenticate".to_owned(),
-                        input: None,
-                        meta: None,
-                    });
-                    available_commands.push(acp::AvailableCommand {
-                        name: "logout".to_owned(),
-                        description: "Authenticate".to_owned(),
-                        input: None,
-                        meta: None,
-                    });
+                    available_commands.push(acp::AvailableCommand::new("login", "Authenticate"));
+                    available_commands.push(acp::AvailableCommand::new("logout", "Authenticate"));
                 }
 
                 let has_commands = !available_commands.is_empty();
                 self.available_commands.replace(available_commands);
 
-                let new_placeholder = placeholder_text(self.agent.name().as_ref(), has_commands);
+                let agent_display_name = self
+                    .agent_server_store
+                    .read(cx)
+                    .agent_display_name(&ExternalAgentServerName(self.agent.name()))
+                    .unwrap_or_else(|| self.agent.name());
+
+                let new_placeholder = placeholder_text(agent_display_name.as_ref(), has_commands);
 
                 self.message_editor.update(cx, |editor, cx| {
                     editor.set_placeholder_text(&new_placeholder, window, cx);
@@ -1532,6 +1541,7 @@ impl AcpThreadView {
         else {
             return;
         };
+        let agent_telemetry_id = connection.telemetry_id();
 
         // Check for the experimental "terminal-auth" _meta field
         let auth_method = connection.auth_methods().iter().find(|m| m.id == method);
@@ -1599,19 +1609,18 @@ impl AcpThreadView {
                             );
                             cx.notify();
                             self.auth_task = Some(cx.spawn_in(window, {
-                                let agent = self.agent.clone();
                                 async move |this, cx| {
                                     let result = authenticate.await;
 
                                     match &result {
                                         Ok(_) => telemetry::event!(
                                             "Authenticate Agent Succeeded",
-                                            agent = agent.telemetry_id()
+                                            agent = agent_telemetry_id
                                         ),
                                         Err(_) => {
                                             telemetry::event!(
                                                 "Authenticate Agent Failed",
-                                                agent = agent.telemetry_id(),
+                                                agent = agent_telemetry_id,
                                             )
                                         }
                                     }
@@ -1666,43 +1675,6 @@ impl AcpThreadView {
                 });
                 return;
             }
-        } else if method.0.as_ref() == "anthropic-api-key" {
-            let registry = LanguageModelRegistry::global(cx);
-            let provider = registry
-                .read(cx)
-                .provider(&language_model::ANTHROPIC_PROVIDER_ID)
-                .unwrap();
-            let this = cx.weak_entity();
-            let agent = self.agent.clone();
-            let connection = connection.clone();
-            window.defer(cx, move |window, cx| {
-                if !provider.is_authenticated(cx) {
-                    Self::handle_auth_required(
-                        this,
-                        AuthRequired {
-                            description: Some("ANTHROPIC_API_KEY must be set".to_owned()),
-                            provider_id: Some(language_model::ANTHROPIC_PROVIDER_ID),
-                        },
-                        agent,
-                        connection,
-                        window,
-                        cx,
-                    );
-                } else {
-                    this.update(cx, |this, cx| {
-                        this.thread_state = Self::initial_state(
-                            agent,
-                            None,
-                            this.workspace.clone(),
-                            this.project.clone(),
-                            window,
-                            cx,
-                        )
-                    })
-                    .ok();
-                }
-            });
-            return;
         } else if method.0.as_ref() == "vertex-ai"
             && std::env::var("GOOGLE_API_KEY").is_err()
             && (std::env::var("GOOGLE_CLOUD_PROJECT").is_err()
@@ -1750,43 +1722,38 @@ impl AcpThreadView {
             connection.authenticate(method, cx)
         };
         cx.notify();
-        self.auth_task =
-            Some(cx.spawn_in(window, {
-                let agent = self.agent.clone();
-                async move |this, cx| {
-                    let result = authenticate.await;
-
-                    match &result {
-                        Ok(_) => telemetry::event!(
-                            "Authenticate Agent Succeeded",
-                            agent = agent.telemetry_id()
-                        ),
-                        Err(_) => {
-                            telemetry::event!(
-                                "Authenticate Agent Failed",
-                                agent = agent.telemetry_id(),
-                            )
-                        }
+        self.auth_task = Some(cx.spawn_in(window, {
+            async move |this, cx| {
+                let result = authenticate.await;
+
+                match &result {
+                    Ok(_) => telemetry::event!(
+                        "Authenticate Agent Succeeded",
+                        agent = agent_telemetry_id
+                    ),
+                    Err(_) => {
+                        telemetry::event!("Authenticate Agent Failed", agent = agent_telemetry_id,)
                     }
+                }
 
-                    this.update_in(cx, |this, window, cx| {
-                        if let Err(err) = result {
-                            if let ThreadState::Unauthenticated {
-                                pending_auth_method,
-                                ..
-                            } = &mut this.thread_state
-                            {
-                                pending_auth_method.take();
-                            }
-                            this.handle_thread_error(err, cx);
-                        } else {
-                            this.reset(window, cx);
+                this.update_in(cx, |this, window, cx| {
+                    if let Err(err) = result {
+                        if let ThreadState::Unauthenticated {
+                            pending_auth_method,
+                            ..
+                        } = &mut this.thread_state
+                        {
+                            pending_auth_method.take();
                         }
-                        this.auth_task.take()
-                    })
-                    .ok();
-                }
-            }));
+                        this.handle_thread_error(err, cx);
+                    } else {
+                        this.reset(window, cx);
+                    }
+                    this.auth_task.take()
+                })
+                .ok();
+            }
+        }));
     }
 
     fn spawn_external_agent_login(
@@ -1905,6 +1872,17 @@ impl AcpThreadView {
         })
     }
 
+    pub fn has_user_submitted_prompt(&self, cx: &App) -> bool {
+        self.thread().is_some_and(|thread| {
+            thread.read(cx).entries().iter().any(|entry| {
+                matches!(
+                    entry,
+                    AgentThreadEntry::UserMessage(user_message) if user_message.id.is_some()
+                )
+            })
+        })
+    }
+
     fn authorize_tool_call(
         &mut self,
         tool_call_id: acp::ToolCallId,
@@ -1916,10 +1894,11 @@ impl AcpThreadView {
         let Some(thread) = self.thread() else {
             return;
         };
+        let agent_telemetry_id = thread.read(cx).connection().telemetry_id();
 
         telemetry::event!(
             "Agent Tool Call Authorized",
-            agent = self.agent.telemetry_id(),
+            agent = agent_telemetry_id,
             session = thread.read(cx).session_id(),
             option = option_kind
         );
@@ -1957,6 +1936,16 @@ impl AcpThreadView {
         window: &mut Window,
         cx: &Context<Self>,
     ) -> AnyElement {
+        let is_indented = entry.is_indented();
+        let is_first_indented = is_indented
+            && self.thread().is_some_and(|thread| {
+                thread
+                    .read(cx)
+                    .entries()
+                    .get(entry_ix.saturating_sub(1))
+                    .is_none_or(|entry| !entry.is_indented())
+            });
+
         let primary = match &entry {
             AgentThreadEntry::UserMessage(message) => {
                 let Some(editor) = self
@@ -1989,7 +1978,9 @@ impl AcpThreadView {
                 v_flex()
                     .id(("user_message", entry_ix))
                     .map(|this| {
-                        if entry_ix == 0 && !has_checkpoint_button && rules_item.is_none()  {
+                        if is_first_indented {
+                            this.pt_0p5()
+                        } else if entry_ix == 0 && !has_checkpoint_button && rules_item.is_none()  {
                             this.pt(rems_from_px(18.))
                         } else if rules_item.is_some() {
                             this.pt_3()
@@ -2035,6 +2026,9 @@ impl AcpThreadView {
                                     .shadow_md()
                                     .bg(cx.theme().colors().editor_background)
                                     .border_1()
+                                    .when(is_indented, |this| {
+                                        this.py_2().px_2().shadow_sm()
+                                    })
                                     .when(editing && !editor_focus, |this| this.border_dashed())
                                     .border_color(cx.theme().colors().border)
                                     .map(|this|{
@@ -2047,7 +2041,7 @@ impl AcpThreadView {
                                         }
                                     })
                                     .text_xs()
-                                    .child(editor.clone().into_any_element()),
+                                    .child(editor.clone().into_any_element())
                             )
                             .when(editor_focus, |this| {
                                 let base_container = h_flex()
@@ -2105,10 +2099,23 @@ impl AcpThreadView {
                                                     .icon_size(IconSize::Small)
                                                     .icon_color(Color::Muted)
                                                     .style(ButtonStyle::Transparent)
-                                                    .tooltip(move |_window, cx| {
-                                                        cx.new(|_| UnavailableEditingTooltip::new(agent_name.clone()))
-                                                            .into()
-                                                    })
+                                                    .tooltip(Tooltip::element({
+                                                        move |_, _| {
+                                                            v_flex()
+                                                                .gap_1()
+                                                                .child(Label::new("Unavailable Editing")).child(
+                                                                    div().max_w_64().child(
+                                                                        Label::new(format!(
+                                                                            "Editing previous messages is not available for {} yet.",
+                                                                            agent_name.clone()
+                                                                        ))
+                                                                        .size(LabelSize::Small)
+                                                                        .color(Color::Muted),
+                                                                    ),
+                                                                )
+                                                                .into_any_element()
+                                                        }
+                                                    }))
                                             )
                                     )
                                 }
@@ -2116,7 +2123,11 @@ impl AcpThreadView {
                     )
                     .into_any()
             }
-            AgentThreadEntry::AssistantMessage(AssistantMessage { chunks }) => {
+            AgentThreadEntry::AssistantMessage(AssistantMessage {
+                chunks,
+                indented: _,
+            }) => {
+                let mut is_blank = true;
                 let is_last = entry_ix + 1 == total_entries;
 
                 let style = default_markdown_style(false, false, window, cx);
@@ -2126,52 +2137,100 @@ impl AcpThreadView {
                     .children(chunks.iter().enumerate().filter_map(
                         |(chunk_ix, chunk)| match chunk {
                             AssistantMessageChunk::Message { block } => {
-                                block.markdown().map(|md| {
-                                    self.render_markdown(md.clone(), style.clone())
-                                        .into_any_element()
+                                block.markdown().and_then(|md| {
+                                    let this_is_blank = md.read(cx).source().trim().is_empty();
+                                    is_blank = is_blank && this_is_blank;
+                                    if this_is_blank {
+                                        return None;
+                                    }
+
+                                    Some(
+                                        self.render_markdown(md.clone(), style.clone())
+                                            .into_any_element(),
+                                    )
                                 })
                             }
                             AssistantMessageChunk::Thought { block } => {
-                                block.markdown().map(|md| {
-                                    self.render_thinking_block(
-                                        entry_ix,
-                                        chunk_ix,
-                                        md.clone(),
-                                        window,
-                                        cx,
+                                block.markdown().and_then(|md| {
+                                    let this_is_blank = md.read(cx).source().trim().is_empty();
+                                    is_blank = is_blank && this_is_blank;
+                                    if this_is_blank {
+                                        return None;
+                                    }
+                                    Some(
+                                        self.render_thinking_block(
+                                            entry_ix,
+                                            chunk_ix,
+                                            md.clone(),
+                                            window,
+                                            cx,
+                                        )
+                                        .into_any_element(),
                                     )
-                                    .into_any_element()
                                 })
                             }
                         },
                     ))
                     .into_any();
 
-                v_flex()
-                    .px_5()
-                    .py_1p5()
-                    .when(is_last, |this| this.pb_4())
-                    .w_full()
-                    .text_ui(cx)
-                    .child(message_body)
-                    .into_any()
+                if is_blank {
+                    Empty.into_any()
+                } else {
+                    v_flex()
+                        .px_5()
+                        .py_1p5()
+                        .when(is_last, |this| this.pb_4())
+                        .w_full()
+                        .text_ui(cx)
+                        .child(self.render_message_context_menu(entry_ix, message_body, cx))
+                        .into_any()
+                }
             }
             AgentThreadEntry::ToolCall(tool_call) => {
                 let has_terminals = tool_call.terminals().next().is_some();
 
-                div().w_full().map(|this| {
-                    if has_terminals {
-                        this.children(tool_call.terminals().map(|terminal| {
-                            self.render_terminal_tool_call(
-                                entry_ix, terminal, tool_call, window, cx,
-                            )
-                        }))
-                    } else {
-                        this.child(self.render_tool_call(entry_ix, tool_call, window, cx))
-                    }
-                })
+                div()
+                    .w_full()
+                    .map(|this| {
+                        if has_terminals {
+                            this.children(tool_call.terminals().map(|terminal| {
+                                self.render_terminal_tool_call(
+                                    entry_ix, terminal, tool_call, window, cx,
+                                )
+                            }))
+                        } else {
+                            this.child(self.render_tool_call(entry_ix, tool_call, window, cx))
+                        }
+                    })
+                    .into_any()
             }
-            .into_any(),
+        };
+
+        let primary = if is_indented {
+            let line_top = if is_first_indented {
+                rems_from_px(-12.0)
+            } else {
+                rems_from_px(0.0)
+            };
+
+            div()
+                .relative()
+                .w_full()
+                .pl_5()
+                .bg(cx.theme().colors().panel_background.opacity(0.2))
+                .child(
+                    div()
+                        .absolute()
+                        .left(rems_from_px(18.0))
+                        .top(line_top)
+                        .bottom_0()
+                        .w_px()
+                        .bg(cx.theme().colors().border.opacity(0.6)),
+                )
+                .child(primary)
+                .into_any_element()
+        } else {
+            primary
         };
 
         let needs_confirmation = if let AgentThreadEntry::ToolCall(tool_call) = entry {
@@ -2230,6 +2289,70 @@ impl AcpThreadView {
         }
     }
 
+    fn render_message_context_menu(
+        &self,
+        entry_ix: usize,
+        message_body: AnyElement,
+        cx: &Context<Self>,
+    ) -> AnyElement {
+        let entity = cx.entity();
+        let workspace = self.workspace.clone();
+
+        right_click_menu(format!("agent_context_menu-{}", entry_ix))
+            .trigger(move |_, _, _| message_body)
+            .menu(move |window, cx| {
+                let focus = window.focused(cx);
+                let entity = entity.clone();
+                let workspace = workspace.clone();
+
+                ContextMenu::build(window, cx, move |menu, _, cx| {
+                    let is_at_top = entity.read(cx).list_state.logical_scroll_top().item_ix == 0;
+
+                    let scroll_item = if is_at_top {
+                        ContextMenuEntry::new("Scroll to Bottom").handler({
+                            let entity = entity.clone();
+                            move |_, cx| {
+                                entity.update(cx, |this, cx| {
+                                    this.scroll_to_bottom(cx);
+                                });
+                            }
+                        })
+                    } else {
+                        ContextMenuEntry::new("Scroll to Top").handler({
+                            let entity = entity.clone();
+                            move |_, cx| {
+                                entity.update(cx, |this, cx| {
+                                    this.scroll_to_top(cx);
+                                });
+                            }
+                        })
+                    };
+
+                    let open_thread_as_markdown = ContextMenuEntry::new("Open Thread as Markdown")
+                        .handler({
+                            let entity = entity.clone();
+                            let workspace = workspace.clone();
+                            move |window, cx| {
+                                if let Some(workspace) = workspace.upgrade() {
+                                    entity
+                                        .update(cx, |this, cx| {
+                                            this.open_thread_as_markdown(workspace, window, cx)
+                                        })
+                                        .detach_and_log_err(cx);
+                                }
+                            }
+                        });
+
+                    menu.when_some(focus, |menu, focus| menu.context(focus))
+                        .action("Copy", Box::new(markdown::CopyAsMarkdown))
+                        .separator()
+                        .item(scroll_item)
+                        .item(open_thread_as_markdown)
+                })
+            })
+            .into_any_element()
+    }
+
     fn tool_card_header_bg(&self, cx: &Context<Self>) -> Hsla {
         cx.theme()
             .colors()
@@ -2374,6 +2497,12 @@ impl AcpThreadView {
         let is_collapsible = !tool_call.content.is_empty() && !needs_confirmation;
 
         let is_open = needs_confirmation || self.expanded_tool_calls.contains(&tool_call.id);
+        let input_output_header = |label: SharedString| {
+            Label::new(label)
+                .size(LabelSize::XSmall)
+                .color(Color::Muted)
+                .buffer_font(cx)
+        };
 
         let tool_output_display =
             if is_open {
@@ -2415,18 +2544,40 @@ impl AcpThreadView {
                     | ToolCallStatus::Completed
                     | ToolCallStatus::Failed
                     | ToolCallStatus::Canceled => v_flex()
-                        .w_full()
+                        .when(!is_edit && !is_terminal_tool, |this| {
+                            this.mt_1p5().w_full().child(
+                                v_flex()
+                                    .ml(rems(0.4))
+                                    .px_3p5()
+                                    .pb_1()
+                                    .gap_1()
+                                    .border_l_1()
+                                    .border_color(self.tool_card_border_color(cx))
+                                    .child(input_output_header("Raw Input:".into()))
+                                    .children(tool_call.raw_input_markdown.clone().map(|input| {
+                                        div().id(("tool-call-raw-input-markdown", entry_ix)).child(
+                                            self.render_markdown(
+                                                input,
+                                                default_markdown_style(false, false, window, cx),
+                                            ),
+                                        )
+                                    }))
+                                    .child(input_output_header("Output:".into())),
+                            )
+                        })
                         .children(tool_call.content.iter().enumerate().map(
                             |(content_ix, content)| {
-                                div().child(self.render_tool_call_content(
-                                    entry_ix,
-                                    content,
-                                    content_ix,
-                                    tool_call,
-                                    use_card_layout,
-                                    window,
-                                    cx,
-                                ))
+                                div().id(("tool-call-output", entry_ix)).child(
+                                    self.render_tool_call_content(
+                                        entry_ix,
+                                        content,
+                                        content_ix,
+                                        tool_call,
+                                        use_card_layout,
+                                        window,
+                                        cx,
+                                    ),
+                                )
                             },
                         ))
                         .into_any(),
@@ -2514,7 +2665,7 @@ impl AcpThreadView {
                                         .gap_px()
                                         .when(is_collapsible, |this| {
                                             this.child(
-                                            Disclosure::new(("expand", entry_ix), is_open)
+                                            Disclosure::new(("expand-output", entry_ix), is_open)
                                                 .opened_icon(IconName::ChevronUp)
                                                 .closed_icon(IconName::ChevronDown)
                                                 .visible_on_hover(&card_header_id)
@@ -2572,7 +2723,7 @@ impl AcpThreadView {
                 acp::ToolKind::Think => IconName::ToolThink,
                 acp::ToolKind::Fetch => IconName::ToolWeb,
                 acp::ToolKind::SwitchMode => IconName::ArrowRightLeft,
-                acp::ToolKind::Other => IconName::ToolHammer,
+                acp::ToolKind::Other | _ => IconName::ToolHammer,
             })
         }
         .size(IconSize::Small)
@@ -2637,7 +2788,7 @@ impl AcpThreadView {
                             ..default_markdown_style(false, true, window, cx)
                         },
                     ))
-                    .tooltip(Tooltip::text("Jump to File"))
+                    .tooltip(Tooltip::text("Go to File"))
                     .on_click(cx.listener(move |this, _, window, cx| {
                         this.open_tool_call_location(entry_ix, 0, window, cx);
                     }))
@@ -2700,20 +2851,20 @@ impl AcpThreadView {
         let button_id = SharedString::from(format!("tool_output-{:?}", tool_call_id));
 
         v_flex()
-            .mt_1p5()
             .gap_2()
-            .when(!card_layout, |this| {
-                this.ml(rems(0.4))
-                    .px_3p5()
-                    .border_l_1()
-                    .border_color(self.tool_card_border_color(cx))
-            })
-            .when(card_layout, |this| {
-                this.px_2().pb_2().when(context_ix > 0, |this| {
-                    this.border_t_1()
-                        .pt_2()
+            .map(|this| {
+                if card_layout {
+                    this.when(context_ix > 0, |this| {
+                        this.pt_2()
+                            .border_t_1()
+                            .border_color(self.tool_card_border_color(cx))
+                    })
+                } else {
+                    this.ml(rems(0.4))
+                        .px_3p5()
+                        .border_l_1()
                         .border_color(self.tool_card_border_color(cx))
-                })
+                }
             })
             .text_xs()
             .text_color(cx.theme().colors().text_muted)
@@ -2824,7 +2975,7 @@ impl AcpThreadView {
             })
             .gap_0p5()
             .children(options.iter().map(move |option| {
-                let option_id = SharedString::from(option.id.0.clone());
+                let option_id = SharedString::from(option.option_id.0.clone());
                 Button::new((option_id, entry_ix), option.name.clone())
                     .map(|this| {
                         let (this, action) = match option.kind {
@@ -2840,7 +2991,7 @@ impl AcpThreadView {
                                 this.icon(IconName::Close).icon_color(Color::Error),
                                 Some(&RejectOnce as &dyn Action),
                             ),
-                            acp::PermissionOptionKind::RejectAlways => {
+                            acp::PermissionOptionKind::RejectAlways | _ => {
                                 (this.icon(IconName::Close).icon_color(Color::Error), None)
                             }
                         };

crates/agent_ui/src/agent_configuration.rs 🔗

@@ -22,7 +22,8 @@ use gpui::{
 };
 use language::LanguageRegistry;
 use language_model::{
-    LanguageModelProvider, LanguageModelProviderId, LanguageModelRegistry, ZED_CLOUD_PROVIDER_ID,
+    IconOrSvg, LanguageModelProvider, LanguageModelProviderId, LanguageModelRegistry,
+    ZED_CLOUD_PROVIDER_ID,
 };
 use language_models::AllLanguageModelSettings;
 use notifications::status_toast::{StatusToast, ToastIcon};
@@ -34,9 +35,9 @@ use project::{
 };
 use settings::{Settings, SettingsStore, update_settings_file};
 use ui::{
-    Button, ButtonStyle, Chip, CommonAnimationExt, ContextMenu, ContextMenuEntry, Disclosure,
-    Divider, DividerColor, ElevationIndex, IconName, IconPosition, IconSize, Indicator, LabelSize,
-    PopoverMenu, Switch, SwitchColor, Tooltip, WithScrollbar, prelude::*,
+    ButtonStyle, Chip, CommonAnimationExt, ContextMenu, ContextMenuEntry, Disclosure, Divider,
+    DividerColor, ElevationIndex, Indicator, LabelSize, PopoverMenu, Switch, Tooltip,
+    WithScrollbar, prelude::*,
 };
 use util::ResultExt as _;
 use workspace::{Workspace, create_and_open_local_file};
@@ -117,7 +118,7 @@ impl AgentConfiguration {
     }
 
     fn build_provider_configuration_views(&mut self, window: &mut Window, cx: &mut Context<Self>) {
-        let providers = LanguageModelRegistry::read_global(cx).providers();
+        let providers = LanguageModelRegistry::read_global(cx).visible_providers();
         for provider in providers {
             self.add_provider_configuration_view(&provider, window, cx);
         }
@@ -261,9 +262,12 @@ impl AgentConfiguration {
                                     .w_full()
                                     .gap_1p5()
                                     .child(
-                                        Icon::new(provider.icon())
-                                            .size(IconSize::Small)
-                                            .color(Color::Muted),
+                                        match provider.icon() {
+                                            IconOrSvg::Svg(path) => Icon::from_external_svg(path),
+                                            IconOrSvg::Icon(name) => Icon::new(name),
+                                        }
+                                        .size(IconSize::Small)
+                                        .color(Color::Muted),
                                     )
                                     .child(
                                         h_flex()
@@ -416,7 +420,7 @@ impl AgentConfiguration {
         &mut self,
         cx: &mut Context<Self>,
     ) -> impl IntoElement {
-        let providers = LanguageModelRegistry::read_global(cx).providers();
+        let providers = LanguageModelRegistry::read_global(cx).visible_providers();
 
         let popover_menu = PopoverMenu::new("add-provider-popover")
             .trigger(
@@ -838,7 +842,7 @@ impl AgentConfiguration {
                             .min_w_0()
                             .child(
                                 h_flex()
-                                    .id(SharedString::from(format!("tooltip-{}", item_id)))
+                                    .id(format!("tooltip-{}", item_id))
                                     .h_full()
                                     .w_3()
                                     .mr_2()
@@ -879,7 +883,6 @@ impl AgentConfiguration {
                             .child(context_server_configuration_menu)
                             .child(
                             Switch::new("context-server-switch", is_running.into())
-                                .color(SwitchColor::Accent)
                                 .on_click({
                                     let context_server_manager = self.context_server_store.clone();
                                     let fs = self.fs.clone();
@@ -976,9 +979,12 @@ impl AgentConfiguration {
                 let icon = if let Some(icon_path) = agent_server_store.agent_icon(&name) {
                     AgentIcon::Path(icon_path)
                 } else {
-                    AgentIcon::Name(IconName::Ai)
+                    AgentIcon::Name(IconName::Sparkle)
                 };
-                (name, icon)
+                let display_name = agent_server_store
+                    .agent_display_name(&name)
+                    .unwrap_or_else(|| name.0.clone());
+                (name, icon, display_name)
             })
             .collect();
 
@@ -1085,6 +1091,7 @@ impl AgentConfiguration {
                             .child(self.render_agent_server(
                                 AgentIcon::Name(IconName::AiClaude),
                                 "Claude Code",
+                                "Claude Code",
                                 false,
                                 cx,
                             ))
@@ -1092,6 +1099,7 @@ impl AgentConfiguration {
                             .child(self.render_agent_server(
                                 AgentIcon::Name(IconName::AiOpenAi),
                                 "Codex CLI",
+                                "Codex CLI",
                                 false,
                                 cx,
                             ))
@@ -1099,16 +1107,23 @@ impl AgentConfiguration {
                             .child(self.render_agent_server(
                                 AgentIcon::Name(IconName::AiGemini),
                                 "Gemini CLI",
+                                "Gemini CLI",
                                 false,
                                 cx,
                             ))
                             .map(|mut parent| {
-                                for (name, icon) in user_defined_agents {
+                                for (name, icon, display_name) in user_defined_agents {
                                     parent = parent
                                         .child(
                                             Divider::horizontal().color(DividerColor::BorderFaded),
                                         )
-                                        .child(self.render_agent_server(icon, name, true, cx));
+                                        .child(self.render_agent_server(
+                                            icon,
+                                            name,
+                                            display_name,
+                                            true,
+                                            cx,
+                                        ));
                                 }
                                 parent
                             }),
@@ -1119,11 +1134,14 @@ impl AgentConfiguration {
     fn render_agent_server(
         &self,
         icon: AgentIcon,
-        name: impl Into<SharedString>,
+        id: impl Into<SharedString>,
+        display_name: impl Into<SharedString>,
         external: bool,
         cx: &mut Context<Self>,
     ) -> impl IntoElement {
-        let name = name.into();
+        let id = id.into();
+        let display_name = display_name.into();
+
         let icon = match icon {
             AgentIcon::Name(icon_name) => Icon::new(icon_name)
                 .size(IconSize::Small)
@@ -1133,12 +1151,15 @@ impl AgentConfiguration {
                 .color(Color::Muted),
         };
 
-        let tooltip_id = SharedString::new(format!("agent-source-{}", name));
-        let tooltip_message = format!("The {} agent was installed from an extension.", name);
+        let tooltip_id = SharedString::new(format!("agent-source-{}", id));
+        let tooltip_message = format!(
+            "The {} agent was installed from an extension.",
+            display_name
+        );
 
-        let agent_server_name = ExternalAgentServerName(name.clone());
+        let agent_server_name = ExternalAgentServerName(id.clone());
 
-        let uninstall_btn_id = SharedString::from(format!("uninstall-{}", name));
+        let uninstall_btn_id = SharedString::from(format!("uninstall-{}", id));
         let uninstall_button = IconButton::new(uninstall_btn_id, IconName::Trash)
             .icon_color(Color::Muted)
             .icon_size(IconSize::Small)
@@ -1162,7 +1183,7 @@ impl AgentConfiguration {
                 h_flex()
                     .gap_1p5()
                     .child(icon)
-                    .child(Label::new(name))
+                    .child(Label::new(display_name))
                     .when(external, |this| {
                         this.child(
                             div()
@@ -1349,6 +1370,7 @@ async fn open_new_agent_servers_entry_in_settings_editor(
                                 env: Some(HashMap::default()),
                                 default_mode: None,
                                 default_model: None,
+                                favorite_models: vec![],
                             },
                         );
                 }

crates/agent_ui/src/agent_configuration/add_llm_provider_modal.rs 🔗

@@ -446,17 +446,17 @@ impl AddLlmProviderModal {
             })
     }
 
-    fn on_tab(&mut self, _: &menu::SelectNext, window: &mut Window, _: &mut Context<Self>) {
-        window.focus_next();
+    fn on_tab(&mut self, _: &menu::SelectNext, window: &mut Window, cx: &mut Context<Self>) {
+        window.focus_next(cx);
     }
 
     fn on_tab_prev(
         &mut self,
         _: &menu::SelectPrevious,
         window: &mut Window,
-        _: &mut Context<Self>,
+        cx: &mut Context<Self>,
     ) {
-        window.focus_prev();
+        window.focus_prev(cx);
     }
 }
 
@@ -493,7 +493,7 @@ impl Render for AddLlmProviderModal {
             .on_action(cx.listener(Self::on_tab))
             .on_action(cx.listener(Self::on_tab_prev))
             .capture_any_mouse_down(cx.listener(|this, _, window, cx| {
-                this.focus_handle(cx).focus(window);
+                this.focus_handle(cx).focus(window, cx);
             }))
             .child(
                 Modal::new("configure-context-server", None)

crates/agent_ui/src/agent_configuration/manage_profiles_modal.rs 🔗

@@ -8,6 +8,7 @@ use editor::Editor;
 use fs::Fs;
 use gpui::{DismissEvent, Entity, EventEmitter, FocusHandle, Focusable, Subscription, prelude::*};
 use language_model::{LanguageModel, LanguageModelRegistry};
+use settings::SettingsStore;
 use settings::{
     LanguageModelProviderSetting, LanguageModelSelection, Settings as _, update_settings_file,
 };
@@ -94,6 +95,7 @@ pub struct ViewProfileMode {
     configure_default_model: NavigableEntry,
     configure_tools: NavigableEntry,
     configure_mcps: NavigableEntry,
+    delete_profile: NavigableEntry,
     cancel_item: NavigableEntry,
 }
 
@@ -109,6 +111,7 @@ pub struct ManageProfilesModal {
     active_model: Option<Arc<dyn LanguageModel>>,
     focus_handle: FocusHandle,
     mode: Mode,
+    _settings_subscription: Subscription,
 }
 
 impl ManageProfilesModal {
@@ -148,18 +151,29 @@ impl ManageProfilesModal {
     ) -> Self {
         let focus_handle = cx.focus_handle();
 
+        // Keep this modal in sync with settings changes (including profile deletion).
+        let settings_subscription =
+            cx.observe_global_in::<SettingsStore>(window, |this, window, cx| {
+                if matches!(this.mode, Mode::ChooseProfile(_)) {
+                    this.mode = Mode::choose_profile(window, cx);
+                    this.focus_handle(cx).focus(window, cx);
+                    cx.notify();
+                }
+            });
+
         Self {
             fs,
             active_model,
             context_server_registry,
             focus_handle,
             mode: Mode::choose_profile(window, cx),
+            _settings_subscription: settings_subscription,
         }
     }
 
     fn choose_profile(&mut self, window: &mut Window, cx: &mut Context<Self>) {
         self.mode = Mode::choose_profile(window, cx);
-        self.focus_handle(cx).focus(window);
+        self.focus_handle(cx).focus(window, cx);
     }
 
     fn new_profile(
@@ -177,7 +191,7 @@ impl ManageProfilesModal {
             name_editor,
             base_profile_id,
         });
-        self.focus_handle(cx).focus(window);
+        self.focus_handle(cx).focus(window, cx);
     }
 
     pub fn view_profile(
@@ -192,9 +206,10 @@ impl ManageProfilesModal {
             configure_default_model: NavigableEntry::focusable(cx),
             configure_tools: NavigableEntry::focusable(cx),
             configure_mcps: NavigableEntry::focusable(cx),
+            delete_profile: NavigableEntry::focusable(cx),
             cancel_item: NavigableEntry::focusable(cx),
         });
-        self.focus_handle(cx).focus(window);
+        self.focus_handle(cx).focus(window, cx);
     }
 
     fn configure_default_model(
@@ -207,7 +222,6 @@ impl ManageProfilesModal {
         let profile_id_for_closure = profile_id.clone();
 
         let model_picker = cx.new(|cx| {
-            let fs = fs.clone();
             let profile_id = profile_id_for_closure.clone();
 
             language_model_selector(
@@ -235,22 +249,36 @@ impl ManageProfilesModal {
                             })
                     }
                 },
-                move |model, cx| {
-                    let provider = model.provider_id().0.to_string();
-                    let model_id = model.id().0.to_string();
-                    let profile_id = profile_id.clone();
+                {
+                    let fs = fs.clone();
+                    move |model, cx| {
+                        let provider = model.provider_id().0.to_string();
+                        let model_id = model.id().0.to_string();
+                        let profile_id = profile_id.clone();
 
-                    update_settings_file(fs.clone(), cx, move |settings, _cx| {
-                        let agent_settings = settings.agent.get_or_insert_default();
-                        if let Some(profiles) = agent_settings.profiles.as_mut() {
-                            if let Some(profile) = profiles.get_mut(profile_id.0.as_ref()) {
-                                profile.default_model = Some(LanguageModelSelection {
-                                    provider: LanguageModelProviderSetting(provider.clone()),
-                                    model: model_id.clone(),
-                                });
+                        update_settings_file(fs.clone(), cx, move |settings, _cx| {
+                            let agent_settings = settings.agent.get_or_insert_default();
+                            if let Some(profiles) = agent_settings.profiles.as_mut() {
+                                if let Some(profile) = profiles.get_mut(profile_id.0.as_ref()) {
+                                    profile.default_model = Some(LanguageModelSelection {
+                                        provider: LanguageModelProviderSetting(provider.clone()),
+                                        model: model_id.clone(),
+                                    });
+                                }
                             }
-                        }
-                    });
+                        });
+                    }
+                },
+                {
+                    let fs = fs.clone();
+                    move |model, should_be_favorite, cx| {
+                        crate::favorite_models::toggle_in_settings(
+                            model,
+                            should_be_favorite,
+                            fs.clone(),
+                            cx,
+                        );
+                    }
                 },
                 false, // Do not use popover styles for the model picker
                 self.focus_handle.clone(),
@@ -272,7 +300,7 @@ impl ManageProfilesModal {
             model_picker,
             _subscription: dismiss_subscription,
         };
-        self.focus_handle(cx).focus(window);
+        self.focus_handle(cx).focus(window, cx);
     }
 
     fn configure_mcp_tools(
@@ -308,7 +336,7 @@ impl ManageProfilesModal {
             tool_picker,
             _subscription: dismiss_subscription,
         };
-        self.focus_handle(cx).focus(window);
+        self.focus_handle(cx).focus(window, cx);
     }
 
     fn configure_builtin_tools(
@@ -349,7 +377,7 @@ impl ManageProfilesModal {
             tool_picker,
             _subscription: dismiss_subscription,
         };
-        self.focus_handle(cx).focus(window);
+        self.focus_handle(cx).focus(window, cx);
     }
 
     fn confirm(&mut self, window: &mut Window, cx: &mut Context<Self>) {
@@ -369,6 +397,42 @@ impl ManageProfilesModal {
         }
     }
 
+    fn delete_profile(
+        &mut self,
+        profile_id: AgentProfileId,
+        window: &mut Window,
+        cx: &mut Context<Self>,
+    ) {
+        if builtin_profiles::is_builtin(&profile_id) {
+            self.view_profile(profile_id, window, cx);
+            return;
+        }
+
+        let fs = self.fs.clone();
+
+        update_settings_file(fs, cx, move |settings, _cx| {
+            let Some(agent_settings) = settings.agent.as_mut() else {
+                return;
+            };
+
+            let Some(profiles) = agent_settings.profiles.as_mut() else {
+                return;
+            };
+
+            profiles.shift_remove(profile_id.0.as_ref());
+
+            if agent_settings
+                .default_profile
+                .as_deref()
+                .is_some_and(|default_profile| default_profile == profile_id.0.as_ref())
+            {
+                agent_settings.default_profile = Some(AgentProfileId::default().0);
+            }
+        });
+
+        self.choose_profile(window, cx);
+    }
+
     fn cancel(&mut self, window: &mut Window, cx: &mut Context<Self>) {
         match &self.mode {
             Mode::ChooseProfile { .. } => {
@@ -422,7 +486,7 @@ impl ManageProfilesModal {
         let is_focused = profile.navigation.focus_handle.contains_focused(window, cx);
 
         div()
-            .id(SharedString::from(format!("profile-{}", profile.id)))
+            .id(format!("profile-{}", profile.id))
             .track_focus(&profile.navigation.focus_handle)
             .on_action({
                 let profile_id = profile.id.clone();
@@ -431,7 +495,7 @@ impl ManageProfilesModal {
                 })
             })
             .child(
-                ListItem::new(SharedString::from(format!("profile-{}", profile.id)))
+                ListItem::new(format!("profile-{}", profile.id))
                     .toggle_state(is_focused)
                     .inset(true)
                     .spacing(ListItemSpacing::Sparse)
@@ -756,6 +820,40 @@ impl ManageProfilesModal {
                                         }),
                                 ),
                         )
+                        .child(
+                            div()
+                                .id("delete-profile")
+                                .track_focus(&mode.delete_profile.focus_handle)
+                                .on_action({
+                                    let profile_id = mode.profile_id.clone();
+                                    cx.listener(move |this, _: &menu::Confirm, window, cx| {
+                                        this.delete_profile(profile_id.clone(), window, cx);
+                                    })
+                                })
+                                .child(
+                                    ListItem::new("delete-profile")
+                                        .toggle_state(
+                                            mode.delete_profile
+                                                .focus_handle
+                                                .contains_focused(window, cx),
+                                        )
+                                        .inset(true)
+                                        .spacing(ListItemSpacing::Sparse)
+                                        .start_slot(
+                                            Icon::new(IconName::Trash)
+                                                .size(IconSize::Small)
+                                                .color(Color::Error),
+                                        )
+                                        .child(Label::new("Delete Profile").color(Color::Error))
+                                        .disabled(builtin_profiles::is_builtin(&mode.profile_id))
+                                        .on_click({
+                                            let profile_id = mode.profile_id.clone();
+                                            cx.listener(move |this, _, window, cx| {
+                                                this.delete_profile(profile_id.clone(), window, cx);
+                                            })
+                                        }),
+                                ),
+                        )
                         .child(ListSeparator)
                         .child(
                             div()
@@ -805,6 +903,7 @@ impl ManageProfilesModal {
         .entry(mode.configure_default_model)
         .entry(mode.configure_tools)
         .entry(mode.configure_mcps)
+        .entry(mode.delete_profile)
         .entry(mode.cancel_item)
     }
 }
@@ -852,7 +951,7 @@ impl Render for ManageProfilesModal {
             .on_action(cx.listener(|this, _: &menu::Cancel, window, cx| this.cancel(window, cx)))
             .on_action(cx.listener(|this, _: &menu::Confirm, window, cx| this.confirm(window, cx)))
             .capture_any_mouse_down(cx.listener(|this, _, window, cx| {
-                this.focus_handle(cx).focus(window);
+                this.focus_handle(cx).focus(window, cx);
             }))
             .on_mouse_down_out(cx.listener(|_this, _, _, cx| cx.emit(DismissEvent)))
             .child(match &self.mode {

crates/agent_ui/src/agent_diff.rs 🔗

@@ -17,7 +17,7 @@ use gpui::{
     Global, SharedString, Subscription, Task, WeakEntity, Window, prelude::*,
 };
 
-use language::{Buffer, Capability, DiskState, OffsetRangeExt, Point};
+use language::{Buffer, Capability, OffsetRangeExt, Point};
 use multi_buffer::PathKey;
 use project::{Project, ProjectItem, ProjectPath};
 use settings::{Settings, SettingsStore};
@@ -130,7 +130,12 @@ impl AgentDiffPane {
             .action_log()
             .read(cx)
             .changed_buffers(cx);
-        let mut paths_to_delete = self.multibuffer.read(cx).paths().collect::<HashSet<_>>();
+        let mut paths_to_delete = self
+            .multibuffer
+            .read(cx)
+            .paths()
+            .cloned()
+            .collect::<HashSet<_>>();
 
         for (buffer, diff_handle) in changed_buffers {
             if buffer.read(cx).file().is_none() {
@@ -187,7 +192,7 @@ impl AgentDiffPane {
                     && buffer
                         .read(cx)
                         .file()
-                        .is_some_and(|file| file.disk_state() == DiskState::Deleted)
+                        .is_some_and(|file| file.disk_state().is_deleted())
                 {
                     editor.fold_buffer(snapshot.text.remote_id(), cx)
                 }
@@ -207,10 +212,10 @@ impl AgentDiffPane {
                 .focus_handle(cx)
                 .contains_focused(window, cx)
         {
-            self.focus_handle.focus(window);
+            self.focus_handle.focus(window, cx);
         } else if self.focus_handle.is_focused(window) && !self.multibuffer.read(cx).is_empty() {
             self.editor.update(cx, |editor, cx| {
-                editor.focus_handle(cx).focus(window);
+                editor.focus_handle(cx).focus(window, cx);
             });
         }
     }
@@ -869,12 +874,12 @@ impl AgentDiffToolbar {
         match active_item {
             AgentDiffToolbarItem::Pane(agent_diff) => {
                 if let Some(agent_diff) = agent_diff.upgrade() {
-                    agent_diff.focus_handle(cx).focus(window);
+                    agent_diff.focus_handle(cx).focus(window, cx);
                 }
             }
             AgentDiffToolbarItem::Editor { editor, .. } => {
                 if let Some(editor) = editor.upgrade() {
-                    editor.read(cx).focus_handle(cx).focus(window);
+                    editor.read(cx).focus_handle(cx).focus(window, cx);
                 }
             }
         }

crates/agent_ui/src/agent_model_selector.rs 🔗

@@ -1,14 +1,15 @@
 use crate::{
     ModelUsageContext,
     language_model_selector::{LanguageModelSelector, language_model_selector},
+    ui::ModelSelectorTooltip,
 };
 use fs::Fs;
 use gpui::{Entity, FocusHandle, SharedString};
+use language_model::IconOrSvg;
 use picker::popover_menu::PickerPopoverMenu;
 use settings::update_settings_file;
 use std::sync::Arc;
 use ui::{ButtonLike, PopoverMenuHandle, TintColor, Tooltip, prelude::*};
-use zed_actions::agent::ToggleModelSelector;
 
 pub struct AgentModelSelector {
     selector: Entity<LanguageModelSelector>,
@@ -29,26 +30,39 @@ impl AgentModelSelector {
 
         Self {
             selector: cx.new(move |cx| {
-                let fs = fs.clone();
                 language_model_selector(
                     {
                         let model_context = model_usage_context.clone();
                         move |cx| model_context.configured_model(cx)
                     },
-                    move |model, cx| {
-                        let provider = model.provider_id().0.to_string();
-                        let model_id = model.id().0.to_string();
-                        match &model_usage_context {
-                            ModelUsageContext::InlineAssistant => {
-                                update_settings_file(fs.clone(), cx, move |settings, _cx| {
-                                    settings
-                                        .agent
-                                        .get_or_insert_default()
-                                        .set_inline_assistant_model(provider.clone(), model_id);
-                                });
+                    {
+                        let fs = fs.clone();
+                        move |model, cx| {
+                            let provider = model.provider_id().0.to_string();
+                            let model_id = model.id().0.to_string();
+                            match &model_usage_context {
+                                ModelUsageContext::InlineAssistant => {
+                                    update_settings_file(fs.clone(), cx, move |settings, _cx| {
+                                        settings
+                                            .agent
+                                            .get_or_insert_default()
+                                            .set_inline_assistant_model(provider.clone(), model_id);
+                                    });
+                                }
                             }
                         }
                     },
+                    {
+                        let fs = fs.clone();
+                        move |model, should_be_favorite, cx| {
+                            crate::favorite_models::toggle_in_settings(
+                                model,
+                                should_be_favorite,
+                                fs.clone(),
+                                cx,
+                            );
+                        }
+                    },
                     true, // Use popover styles for picker
                     focus_handle_clone,
                     window,
@@ -63,6 +77,16 @@ impl AgentModelSelector {
     pub fn toggle(&self, window: &mut Window, cx: &mut Context<Self>) {
         self.menu_handle.toggle(window, cx);
     }
+
+    pub fn active_model(&self, cx: &App) -> Option<language_model::ConfiguredModel> {
+        self.selector.read(cx).delegate.active_model(cx)
+    }
+
+    pub fn cycle_favorite_models(&self, window: &mut Window, cx: &mut Context<Self>) {
+        self.selector.update(cx, |selector, cx| {
+            selector.delegate.cycle_favorite_models(window, cx);
+        });
+    }
 }
 
 impl Render for AgentModelSelector {
@@ -80,13 +104,30 @@ impl Render for AgentModelSelector {
             Color::Muted
         };
 
+        let show_cycle_row = self.selector.read(cx).delegate.favorites_count() > 1;
+
         let focus_handle = self.focus_handle.clone();
 
+        let tooltip = Tooltip::element({
+            move |_, _cx| {
+                ModelSelectorTooltip::new(focus_handle.clone())
+                    .show_cycle_row(show_cycle_row)
+                    .into_any_element()
+            }
+        });
+
         PickerPopoverMenu::new(
             self.selector.clone(),
             ButtonLike::new("active-model")
                 .when_some(provider_icon, |this, icon| {
-                    this.child(Icon::new(icon).color(color).size(IconSize::XSmall))
+                    this.child(
+                        match icon {
+                            IconOrSvg::Svg(path) => Icon::from_external_svg(path),
+                            IconOrSvg::Icon(name) => Icon::new(name),
+                        }
+                        .color(color)
+                        .size(IconSize::XSmall),
+                    )
                 })
                 .selected_style(ButtonStyle::Tinted(TintColor::Accent))
                 .child(
@@ -100,9 +141,7 @@ impl Render for AgentModelSelector {
                         .color(color)
                         .size(IconSize::XSmall),
                 ),
-            move |_window, cx| {
-                Tooltip::for_action_in("Change Model", &ToggleModelSelector, &focus_handle, cx)
-            },
+            tooltip,
             gpui::Corner::TopRight,
             cx,
         )

crates/agent_ui/src/agent_panel.rs 🔗

@@ -2,6 +2,7 @@ use std::{ops::Range, path::Path, rc::Rc, sync::Arc, time::Duration};
 
 use acp_thread::AcpThread;
 use agent::{ContextServerRegistry, DbThreadMetadata, HistoryEntry, HistoryStore};
+use agent_servers::AgentServer;
 use db::kvp::{Dismissable, KEY_VALUE_STORE};
 use project::{
     ExternalAgentServerName,
@@ -259,7 +260,7 @@ impl AgentType {
             Self::Gemini => Some(IconName::AiGemini),
             Self::ClaudeCode => Some(IconName::AiClaude),
             Self::Codex => Some(IconName::AiOpenAi),
-            Self::Custom { .. } => Some(IconName::Terminal),
+            Self::Custom { .. } => Some(IconName::Sparkle),
         }
     }
 }
@@ -287,7 +288,7 @@ impl ActiveView {
         }
     }
 
-    pub fn native_agent(
+    fn native_agent(
         fs: Arc<dyn Fs>,
         prompt_store: Option<Entity<PromptStore>>,
         history_store: Entity<agent::HistoryStore>,
@@ -305,6 +306,7 @@ impl ActiveView {
                 project,
                 history_store,
                 prompt_store,
+                false,
                 window,
                 cx,
             )
@@ -441,6 +443,7 @@ pub struct AgentPanel {
     pending_serialization: Option<Task<Result<()>>>,
     onboarding: Entity<AgentPanelOnboarding>,
     selected_agent: AgentType,
+    show_trust_workspace_message: bool,
 }
 
 impl AgentPanel {
@@ -691,6 +694,7 @@ impl AgentPanel {
             history_store,
             selected_agent: AgentType::default(),
             loading: false,
+            show_trust_workspace_message: false,
         };
 
         // Initial sync of agent servers from extensions
@@ -818,7 +822,7 @@ impl AgentPanel {
             window,
             cx,
         );
-        text_thread_editor.focus_handle(cx).focus(window);
+        text_thread_editor.focus_handle(cx).focus(window, cx);
     }
 
     fn external_thread(
@@ -884,39 +888,21 @@ impl AgentPanel {
             };
 
             let server = ext_agent.server(fs, history);
-
-            if !loading {
-                telemetry::event!("Agent Thread Started", agent = server.telemetry_id());
-            }
-
-            this.update_in(cx, |this, window, cx| {
-                let selected_agent = ext_agent.into();
-                if this.selected_agent != selected_agent {
-                    this.selected_agent = selected_agent;
-                    this.serialize(cx);
-                }
-
-                let thread_view = cx.new(|cx| {
-                    crate::acp::AcpThreadView::new(
-                        server,
-                        resume_thread,
-                        summarize_thread,
-                        workspace.clone(),
-                        project,
-                        this.history_store.clone(),
-                        this.prompt_store.clone(),
-                        window,
-                        cx,
-                    )
-                });
-
-                this.set_active_view(
-                    ActiveView::ExternalAgentThread { thread_view },
-                    !loading,
+            this.update_in(cx, |agent_panel, window, cx| {
+                agent_panel._external_thread(
+                    server,
+                    resume_thread,
+                    summarize_thread,
+                    workspace,
+                    project,
+                    loading,
+                    ext_agent,
                     window,
                     cx,
                 );
-            })
+            })?;
+
+            anyhow::Ok(())
         })
         .detach_and_log_err(cx);
     }
@@ -949,7 +935,7 @@ impl AgentPanel {
         if let Some(thread_view) = self.active_thread_view() {
             thread_view.update(cx, |view, cx| {
                 view.expand_message_editor(&ExpandMessageEditor, window, cx);
-                view.focus_handle(cx).focus(window);
+                view.focus_handle(cx).focus(window, cx);
             });
         }
     }
@@ -1030,12 +1016,12 @@ impl AgentPanel {
 
                     match &self.active_view {
                         ActiveView::ExternalAgentThread { thread_view } => {
-                            thread_view.focus_handle(cx).focus(window);
+                            thread_view.focus_handle(cx).focus(window, cx);
                         }
                         ActiveView::TextThread {
                             text_thread_editor, ..
                         } => {
-                            text_thread_editor.focus_handle(cx).focus(window);
+                            text_thread_editor.focus_handle(cx).focus(window, cx);
                         }
                         ActiveView::History | ActiveView::Configuration => {}
                     }
@@ -1183,7 +1169,7 @@ impl AgentPanel {
                 Self::handle_agent_configuration_event,
             ));
 
-            configuration.focus_handle(cx).focus(window);
+            configuration.focus_handle(cx).focus(window, cx);
         }
     }
 
@@ -1319,7 +1305,7 @@ impl AgentPanel {
         }
 
         if focus {
-            self.focus_handle(cx).focus(window);
+            self.focus_handle(cx).focus(window, cx);
         }
     }
 
@@ -1479,6 +1465,47 @@ impl AgentPanel {
             cx,
         );
     }
+
+    fn _external_thread(
+        &mut self,
+        server: Rc<dyn AgentServer>,
+        resume_thread: Option<DbThreadMetadata>,
+        summarize_thread: Option<DbThreadMetadata>,
+        workspace: WeakEntity<Workspace>,
+        project: Entity<Project>,
+        loading: bool,
+        ext_agent: ExternalAgent,
+        window: &mut Window,
+        cx: &mut Context<Self>,
+    ) {
+        let selected_agent = AgentType::from(ext_agent);
+        if self.selected_agent != selected_agent {
+            self.selected_agent = selected_agent;
+            self.serialize(cx);
+        }
+
+        let thread_view = cx.new(|cx| {
+            crate::acp::AcpThreadView::new(
+                server,
+                resume_thread,
+                summarize_thread,
+                workspace.clone(),
+                project,
+                self.history_store.clone(),
+                self.prompt_store.clone(),
+                !loading,
+                window,
+                cx,
+            )
+        });
+
+        self.set_active_view(
+            ActiveView::ExternalAgentThread { thread_view },
+            !loading,
+            window,
+            cx,
+        );
+    }
 }
 
 impl Focusable for AgentPanel {
@@ -1593,14 +1620,19 @@ impl AgentPanel {
 
         let content = match &self.active_view {
             ActiveView::ExternalAgentThread { thread_view } => {
+                let is_generating_title = thread_view
+                    .read(cx)
+                    .as_native_thread(cx)
+                    .map_or(false, |t| t.read(cx).is_generating_title());
+
                 if let Some(title_editor) = thread_view.read(cx).title_editor() {
-                    div()
+                    let container = div()
                         .w_full()
                         .on_action({
                             let thread_view = thread_view.downgrade();
                             move |_: &menu::Confirm, window, cx| {
                                 if let Some(thread_view) = thread_view.upgrade() {
-                                    thread_view.focus_handle(cx).focus(window);
+                                    thread_view.focus_handle(cx).focus(window, cx);
                                 }
                             }
                         })
@@ -1608,12 +1640,25 @@ impl AgentPanel {
                             let thread_view = thread_view.downgrade();
                             move |_: &editor::actions::Cancel, window, cx| {
                                 if let Some(thread_view) = thread_view.upgrade() {
-                                    thread_view.focus_handle(cx).focus(window);
+                                    thread_view.focus_handle(cx).focus(window, cx);
                                 }
                             }
                         })
-                        .child(title_editor)
-                        .into_any_element()
+                        .child(title_editor);
+
+                    if is_generating_title {
+                        container
+                            .with_animation(
+                                "generating_title",
+                                Animation::new(Duration::from_secs(2))
+                                    .repeat()
+                                    .with_easing(pulsating_between(0.4, 0.8)),
+                                |div, delta| div.opacity(delta),
+                            )
+                            .into_any_element()
+                    } else {
+                        container.into_any_element()
+                    }
                 } else {
                     Label::new(thread_view.read(cx).title(cx))
                         .color(Color::Muted)
@@ -1643,6 +1688,13 @@ impl AgentPanel {
                             Label::new(LOADING_SUMMARY_PLACEHOLDER)
                                 .truncate()
                                 .color(Color::Muted)
+                                .with_animation(
+                                    "generating_title",
+                                    Animation::new(Duration::from_secs(2))
+                                        .repeat()
+                                        .with_easing(pulsating_between(0.4, 0.8)),
+                                    |label, delta| label.alpha(delta),
+                                )
                                 .into_any_element()
                         }
                     }
@@ -1686,6 +1738,25 @@ impl AgentPanel {
             .into_any()
     }
 
+    fn handle_regenerate_thread_title(thread_view: Entity<AcpThreadView>, cx: &mut App) {
+        thread_view.update(cx, |thread_view, cx| {
+            if let Some(thread) = thread_view.as_native_thread(cx) {
+                thread.update(cx, |thread, cx| {
+                    thread.generate_title(cx);
+                });
+            }
+        });
+    }
+
+    fn handle_regenerate_text_thread_title(
+        text_thread_editor: Entity<TextThreadEditor>,
+        cx: &mut App,
+    ) {
+        text_thread_editor.update(cx, |text_thread_editor, cx| {
+            text_thread_editor.regenerate_summary(cx);
+        });
+    }
+
     fn render_panel_options_menu(
         &self,
         window: &mut Window,
@@ -1705,6 +1776,35 @@ impl AgentPanel {
 
         let selected_agent = self.selected_agent.clone();
 
+        let text_thread_view = match &self.active_view {
+            ActiveView::TextThread {
+                text_thread_editor, ..
+            } => Some(text_thread_editor.clone()),
+            _ => None,
+        };
+        let text_thread_with_messages = match &self.active_view {
+            ActiveView::TextThread {
+                text_thread_editor, ..
+            } => text_thread_editor
+                .read(cx)
+                .text_thread()
+                .read(cx)
+                .messages(cx)
+                .any(|message| message.role == language_model::Role::Assistant),
+            _ => false,
+        };
+
+        let thread_view = match &self.active_view {
+            ActiveView::ExternalAgentThread { thread_view } => Some(thread_view.clone()),
+            _ => None,
+        };
+        let thread_with_messages = match &self.active_view {
+            ActiveView::ExternalAgentThread { thread_view } => {
+                thread_view.read(cx).has_user_submitted_prompt(cx)
+            }
+            _ => false,
+        };
+
         PopoverMenu::new("agent-options-menu")
             .trigger_with_tooltip(
                 IconButton::new("agent-options-menu", IconName::Ellipsis)
@@ -1727,6 +1827,7 @@ impl AgentPanel {
                 move |window, cx| {
                     Some(ContextMenu::build(window, cx, |mut menu, _window, _| {
                         menu = menu.context(focus_handle.clone());
+
                         if let Some(usage) = usage {
                             menu = menu
                                 .header_with_link("Prompt Usage", "Manage", account_url.clone())
@@ -1764,6 +1865,38 @@ impl AgentPanel {
                                 .separator()
                         }
 
+                        if thread_with_messages | text_thread_with_messages {
+                            menu = menu.header("Current Thread");
+
+                            if let Some(text_thread_view) = text_thread_view.as_ref() {
+                                menu = menu
+                                    .entry("Regenerate Thread Title", None, {
+                                        let text_thread_view = text_thread_view.clone();
+                                        move |_, cx| {
+                                            Self::handle_regenerate_text_thread_title(
+                                                text_thread_view.clone(),
+                                                cx,
+                                            );
+                                        }
+                                    })
+                                    .separator();
+                            }
+
+                            if let Some(thread_view) = thread_view.as_ref() {
+                                menu = menu
+                                    .entry("Regenerate Thread Title", None, {
+                                        let thread_view = thread_view.clone();
+                                        move |_, cx| {
+                                            Self::handle_regenerate_thread_title(
+                                                thread_view.clone(),
+                                                cx,
+                                            );
+                                        }
+                                    })
+                                    .separator();
+                            }
+                        }
+
                         menu = menu
                             .header("MCP Servers")
                             .action(
@@ -1853,14 +1986,17 @@ impl AgentPanel {
         let agent_server_store = self.project.read(cx).agent_server_store().clone();
         let focus_handle = self.focus_handle(cx);
 
-        // Get custom icon path for selected agent before building menu (to avoid borrow issues)
-        let selected_agent_custom_icon =
+        let (selected_agent_custom_icon, selected_agent_label) =
             if let AgentType::Custom { name, .. } = &self.selected_agent {
-                agent_server_store
-                    .read(cx)
-                    .agent_icon(&ExternalAgentServerName(name.clone()))
+                let store = agent_server_store.read(cx);
+                let icon = store.agent_icon(&ExternalAgentServerName(name.clone()));
+
+                let label = store
+                    .agent_display_name(&ExternalAgentServerName(name.clone()))
+                    .unwrap_or_else(|| self.selected_agent.label());
+                (icon, label)
             } else {
-                None
+                (None, self.selected_agent.label())
             };
 
         let active_thread = match &self.active_view {
@@ -2083,13 +2219,16 @@ impl AgentPanel {
 
                                 for agent_name in agent_names {
                                     let icon_path = agent_server_store.agent_icon(&agent_name);
+                                    let display_name = agent_server_store
+                                        .agent_display_name(&agent_name)
+                                        .unwrap_or_else(|| agent_name.0.clone());
 
-                                    let mut entry = ContextMenuEntry::new(agent_name.clone());
+                                    let mut entry = ContextMenuEntry::new(display_name);
 
                                     if let Some(icon_path) = icon_path {
                                         entry = entry.custom_icon_svg(icon_path);
                                     } else {
-                                        entry = entry.icon(IconName::Terminal);
+                                        entry = entry.icon(IconName::Sparkle);
                                     }
                                     entry = entry
                                         .when(
@@ -2153,8 +2292,6 @@ impl AgentPanel {
                 }
             });
 
-        let selected_agent_label = self.selected_agent.label();
-
         let is_thread_loading = self
             .active_thread_view()
             .map(|thread| thread.read(cx).is_loading())
@@ -2291,7 +2428,7 @@ impl AgentPanel {
                 let history_is_empty = self.history_store.read(cx).is_empty(cx);
 
                 let has_configured_non_zed_providers = LanguageModelRegistry::read_global(cx)
-                    .providers()
+                    .visible_providers()
                     .iter()
                     .any(|provider| {
                         provider.is_authenticated(cx)
@@ -2555,6 +2692,38 @@ impl AgentPanel {
         }
     }
 
+    fn render_workspace_trust_message(&self, cx: &Context<Self>) -> Option<impl IntoElement> {
+        if !self.show_trust_workspace_message {
+            return None;
+        }
+
+        let description = "To protect your system, third-party code—like MCP servers—won't run until you mark this workspace as safe.";
+
+        Some(
+            Callout::new()
+                .icon(IconName::Warning)
+                .severity(Severity::Warning)
+                .border_position(ui::BorderPosition::Bottom)
+                .title("You're in Restricted Mode")
+                .description(description)
+                .actions_slot(
+                    Button::new("open-trust-modal", "Configure Project Trust")
+                        .label_size(LabelSize::Small)
+                        .style(ButtonStyle::Outlined)
+                        .on_click({
+                            cx.listener(move |this, _, window, cx| {
+                                this.workspace
+                                    .update(cx, |workspace, cx| {
+                                        workspace
+                                            .show_worktree_trust_security_modal(true, window, cx)
+                                    })
+                                    .log_err();
+                            })
+                        }),
+                ),
+        )
+    }
+
     fn key_context(&self) -> KeyContext {
         let mut key_context = KeyContext::new_with_defaults();
         key_context.add("AgentPanel");
@@ -2607,6 +2776,7 @@ impl Render for AgentPanel {
                 }
             }))
             .child(self.render_toolbar(window, cx))
+            .children(self.render_workspace_trust_message(cx))
             .children(self.render_onboarding(window, cx))
             .map(|parent| match &self.active_view {
                 ActiveView::ExternalAgentThread { thread_view, .. } => parent
@@ -2685,16 +2855,17 @@ impl rules_library::InlineAssistDelegate for PromptLibraryInlineAssist {
                 return;
             };
             let project = workspace.read(cx).project().downgrade();
+            let thread_store = panel.read(cx).thread_store().clone();
             assistant.assist(
                 prompt_editor,
                 self.workspace.clone(),
                 project,
-                panel.read(cx).thread_store().clone(),
+                thread_store,
                 None,
                 initial_prompt,
                 window,
                 cx,
-            )
+            );
         })
     }
 

crates/agent_ui/src/agent_ui.rs 🔗

@@ -1,4 +1,4 @@
-mod acp;
+pub mod acp;
 mod agent_configuration;
 mod agent_diff;
 mod agent_model_selector;
@@ -7,6 +7,7 @@ mod buffer_codegen;
 mod completion_provider;
 mod context;
 mod context_server_configuration;
+mod favorite_models;
 mod inline_assistant;
 mod inline_prompt_editor;
 mod language_model_selector;
@@ -26,7 +27,7 @@ use agent_settings::{AgentProfileId, AgentSettings};
 use assistant_slash_command::SlashCommandRegistry;
 use client::Client;
 use command_palette_hooks::CommandPaletteFilter;
-use feature_flags::FeatureFlagAppExt as _;
+use feature_flags::{AgentV2FeatureFlag, FeatureFlagAppExt as _};
 use fs::Fs;
 use gpui::{Action, App, Entity, SharedString, actions};
 use language::{
@@ -67,6 +68,8 @@ actions!(
         ToggleProfileSelector,
         /// Cycles through available session modes.
         CycleModeSelector,
+        /// Cycles through favorited models in the ACP model selector.
+        CycleFavoriteModels,
         /// Expands the message editor to full size.
         ExpandMessageEditor,
         /// Removes all thread history.
@@ -158,16 +161,6 @@ pub enum ExternalAgent {
 }
 
 impl ExternalAgent {
-    pub fn parse_built_in(server: &dyn agent_servers::AgentServer) -> Option<Self> {
-        match server.telemetry_id() {
-            "gemini-cli" => Some(Self::Gemini),
-            "claude-code" => Some(Self::ClaudeCode),
-            "codex" => Some(Self::Codex),
-            "zed" => Some(Self::NativeAgent),
-            _ => None,
-        }
-    }
-
     pub fn server(
         &self,
         fs: Arc<dyn fs::Fs>,
@@ -224,7 +217,7 @@ pub fn init(
     is_eval: bool,
     cx: &mut App,
 ) {
-    assistant_text_thread::init(client.clone(), cx);
+    assistant_text_thread::init(client, cx);
     rules_library::init(cx);
     if !is_eval {
         // Initializing the language model from the user settings messes with the eval, so we only initialize them when
@@ -237,13 +230,8 @@ pub fn init(
     TextThreadEditor::init(cx);
 
     register_slash_commands(cx);
-    inline_assistant::init(
-        fs.clone(),
-        prompt_builder.clone(),
-        client.telemetry().clone(),
-        cx,
-    );
-    terminal_inline_assistant::init(fs.clone(), prompt_builder, client.telemetry().clone(), cx);
+    inline_assistant::init(fs.clone(), prompt_builder.clone(), cx);
+    terminal_inline_assistant::init(fs.clone(), prompt_builder, cx);
     cx.observe_new(move |workspace, window, cx| {
         ConfigureContextServerModal::register(workspace, language_registry.clone(), window, cx)
     })
@@ -259,23 +247,31 @@ pub fn init(
         update_command_palette_filter(app_cx);
     })
     .detach();
+
+    cx.on_flags_ready(|_, cx| {
+        update_command_palette_filter(cx);
+    })
+    .detach();
 }
 
 fn update_command_palette_filter(cx: &mut App) {
     let disable_ai = DisableAiSettings::get_global(cx).disable_ai;
     let agent_enabled = AgentSettings::get_global(cx).enabled;
+    let agent_v2_enabled = cx.has_flag::<AgentV2FeatureFlag>();
     let edit_prediction_provider = AllLanguageSettings::get_global(cx)
         .edit_predictions
         .provider;
 
     CommandPaletteFilter::update_global(cx, |filter, _| {
         use editor::actions::{
-            AcceptEditPrediction, AcceptPartialEditPrediction, NextEditPrediction,
-            PreviousEditPrediction, ShowEditPrediction, ToggleEditPrediction,
+            AcceptEditPrediction, AcceptNextLineEditPrediction, AcceptNextWordEditPrediction,
+            NextEditPrediction, PreviousEditPrediction, ShowEditPrediction, ToggleEditPrediction,
         };
         let edit_prediction_actions = [
             TypeId::of::<AcceptEditPrediction>(),
-            TypeId::of::<AcceptPartialEditPrediction>(),
+            TypeId::of::<AcceptNextWordEditPrediction>(),
+            TypeId::of::<AcceptNextLineEditPrediction>(),
+            TypeId::of::<AcceptEditPrediction>(),
             TypeId::of::<ShowEditPrediction>(),
             TypeId::of::<NextEditPrediction>(),
             TypeId::of::<PreviousEditPrediction>(),
@@ -284,6 +280,7 @@ fn update_command_palette_filter(cx: &mut App) {
 
         if disable_ai {
             filter.hide_namespace("agent");
+            filter.hide_namespace("agents");
             filter.hide_namespace("assistant");
             filter.hide_namespace("copilot");
             filter.hide_namespace("supermaven");
@@ -295,8 +292,10 @@ fn update_command_palette_filter(cx: &mut App) {
         } else {
             if agent_enabled {
                 filter.show_namespace("agent");
+                filter.show_namespace("agents");
             } else {
                 filter.hide_namespace("agent");
+                filter.hide_namespace("agents");
             }
 
             filter.show_namespace("assistant");
@@ -332,6 +331,9 @@ fn update_command_palette_filter(cx: &mut App) {
 
             filter.show_namespace("zed_predict_onboarding");
             filter.show_action_types(&[TypeId::of::<zed_actions::OpenZedPredictOnboarding>()]);
+            if !agent_v2_enabled {
+                filter.hide_action_types(&[TypeId::of::<zed_actions::agent::ToggleAgentPane>()]);
+            }
         }
     });
 }
@@ -346,7 +348,8 @@ fn init_language_model_settings(cx: &mut App) {
         |_, event: &language_model::Event, cx| match event {
             language_model::Event::ProviderStateChanged(_)
             | language_model::Event::AddedProvider(_)
-            | language_model::Event::RemovedProvider(_) => {
+            | language_model::Event::RemovedProvider(_)
+            | language_model::Event::ProvidersChanged => {
                 update_active_language_model_from_settings(cx);
             }
             _ => {}
@@ -430,7 +433,7 @@ mod tests {
     use gpui::{BorrowAppContext, TestAppContext, px};
     use project::DisableAiSettings;
     use settings::{
-        DefaultAgentView, DockPosition, NotifyWhenAgentWaiting, Settings, SettingsStore,
+        DefaultAgentView, DockPosition, DockSide, NotifyWhenAgentWaiting, Settings, SettingsStore,
     };
 
     #[gpui::test]
@@ -449,13 +452,16 @@ mod tests {
             enabled: true,
             button: true,
             dock: DockPosition::Right,
+            agents_panel_dock: DockSide::Left,
             default_width: px(300.),
             default_height: px(600.),
             default_model: None,
             inline_assistant_model: None,
+            inline_assistant_use_streaming_tools: false,
             commit_message_model: None,
             thread_summary_model: None,
             inline_alternatives: vec![],
+            favorite_models: vec![],
             default_profile: AgentProfileId::default(),
             default_view: DefaultAgentView::Thread,
             profiles: Default::default(),

crates/agent_ui/src/buffer_codegen.rs 🔗

@@ -1,26 +1,34 @@
 use crate::{context::LoadedContext, inline_prompt_editor::CodegenStatus};
 use agent_settings::AgentSettings;
 use anyhow::{Context as _, Result};
-use client::telemetry::Telemetry;
+use uuid::Uuid;
+
 use cloud_llm_client::CompletionIntent;
 use collections::HashSet;
 use editor::{Anchor, AnchorRangeExt, MultiBuffer, MultiBufferSnapshot, ToOffset as _, ToPoint};
+use feature_flags::{FeatureFlagAppExt as _, InlineAssistantUseToolFeatureFlag};
 use futures::{
     SinkExt, Stream, StreamExt, TryStreamExt as _,
     channel::mpsc,
     future::{LocalBoxFuture, Shared},
     join,
+    stream::BoxStream,
 };
-use gpui::{App, AppContext as _, Context, Entity, EventEmitter, Subscription, Task};
-use language::{Buffer, IndentKind, Point, TransactionId, line_diff};
+use gpui::{App, AppContext as _, AsyncApp, Context, Entity, EventEmitter, Subscription, Task};
+use language::{Buffer, IndentKind, LanguageName, Point, TransactionId, line_diff};
 use language_model::{
-    LanguageModel, LanguageModelRegistry, LanguageModelRequest, LanguageModelRequestMessage,
-    LanguageModelTextStream, Role, report_assistant_event,
+    LanguageModel, LanguageModelCompletionError, LanguageModelCompletionEvent,
+    LanguageModelRegistry, LanguageModelRequest, LanguageModelRequestMessage,
+    LanguageModelRequestTool, LanguageModelTextStream, LanguageModelToolChoice,
+    LanguageModelToolUse, Role, TokenUsage,
 };
 use multi_buffer::MultiBufferRow;
 use parking_lot::Mutex;
 use prompt_store::PromptBuilder;
 use rope::Rope;
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+use settings::Settings as _;
 use smol::future::FutureExt;
 use std::{
     cmp,
@@ -33,7 +41,26 @@ use std::{
     time::Instant,
 };
 use streaming_diff::{CharOperation, LineDiff, LineOperation, StreamingDiff};
-use telemetry_events::{AssistantEventData, AssistantKind, AssistantPhase};
+
+/// Use this tool when you cannot or should not make a rewrite. This includes:
+/// - The user's request is unclear, ambiguous, or nonsensical
+/// - The requested change cannot be made by only editing the <rewrite_this> section
+#[derive(Debug, Serialize, Deserialize, JsonSchema)]
+pub struct FailureMessageInput {
+    /// A brief message to the user explaining why you're unable to fulfill the request or to ask a question about the request.
+    #[serde(default)]
+    pub message: String,
+}
+
+/// Replaces text in <rewrite_this></rewrite_this> tags with your replacement_text.
+/// Only use this tool when you are confident you understand the user's request and can fulfill it
+/// by editing the marked section.
+#[derive(Debug, Serialize, Deserialize, JsonSchema)]
+pub struct RewriteSectionInput {
+    /// The text to replace the section with.
+    #[serde(default)]
+    pub replacement_text: String,
+}
 
 pub struct BufferCodegen {
     alternatives: Vec<Entity<CodegenAlternative>>,
@@ -43,17 +70,20 @@ pub struct BufferCodegen {
     buffer: Entity<MultiBuffer>,
     range: Range<Anchor>,
     initial_transaction_id: Option<TransactionId>,
-    telemetry: Arc<Telemetry>,
     builder: Arc<PromptBuilder>,
     pub is_insertion: bool,
+    session_id: Uuid,
 }
 
+pub const REWRITE_SECTION_TOOL_NAME: &str = "rewrite_section";
+pub const FAILURE_MESSAGE_TOOL_NAME: &str = "failure_message";
+
 impl BufferCodegen {
     pub fn new(
         buffer: Entity<MultiBuffer>,
         range: Range<Anchor>,
         initial_transaction_id: Option<TransactionId>,
-        telemetry: Arc<Telemetry>,
+        session_id: Uuid,
         builder: Arc<PromptBuilder>,
         cx: &mut Context<Self>,
     ) -> Self {
@@ -62,8 +92,8 @@ impl BufferCodegen {
                 buffer.clone(),
                 range.clone(),
                 false,
-                Some(telemetry.clone()),
                 builder.clone(),
+                session_id,
                 cx,
             )
         });
@@ -76,8 +106,8 @@ impl BufferCodegen {
             buffer,
             range,
             initial_transaction_id,
-            telemetry,
             builder,
+            session_id,
         };
         this.activate(0, cx);
         this
@@ -92,10 +122,18 @@ impl BufferCodegen {
             .push(cx.subscribe(&codegen, |_, _, event, cx| cx.emit(*event)));
     }
 
+    pub fn active_completion(&self, cx: &App) -> Option<String> {
+        self.active_alternative().read(cx).current_completion()
+    }
+
     pub fn active_alternative(&self) -> &Entity<CodegenAlternative> {
         &self.alternatives[self.active_alternative]
     }
 
+    pub fn language_name(&self, cx: &App) -> Option<LanguageName> {
+        self.active_alternative().read(cx).language_name(cx)
+    }
+
     pub fn status<'a>(&self, cx: &'a App) -> &'a CodegenStatus {
         &self.active_alternative().read(cx).status
     }
@@ -154,8 +192,8 @@ impl BufferCodegen {
                     self.buffer.clone(),
                     self.range.clone(),
                     false,
-                    Some(self.telemetry.clone()),
                     self.builder.clone(),
+                    self.session_id,
                     cx,
                 )
             }));
@@ -214,6 +252,14 @@ impl BufferCodegen {
     pub fn last_equal_ranges<'a>(&self, cx: &'a App) -> &'a [Range<Anchor>] {
         self.active_alternative().read(cx).last_equal_ranges()
     }
+
+    pub fn selected_text<'a>(&self, cx: &'a App) -> Option<&'a str> {
+        self.active_alternative().read(cx).selected_text()
+    }
+
+    pub fn session_id(&self) -> Uuid {
+        self.session_id
+    }
 }
 
 impl EventEmitter<CodegenEvent> for BufferCodegen {}
@@ -229,7 +275,6 @@ pub struct CodegenAlternative {
     status: CodegenStatus,
     generation: Task<()>,
     diff: Diff,
-    telemetry: Option<Arc<Telemetry>>,
     _subscription: gpui::Subscription,
     builder: Arc<PromptBuilder>,
     active: bool,
@@ -237,7 +282,11 @@ pub struct CodegenAlternative {
     line_operations: Vec<LineOperation>,
     elapsed_time: Option<f64>,
     completion: Option<String>,
+    selected_text: Option<String>,
     pub message_id: Option<String>,
+    session_id: Uuid,
+    pub description: Option<String>,
+    pub failure: Option<String>,
 }
 
 impl EventEmitter<CodegenEvent> for CodegenAlternative {}
@@ -247,8 +296,8 @@ impl CodegenAlternative {
         buffer: Entity<MultiBuffer>,
         range: Range<Anchor>,
         active: bool,
-        telemetry: Option<Arc<Telemetry>>,
         builder: Arc<PromptBuilder>,
+        session_id: Uuid,
         cx: &mut Context<Self>,
     ) -> Self {
         let snapshot = buffer.read(cx).snapshot(cx);
@@ -287,18 +336,28 @@ impl CodegenAlternative {
             status: CodegenStatus::Idle,
             generation: Task::ready(()),
             diff: Diff::default(),
-            telemetry,
-            _subscription: cx.subscribe(&buffer, Self::handle_buffer_event),
             builder,
-            active,
+            active: active,
             edits: Vec::new(),
             line_operations: Vec::new(),
             range,
             elapsed_time: None,
             completion: None,
+            selected_text: None,
+            session_id,
+            description: None,
+            failure: None,
+            _subscription: cx.subscribe(&buffer, Self::handle_buffer_event),
         }
     }
 
+    pub fn language_name(&self, cx: &App) -> Option<LanguageName> {
+        self.old_buffer
+            .read(cx)
+            .language()
+            .map(|language| language.name())
+    }
+
     pub fn set_active(&mut self, active: bool, cx: &mut Context<Self>) {
         if active != self.active {
             self.active = active;
@@ -340,6 +399,12 @@ impl CodegenAlternative {
         &self.last_equal_ranges
     }
 
+    pub fn use_streaming_tools(model: &dyn LanguageModel, cx: &App) -> bool {
+        model.supports_streaming_tools()
+            && cx.has_flag::<InlineAssistantUseToolFeatureFlag>()
+            && AgentSettings::get_global(cx).inline_assistant_use_streaming_tools
+    }
+
     pub fn start(
         &mut self,
         user_prompt: String,
@@ -347,6 +412,9 @@ impl CodegenAlternative {
         model: Arc<dyn LanguageModel>,
         cx: &mut Context<Self>,
     ) -> Result<()> {
+        // Clear the model explanation since the user has started a new generation.
+        self.description = None;
+
         if let Some(transformation_transaction_id) = self.transformation_transaction_id.take() {
             self.buffer.update(cx, |buffer, cx| {
                 buffer.undo_transaction(transformation_transaction_id, cx);
@@ -355,21 +423,132 @@ impl CodegenAlternative {
 
         self.edit_position = Some(self.range.start.bias_right(&self.snapshot));
 
-        let api_key = model.api_key(cx);
-        let telemetry_id = model.telemetry_id();
-        let provider_id = model.provider_id();
-        let stream: LocalBoxFuture<Result<LanguageModelTextStream>> =
-            if user_prompt.trim().to_lowercase() == "delete" {
-                async { Ok(LanguageModelTextStream::default()) }.boxed_local()
+        if Self::use_streaming_tools(model.as_ref(), cx) {
+            let request = self.build_request(&model, user_prompt, context_task, cx)?;
+            let completion_events = cx.spawn({
+                let model = model.clone();
+                async move |_, cx| model.stream_completion(request.await, cx).await
+            });
+            self.generation = self.handle_completion(model, completion_events, cx);
+        } else {
+            let stream: LocalBoxFuture<Result<LanguageModelTextStream>> =
+                if user_prompt.trim().to_lowercase() == "delete" {
+                    async { Ok(LanguageModelTextStream::default()) }.boxed_local()
+                } else {
+                    let request = self.build_request(&model, user_prompt, context_task, cx)?;
+                    cx.spawn({
+                        let model = model.clone();
+                        async move |_, cx| {
+                            Ok(model.stream_completion_text(request.await, cx).await?)
+                        }
+                    })
+                    .boxed_local()
+                };
+            self.generation =
+                self.handle_stream(model, /* strip_invalid_spans: */ true, stream, cx);
+        }
+
+        Ok(())
+    }
+
+    fn build_request_tools(
+        &self,
+        model: &Arc<dyn LanguageModel>,
+        user_prompt: String,
+        context_task: Shared<Task<Option<LoadedContext>>>,
+        cx: &mut App,
+    ) -> Result<Task<LanguageModelRequest>> {
+        let buffer = self.buffer.read(cx).snapshot(cx);
+        let language = buffer.language_at(self.range.start);
+        let language_name = if let Some(language) = language.as_ref() {
+            if Arc::ptr_eq(language, &language::PLAIN_TEXT) {
+                None
             } else {
-                let request = self.build_request(&model, user_prompt, context_task, cx)?;
-                cx.spawn(async move |_, cx| {
-                    Ok(model.stream_completion_text(request.await, cx).await?)
-                })
-                .boxed_local()
+                Some(language.name())
+            }
+        } else {
+            None
+        };
+
+        let language_name = language_name.as_ref();
+        let start = buffer.point_to_buffer_offset(self.range.start);
+        let end = buffer.point_to_buffer_offset(self.range.end);
+        let (buffer, range) = if let Some((start, end)) = start.zip(end) {
+            let (start_buffer, start_buffer_offset) = start;
+            let (end_buffer, end_buffer_offset) = end;
+            if start_buffer.remote_id() == end_buffer.remote_id() {
+                (start_buffer.clone(), start_buffer_offset..end_buffer_offset)
+            } else {
+                anyhow::bail!("invalid transformation range");
+            }
+        } else {
+            anyhow::bail!("invalid transformation range");
+        };
+
+        let system_prompt = self
+            .builder
+            .generate_inline_transformation_prompt_tools(
+                language_name,
+                buffer,
+                range.start.0..range.end.0,
+            )
+            .context("generating content prompt")?;
+
+        let temperature = AgentSettings::temperature_for_model(model, cx);
+
+        let tool_input_format = model.tool_input_format();
+        let tool_choice = model
+            .supports_tool_choice(LanguageModelToolChoice::Any)
+            .then_some(LanguageModelToolChoice::Any);
+
+        Ok(cx.spawn(async move |_cx| {
+            let mut messages = vec![LanguageModelRequestMessage {
+                role: Role::System,
+                content: vec![system_prompt.into()],
+                cache: false,
+                reasoning_details: None,
+            }];
+
+            let mut user_message = LanguageModelRequestMessage {
+                role: Role::User,
+                content: Vec::new(),
+                cache: false,
+                reasoning_details: None,
             };
-        self.handle_stream(telemetry_id, provider_id.to_string(), api_key, stream, cx);
-        Ok(())
+
+            if let Some(context) = context_task.await {
+                context.add_to_request_message(&mut user_message);
+            }
+
+            user_message.content.push(user_prompt.into());
+            messages.push(user_message);
+
+            let tools = vec![
+                LanguageModelRequestTool {
+                    name: REWRITE_SECTION_TOOL_NAME.to_string(),
+                    description: "Replaces text in <rewrite_this></rewrite_this> tags with your replacement_text.".to_string(),
+                    input_schema: language_model::tool_schema::root_schema_for::<RewriteSectionInput>(tool_input_format).to_value(),
+                },
+                LanguageModelRequestTool {
+                    name: FAILURE_MESSAGE_TOOL_NAME.to_string(),
+                    description: "Use this tool to provide a message to the user when you're unable to complete a task.".to_string(),
+                    input_schema: language_model::tool_schema::root_schema_for::<FailureMessageInput>(tool_input_format).to_value(),
+                },
+            ];
+
+            LanguageModelRequest {
+                thread_id: None,
+                prompt_id: None,
+                intent: Some(CompletionIntent::InlineAssist),
+                mode: None,
+                tools,
+                tool_choice,
+                stop: Vec::new(),
+                temperature,
+                messages,
+                thinking_allowed: false,
+            }
+        }))
     }
 
     fn build_request(
@@ -379,6 +558,10 @@ impl CodegenAlternative {
         context_task: Shared<Task<Option<LoadedContext>>>,
         cx: &mut App,
     ) -> Result<Task<LanguageModelRequest>> {
+        if Self::use_streaming_tools(model.as_ref(), cx) {
+            return self.build_request_tools(model, user_prompt, context_task, cx);
+        }
+
         let buffer = self.buffer.read(cx).snapshot(cx);
         let language = buffer.language_at(self.range.start);
         let language_name = if let Some(language) = language.as_ref() {
@@ -449,12 +632,15 @@ impl CodegenAlternative {
 
     pub fn handle_stream(
         &mut self,
-        model_telemetry_id: String,
-        model_provider_id: String,
-        model_api_key: Option<String>,
+        model: Arc<dyn LanguageModel>,
+        strip_invalid_spans: bool,
         stream: impl 'static + Future<Output = Result<LanguageModelTextStream>>,
         cx: &mut Context<Self>,
-    ) {
+    ) -> Task<()> {
+        let anthropic_reporter = language_model::AnthropicEventReporter::new(&model, cx);
+        let session_id = self.session_id;
+        let model_telemetry_id = model.telemetry_id();
+        let model_provider_id = model.provider_id().to_string();
         let start_time = Instant::now();
 
         // Make a new snapshot and re-resolve anchor in case the document was modified.
@@ -469,6 +655,8 @@ impl CodegenAlternative {
             .text_for_range(self.range.start..self.range.end)
             .collect::<Rope>();
 
+        self.selected_text = Some(selected_text.to_string());
+
         let selection_start = self.range.start.to_point(&snapshot);
 
         // Start with the indentation of the first line in the selection
@@ -490,8 +678,6 @@ impl CodegenAlternative {
             }
         }
 
-        let http_client = cx.http_client();
-        let telemetry = self.telemetry.clone();
         let language_name = {
             let multibuffer = self.buffer.read(cx);
             let snapshot = multibuffer.snapshot(cx);
@@ -508,8 +694,10 @@ impl CodegenAlternative {
         let completion = Arc::new(Mutex::new(String::new()));
         let completion_clone = completion.clone();
 
-        self.generation = cx.spawn(async move |codegen, cx| {
+        cx.notify();
+        cx.spawn(async move |codegen, cx| {
             let stream = stream.await;
+
             let token_usage = stream
                 .as_ref()
                 .ok()
@@ -522,17 +710,25 @@ impl CodegenAlternative {
                 let model_telemetry_id = model_telemetry_id.clone();
                 let model_provider_id = model_provider_id.clone();
                 let (mut diff_tx, mut diff_rx) = mpsc::channel(1);
-                let executor = cx.background_executor().clone();
                 let message_id = message_id.clone();
-                let line_based_stream_diff: Task<anyhow::Result<()>> =
-                    cx.background_spawn(async move {
+                let line_based_stream_diff: Task<anyhow::Result<()>> = cx.background_spawn({
+                    let anthropic_reporter = anthropic_reporter.clone();
+                    let language_name = language_name.clone();
+                    async move {
                         let mut response_latency = None;
                         let request_start = Instant::now();
                         let diff = async {
-                            let chunks = StripInvalidSpans::new(
-                                stream?.stream.map_err(|error| error.into()),
-                            );
-                            futures::pin_mut!(chunks);
+                            let raw_stream = stream?.stream.map_err(|error| error.into());
+
+                            let stripped;
+                            let mut chunks: Pin<Box<dyn Stream<Item = Result<String>> + Send>> =
+                                if strip_invalid_spans {
+                                    stripped = StripInvalidSpans::new(raw_stream);
+                                    Box::pin(stripped)
+                                } else {
+                                    Box::pin(raw_stream)
+                                };
+
                             let mut diff = StreamingDiff::new(selected_text.to_string());
                             let mut line_diff = LineDiff::default();
 
@@ -621,27 +817,30 @@ impl CodegenAlternative {
                         let result = diff.await;
 
                         let error_message = result.as_ref().err().map(|error| error.to_string());
-                        report_assistant_event(
-                            AssistantEventData {
-                                conversation_id: None,
-                                message_id,
-                                kind: AssistantKind::Inline,
-                                phase: AssistantPhase::Response,
-                                model: model_telemetry_id,
-                                model_provider: model_provider_id,
-                                response_latency,
-                                error_message,
-                                language_name: language_name.map(|name| name.to_proto()),
-                            },
-                            telemetry,
-                            http_client,
-                            model_api_key,
-                            &executor,
+                        telemetry::event!(
+                            "Assistant Responded",
+                            kind = "inline",
+                            phase = "response",
+                            session_id = session_id.to_string(),
+                            model = model_telemetry_id,
+                            model_provider = model_provider_id,
+                            language_name = language_name.as_ref().map(|n| n.to_string()),
+                            message_id = message_id.as_deref(),
+                            response_latency = response_latency,
+                            error_message = error_message.as_deref(),
                         );
 
+                        anthropic_reporter.report(language_model::AnthropicEventData {
+                            completion_type: language_model::AnthropicCompletionType::Editor,
+                            event: language_model::AnthropicEventType::Response,
+                            language_name: language_name.map(|n| n.to_string()),
+                            message_id,
+                        });
+
                         result?;
                         Ok(())
-                    });
+                    }
+                });
 
                 while let Some((char_ops, line_ops)) = diff_rx.next().await {
                     codegen.update(cx, |codegen, cx| {
@@ -719,12 +918,30 @@ impl CodegenAlternative {
                             output_tokens = usage.output_tokens,
                         )
                     }
+
                     cx.emit(CodegenEvent::Finished);
                     cx.notify();
                 })
                 .ok();
-        });
-        cx.notify();
+        })
+    }
+
+    pub fn current_completion(&self) -> Option<String> {
+        self.completion.clone()
+    }
+
+    #[cfg(any(test, feature = "test-support"))]
+    pub fn current_description(&self) -> Option<String> {
+        self.description.clone()
+    }
+
+    #[cfg(any(test, feature = "test-support"))]
+    pub fn current_failure(&self) -> Option<String> {
+        self.failure.clone()
+    }
+
+    pub fn selected_text(&self) -> Option<&str> {
+        self.selected_text.as_deref()
     }
 
     pub fn stop(&mut self, cx: &mut Context<Self>) {
@@ -898,6 +1115,224 @@ impl CodegenAlternative {
                 .ok();
         })
     }
+
+    fn handle_completion(
+        &mut self,
+        model: Arc<dyn LanguageModel>,
+        completion_stream: Task<
+            Result<
+                BoxStream<
+                    'static,
+                    Result<LanguageModelCompletionEvent, LanguageModelCompletionError>,
+                >,
+                LanguageModelCompletionError,
+            >,
+        >,
+        cx: &mut Context<Self>,
+    ) -> Task<()> {
+        self.diff = Diff::default();
+        self.status = CodegenStatus::Pending;
+
+        cx.notify();
+        // Leaving this in generation so that STOP equivalent events are respected even
+        // while we're still pre-processing the completion event
+        cx.spawn(async move |codegen, cx| {
+            let finish_with_status = |status: CodegenStatus, cx: &mut AsyncApp| {
+                let _ = codegen.update(cx, |this, cx| {
+                    this.status = status;
+                    cx.emit(CodegenEvent::Finished);
+                    cx.notify();
+                });
+            };
+
+            let mut completion_events = match completion_stream.await {
+                Ok(events) => events,
+                Err(err) => {
+                    finish_with_status(CodegenStatus::Error(err.into()), cx);
+                    return;
+                }
+            };
+
+            enum ToolUseOutput {
+                Rewrite {
+                    text: String,
+                    description: Option<String>,
+                },
+                Failure(String),
+            }
+
+            enum ModelUpdate {
+                Description(String),
+                Failure(String),
+            }
+
+            let chars_read_so_far = Arc::new(Mutex::new(0usize));
+            let process_tool_use = move |tool_use: LanguageModelToolUse| -> Option<ToolUseOutput> {
+                let mut chars_read_so_far = chars_read_so_far.lock();
+                match tool_use.name.as_ref() {
+                    REWRITE_SECTION_TOOL_NAME => {
+                        let Ok(input) =
+                            serde_json::from_value::<RewriteSectionInput>(tool_use.input)
+                        else {
+                            return None;
+                        };
+                        let text = input.replacement_text[*chars_read_so_far..].to_string();
+                        *chars_read_so_far = input.replacement_text.len();
+                        Some(ToolUseOutput::Rewrite {
+                            text,
+                            description: None,
+                        })
+                    }
+                    FAILURE_MESSAGE_TOOL_NAME => {
+                        let Ok(mut input) =
+                            serde_json::from_value::<FailureMessageInput>(tool_use.input)
+                        else {
+                            return None;
+                        };
+                        Some(ToolUseOutput::Failure(std::mem::take(&mut input.message)))
+                    }
+                    _ => None,
+                }
+            };
+
+            let (message_tx, mut message_rx) = futures::channel::mpsc::unbounded::<ModelUpdate>();
+
+            cx.spawn({
+                let codegen = codegen.clone();
+                async move |cx| {
+                    while let Some(update) = message_rx.next().await {
+                        let _ = codegen.update(cx, |this, _cx| match update {
+                            ModelUpdate::Description(d) => this.description = Some(d),
+                            ModelUpdate::Failure(f) => this.failure = Some(f),
+                        });
+                    }
+                }
+            })
+            .detach();
+
+            let mut message_id = None;
+            let mut first_text = None;
+            let last_token_usage = Arc::new(Mutex::new(TokenUsage::default()));
+            let total_text = Arc::new(Mutex::new(String::new()));
+
+            loop {
+                if let Some(first_event) = completion_events.next().await {
+                    match first_event {
+                        Ok(LanguageModelCompletionEvent::StartMessage { message_id: id }) => {
+                            message_id = Some(id);
+                        }
+                        Ok(LanguageModelCompletionEvent::ToolUse(tool_use)) => {
+                            if let Some(output) = process_tool_use(tool_use) {
+                                let (text, update) = match output {
+                                    ToolUseOutput::Rewrite { text, description } => {
+                                        (Some(text), description.map(ModelUpdate::Description))
+                                    }
+                                    ToolUseOutput::Failure(message) => {
+                                        (None, Some(ModelUpdate::Failure(message)))
+                                    }
+                                };
+                                if let Some(update) = update {
+                                    let _ = message_tx.unbounded_send(update);
+                                }
+                                first_text = text;
+                                if first_text.is_some() {
+                                    break;
+                                }
+                            }
+                        }
+                        Ok(LanguageModelCompletionEvent::UsageUpdate(token_usage)) => {
+                            *last_token_usage.lock() = token_usage;
+                        }
+                        Ok(LanguageModelCompletionEvent::Text(text)) => {
+                            let mut lock = total_text.lock();
+                            lock.push_str(&text);
+                        }
+                        Ok(e) => {
+                            log::warn!("Unexpected event: {:?}", e);
+                            break;
+                        }
+                        Err(e) => {
+                            finish_with_status(CodegenStatus::Error(e.into()), cx);
+                            break;
+                        }
+                    }
+                }
+            }
+
+            let Some(first_text) = first_text else {
+                finish_with_status(CodegenStatus::Done, cx);
+                return;
+            };
+
+            let move_last_token_usage = last_token_usage.clone();
+
+            let text_stream = Box::pin(futures::stream::once(async { Ok(first_text) }).chain(
+                completion_events.filter_map(move |e| {
+                    let process_tool_use = process_tool_use.clone();
+                    let last_token_usage = move_last_token_usage.clone();
+                    let total_text = total_text.clone();
+                    let mut message_tx = message_tx.clone();
+                    async move {
+                        match e {
+                            Ok(LanguageModelCompletionEvent::ToolUse(tool_use)) => {
+                                let Some(output) = process_tool_use(tool_use) else {
+                                    return None;
+                                };
+                                let (text, update) = match output {
+                                    ToolUseOutput::Rewrite { text, description } => {
+                                        (Some(text), description.map(ModelUpdate::Description))
+                                    }
+                                    ToolUseOutput::Failure(message) => {
+                                        (None, Some(ModelUpdate::Failure(message)))
+                                    }
+                                };
+                                if let Some(update) = update {
+                                    let _ = message_tx.send(update).await;
+                                }
+                                text.map(Ok)
+                            }
+                            Ok(LanguageModelCompletionEvent::UsageUpdate(token_usage)) => {
+                                *last_token_usage.lock() = token_usage;
+                                None
+                            }
+                            Ok(LanguageModelCompletionEvent::Text(text)) => {
+                                let mut lock = total_text.lock();
+                                lock.push_str(&text);
+                                None
+                            }
+                            Ok(LanguageModelCompletionEvent::Stop(_reason)) => None,
+                            e => {
+                                log::error!("UNEXPECTED EVENT {:?}", e);
+                                None
+                            }
+                        }
+                    }
+                }),
+            ));
+
+            let language_model_text_stream = LanguageModelTextStream {
+                message_id: message_id,
+                stream: text_stream,
+                last_token_usage,
+            };
+
+            let Some(task) = codegen
+                .update(cx, move |codegen, cx| {
+                    codegen.handle_stream(
+                        model,
+                        /* strip_invalid_spans: */ false,
+                        async { Ok(language_model_text_stream) },
+                        cx,
+                    )
+                })
+                .ok()
+            else {
+                return;
+            };
+
+            task.await;
+        })
+    }
 }
 
 #[derive(Copy, Clone, Debug)]
@@ -1059,8 +1494,13 @@ mod tests {
     };
     use gpui::TestAppContext;
     use indoc::indoc;
-    use language::{Buffer, Language, LanguageConfig, LanguageMatcher, Point, tree_sitter_rust};
-    use language_model::{LanguageModelRegistry, TokenUsage};
+    use language::{Buffer, Point};
+    use language_model::fake_provider::FakeLanguageModel;
+    use language_model::{
+        LanguageModelCompletionError, LanguageModelCompletionEvent, LanguageModelRegistry,
+        LanguageModelToolUse, StopReason, TokenUsage,
+    };
+    use languages::rust_lang;
     use rand::prelude::*;
     use settings::SettingsStore;
     use std::{future, sync::Arc};
@@ -1077,7 +1517,7 @@ mod tests {
                 }
             }
         "};
-        let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(Arc::new(rust_lang()), cx));
+        let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(rust_lang(), cx));
         let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
         let range = buffer.read_with(cx, |buffer, cx| {
             let snapshot = buffer.snapshot(cx);
@@ -1089,8 +1529,8 @@ mod tests {
                 buffer.clone(),
                 range.clone(),
                 true,
-                None,
                 prompt_builder,
+                Uuid::new_v4(),
                 cx,
             )
         });
@@ -1139,7 +1579,7 @@ mod tests {
                 le
             }
         "};
-        let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(Arc::new(rust_lang()), cx));
+        let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(rust_lang(), cx));
         let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
         let range = buffer.read_with(cx, |buffer, cx| {
             let snapshot = buffer.snapshot(cx);
@@ -1151,8 +1591,8 @@ mod tests {
                 buffer.clone(),
                 range.clone(),
                 true,
-                None,
                 prompt_builder,
+                Uuid::new_v4(),
                 cx,
             )
         });
@@ -1203,7 +1643,7 @@ mod tests {
             "  \n",
             "}\n" //
         );
-        let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(Arc::new(rust_lang()), cx));
+        let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(rust_lang(), cx));
         let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
         let range = buffer.read_with(cx, |buffer, cx| {
             let snapshot = buffer.snapshot(cx);
@@ -1215,8 +1655,8 @@ mod tests {
                 buffer.clone(),
                 range.clone(),
                 true,
-                None,
                 prompt_builder,
+                Uuid::new_v4(),
                 cx,
             )
         });
@@ -1279,8 +1719,8 @@ mod tests {
                 buffer.clone(),
                 range.clone(),
                 true,
-                None,
                 prompt_builder,
+                Uuid::new_v4(),
                 cx,
             )
         });
@@ -1319,7 +1759,7 @@ mod tests {
                 let x = 0;
             }
         "};
-        let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(Arc::new(rust_lang()), cx));
+        let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(rust_lang(), cx));
         let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
         let range = buffer.read_with(cx, |buffer, cx| {
             let snapshot = buffer.snapshot(cx);
@@ -1331,8 +1771,8 @@ mod tests {
                 buffer.clone(),
                 range.clone(),
                 false,
-                None,
                 prompt_builder,
+                Uuid::new_v4(),
                 cx,
             )
         });
@@ -1371,6 +1811,51 @@ mod tests {
         );
     }
 
+    // When not streaming tool calls, we strip backticks as part of parsing the model's
+    // plain text response. This is a regression test for a bug where we stripped
+    // backticks incorrectly.
+    #[gpui::test]
+    async fn test_allows_model_to_output_backticks(cx: &mut TestAppContext) {
+        init_test(cx);
+        let text = "- Improved; `cmd+click` behavior. Now requires `cmd` to be pressed before the click starts or it doesn't run. ([#44579](https://github.com/zed-industries/zed/pull/44579); thanks [Zachiah](https://github.com/Zachiah))";
+        let buffer = cx.new(|cx| Buffer::local("", cx));
+        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
+        let range = buffer.read_with(cx, |buffer, cx| {
+            let snapshot = buffer.snapshot(cx);
+            snapshot.anchor_before(Point::new(0, 0))..snapshot.anchor_after(Point::new(0, 0))
+        });
+        let prompt_builder = Arc::new(PromptBuilder::new(None).unwrap());
+        let codegen = cx.new(|cx| {
+            CodegenAlternative::new(
+                buffer.clone(),
+                range.clone(),
+                true,
+                prompt_builder,
+                Uuid::new_v4(),
+                cx,
+            )
+        });
+
+        let events_tx = simulate_tool_based_completion(&codegen, cx);
+        let chunk_len = text.find('`').unwrap();
+        events_tx
+            .unbounded_send(rewrite_tool_use("tool_1", &text[..chunk_len], false))
+            .unwrap();
+        events_tx
+            .unbounded_send(rewrite_tool_use("tool_2", &text, true))
+            .unwrap();
+        events_tx
+            .unbounded_send(LanguageModelCompletionEvent::Stop(StopReason::EndTurn))
+            .unwrap();
+        drop(events_tx);
+        cx.run_until_parked();
+
+        assert_eq!(
+            buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx).text()),
+            text
+        );
+    }
+
     #[gpui::test]
     async fn test_strip_invalid_spans_from_codeblock() {
         assert_chunks("Lorem ipsum dolor", "Lorem ipsum dolor").await;
@@ -1421,11 +1906,11 @@ mod tests {
         cx: &mut TestAppContext,
     ) -> mpsc::UnboundedSender<String> {
         let (chunks_tx, chunks_rx) = mpsc::unbounded();
+        let model = Arc::new(FakeLanguageModel::default());
         codegen.update(cx, |codegen, cx| {
-            codegen.handle_stream(
-                String::new(),
-                String::new(),
-                None,
+            codegen.generation = codegen.handle_stream(
+                model,
+                /* strip_invalid_spans: */ false,
                 future::ready(Ok(LanguageModelTextStream {
                     message_id: None,
                     stream: chunks_rx.map(Ok).boxed(),
@@ -1437,26 +1922,38 @@ mod tests {
         chunks_tx
     }
 
-    fn rust_lang() -> Language {
-        Language::new(
-            LanguageConfig {
-                name: "Rust".into(),
-                matcher: LanguageMatcher {
-                    path_suffixes: vec!["rs".to_string()],
-                    ..Default::default()
-                },
-                ..Default::default()
-            },
-            Some(tree_sitter_rust::LANGUAGE.into()),
-        )
-        .with_indents_query(
-            r#"
-            (call_expression) @indent
-            (field_expression) @indent
-            (_ "(" ")" @end) @indent
-            (_ "{" "}" @end) @indent
-            "#,
-        )
-        .unwrap()
+    fn simulate_tool_based_completion(
+        codegen: &Entity<CodegenAlternative>,
+        cx: &mut TestAppContext,
+    ) -> mpsc::UnboundedSender<LanguageModelCompletionEvent> {
+        let (events_tx, events_rx) = mpsc::unbounded();
+        let model = Arc::new(FakeLanguageModel::default());
+        codegen.update(cx, |codegen, cx| {
+            let completion_stream = Task::ready(Ok(events_rx.map(Ok).boxed()
+                as BoxStream<
+                    'static,
+                    Result<LanguageModelCompletionEvent, LanguageModelCompletionError>,
+                >));
+            codegen.generation = codegen.handle_completion(model, completion_stream, cx);
+        });
+        events_tx
+    }
+
+    fn rewrite_tool_use(
+        id: &str,
+        replacement_text: &str,
+        is_complete: bool,
+    ) -> LanguageModelCompletionEvent {
+        let input = RewriteSectionInput {
+            replacement_text: replacement_text.into(),
+        };
+        LanguageModelCompletionEvent::ToolUse(LanguageModelToolUse {
+            id: id.into(),
+            name: REWRITE_SECTION_TOOL_NAME.into(),
+            raw_input: serde_json::to_string(&input).unwrap(),
+            input: serde_json::to_value(&input).unwrap(),
+            is_input_complete: is_complete,
+            thought_signature: None,
+        })
     }
 }

crates/agent_ui/src/completion_provider.rs 🔗

@@ -20,7 +20,7 @@ use project::{
     Completion, CompletionDisplayOptions, CompletionIntent, CompletionResponse,
     PathMatchCandidateSet, Project, ProjectPath, Symbol, WorktreeId,
 };
-use prompt_store::{PromptId, PromptStore, UserPromptId};
+use prompt_store::{PromptStore, UserPromptId};
 use rope::Point;
 use text::{Anchor, ToPoint as _};
 use ui::prelude::*;
@@ -1114,7 +1114,6 @@ impl<T: PromptCompletionProviderDelegate> CompletionProvider for PromptCompletio
         position: language::Anchor,
         _text: &str,
         _trigger_in_words: bool,
-        _menu_is_open: bool,
         cx: &mut Context<Editor>,
     ) -> bool {
         let buffer = buffer.read(cx);
@@ -1586,13 +1585,10 @@ pub(crate) fn search_rules(
                 if metadata.default {
                     None
                 } else {
-                    match metadata.id {
-                        PromptId::EditWorkflow => None,
-                        PromptId::User { uuid } => Some(RulesContextEntry {
-                            prompt_id: uuid,
-                            title: metadata.title?,
-                        }),
-                    }
+                    Some(RulesContextEntry {
+                        prompt_id: metadata.id.as_user()?,
+                        title: metadata.title?,
+                    })
                 }
             })
             .collect::<Vec<_>>()

crates/agent_ui/src/favorite_models.rs 🔗

@@ -0,0 +1,30 @@
+use std::sync::Arc;
+
+use fs::Fs;
+use language_model::LanguageModel;
+use settings::{LanguageModelSelection, update_settings_file};
+use ui::App;
+
+fn language_model_to_selection(model: &Arc<dyn LanguageModel>) -> LanguageModelSelection {
+    LanguageModelSelection {
+        provider: model.provider_id().to_string().into(),
+        model: model.id().0.to_string(),
+    }
+}
+
+pub fn toggle_in_settings(
+    model: Arc<dyn LanguageModel>,
+    should_be_favorite: bool,
+    fs: Arc<dyn Fs>,
+    cx: &mut App,
+) {
+    let selection = language_model_to_selection(&model);
+    update_settings_file(fs, cx, move |settings, _| {
+        let agent = settings.agent.get_or_insert_default();
+        if should_be_favorite {
+            agent.add_favorite_model(selection.clone());
+        } else {
+            agent.remove_favorite_model(&selection);
+        }
+    });
+}

crates/agent_ui/src/inline_assistant.rs 🔗

@@ -1,8 +1,11 @@
+use language_model::AnthropicEventData;
+use language_model::report_anthropic_event;
 use std::cmp;
 use std::mem;
 use std::ops::Range;
 use std::rc::Rc;
 use std::sync::Arc;
+use uuid::Uuid;
 
 use crate::context::load_context;
 use crate::mention_set::MentionSet;
@@ -15,7 +18,6 @@ use crate::{
 use agent::HistoryStore;
 use agent_settings::AgentSettings;
 use anyhow::{Context as _, Result};
-use client::telemetry::Telemetry;
 use collections::{HashMap, HashSet, VecDeque, hash_map};
 use editor::EditorSnapshot;
 use editor::MultiBufferOffset;
@@ -32,21 +34,19 @@ use editor::{
     },
 };
 use fs::Fs;
-use futures::FutureExt;
+use futures::{FutureExt, channel::mpsc};
 use gpui::{
     App, Context, Entity, Focusable, Global, HighlightStyle, Subscription, Task, UpdateGlobal,
     WeakEntity, Window, point,
 };
 use language::{Buffer, Point, Selection, TransactionId};
-use language_model::{
-    ConfigurationError, ConfiguredModel, LanguageModelRegistry, report_assistant_event,
-};
+use language_model::{ConfigurationError, ConfiguredModel, LanguageModelRegistry};
 use multi_buffer::MultiBufferRow;
 use parking_lot::Mutex;
 use project::{CodeAction, DisableAiSettings, LspAction, Project, ProjectTransaction};
 use prompt_store::{PromptBuilder, PromptStore};
 use settings::{Settings, SettingsStore};
-use telemetry_events::{AssistantEventData, AssistantKind, AssistantPhase};
+
 use terminal_view::{TerminalView, terminal_panel::TerminalPanel};
 use text::{OffsetRangeExt, ToPoint as _};
 use ui::prelude::*;
@@ -54,13 +54,8 @@ use util::{RangeExt, ResultExt, maybe};
 use workspace::{ItemHandle, Toast, Workspace, dock::Panel, notifications::NotificationId};
 use zed_actions::agent::OpenSettings;
 
-pub fn init(
-    fs: Arc<dyn Fs>,
-    prompt_builder: Arc<PromptBuilder>,
-    telemetry: Arc<Telemetry>,
-    cx: &mut App,
-) {
-    cx.set_global(InlineAssistant::new(fs, prompt_builder, telemetry));
+pub fn init(fs: Arc<dyn Fs>, prompt_builder: Arc<PromptBuilder>, cx: &mut App) {
+    cx.set_global(InlineAssistant::new(fs, prompt_builder));
 
     cx.observe_global::<SettingsStore>(|cx| {
         if DisableAiSettings::get_global(cx).disable_ai {
@@ -100,18 +95,14 @@ pub struct InlineAssistant {
     confirmed_assists: HashMap<InlineAssistId, Entity<CodegenAlternative>>,
     prompt_history: VecDeque<String>,
     prompt_builder: Arc<PromptBuilder>,
-    telemetry: Arc<Telemetry>,
     fs: Arc<dyn Fs>,
+    _inline_assistant_completions: Option<mpsc::UnboundedSender<anyhow::Result<InlineAssistId>>>,
 }
 
 impl Global for InlineAssistant {}
 
 impl InlineAssistant {
-    pub fn new(
-        fs: Arc<dyn Fs>,
-        prompt_builder: Arc<PromptBuilder>,
-        telemetry: Arc<Telemetry>,
-    ) -> Self {
+    pub fn new(fs: Arc<dyn Fs>, prompt_builder: Arc<PromptBuilder>) -> Self {
         Self {
             next_assist_id: InlineAssistId::default(),
             next_assist_group_id: InlineAssistGroupId::default(),
@@ -121,8 +112,8 @@ impl InlineAssistant {
             confirmed_assists: HashMap::default(),
             prompt_history: VecDeque::default(),
             prompt_builder,
-            telemetry,
             fs,
+            _inline_assistant_completions: None,
         }
     }
 
@@ -287,7 +278,7 @@ impl InlineAssistant {
                             action.prompt.clone(),
                             window,
                             cx,
-                        )
+                        );
                     })
                 }
                 InlineAssistTarget::Terminal(active_terminal) => {
@@ -301,8 +292,8 @@ impl InlineAssistant {
                             action.prompt.clone(),
                             window,
                             cx,
-                        )
-                    })
+                        );
+                    });
                 }
             };
 
@@ -377,17 +368,9 @@ impl InlineAssistant {
         let mut selections = Vec::<Selection<Point>>::new();
         let mut newest_selection = None;
         for mut selection in initial_selections {
-            if selection.end > selection.start {
-                selection.start.column = 0;
-                // If the selection ends at the start of the line, we don't want to include it.
-                if selection.end.column == 0 {
-                    selection.end.row -= 1;
-                }
-                selection.end.column = snapshot
-                    .buffer_snapshot()
-                    .line_len(MultiBufferRow(selection.end.row));
-            } else if let Some(fold) =
-                snapshot.crease_for_buffer_row(MultiBufferRow(selection.end.row))
+            if selection.end == selection.start
+                && let Some(fold) =
+                    snapshot.crease_for_buffer_row(MultiBufferRow(selection.end.row))
             {
                 selection.start = fold.range().start;
                 selection.end = fold.range().end;
@@ -414,6 +397,15 @@ impl InlineAssistant {
                         }
                     }
                 }
+            } else {
+                selection.start.column = 0;
+                // If the selection ends at the start of the line, we don't want to include it.
+                if selection.end.column == 0 && selection.start.row != selection.end.row {
+                    selection.end.row -= 1;
+                }
+                selection.end.column = snapshot
+                    .buffer_snapshot()
+                    .line_len(MultiBufferRow(selection.end.row));
             }
 
             if let Some(prev_selection) = selections.last_mut()
@@ -446,17 +438,25 @@ impl InlineAssistant {
             codegen_ranges.push(anchor_range);
 
             if let Some(model) = LanguageModelRegistry::read_global(cx).inline_assistant_model() {
-                self.telemetry.report_assistant_event(AssistantEventData {
-                    conversation_id: None,
-                    kind: AssistantKind::Inline,
-                    phase: AssistantPhase::Invoked,
-                    message_id: None,
-                    model: model.model.telemetry_id(),
-                    model_provider: model.provider.id().to_string(),
-                    response_latency: None,
-                    error_message: None,
-                    language_name: buffer.language().map(|language| language.name().to_proto()),
-                });
+                telemetry::event!(
+                    "Assistant Invoked",
+                    kind = "inline",
+                    phase = "invoked",
+                    model = model.model.telemetry_id(),
+                    model_provider = model.provider.id().to_string(),
+                    language_name = buffer.language().map(|language| language.name().to_proto())
+                );
+
+                report_anthropic_event(
+                    &model.model,
+                    AnthropicEventData {
+                        completion_type: language_model::AnthropicCompletionType::Editor,
+                        event: language_model::AnthropicEventType::Invoked,
+                        language_name: buffer.language().map(|language| language.name().to_proto()),
+                        message_id: None,
+                    },
+                    cx,
+                );
             }
         }
 
@@ -480,6 +480,7 @@ impl InlineAssistant {
         let snapshot = editor.update(cx, |editor, cx| editor.snapshot(window, cx));
 
         let assist_group_id = self.next_assist_group_id.post_inc();
+        let session_id = Uuid::new_v4();
         let prompt_buffer = cx.new(|cx| {
             MultiBuffer::singleton(
                 cx.new(|cx| Buffer::local(initial_prompt.unwrap_or_default(), cx)),
@@ -497,7 +498,7 @@ impl InlineAssistant {
                     editor.read(cx).buffer().clone(),
                     range.clone(),
                     initial_transaction_id,
-                    self.telemetry.clone(),
+                    session_id,
                     self.prompt_builder.clone(),
                     cx,
                 )
@@ -511,6 +512,7 @@ impl InlineAssistant {
                     self.prompt_history.clone(),
                     prompt_buffer.clone(),
                     codegen.clone(),
+                    session_id,
                     self.fs.clone(),
                     thread_store.clone(),
                     prompt_store.clone(),
@@ -534,14 +536,15 @@ impl InlineAssistant {
                 }
             }
 
-            let [prompt_block_id, end_block_id] =
-                self.insert_assist_blocks(editor, &range, &prompt_editor, cx);
+            let [prompt_block_id, tool_description_block_id, end_block_id] =
+                self.insert_assist_blocks(&editor, &range, &prompt_editor, cx);
 
             assists.push((
                 assist_id,
                 range.clone(),
                 prompt_editor,
                 prompt_block_id,
+                tool_description_block_id,
                 end_block_id,
             ));
         }
@@ -560,7 +563,15 @@ impl InlineAssistant {
         };
 
         let mut assist_group = InlineAssistGroup::new();
-        for (assist_id, range, prompt_editor, prompt_block_id, end_block_id) in assists {
+        for (
+            assist_id,
+            range,
+            prompt_editor,
+            prompt_block_id,
+            tool_description_block_id,
+            end_block_id,
+        ) in assists
+        {
             let codegen = prompt_editor.read(cx).codegen().clone();
 
             self.assists.insert(
@@ -571,6 +582,7 @@ impl InlineAssistant {
                     editor,
                     &prompt_editor,
                     prompt_block_id,
+                    tool_description_block_id,
                     end_block_id,
                     range,
                     codegen,
@@ -598,13 +610,13 @@ impl InlineAssistant {
         initial_prompt: Option<String>,
         window: &mut Window,
         cx: &mut App,
-    ) {
+    ) -> Option<InlineAssistId> {
         let snapshot = editor.update(cx, |editor, cx| editor.snapshot(window, cx));
 
         let Some((codegen_ranges, newest_selection)) =
             self.codegen_ranges(editor, &snapshot, window, cx)
         else {
-            return;
+            return None;
         };
 
         let assist_to_focus = self.batch_assist(
@@ -624,6 +636,8 @@ impl InlineAssistant {
         if let Some(assist_id) = assist_to_focus {
             self.focus_assist(assist_id, window, cx);
         }
+
+        assist_to_focus
     }
 
     pub fn suggest_assist(
@@ -677,7 +691,7 @@ impl InlineAssistant {
         range: &Range<Anchor>,
         prompt_editor: &Entity<PromptEditor<BufferCodegen>>,
         cx: &mut App,
-    ) -> [CustomBlockId; 2] {
+    ) -> [CustomBlockId; 3] {
         let prompt_editor_height = prompt_editor.update(cx, |prompt_editor, cx| {
             prompt_editor
                 .editor
@@ -691,6 +705,14 @@ impl InlineAssistant {
                 render: build_assist_editor_renderer(prompt_editor),
                 priority: 0,
             },
+            // Placeholder for tool description - will be updated dynamically
+            BlockProperties {
+                style: BlockStyle::Flex,
+                placement: BlockPlacement::Below(range.end),
+                height: Some(0),
+                render: Arc::new(|_cx| div().into_any_element()),
+                priority: 0,
+            },
             BlockProperties {
                 style: BlockStyle::Sticky,
                 placement: BlockPlacement::Below(range.end),
@@ -709,7 +731,7 @@ impl InlineAssistant {
 
         editor.update(cx, |editor, cx| {
             let block_ids = editor.insert_blocks(assist_blocks, None, cx);
-            [block_ids[0], block_ids[1]]
+            [block_ids[0], block_ids[1], block_ids[2]]
         })
     }
 
@@ -1038,8 +1060,6 @@ impl InlineAssistant {
             }
 
             let active_alternative = assist.codegen.read(cx).active_alternative().clone();
-            let message_id = active_alternative.read(cx).message_id.clone();
-
             if let Some(model) = LanguageModelRegistry::read_global(cx).inline_assistant_model() {
                 let language_name = assist.editor.upgrade().and_then(|editor| {
                     let multibuffer = editor.read(cx).buffer().read(cx);
@@ -1048,28 +1068,49 @@ impl InlineAssistant {
                     ranges
                         .first()
                         .and_then(|(buffer, _, _)| buffer.language())
-                        .map(|language| language.name())
+                        .map(|language| language.name().0.to_string())
                 });
-                report_assistant_event(
-                    AssistantEventData {
-                        conversation_id: None,
-                        kind: AssistantKind::Inline,
+
+                let codegen = assist.codegen.read(cx);
+                let session_id = codegen.session_id();
+                let message_id = active_alternative.read(cx).message_id.clone();
+                let model_telemetry_id = model.model.telemetry_id();
+                let model_provider_id = model.model.provider_id().to_string();
+
+                let (phase, event_type, anthropic_event_type) = if undo {
+                    (
+                        "rejected",
+                        "Assistant Response Rejected",
+                        language_model::AnthropicEventType::Reject,
+                    )
+                } else {
+                    (
+                        "accepted",
+                        "Assistant Response Accepted",
+                        language_model::AnthropicEventType::Accept,
+                    )
+                };
+
+                telemetry::event!(
+                    event_type,
+                    phase,
+                    session_id = session_id.to_string(),
+                    kind = "inline",
+                    model = model_telemetry_id,
+                    model_provider = model_provider_id,
+                    language_name = language_name,
+                    message_id = message_id.as_deref(),
+                );
+
+                report_anthropic_event(
+                    &model.model,
+                    language_model::AnthropicEventData {
+                        completion_type: language_model::AnthropicCompletionType::Editor,
+                        event: anthropic_event_type,
+                        language_name,
                         message_id,
-                        phase: if undo {
-                            AssistantPhase::Rejected
-                        } else {
-                            AssistantPhase::Accepted
-                        },
-                        model: model.model.telemetry_id(),
-                        model_provider: model.model.provider_id().to_string(),
-                        response_latency: None,
-                        error_message: None,
-                        language_name: language_name.map(|name| name.to_proto()),
                     },
-                    Some(self.telemetry.clone()),
-                    cx.http_client(),
-                    model.model.api_key(cx),
-                    cx.background_executor(),
+                    cx,
                 );
             }
 
@@ -1101,6 +1142,9 @@ impl InlineAssistant {
             let mut to_remove = decorations.removed_line_block_ids;
             to_remove.insert(decorations.prompt_block_id);
             to_remove.insert(decorations.end_block_id);
+            if let Some(tool_description_block_id) = decorations.model_explanation {
+                to_remove.insert(tool_description_block_id);
+            }
             editor.remove_blocks(to_remove, None, cx);
         });
 
@@ -1153,7 +1197,7 @@ impl InlineAssistant {
 
         assist
             .editor
-            .update(cx, |editor, cx| window.focus(&editor.focus_handle(cx)))
+            .update(cx, |editor, cx| window.focus(&editor.focus_handle(cx), cx))
             .ok();
     }
 
@@ -1165,7 +1209,7 @@ impl InlineAssistant {
         if let Some(decorations) = assist.decorations.as_ref() {
             decorations.prompt_editor.update(cx, |prompt_editor, cx| {
                 prompt_editor.editor.update(cx, |editor, cx| {
-                    window.focus(&editor.focus_handle(cx));
+                    window.focus(&editor.focus_handle(cx), cx);
                     editor.select_all(&SelectAll, window, cx);
                 })
             });
@@ -1215,28 +1259,26 @@ impl InlineAssistant {
                 let bottom = top + 1.0;
                 (top, bottom)
             });
-            let mut scroll_target_top = scroll_target_range.0;
-            let mut scroll_target_bottom = scroll_target_range.1;
-
-            scroll_target_top -= editor.vertical_scroll_margin() as ScrollOffset;
-            scroll_target_bottom += editor.vertical_scroll_margin() as ScrollOffset;
-
             let height_in_lines = editor.visible_line_count().unwrap_or(0.);
+            let vertical_scroll_margin = editor.vertical_scroll_margin() as ScrollOffset;
+            let scroll_target_top = (scroll_target_range.0 - vertical_scroll_margin)
+                // Don't scroll up too far in the case of a large vertical_scroll_margin.
+                .max(scroll_target_range.0 - height_in_lines / 2.0);
+            let scroll_target_bottom = (scroll_target_range.1 + vertical_scroll_margin)
+                // Don't scroll down past where the top would still be visible.
+                .min(scroll_target_top + height_in_lines);
+
             let scroll_top = editor.scroll_position(cx).y;
             let scroll_bottom = scroll_top + height_in_lines;
 
             if scroll_target_top < scroll_top {
                 editor.set_scroll_position(point(0., scroll_target_top), window, cx);
             } else if scroll_target_bottom > scroll_bottom {
-                if (scroll_target_bottom - scroll_target_top) <= height_in_lines {
-                    editor.set_scroll_position(
-                        point(0., scroll_target_bottom - height_in_lines),
-                        window,
-                        cx,
-                    );
-                } else {
-                    editor.set_scroll_position(point(0., scroll_target_top), window, cx);
-                }
+                editor.set_scroll_position(
+                    point(0., scroll_target_bottom - height_in_lines),
+                    window,
+                    cx,
+                );
             }
         });
     }
@@ -1541,6 +1583,27 @@ impl InlineAssistant {
                 .map(InlineAssistTarget::Terminal)
         }
     }
+
+    #[cfg(any(test, feature = "test-support"))]
+    pub fn set_completion_receiver(
+        &mut self,
+        sender: mpsc::UnboundedSender<anyhow::Result<InlineAssistId>>,
+    ) {
+        self._inline_assistant_completions = Some(sender);
+    }
+
+    #[cfg(any(test, feature = "test-support"))]
+    pub fn get_codegen(
+        &mut self,
+        assist_id: InlineAssistId,
+        cx: &mut App,
+    ) -> Option<Entity<CodegenAlternative>> {
+        self.assists.get(&assist_id).map(|inline_assist| {
+            inline_assist
+                .codegen
+                .update(cx, |codegen, _cx| codegen.active_alternative().clone())
+        })
+    }
 }
 
 struct EditorInlineAssists {
@@ -1674,6 +1737,7 @@ impl InlineAssist {
         editor: &Entity<Editor>,
         prompt_editor: &Entity<PromptEditor<BufferCodegen>>,
         prompt_block_id: CustomBlockId,
+        tool_description_block_id: CustomBlockId,
         end_block_id: CustomBlockId,
         range: Range<Anchor>,
         codegen: Entity<BufferCodegen>,
@@ -1688,7 +1752,8 @@ impl InlineAssist {
             decorations: Some(InlineAssistDecorations {
                 prompt_block_id,
                 prompt_editor: prompt_editor.clone(),
-                removed_line_block_ids: HashSet::default(),
+                removed_line_block_ids: Default::default(),
+                model_explanation: Some(tool_description_block_id),
                 end_block_id,
             }),
             range,
@@ -1740,6 +1805,16 @@ impl InlineAssist {
                                 && assist.decorations.is_none()
                                 && let Some(workspace) = assist.workspace.upgrade()
                             {
+                                #[cfg(any(test, feature = "test-support"))]
+                                if let Some(sender) = &mut this._inline_assistant_completions {
+                                    sender
+                                        .unbounded_send(Err(anyhow::anyhow!(
+                                            "Inline assistant error: {}",
+                                            error
+                                        )))
+                                        .ok();
+                                }
+
                                 let error = format!("Inline assistant error: {}", error);
                                 workspace.update(cx, |workspace, cx| {
                                     struct InlineAssistantError;
@@ -1750,6 +1825,11 @@ impl InlineAssist {
 
                                     workspace.show_toast(Toast::new(id, error), cx);
                                 })
+                            } else {
+                                #[cfg(any(test, feature = "test-support"))]
+                                if let Some(sender) = &mut this._inline_assistant_completions {
+                                    sender.unbounded_send(Ok(assist_id)).ok();
+                                }
                             }
 
                             if assist.decorations.is_none() {
@@ -1777,6 +1857,7 @@ struct InlineAssistDecorations {
     prompt_block_id: CustomBlockId,
     prompt_editor: Entity<PromptEditor<BufferCodegen>>,
     removed_line_block_ids: HashSet<CustomBlockId>,
+    model_explanation: Option<CustomBlockId>,
     end_block_id: CustomBlockId,
 }
 
@@ -1943,3 +2024,387 @@ fn merge_ranges(ranges: &mut Vec<Range<Anchor>>, buffer: &MultiBufferSnapshot) {
         }
     }
 }
+
+#[cfg(any(test, feature = "unit-eval"))]
+#[cfg_attr(not(test), allow(dead_code))]
+pub mod test {
+
+    use std::sync::Arc;
+
+    use agent::HistoryStore;
+    use assistant_text_thread::TextThreadStore;
+    use client::{Client, UserStore};
+    use editor::{Editor, MultiBuffer, MultiBufferOffset};
+    use fs::FakeFs;
+    use futures::channel::mpsc;
+    use gpui::{AppContext, TestAppContext, UpdateGlobal as _};
+    use language::Buffer;
+    use project::Project;
+    use prompt_store::PromptBuilder;
+    use smol::stream::StreamExt as _;
+    use util::test::marked_text_ranges;
+    use workspace::Workspace;
+
+    use crate::InlineAssistant;
+
+    #[derive(Debug)]
+    pub enum InlineAssistantOutput {
+        Success {
+            completion: Option<String>,
+            description: Option<String>,
+            full_buffer_text: String,
+        },
+        Failure {
+            failure: String,
+        },
+        // These fields are used for logging
+        #[allow(unused)]
+        Malformed {
+            completion: Option<String>,
+            description: Option<String>,
+            failure: Option<String>,
+        },
+    }
+
+    pub fn run_inline_assistant_test<SetupF, TestF>(
+        base_buffer: String,
+        prompt: String,
+        setup: SetupF,
+        test: TestF,
+        cx: &mut TestAppContext,
+    ) -> InlineAssistantOutput
+    where
+        SetupF: FnOnce(&mut gpui::VisualTestContext),
+        TestF: FnOnce(&mut gpui::VisualTestContext),
+    {
+        let fs = FakeFs::new(cx.executor());
+        let app_state = cx.update(|cx| workspace::AppState::test(cx));
+        let prompt_builder = Arc::new(PromptBuilder::new(None).unwrap());
+        let http = Arc::new(reqwest_client::ReqwestClient::user_agent("agent tests").unwrap());
+        let client = cx.update(|cx| {
+            cx.set_http_client(http);
+            Client::production(cx)
+        });
+        let mut inline_assistant = InlineAssistant::new(fs.clone(), prompt_builder);
+
+        let (tx, mut completion_rx) = mpsc::unbounded();
+        inline_assistant.set_completion_receiver(tx);
+
+        // Initialize settings and client
+        cx.update(|cx| {
+            gpui_tokio::init(cx);
+            settings::init(cx);
+            client::init(&client, cx);
+            workspace::init(app_state.clone(), cx);
+            let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
+            language_model::init(client.clone(), cx);
+            language_models::init(user_store, client.clone(), cx);
+
+            cx.set_global(inline_assistant);
+        });
+
+        let project = cx
+            .executor()
+            .block_test(async { Project::test(fs.clone(), [], cx).await });
+
+        // Create workspace with window
+        let (workspace, cx) = cx.add_window_view(|window, cx| {
+            window.activate_window();
+            Workspace::new(None, project.clone(), app_state.clone(), window, cx)
+        });
+
+        setup(cx);
+
+        let (_editor, buffer) = cx.update(|window, cx| {
+            let buffer = cx.new(|cx| Buffer::local("", cx));
+            let multibuffer = cx.new(|cx| MultiBuffer::singleton(buffer.clone(), cx));
+            let editor = cx.new(|cx| Editor::for_multibuffer(multibuffer, None, window, cx));
+            editor.update(cx, |editor, cx| {
+                let (unmarked_text, selection_ranges) = marked_text_ranges(&base_buffer, true);
+                editor.set_text(unmarked_text, window, cx);
+                editor.change_selections(Default::default(), window, cx, |s| {
+                    s.select_ranges(
+                        selection_ranges.into_iter().map(|range| {
+                            MultiBufferOffset(range.start)..MultiBufferOffset(range.end)
+                        }),
+                    )
+                })
+            });
+
+            let text_thread_store = cx.new(|cx| TextThreadStore::fake(project.clone(), cx));
+            let history_store = cx.new(|cx| HistoryStore::new(text_thread_store, cx));
+
+            // Add editor to workspace
+            workspace.update(cx, |workspace, cx| {
+                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
+            });
+
+            // Call assist method
+            InlineAssistant::update_global(cx, |inline_assistant, cx| {
+                let assist_id = inline_assistant
+                    .assist(
+                        &editor,
+                        workspace.downgrade(),
+                        project.downgrade(),
+                        history_store, // thread_store
+                        None,          // prompt_store
+                        Some(prompt),
+                        window,
+                        cx,
+                    )
+                    .unwrap();
+
+                inline_assistant.start_assist(assist_id, window, cx);
+            });
+
+            (editor, buffer)
+        });
+
+        cx.run_until_parked();
+
+        test(cx);
+
+        let assist_id = cx
+            .executor()
+            .block_test(async { completion_rx.next().await })
+            .unwrap()
+            .unwrap();
+
+        let (completion, description, failure) = cx.update(|_, cx| {
+            InlineAssistant::update_global(cx, |inline_assistant, cx| {
+                let codegen = inline_assistant.get_codegen(assist_id, cx).unwrap();
+
+                let completion = codegen.read(cx).current_completion();
+                let description = codegen.read(cx).current_description();
+                let failure = codegen.read(cx).current_failure();
+
+                (completion, description, failure)
+            })
+        });
+
+        if failure.is_some() && (completion.is_some() || description.is_some()) {
+            InlineAssistantOutput::Malformed {
+                completion,
+                description,
+                failure,
+            }
+        } else if let Some(failure) = failure {
+            InlineAssistantOutput::Failure { failure }
+        } else {
+            InlineAssistantOutput::Success {
+                completion,
+                description,
+                full_buffer_text: buffer.read_with(cx, |buffer, _| buffer.text()),
+            }
+        }
+    }
+}
+
+#[cfg(any(test, feature = "unit-eval"))]
+#[cfg_attr(not(test), allow(dead_code))]
+pub mod evals {
+    use std::str::FromStr;
+
+    use eval_utils::{EvalOutput, NoProcessor};
+    use gpui::TestAppContext;
+    use language_model::{LanguageModelRegistry, SelectedModel};
+    use rand::{SeedableRng as _, rngs::StdRng};
+
+    use crate::inline_assistant::test::{InlineAssistantOutput, run_inline_assistant_test};
+
+    #[test]
+    #[cfg_attr(not(feature = "unit-eval"), ignore)]
+    fn eval_single_cursor_edit() {
+        run_eval(
+            20,
+            1.0,
+            "Rename this variable to buffer_text".to_string(),
+            indoc::indoc! {"
+                struct EvalExampleStruct {
+                    text: Strˇing,
+                    prompt: String,
+                }
+            "}
+            .to_string(),
+            exact_buffer_match(indoc::indoc! {"
+                struct EvalExampleStruct {
+                    buffer_text: String,
+                    prompt: String,
+                }
+            "}),
+        );
+    }
+
+    #[test]
+    #[cfg_attr(not(feature = "unit-eval"), ignore)]
+    fn eval_cant_do() {
+        run_eval(
+            20,
+            0.95,
+            "Rename the struct to EvalExampleStructNope",
+            indoc::indoc! {"
+                struct EvalExampleStruct {
+                    text: Strˇing,
+                    prompt: String,
+                }
+            "},
+            uncertain_output,
+        );
+    }
+
+    #[test]
+    #[cfg_attr(not(feature = "unit-eval"), ignore)]
+    fn eval_unclear() {
+        run_eval(
+            20,
+            0.95,
+            "Make exactly the change I want you to make",
+            indoc::indoc! {"
+                struct EvalExampleStruct {
+                    text: Strˇing,
+                    prompt: String,
+                }
+            "},
+            uncertain_output,
+        );
+    }
+
+    #[test]
+    #[cfg_attr(not(feature = "unit-eval"), ignore)]
+    fn eval_empty_buffer() {
+        run_eval(
+            20,
+            1.0,
+            "Write a Python hello, world program".to_string(),
+            "ˇ".to_string(),
+            |output| match output {
+                InlineAssistantOutput::Success {
+                    full_buffer_text, ..
+                } => {
+                    if full_buffer_text.is_empty() {
+                        EvalOutput::failed("expected some output".to_string())
+                    } else {
+                        EvalOutput::passed(format!("Produced {full_buffer_text}"))
+                    }
+                }
+                o @ InlineAssistantOutput::Failure { .. } => EvalOutput::failed(format!(
+                    "Assistant output does not match expected output: {:?}",
+                    o
+                )),
+                o @ InlineAssistantOutput::Malformed { .. } => EvalOutput::failed(format!(
+                    "Assistant output does not match expected output: {:?}",
+                    o
+                )),
+            },
+        );
+    }
+
+    fn run_eval(
+        iterations: usize,
+        expected_pass_ratio: f32,
+        prompt: impl Into<String>,
+        buffer: impl Into<String>,
+        judge: impl Fn(InlineAssistantOutput) -> eval_utils::EvalOutput<()> + Send + Sync + 'static,
+    ) {
+        let buffer = buffer.into();
+        let prompt = prompt.into();
+
+        eval_utils::eval(iterations, expected_pass_ratio, NoProcessor, move || {
+            let dispatcher = gpui::TestDispatcher::new(StdRng::from_os_rng());
+            let mut cx = TestAppContext::build(dispatcher, None);
+            cx.skip_drawing();
+
+            let output = run_inline_assistant_test(
+                buffer.clone(),
+                prompt.clone(),
+                |cx| {
+                    // Reconfigure to use a real model instead of the fake one
+                    let model_name = std::env::var("ZED_AGENT_MODEL")
+                        .unwrap_or("anthropic/claude-sonnet-4-latest".into());
+
+                    let selected_model = SelectedModel::from_str(&model_name)
+                        .expect("Invalid model format. Use 'provider/model-id'");
+
+                    log::info!("Selected model: {selected_model:?}");
+
+                    cx.update(|_, cx| {
+                        LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
+                            registry.select_inline_assistant_model(Some(&selected_model), cx);
+                        });
+                    });
+                },
+                |_cx| {
+                    log::info!("Waiting for actual response from the LLM...");
+                },
+                &mut cx,
+            );
+
+            cx.quit();
+
+            judge(output)
+        });
+    }
+
+    fn uncertain_output(output: InlineAssistantOutput) -> EvalOutput<()> {
+        match &output {
+            o @ InlineAssistantOutput::Success {
+                completion,
+                description,
+                ..
+            } => {
+                if description.is_some() && completion.is_none() {
+                    EvalOutput::passed(format!(
+                        "Assistant produced no completion, but a description:\n{}",
+                        description.as_ref().unwrap()
+                    ))
+                } else {
+                    EvalOutput::failed(format!("Assistant produced a completion:\n{:?}", o))
+                }
+            }
+            InlineAssistantOutput::Failure {
+                failure: error_message,
+            } => EvalOutput::passed(format!(
+                "Assistant produced a failure message: {}",
+                error_message
+            )),
+            o @ InlineAssistantOutput::Malformed { .. } => {
+                EvalOutput::failed(format!("Assistant produced a malformed response:\n{:?}", o))
+            }
+        }
+    }
+
+    fn exact_buffer_match(
+        correct_output: impl Into<String>,
+    ) -> impl Fn(InlineAssistantOutput) -> EvalOutput<()> {
+        let correct_output = correct_output.into();
+        move |output| match output {
+            InlineAssistantOutput::Success {
+                description,
+                full_buffer_text,
+                ..
+            } => {
+                if full_buffer_text == correct_output && description.is_none() {
+                    EvalOutput::passed("Assistant output matches")
+                } else if full_buffer_text == correct_output {
+                    EvalOutput::failed(format!(
+                        "Assistant output produced an unescessary description description:\n{:?}",
+                        description
+                    ))
+                } else {
+                    EvalOutput::failed(format!(
+                        "Assistant output does not match expected output:\n{:?}\ndescription:\n{:?}",
+                        full_buffer_text, description
+                    ))
+                }
+            }
+            o @ InlineAssistantOutput::Failure { .. } => EvalOutput::failed(format!(
+                "Assistant output does not match expected output: {:?}",
+                o
+            )),
+            o @ InlineAssistantOutput::Malformed { .. } => EvalOutput::failed(format!(
+                "Assistant output does not match expected output: {:?}",
+                o
+            )),
+        }
+    }
+}

crates/agent_ui/src/inline_prompt_editor.rs 🔗

@@ -8,12 +8,14 @@ use editor::{
     ContextMenuOptions, Editor, EditorElement, EditorEvent, EditorMode, EditorStyle, MultiBuffer,
     actions::{MoveDown, MoveUp},
 };
+use feature_flags::{FeatureFlagAppExt, InlineAssistantUseToolFeatureFlag};
 use fs::Fs;
 use gpui::{
-    AnyElement, App, Context, CursorStyle, Entity, EventEmitter, FocusHandle, Focusable,
-    Subscription, TextStyle, WeakEntity, Window,
+    AnyElement, App, ClipboardItem, Context, Entity, EventEmitter, FocusHandle, Focusable,
+    Subscription, TextStyle, TextStyleRefinement, WeakEntity, Window, actions,
 };
 use language_model::{LanguageModel, LanguageModelRegistry};
+use markdown::{HeadingLevelStyles, Markdown, MarkdownElement, MarkdownStyle};
 use parking_lot::Mutex;
 use project::Project;
 use prompt_store::PromptStore;
@@ -25,18 +27,35 @@ use std::sync::Arc;
 use theme::ThemeSettings;
 use ui::utils::WithRemSize;
 use ui::{IconButtonShape, KeyBinding, PopoverMenuHandle, Tooltip, prelude::*};
-use workspace::Workspace;
+use uuid::Uuid;
+use workspace::notifications::NotificationId;
+use workspace::{Toast, Workspace};
 use zed_actions::agent::ToggleModelSelector;
 
 use crate::agent_model_selector::AgentModelSelector;
-use crate::buffer_codegen::BufferCodegen;
+use crate::buffer_codegen::{BufferCodegen, CodegenAlternative};
 use crate::completion_provider::{
     PromptCompletionProvider, PromptCompletionProviderDelegate, PromptContextType,
 };
 use crate::mention_set::paste_images_as_context;
 use crate::mention_set::{MentionSet, crease_for_mention};
 use crate::terminal_codegen::TerminalCodegen;
-use crate::{CycleNextInlineAssist, CyclePreviousInlineAssist, ModelUsageContext};
+use crate::{
+    CycleFavoriteModels, CycleNextInlineAssist, CyclePreviousInlineAssist, ModelUsageContext,
+};
+
+actions!(inline_assistant, [ThumbsUpResult, ThumbsDownResult]);
+
+enum CompletionState {
+    Pending,
+    Generated { completion_text: Option<String> },
+    Rated,
+}
+
+struct SessionState {
+    session_id: Uuid,
+    completion: CompletionState,
+}
 
 pub struct PromptEditor<T> {
     pub editor: Entity<Editor>,
@@ -53,6 +72,7 @@ pub struct PromptEditor<T> {
     _codegen_subscription: Subscription,
     editor_subscriptions: Vec<Subscription>,
     show_rate_limit_notice: bool,
+    session_state: SessionState,
     _phantom: std::marker::PhantomData<T>,
 }
 
@@ -65,7 +85,7 @@ impl<T: 'static> Render for PromptEditor<T> {
 
         const RIGHT_PADDING: Pixels = px(9.);
 
-        let (left_gutter_width, right_padding) = match &self.mode {
+        let (left_gutter_width, right_padding, explanation) = match &self.mode {
             PromptEditorMode::Buffer {
                 id: _,
                 codegen,
@@ -83,17 +103,23 @@ impl<T: 'static> Render for PromptEditor<T> {
                 let left_gutter_width = gutter.full_width() + (gutter.margin / 2.0);
                 let right_padding = editor_margins.right + RIGHT_PADDING;
 
-                (left_gutter_width, right_padding)
+                let active_alternative = codegen.active_alternative().read(cx);
+                let explanation = active_alternative
+                    .description
+                    .clone()
+                    .or_else(|| active_alternative.failure.clone());
+
+                (left_gutter_width, right_padding, explanation)
             }
             PromptEditorMode::Terminal { .. } => {
                 // Give the equivalent of the same left-padding that we're using on the right
-                (Pixels::from(40.0), Pixels::from(24.))
+                (Pixels::from(40.0), Pixels::from(24.), None)
             }
         };
 
         let bottom_padding = match &self.mode {
             PromptEditorMode::Buffer { .. } => rems_from_px(2.0),
-            PromptEditorMode::Terminal { .. } => rems_from_px(8.0),
+            PromptEditorMode::Terminal { .. } => rems_from_px(4.0),
         };
 
         buttons.extend(self.render_buttons(window, cx));
@@ -111,42 +137,60 @@ impl<T: 'static> Render for PromptEditor<T> {
                 this.trigger_completion_menu(window, cx);
             }));
 
+        let markdown = window.use_state(cx, |_, cx| Markdown::new("".into(), None, None, cx));
+
+        if let Some(explanation) = &explanation {
+            markdown.update(cx, |markdown, cx| {
+                markdown.reset(SharedString::from(explanation), cx);
+            });
+        }
+
+        let explanation_label = self
+            .render_markdown(markdown, markdown_style(window, cx))
+            .into_any_element();
+
         v_flex()
-            .key_context("PromptEditor")
+            .key_context("InlineAssistant")
             .capture_action(cx.listener(Self::paste))
-            .bg(cx.theme().colors().editor_background)
             .block_mouse_except_scroll()
-            .gap_0p5()
-            .border_y_1()
-            .border_color(cx.theme().status().info_border)
             .size_full()
             .pt_0p5()
             .pb(bottom_padding)
             .pr(right_padding)
+            .gap_0p5()
+            .justify_center()
+            .border_y_1()
+            .border_color(cx.theme().colors().border)
+            .bg(cx.theme().colors().editor_background)
             .child(
                 h_flex()
-                    .items_start()
-                    .cursor(CursorStyle::Arrow)
-                    .on_action(cx.listener(|this, _: &ToggleModelSelector, window, cx| {
-                        this.model_selector
-                            .update(cx, |model_selector, cx| model_selector.toggle(window, cx));
-                    }))
                     .on_action(cx.listener(Self::confirm))
                     .on_action(cx.listener(Self::cancel))
                     .on_action(cx.listener(Self::move_up))
                     .on_action(cx.listener(Self::move_down))
+                    .on_action(cx.listener(Self::thumbs_up))
+                    .on_action(cx.listener(Self::thumbs_down))
                     .capture_action(cx.listener(Self::cycle_prev))
                     .capture_action(cx.listener(Self::cycle_next))
+                    .on_action(cx.listener(|this, _: &ToggleModelSelector, window, cx| {
+                        this.model_selector
+                            .update(cx, |model_selector, cx| model_selector.toggle(window, cx));
+                    }))
+                    .on_action(cx.listener(|this, _: &CycleFavoriteModels, window, cx| {
+                        this.model_selector.update(cx, |model_selector, cx| {
+                            model_selector.cycle_favorite_models(window, cx);
+                        });
+                    }))
                     .child(
                         WithRemSize::new(ui_font_size)
+                            .h_full()
+                            .w(left_gutter_width)
                             .flex()
                             .flex_row()
                             .flex_shrink_0()
                             .items_center()
-                            .h_full()
-                            .w(left_gutter_width)
                             .justify_center()
-                            .gap_2()
+                            .gap_1()
                             .child(self.render_close_button(cx))
                             .map(|el| {
                                 let CodegenStatus::Error(error) = self.codegen_status(cx) else {
@@ -177,26 +221,83 @@ impl<T: 'static> Render for PromptEditor<T> {
                                     .flex_row()
                                     .items_center()
                                     .gap_1()
+                                    .child(add_context_button)
+                                    .child(self.model_selector.clone())
                                     .children(buttons),
                             ),
                     ),
             )
-            .child(
-                WithRemSize::new(ui_font_size)
-                    .flex()
-                    .flex_row()
-                    .items_center()
-                    .child(h_flex().flex_shrink_0().w(left_gutter_width))
-                    .child(
-                        h_flex()
-                            .w_full()
-                            .pl_1()
-                            .items_start()
-                            .justify_between()
-                            .child(add_context_button)
-                            .child(self.model_selector.clone()),
-                    ),
-            )
+            .when_some(explanation, |this, _| {
+                this.child(
+                    h_flex()
+                        .size_full()
+                        .justify_center()
+                        .child(div().w(left_gutter_width + px(6.)))
+                        .child(
+                            div()
+                                .size_full()
+                                .min_w_0()
+                                .pt(rems_from_px(3.))
+                                .pl_0p5()
+                                .flex_1()
+                                .border_t_1()
+                                .border_color(cx.theme().colors().border_variant)
+                                .child(explanation_label),
+                        ),
+                )
+            })
+    }
+}
+
+fn markdown_style(window: &Window, cx: &App) -> MarkdownStyle {
+    let theme_settings = ThemeSettings::get_global(cx);
+    let colors = cx.theme().colors();
+    let mut text_style = window.text_style();
+
+    text_style.refine(&TextStyleRefinement {
+        font_family: Some(theme_settings.ui_font.family.clone()),
+        color: Some(colors.text),
+        ..Default::default()
+    });
+
+    MarkdownStyle {
+        base_text_style: text_style.clone(),
+        syntax: cx.theme().syntax().clone(),
+        selection_background_color: colors.element_selection_background,
+        heading_level_styles: Some(HeadingLevelStyles {
+            h1: Some(TextStyleRefinement {
+                font_size: Some(rems(1.15).into()),
+                ..Default::default()
+            }),
+            h2: Some(TextStyleRefinement {
+                font_size: Some(rems(1.1).into()),
+                ..Default::default()
+            }),
+            h3: Some(TextStyleRefinement {
+                font_size: Some(rems(1.05).into()),
+                ..Default::default()
+            }),
+            h4: Some(TextStyleRefinement {
+                font_size: Some(rems(1.).into()),
+                ..Default::default()
+            }),
+            h5: Some(TextStyleRefinement {
+                font_size: Some(rems(0.95).into()),
+                ..Default::default()
+            }),
+            h6: Some(TextStyleRefinement {
+                font_size: Some(rems(0.875).into()),
+                ..Default::default()
+            }),
+        }),
+        inline_code: TextStyleRefinement {
+            font_family: Some(theme_settings.buffer_font.family.clone()),
+            font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
+            font_features: Some(theme_settings.buffer_font.features.clone()),
+            background_color: Some(colors.editor_foreground.opacity(0.08)),
+            ..Default::default()
+        },
+        ..Default::default()
     }
 }
 
@@ -263,7 +364,7 @@ impl<T: 'static> PromptEditor<T> {
             creases = insert_message_creases(&mut editor, &existing_creases, window, cx);
 
             if focus {
-                window.focus(&editor.focus_handle(cx));
+                window.focus(&editor.focus_handle(cx), cx);
             }
             editor
         });
@@ -354,6 +455,7 @@ impl<T: 'static> PromptEditor<T> {
                 }
 
                 self.edited_since_done = true;
+                self.session_state.completion = CompletionState::Pending;
                 cx.notify();
             }
             EditorEvent::Blurred => {
@@ -425,22 +527,207 @@ impl<T: 'static> PromptEditor<T> {
     fn confirm(&mut self, _: &menu::Confirm, _window: &mut Window, cx: &mut Context<Self>) {
         match self.codegen_status(cx) {
             CodegenStatus::Idle => {
+                self.fire_started_telemetry(cx);
                 cx.emit(PromptEditorEvent::StartRequested);
             }
             CodegenStatus::Pending => {}
             CodegenStatus::Done => {
                 if self.edited_since_done {
+                    self.fire_started_telemetry(cx);
                     cx.emit(PromptEditorEvent::StartRequested);
                 } else {
                     cx.emit(PromptEditorEvent::ConfirmRequested { execute: false });
                 }
             }
             CodegenStatus::Error(_) => {
+                self.fire_started_telemetry(cx);
                 cx.emit(PromptEditorEvent::StartRequested);
             }
         }
     }
 
+    fn fire_started_telemetry(&self, cx: &Context<Self>) {
+        let Some(model) = LanguageModelRegistry::read_global(cx).inline_assistant_model() else {
+            return;
+        };
+
+        let model_telemetry_id = model.model.telemetry_id();
+        let model_provider_id = model.provider.id().to_string();
+
+        let (kind, language_name) = match &self.mode {
+            PromptEditorMode::Buffer { codegen, .. } => {
+                let codegen = codegen.read(cx);
+                (
+                    "inline",
+                    codegen.language_name(cx).map(|name| name.to_string()),
+                )
+            }
+            PromptEditorMode::Terminal { .. } => ("inline_terminal", None),
+        };
+
+        telemetry::event!(
+            "Assistant Started",
+            session_id = self.session_state.session_id.to_string(),
+            kind = kind,
+            phase = "started",
+            model = model_telemetry_id,
+            model_provider = model_provider_id,
+            language_name = language_name,
+        );
+    }
+
+    fn thumbs_up(&mut self, _: &ThumbsUpResult, _window: &mut Window, cx: &mut Context<Self>) {
+        match &self.session_state.completion {
+            CompletionState::Pending => {
+                self.toast("Can't rate, still generating...", None, cx);
+                return;
+            }
+            CompletionState::Rated => {
+                self.toast(
+                    "Already rated this completion",
+                    Some(self.session_state.session_id),
+                    cx,
+                );
+                return;
+            }
+            CompletionState::Generated { completion_text } => {
+                let model_info = self.model_selector.read(cx).active_model(cx);
+                let (model_id, use_streaming_tools) = {
+                    let Some(configured_model) = model_info else {
+                        self.toast("No configured model", None, cx);
+                        return;
+                    };
+                    (
+                        configured_model.model.telemetry_id(),
+                        CodegenAlternative::use_streaming_tools(
+                            configured_model.model.as_ref(),
+                            cx,
+                        ),
+                    )
+                };
+
+                let selected_text = match &self.mode {
+                    PromptEditorMode::Buffer { codegen, .. } => {
+                        codegen.read(cx).selected_text(cx).map(|s| s.to_string())
+                    }
+                    PromptEditorMode::Terminal { .. } => None,
+                };
+
+                let prompt = self.editor.read(cx).text(cx);
+
+                let kind = match &self.mode {
+                    PromptEditorMode::Buffer { .. } => "inline",
+                    PromptEditorMode::Terminal { .. } => "inline_terminal",
+                };
+
+                telemetry::event!(
+                    "Inline Assistant Rated",
+                    rating = "positive",
+                    session_id = self.session_state.session_id.to_string(),
+                    kind = kind,
+                    model = model_id,
+                    prompt = prompt,
+                    completion = completion_text,
+                    selected_text = selected_text,
+                    use_streaming_tools
+                );
+
+                self.session_state.completion = CompletionState::Rated;
+
+                cx.notify();
+            }
+        }
+    }
+
+    fn thumbs_down(&mut self, _: &ThumbsDownResult, _window: &mut Window, cx: &mut Context<Self>) {
+        match &self.session_state.completion {
+            CompletionState::Pending => {
+                self.toast("Can't rate, still generating...", None, cx);
+                return;
+            }
+            CompletionState::Rated => {
+                self.toast(
+                    "Already rated this completion",
+                    Some(self.session_state.session_id),
+                    cx,
+                );
+                return;
+            }
+            CompletionState::Generated { completion_text } => {
+                let model_info = self.model_selector.read(cx).active_model(cx);
+                let (model_telemetry_id, use_streaming_tools) = {
+                    let Some(configured_model) = model_info else {
+                        self.toast("No configured model", None, cx);
+                        return;
+                    };
+                    (
+                        configured_model.model.telemetry_id(),
+                        CodegenAlternative::use_streaming_tools(
+                            configured_model.model.as_ref(),
+                            cx,
+                        ),
+                    )
+                };
+
+                let selected_text = match &self.mode {
+                    PromptEditorMode::Buffer { codegen, .. } => {
+                        codegen.read(cx).selected_text(cx).map(|s| s.to_string())
+                    }
+                    PromptEditorMode::Terminal { .. } => None,
+                };
+
+                let prompt = self.editor.read(cx).text(cx);
+
+                let kind = match &self.mode {
+                    PromptEditorMode::Buffer { .. } => "inline",
+                    PromptEditorMode::Terminal { .. } => "inline_terminal",
+                };
+
+                telemetry::event!(
+                    "Inline Assistant Rated",
+                    rating = "negative",
+                    session_id = self.session_state.session_id.to_string(),
+                    kind = kind,
+                    model = model_telemetry_id,
+                    prompt = prompt,
+                    completion = completion_text,
+                    selected_text = selected_text,
+                    use_streaming_tools
+                );
+
+                self.session_state.completion = CompletionState::Rated;
+
+                cx.notify();
+            }
+        }
+    }
+
+    fn toast(&mut self, msg: &str, uuid: Option<Uuid>, cx: &mut Context<'_, PromptEditor<T>>) {
+        self.workspace
+            .update(cx, |workspace, cx| {
+                enum InlinePromptRating {}
+                workspace.show_toast(
+                    {
+                        let mut toast = Toast::new(
+                            NotificationId::unique::<InlinePromptRating>(),
+                            msg.to_string(),
+                        )
+                        .autohide();
+
+                        if let Some(uuid) = uuid {
+                            toast = toast.on_click("Click to copy rating ID", move |_, cx| {
+                                cx.write_to_clipboard(ClipboardItem::new_string(uuid.to_string()));
+                            });
+                        };
+
+                        toast
+                    },
+                    cx,
+                );
+            })
+            .ok();
+    }
+
     fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
         if let Some(ix) = self.prompt_history_ix {
             if ix > 0 {
@@ -546,6 +833,9 @@ impl<T: 'static> PromptEditor<T> {
                             .into_any_element(),
                     ]
                 } else {
+                    let show_rating_buttons = cx.has_flag::<InlineAssistantUseToolFeatureFlag>();
+                    let rated = matches!(self.session_state.completion, CompletionState::Rated);
+
                     let accept = IconButton::new("accept", IconName::Check)
                         .icon_color(Color::Info)
                         .shape(IconButtonShape::Square)
@@ -557,25 +847,106 @@ impl<T: 'static> PromptEditor<T> {
                         }))
                         .into_any_element();
 
-                    match &self.mode {
-                        PromptEditorMode::Terminal { .. } => vec![
-                            accept,
-                            IconButton::new("confirm", IconName::PlayFilled)
-                                .icon_color(Color::Info)
-                                .shape(IconButtonShape::Square)
-                                .tooltip(|_window, cx| {
-                                    Tooltip::for_action(
-                                        "Execute Generated Command",
-                                        &menu::SecondaryConfirm,
-                                        cx,
-                                    )
-                                })
-                                .on_click(cx.listener(|_, _, _, cx| {
-                                    cx.emit(PromptEditorEvent::ConfirmRequested { execute: true });
-                                }))
+                    let mut buttons = Vec::new();
+
+                    if show_rating_buttons {
+                        buttons.push(
+                            h_flex()
+                                .pl_1()
+                                .gap_1()
+                                .border_l_1()
+                                .border_color(cx.theme().colors().border_variant)
+                                .child(
+                                    IconButton::new("thumbs-up", IconName::ThumbsUp)
+                                        .shape(IconButtonShape::Square)
+                                        .map(|this| {
+                                            if rated {
+                                                this.disabled(true)
+                                                    .icon_color(Color::Disabled)
+                                                    .tooltip(move |_, cx| {
+                                                        Tooltip::with_meta(
+                                                            "Good Result",
+                                                            None,
+                                                            "You already rated this result",
+                                                            cx,
+                                                        )
+                                                    })
+                                            } else {
+                                                this.icon_color(Color::Muted).tooltip(
+                                                    move |_, cx| {
+                                                        Tooltip::for_action(
+                                                            "Good Result",
+                                                            &ThumbsUpResult,
+                                                            cx,
+                                                        )
+                                                    },
+                                                )
+                                            }
+                                        })
+                                        .on_click(cx.listener(|this, _, window, cx| {
+                                            this.thumbs_up(&ThumbsUpResult, window, cx);
+                                        })),
+                                )
+                                .child(
+                                    IconButton::new("thumbs-down", IconName::ThumbsDown)
+                                        .shape(IconButtonShape::Square)
+                                        .map(|this| {
+                                            if rated {
+                                                this.disabled(true)
+                                                    .icon_color(Color::Disabled)
+                                                    .tooltip(move |_, cx| {
+                                                        Tooltip::with_meta(
+                                                            "Bad Result",
+                                                            None,
+                                                            "You already rated this result",
+                                                            cx,
+                                                        )
+                                                    })
+                                            } else {
+                                                this.icon_color(Color::Muted).tooltip(
+                                                    move |_, cx| {
+                                                        Tooltip::for_action(
+                                                            "Bad Result",
+                                                            &ThumbsDownResult,
+                                                            cx,
+                                                        )
+                                                    },
+                                                )
+                                            }
+                                        })
+                                        .on_click(cx.listener(|this, _, window, cx| {
+                                            this.thumbs_down(&ThumbsDownResult, window, cx);
+                                        })),
+                                )
                                 .into_any_element(),
-                        ],
-                        PromptEditorMode::Buffer { .. } => vec![accept],
+                        );
+                    }
+
+                    buttons.push(accept);
+
+                    match &self.mode {
+                        PromptEditorMode::Terminal { .. } => {
+                            buttons.push(
+                                IconButton::new("confirm", IconName::PlayFilled)
+                                    .icon_color(Color::Info)
+                                    .shape(IconButtonShape::Square)
+                                    .tooltip(|_window, cx| {
+                                        Tooltip::for_action(
+                                            "Execute Generated Command",
+                                            &menu::SecondaryConfirm,
+                                            cx,
+                                        )
+                                    })
+                                    .on_click(cx.listener(|_, _, _, cx| {
+                                        cx.emit(PromptEditorEvent::ConfirmRequested {
+                                            execute: true,
+                                        });
+                                    }))
+                                    .into_any_element(),
+                            );
+                            buttons
+                        }
+                        PromptEditorMode::Buffer { .. } => buttons,
                     }
                 }
             }
@@ -610,10 +981,21 @@ impl<T: 'static> PromptEditor<T> {
     }
 
     fn render_close_button(&self, cx: &mut Context<Self>) -> AnyElement {
+        let focus_handle = self.editor.focus_handle(cx);
+
         IconButton::new("cancel", IconName::Close)
             .icon_color(Color::Muted)
             .shape(IconButtonShape::Square)
-            .tooltip(Tooltip::text("Close Assistant"))
+            .tooltip({
+                move |_window, cx| {
+                    Tooltip::for_action_in(
+                        "Close Assistant",
+                        &editor::actions::Cancel,
+                        &focus_handle,
+                        cx,
+                    )
+                }
+            })
             .on_click(cx.listener(|_, _, _, cx| cx.emit(PromptEditorEvent::CancelRequested)))
             .into_any_element()
     }
@@ -727,7 +1109,6 @@ impl<T: 'static> PromptEditor<T> {
         let colors = cx.theme().colors();
 
         div()
-            .key_context("InlineAssistEditor")
             .size_full()
             .p_2()
             .pl_1()
@@ -759,6 +1140,10 @@ impl<T: 'static> PromptEditor<T> {
             })
             .into_any_element()
     }
+
+    fn render_markdown(&self, markdown: Entity<Markdown>, style: MarkdownStyle) -> MarkdownElement {
+        MarkdownElement::new(markdown, style)
+    }
 }
 
 pub enum PromptEditorMode {
@@ -830,6 +1215,7 @@ impl PromptEditor<BufferCodegen> {
         prompt_history: VecDeque<String>,
         prompt_buffer: Entity<MultiBuffer>,
         codegen: Entity<BufferCodegen>,
+        session_id: Uuid,
         fs: Arc<dyn Fs>,
         history_store: Entity<HistoryStore>,
         prompt_store: Option<Entity<PromptStore>>,
@@ -900,6 +1286,10 @@ impl PromptEditor<BufferCodegen> {
             editor_subscriptions: Vec::new(),
             show_rate_limit_notice: false,
             mode,
+            session_state: SessionState {
+                session_id,
+                completion: CompletionState::Pending,
+            },
             _phantom: Default::default(),
         };
 
@@ -910,7 +1300,7 @@ impl PromptEditor<BufferCodegen> {
 
     fn handle_codegen_changed(
         &mut self,
-        _: Entity<BufferCodegen>,
+        codegen: Entity<BufferCodegen>,
         cx: &mut Context<PromptEditor<BufferCodegen>>,
     ) {
         match self.codegen_status(cx) {
@@ -919,10 +1309,15 @@ impl PromptEditor<BufferCodegen> {
                     .update(cx, |editor, _| editor.set_read_only(false));
             }
             CodegenStatus::Pending => {
+                self.session_state.completion = CompletionState::Pending;
                 self.editor
                     .update(cx, |editor, _| editor.set_read_only(true));
             }
             CodegenStatus::Done => {
+                let completion = codegen.read(cx).active_completion(cx);
+                self.session_state.completion = CompletionState::Generated {
+                    completion_text: completion,
+                };
                 self.edited_since_done = false;
                 self.editor
                     .update(cx, |editor, _| editor.set_read_only(false));
@@ -978,6 +1373,7 @@ impl PromptEditor<TerminalCodegen> {
         prompt_history: VecDeque<String>,
         prompt_buffer: Entity<MultiBuffer>,
         codegen: Entity<TerminalCodegen>,
+        session_id: Uuid,
         fs: Arc<dyn Fs>,
         history_store: Entity<HistoryStore>,
         prompt_store: Option<Entity<PromptStore>>,
@@ -1043,6 +1439,10 @@ impl PromptEditor<TerminalCodegen> {
             editor_subscriptions: Vec::new(),
             mode,
             show_rate_limit_notice: false,
+            session_state: SessionState {
+                session_id,
+                completion: CompletionState::Pending,
+            },
             _phantom: Default::default(),
         };
         this.count_lines(cx);
@@ -1075,17 +1475,21 @@ impl PromptEditor<TerminalCodegen> {
         }
     }
 
-    fn handle_codegen_changed(&mut self, _: Entity<TerminalCodegen>, cx: &mut Context<Self>) {
+    fn handle_codegen_changed(&mut self, codegen: Entity<TerminalCodegen>, cx: &mut Context<Self>) {
         match &self.codegen().read(cx).status {
             CodegenStatus::Idle => {
                 self.editor
                     .update(cx, |editor, _| editor.set_read_only(false));
             }
             CodegenStatus::Pending => {
+                self.session_state.completion = CompletionState::Pending;
                 self.editor
                     .update(cx, |editor, _| editor.set_read_only(true));
             }
             CodegenStatus::Done | CodegenStatus::Error(_) => {
+                self.session_state.completion = CompletionState::Generated {
+                    completion_text: codegen.read(cx).completion(),
+                };
                 self.edited_since_done = false;
                 self.editor
                     .update(cx, |editor, _| editor.set_read_only(false));

crates/agent_ui/src/language_model_selector.rs 🔗

@@ -1,27 +1,33 @@
 use std::{cmp::Reverse, sync::Arc};
 
-use collections::IndexMap;
+use agent_settings::AgentSettings;
+use collections::{HashMap, HashSet, IndexMap};
 use fuzzy::{StringMatch, StringMatchCandidate, match_strings};
 use gpui::{
     Action, AnyElement, App, BackgroundExecutor, DismissEvent, FocusHandle, Subscription, Task,
 };
 use language_model::{
-    AuthenticateError, ConfiguredModel, LanguageModel, LanguageModelProviderId,
-    LanguageModelRegistry,
+    AuthenticateError, ConfiguredModel, IconOrSvg, LanguageModel, LanguageModelId,
+    LanguageModelProvider, LanguageModelProviderId, LanguageModelRegistry,
 };
 use ordered_float::OrderedFloat;
 use picker::{Picker, PickerDelegate};
-use ui::{KeyBinding, ListItem, ListItemSpacing, prelude::*};
+use settings::Settings;
+use ui::prelude::*;
 use zed_actions::agent::OpenSettings;
 
+use crate::ui::{ModelSelectorFooter, ModelSelectorHeader, ModelSelectorListItem};
+
 type OnModelChanged = Arc<dyn Fn(Arc<dyn LanguageModel>, &mut App) + 'static>;
 type GetActiveModel = Arc<dyn Fn(&App) -> Option<ConfiguredModel> + 'static>;
+type OnToggleFavorite = Arc<dyn Fn(Arc<dyn LanguageModel>, bool, &mut App) + 'static>;
 
 pub type LanguageModelSelector = Picker<LanguageModelPickerDelegate>;
 
 pub fn language_model_selector(
     get_active_model: impl Fn(&App) -> Option<ConfiguredModel> + 'static,
     on_model_changed: impl Fn(Arc<dyn LanguageModel>, &mut App) + 'static,
+    on_toggle_favorite: impl Fn(Arc<dyn LanguageModel>, bool, &mut App) + 'static,
     popover_styles: bool,
     focus_handle: FocusHandle,
     window: &mut Window,
@@ -30,6 +36,7 @@ pub fn language_model_selector(
     let delegate = LanguageModelPickerDelegate::new(
         get_active_model,
         on_model_changed,
+        on_toggle_favorite,
         popover_styles,
         focus_handle,
         window,
@@ -47,7 +54,17 @@ pub fn language_model_selector(
 }
 
 fn all_models(cx: &App) -> GroupedModels {
-    let providers = LanguageModelRegistry::global(cx).read(cx).providers();
+    let lm_registry = LanguageModelRegistry::global(cx).read(cx);
+    let providers = lm_registry.visible_providers();
+
+    let mut favorites_index = FavoritesIndex::default();
+
+    for sel in &AgentSettings::get_global(cx).favorite_models {
+        favorites_index
+            .entry(sel.provider.0.clone().into())
+            .or_default()
+            .insert(sel.model.clone().into());
+    }
 
     let recommended = providers
         .iter()
@@ -55,10 +72,7 @@ fn all_models(cx: &App) -> GroupedModels {
             provider
                 .recommended_models(cx)
                 .into_iter()
-                .map(|model| ModelInfo {
-                    model,
-                    icon: provider.icon(),
-                })
+                .map(|model| ModelInfo::new(&**provider, model, &favorites_index))
         })
         .collect();
 
@@ -68,25 +82,44 @@ fn all_models(cx: &App) -> GroupedModels {
             provider
                 .provided_models(cx)
                 .into_iter()
-                .map(|model| ModelInfo {
-                    model,
-                    icon: provider.icon(),
-                })
+                .map(|model| ModelInfo::new(&**provider, model, &favorites_index))
         })
         .collect();
 
     GroupedModels::new(all, recommended)
 }
 
+type FavoritesIndex = HashMap<LanguageModelProviderId, HashSet<LanguageModelId>>;
+
 #[derive(Clone)]
 struct ModelInfo {
     model: Arc<dyn LanguageModel>,
-    icon: IconName,
+    icon: IconOrSvg,
+    is_favorite: bool,
+}
+
+impl ModelInfo {
+    fn new(
+        provider: &dyn LanguageModelProvider,
+        model: Arc<dyn LanguageModel>,
+        favorites_index: &FavoritesIndex,
+    ) -> Self {
+        let is_favorite = favorites_index
+            .get(&provider.id())
+            .map_or(false, |set| set.contains(&model.id()));
+
+        Self {
+            model,
+            icon: provider.icon(),
+            is_favorite,
+        }
+    }
 }
 
 pub struct LanguageModelPickerDelegate {
     on_model_changed: OnModelChanged,
     get_active_model: GetActiveModel,
+    on_toggle_favorite: OnToggleFavorite,
     all_models: Arc<GroupedModels>,
     filtered_entries: Vec<LanguageModelPickerEntry>,
     selected_index: usize,
@@ -100,6 +133,7 @@ impl LanguageModelPickerDelegate {
     fn new(
         get_active_model: impl Fn(&App) -> Option<ConfiguredModel> + 'static,
         on_model_changed: impl Fn(Arc<dyn LanguageModel>, &mut App) + 'static,
+        on_toggle_favorite: impl Fn(Arc<dyn LanguageModel>, bool, &mut App) + 'static,
         popover_styles: bool,
         focus_handle: FocusHandle,
         window: &mut Window,
@@ -115,6 +149,7 @@ impl LanguageModelPickerDelegate {
             selected_index: Self::get_active_model_index(&entries, get_active_model(cx)),
             filtered_entries: entries,
             get_active_model: Arc::new(get_active_model),
+            on_toggle_favorite: Arc::new(on_toggle_favorite),
             _authenticate_all_providers_task: Self::authenticate_all_providers(cx),
             _subscriptions: vec![cx.subscribe_in(
                 &LanguageModelRegistry::global(cx),
@@ -168,7 +203,7 @@ impl LanguageModelPickerDelegate {
     fn authenticate_all_providers(cx: &mut App) -> Task<()> {
         let authenticate_all_providers = LanguageModelRegistry::global(cx)
             .read(cx)
-            .providers()
+            .visible_providers()
             .iter()
             .map(|provider| (provider.id(), provider.name(), provider.authenticate(cx)))
             .collect::<Vec<_>>();
@@ -214,15 +249,61 @@ impl LanguageModelPickerDelegate {
     pub fn active_model(&self, cx: &App) -> Option<ConfiguredModel> {
         (self.get_active_model)(cx)
     }
+
+    pub fn favorites_count(&self) -> usize {
+        self.all_models.favorites.len()
+    }
+
+    pub fn cycle_favorite_models(&mut self, window: &mut Window, cx: &mut Context<Picker<Self>>) {
+        if self.all_models.favorites.is_empty() {
+            return;
+        }
+
+        let active_model = (self.get_active_model)(cx);
+        let active_provider_id = active_model.as_ref().map(|m| m.provider.id());
+        let active_model_id = active_model.as_ref().map(|m| m.model.id());
+
+        let current_index = self
+            .all_models
+            .favorites
+            .iter()
+            .position(|info| {
+                Some(info.model.provider_id()) == active_provider_id
+                    && Some(info.model.id()) == active_model_id
+            })
+            .unwrap_or(usize::MAX);
+
+        let next_index = if current_index == usize::MAX {
+            0
+        } else {
+            (current_index + 1) % self.all_models.favorites.len()
+        };
+
+        let next_model = self.all_models.favorites[next_index].model.clone();
+
+        (self.on_model_changed)(next_model, cx);
+
+        // Align the picker selection with the newly-active model
+        let new_index =
+            Self::get_active_model_index(&self.filtered_entries, (self.get_active_model)(cx));
+        self.set_selected_index(new_index, window, cx);
+    }
 }
 
 struct GroupedModels {
+    favorites: Vec<ModelInfo>,
     recommended: Vec<ModelInfo>,
     all: IndexMap<LanguageModelProviderId, Vec<ModelInfo>>,
 }
 
 impl GroupedModels {
     pub fn new(all: Vec<ModelInfo>, recommended: Vec<ModelInfo>) -> Self {
+        let favorites = all
+            .iter()
+            .filter(|info| info.is_favorite)
+            .cloned()
+            .collect();
+
         let mut all_by_provider: IndexMap<_, Vec<ModelInfo>> = IndexMap::default();
         for model in all {
             let provider = model.model.provider_id();
@@ -234,6 +315,7 @@ impl GroupedModels {
         }
 
         Self {
+            favorites,
             recommended,
             all: all_by_provider,
         }
@@ -242,13 +324,18 @@ impl GroupedModels {
     fn entries(&self) -> Vec<LanguageModelPickerEntry> {
         let mut entries = Vec::new();
 
+        if !self.favorites.is_empty() {
+            entries.push(LanguageModelPickerEntry::Separator("Favorite".into()));
+            for info in &self.favorites {
+                entries.push(LanguageModelPickerEntry::Model(info.clone()));
+            }
+        }
+
         if !self.recommended.is_empty() {
             entries.push(LanguageModelPickerEntry::Separator("Recommended".into()));
-            entries.extend(
-                self.recommended
-                    .iter()
-                    .map(|info| LanguageModelPickerEntry::Model(info.clone())),
-            );
+            for info in &self.recommended {
+                entries.push(LanguageModelPickerEntry::Model(info.clone()));
+            }
         }
 
         for models in self.all.values() {
@@ -258,12 +345,11 @@ impl GroupedModels {
             entries.push(LanguageModelPickerEntry::Separator(
                 models[0].model.provider_name().0,
             ));
-            entries.extend(
-                models
-                    .iter()
-                    .map(|info| LanguageModelPickerEntry::Model(info.clone())),
-            );
+            for info in models {
+                entries.push(LanguageModelPickerEntry::Model(info.clone()));
+            }
         }
+
         entries
     }
 }
@@ -392,7 +478,7 @@ impl PickerDelegate for LanguageModelPickerDelegate {
 
         let configured_providers = language_model_registry
             .read(cx)
-            .providers()
+            .visible_providers()
             .into_iter()
             .filter(|provider| provider.is_authenticated(cx))
             .collect::<Vec<_>>();
@@ -464,23 +550,9 @@ impl PickerDelegate for LanguageModelPickerDelegate {
         cx: &mut Context<Picker<Self>>,
     ) -> Option<Self::ListItem> {
         match self.filtered_entries.get(ix)? {
-            LanguageModelPickerEntry::Separator(title) => Some(
-                div()
-                    .px_2()
-                    .pb_1()
-                    .when(ix > 1, |this| {
-                        this.mt_1()
-                            .pt_2()
-                            .border_t_1()
-                            .border_color(cx.theme().colors().border_variant)
-                    })
-                    .child(
-                        Label::new(title)
-                            .size(LabelSize::XSmall)
-                            .color(Color::Muted),
-                    )
-                    .into_any_element(),
-            ),
+            LanguageModelPickerEntry::Separator(title) => {
+                Some(ModelSelectorHeader::new(title, ix > 1).into_any_element())
+            }
             LanguageModelPickerEntry::Model(model_info) => {
                 let active_model = (self.get_active_model)(cx);
                 let active_provider_id = active_model.as_ref().map(|m| m.provider.id());
@@ -489,35 +561,26 @@ impl PickerDelegate for LanguageModelPickerDelegate {
                 let is_selected = Some(model_info.model.provider_id()) == active_provider_id
                     && Some(model_info.model.id()) == active_model_id;
 
-                let model_icon_color = if is_selected {
-                    Color::Accent
-                } else {
-                    Color::Muted
+                let is_favorite = model_info.is_favorite;
+                let handle_action_click = {
+                    let model = model_info.model.clone();
+                    let on_toggle_favorite = self.on_toggle_favorite.clone();
+                    cx.listener(move |picker, _, window, cx| {
+                        on_toggle_favorite(model.clone(), !is_favorite, cx);
+                        picker.refresh(window, cx);
+                    })
                 };
 
                 Some(
-                    ListItem::new(ix)
-                        .inset(true)
-                        .spacing(ListItemSpacing::Sparse)
-                        .toggle_state(selected)
-                        .child(
-                            h_flex()
-                                .w_full()
-                                .gap_1p5()
-                                .child(
-                                    Icon::new(model_info.icon)
-                                        .color(model_icon_color)
-                                        .size(IconSize::Small),
-                                )
-                                .child(Label::new(model_info.model.name().0).truncate()),
-                        )
-                        .end_slot(div().pr_3().when(is_selected, |this| {
-                            this.child(
-                                Icon::new(IconName::Check)
-                                    .color(Color::Accent)
-                                    .size(IconSize::Small),
-                            )
-                        }))
+                    ModelSelectorListItem::new(ix, model_info.model.name().0)
+                        .map(|this| match &model_info.icon {
+                            IconOrSvg::Icon(icon_name) => this.icon(*icon_name),
+                            IconOrSvg::Svg(icon_path) => this.icon_path(icon_path.clone()),
+                        })
+                        .is_selected(is_selected)
+                        .is_focused(selected)
+                        .is_favorite(is_favorite)
+                        .on_toggle_favorite(handle_action_click)
                         .into_any_element(),
                 )
             }
@@ -527,7 +590,7 @@ impl PickerDelegate for LanguageModelPickerDelegate {
     fn render_footer(
         &self,
         _window: &mut Window,
-        cx: &mut Context<Picker<Self>>,
+        _cx: &mut Context<Picker<Self>>,
     ) -> Option<gpui::AnyElement> {
         let focus_handle = self.focus_handle.clone();
 
@@ -535,26 +598,7 @@ impl PickerDelegate for LanguageModelPickerDelegate {
             return None;
         }
 
-        Some(
-            h_flex()
-                .w_full()
-                .p_1p5()
-                .border_t_1()
-                .border_color(cx.theme().colors().border_variant)
-                .child(
-                    Button::new("configure", "Configure")
-                        .full_width()
-                        .style(ButtonStyle::Outlined)
-                        .key_binding(
-                            KeyBinding::for_action_in(&OpenSettings, &focus_handle, cx)
-                                .map(|kb| kb.size(rems_from_px(12.))),
-                        )
-                        .on_click(|_, window, cx| {
-                            window.dispatch_action(OpenSettings.boxed_clone(), cx);
-                        }),
-                )
-                .into_any(),
-        )
+        Some(ModelSelectorFooter::new(OpenSettings.boxed_clone(), focus_handle).into_any_element())
     }
 }
 
@@ -653,11 +697,24 @@ mod tests {
     }
 
     fn create_models(model_specs: Vec<(&str, &str)>) -> Vec<ModelInfo> {
+        create_models_with_favorites(model_specs, vec![])
+    }
+
+    fn create_models_with_favorites(
+        model_specs: Vec<(&str, &str)>,
+        favorites: Vec<(&str, &str)>,
+    ) -> Vec<ModelInfo> {
         model_specs
             .into_iter()
-            .map(|(provider, name)| ModelInfo {
-                model: Arc::new(TestLanguageModel::new(name, provider)),
-                icon: IconName::Ai,
+            .map(|(provider, name)| {
+                let is_favorite = favorites
+                    .iter()
+                    .any(|(fav_provider, fav_name)| *fav_provider == provider && *fav_name == name);
+                ModelInfo {
+                    model: Arc::new(TestLanguageModel::new(name, provider)),
+                    icon: IconOrSvg::Icon(IconName::Ai),
+                    is_favorite,
+                }
             })
             .collect()
     }
@@ -795,4 +852,93 @@ mod tests {
             vec!["zed/claude", "zed/gemini", "copilot/claude"],
         );
     }
+
+    #[gpui::test]
+    fn test_favorites_section_appears_when_favorites_exist(_cx: &mut TestAppContext) {
+        let recommended_models = create_models(vec![("zed", "claude")]);
+        let all_models = create_models_with_favorites(
+            vec![("zed", "claude"), ("zed", "gemini"), ("openai", "gpt-4")],
+            vec![("zed", "gemini")],
+        );
+
+        let grouped_models = GroupedModels::new(all_models, recommended_models);
+        let entries = grouped_models.entries();
+
+        assert!(matches!(
+            entries.first(),
+            Some(LanguageModelPickerEntry::Separator(s)) if s == "Favorite"
+        ));
+
+        assert_models_eq(grouped_models.favorites, vec!["zed/gemini"]);
+    }
+
+    #[gpui::test]
+    fn test_no_favorites_section_when_no_favorites(_cx: &mut TestAppContext) {
+        let recommended_models = create_models(vec![("zed", "claude")]);
+        let all_models = create_models(vec![("zed", "claude"), ("zed", "gemini")]);
+
+        let grouped_models = GroupedModels::new(all_models, recommended_models);
+        let entries = grouped_models.entries();
+
+        assert!(matches!(
+            entries.first(),
+            Some(LanguageModelPickerEntry::Separator(s)) if s == "Recommended"
+        ));
+
+        assert!(grouped_models.favorites.is_empty());
+    }
+
+    #[gpui::test]
+    fn test_models_have_correct_actions(_cx: &mut TestAppContext) {
+        let recommended_models =
+            create_models_with_favorites(vec![("zed", "claude")], vec![("zed", "claude")]);
+        let all_models = create_models_with_favorites(
+            vec![("zed", "claude"), ("zed", "gemini"), ("openai", "gpt-4")],
+            vec![("zed", "claude")],
+        );
+
+        let grouped_models = GroupedModels::new(all_models, recommended_models);
+        let entries = grouped_models.entries();
+
+        for entry in &entries {
+            if let LanguageModelPickerEntry::Model(info) = entry {
+                if info.model.telemetry_id() == "zed/claude" {
+                    assert!(info.is_favorite, "zed/claude should be a favorite");
+                } else {
+                    assert!(
+                        !info.is_favorite,
+                        "{} should not be a favorite",
+                        info.model.telemetry_id()
+                    );
+                }
+            }
+        }
+    }
+
+    #[gpui::test]
+    fn test_favorites_appear_in_other_sections(_cx: &mut TestAppContext) {
+        let favorites = vec![("zed", "gemini"), ("openai", "gpt-4")];
+
+        let recommended_models =
+            create_models_with_favorites(vec![("zed", "claude")], favorites.clone());
+
+        let all_models = create_models_with_favorites(
+            vec![
+                ("zed", "claude"),
+                ("zed", "gemini"),
+                ("openai", "gpt-4"),
+                ("openai", "gpt-3.5"),
+            ],
+            favorites,
+        );
+
+        let grouped_models = GroupedModels::new(all_models, recommended_models);
+
+        assert_models_eq(grouped_models.favorites, vec!["zed/gemini", "openai/gpt-4"]);
+        assert_models_eq(grouped_models.recommended, vec!["zed/claude"]);
+        assert_models_eq(
+            grouped_models.all.values().flatten().cloned().collect(),
+            vec!["zed/claude", "zed/gemini", "openai/gpt-4", "openai/gpt-3.5"],
+        );
+    }
 }

crates/agent_ui/src/profile_selector.rs 🔗

@@ -1,4 +1,4 @@
-use crate::{ManageProfiles, ToggleProfileSelector};
+use crate::{CycleModeSelector, ManageProfiles, ToggleProfileSelector};
 use agent_settings::{
     AgentProfile, AgentProfileId, AgentSettings, AvailableProfiles, builtin_profiles,
 };
@@ -70,6 +70,29 @@ impl ProfileSelector {
         self.picker_handle.clone()
     }
 
+    pub fn cycle_profile(&mut self, cx: &mut Context<Self>) {
+        if !self.provider.profiles_supported(cx) {
+            return;
+        }
+
+        let profiles = AgentProfile::available_profiles(cx);
+        if profiles.is_empty() {
+            return;
+        }
+
+        let current_profile_id = self.provider.profile_id(cx);
+        let current_index = profiles
+            .keys()
+            .position(|id| id == &current_profile_id)
+            .unwrap_or(0);
+
+        let next_index = (current_index + 1) % profiles.len();
+
+        if let Some((next_profile_id, _)) = profiles.get_index(next_index) {
+            self.provider.set_profile(next_profile_id.clone(), cx);
+        }
+    }
+
     fn ensure_picker(
         &mut self,
         window: &mut Window,
@@ -163,14 +186,29 @@ impl Render for ProfileSelector {
         PickerPopoverMenu::new(
             picker,
             trigger_button,
-            move |_window, cx| {
-                Tooltip::for_action_in(
-                    "Toggle Profile Menu",
-                    &ToggleProfileSelector,
-                    &focus_handle,
-                    cx,
-                )
-            },
+            Tooltip::element({
+                move |_window, cx| {
+                    let container = || h_flex().gap_1().justify_between();
+                    v_flex()
+                        .gap_1()
+                        .child(container().child(Label::new("Toggle Profile Menu")).child(
+                            KeyBinding::for_action_in(&ToggleProfileSelector, &focus_handle, cx),
+                        ))
+                        .child(
+                            container()
+                                .pb_1()
+                                .border_b_1()
+                                .border_color(cx.theme().colors().border_variant)
+                                .child(Label::new("Cycle Through Profiles"))
+                                .child(KeyBinding::for_action_in(
+                                    &CycleModeSelector,
+                                    &focus_handle,
+                                    cx,
+                                )),
+                        )
+                        .into_any()
+                }
+            }),
             gpui::Corner::BottomRight,
             cx,
         )
@@ -542,7 +580,7 @@ impl PickerDelegate for ProfilePickerDelegate {
                 let is_active = active_id == candidate.id;
 
                 Some(
-                    ListItem::new(SharedString::from(candidate.id.0.clone()))
+                    ListItem::new(candidate.id.0.clone())
                         .inset(true)
                         .spacing(ListItemSpacing::Sparse)
                         .toggle_state(selected)

crates/agent_ui/src/slash_command.rs 🔗

@@ -341,7 +341,6 @@ impl CompletionProvider for SlashCommandCompletionProvider {
         position: language::Anchor,
         _text: &str,
         _trigger_in_words: bool,
-        _menu_is_open: bool,
         cx: &mut Context<Editor>,
     ) -> bool {
         let buffer = buffer.read(cx);

crates/agent_ui/src/terminal_codegen.rs 🔗

@@ -1,37 +1,38 @@
 use crate::inline_prompt_editor::CodegenStatus;
-use client::telemetry::Telemetry;
 use futures::{SinkExt, StreamExt, channel::mpsc};
 use gpui::{App, AppContext as _, Context, Entity, EventEmitter, Task};
-use language_model::{
-    ConfiguredModel, LanguageModelRegistry, LanguageModelRequest, report_assistant_event,
-};
-use std::{sync::Arc, time::Instant};
-use telemetry_events::{AssistantEventData, AssistantKind, AssistantPhase};
+use language_model::{ConfiguredModel, LanguageModelRegistry, LanguageModelRequest};
+use std::time::Instant;
 use terminal::Terminal;
+use uuid::Uuid;
 
 pub struct TerminalCodegen {
     pub status: CodegenStatus,
-    pub telemetry: Option<Arc<Telemetry>>,
     terminal: Entity<Terminal>,
     generation: Task<()>,
     pub message_id: Option<String>,
     transaction: Option<TerminalTransaction>,
+    session_id: Uuid,
 }
 
 impl EventEmitter<CodegenEvent> for TerminalCodegen {}
 
 impl TerminalCodegen {
-    pub fn new(terminal: Entity<Terminal>, telemetry: Option<Arc<Telemetry>>) -> Self {
+    pub fn new(terminal: Entity<Terminal>, session_id: Uuid) -> Self {
         Self {
             terminal,
-            telemetry,
             status: CodegenStatus::Idle,
             generation: Task::ready(()),
             message_id: None,
             transaction: None,
+            session_id,
         }
     }
 
+    pub fn session_id(&self) -> Uuid {
+        self.session_id
+    }
+
     pub fn start(&mut self, prompt_task: Task<LanguageModelRequest>, cx: &mut Context<Self>) {
         let Some(ConfiguredModel { model, .. }) =
             LanguageModelRegistry::read_global(cx).inline_assistant_model()
@@ -39,15 +40,15 @@ impl TerminalCodegen {
             return;
         };
 
-        let model_api_key = model.api_key(cx);
-        let http_client = cx.http_client();
-        let telemetry = self.telemetry.clone();
+        let anthropic_reporter = language_model::AnthropicEventReporter::new(&model, cx);
+        let session_id = self.session_id;
+        let model_telemetry_id = model.telemetry_id();
+        let model_provider_id = model.provider_id().to_string();
+
         self.status = CodegenStatus::Pending;
         self.transaction = Some(TerminalTransaction::start(self.terminal.clone()));
         self.generation = cx.spawn(async move |this, cx| {
             let prompt = prompt_task.await;
-            let model_telemetry_id = model.telemetry_id();
-            let model_provider_id = model.provider_id();
             let response = model.stream_completion_text(prompt, cx).await;
             let generate = async {
                 let message_id = response
@@ -59,7 +60,7 @@ impl TerminalCodegen {
 
                 let task = cx.background_spawn({
                     let message_id = message_id.clone();
-                    let executor = cx.background_executor().clone();
+                    let anthropic_reporter = anthropic_reporter.clone();
                     async move {
                         let mut response_latency = None;
                         let request_start = Instant::now();
@@ -79,24 +80,27 @@ impl TerminalCodegen {
                         let result = task.await;
 
                         let error_message = result.as_ref().err().map(|error| error.to_string());
-                        report_assistant_event(
-                            AssistantEventData {
-                                conversation_id: None,
-                                kind: AssistantKind::InlineTerminal,
-                                message_id,
-                                phase: AssistantPhase::Response,
-                                model: model_telemetry_id,
-                                model_provider: model_provider_id.to_string(),
-                                response_latency,
-                                error_message,
-                                language_name: None,
-                            },
-                            telemetry,
-                            http_client,
-                            model_api_key,
-                            &executor,
+
+                        telemetry::event!(
+                            "Assistant Responded",
+                            session_id = session_id.to_string(),
+                            kind = "inline_terminal",
+                            phase = "response",
+                            model = model_telemetry_id,
+                            model_provider = model_provider_id,
+                            language_name = Option::<&str>::None,
+                            message_id = message_id,
+                            response_latency = response_latency,
+                            error_message = error_message,
                         );
 
+                        anthropic_reporter.report(language_model::AnthropicEventData {
+                            completion_type: language_model::AnthropicCompletionType::Terminal,
+                            event: language_model::AnthropicEventType::Response,
+                            language_name: None,
+                            message_id,
+                        });
+
                         result?;
                         anyhow::Ok(())
                     }
@@ -135,6 +139,12 @@ impl TerminalCodegen {
         cx.notify();
     }
 
+    pub fn completion(&self) -> Option<String> {
+        self.transaction
+            .as_ref()
+            .map(|transaction| transaction.completion.clone())
+    }
+
     pub fn stop(&mut self, cx: &mut Context<Self>) {
         self.status = CodegenStatus::Done;
         self.generation = Task::ready(());
@@ -167,27 +177,32 @@ pub const CLEAR_INPUT: &str = "\x03";
 const CARRIAGE_RETURN: &str = "\x0d";
 
 struct TerminalTransaction {
+    completion: String,
     terminal: Entity<Terminal>,
 }
 
 impl TerminalTransaction {
     pub fn start(terminal: Entity<Terminal>) -> Self {
-        Self { terminal }
+        Self {
+            completion: String::new(),
+            terminal,
+        }
     }
 
     pub fn push(&mut self, hunk: String, cx: &mut App) {
         // Ensure that the assistant cannot accidentally execute commands that are streamed into the terminal
         let input = Self::sanitize_input(hunk);
+        self.completion.push_str(&input);
         self.terminal
             .update(cx, |terminal, _| terminal.input(input.into_bytes()));
     }
 
-    pub fn undo(&self, cx: &mut App) {
+    pub fn undo(self, cx: &mut App) {
         self.terminal
             .update(cx, |terminal, _| terminal.input(CLEAR_INPUT.as_bytes()));
     }
 
-    pub fn complete(&self, cx: &mut App) {
+    pub fn complete(self, cx: &mut App) {
         self.terminal
             .update(cx, |terminal, _| terminal.input(CARRIAGE_RETURN.as_bytes()));
     }

crates/agent_ui/src/terminal_inline_assistant.rs 🔗

@@ -8,7 +8,7 @@ use crate::{
 use agent::HistoryStore;
 use agent_settings::AgentSettings;
 use anyhow::{Context as _, Result};
-use client::telemetry::Telemetry;
+
 use cloud_llm_client::CompletionIntent;
 use collections::{HashMap, VecDeque};
 use editor::{MultiBuffer, actions::SelectAll};
@@ -17,24 +17,19 @@ use gpui::{App, Entity, Focusable, Global, Subscription, Task, UpdateGlobal, Wea
 use language::Buffer;
 use language_model::{
     ConfiguredModel, LanguageModelRegistry, LanguageModelRequest, LanguageModelRequestMessage,
-    Role, report_assistant_event,
+    Role, report_anthropic_event,
 };
 use project::Project;
 use prompt_store::{PromptBuilder, PromptStore};
 use std::sync::Arc;
-use telemetry_events::{AssistantEventData, AssistantKind, AssistantPhase};
 use terminal_view::TerminalView;
 use ui::prelude::*;
 use util::ResultExt;
+use uuid::Uuid;
 use workspace::{Toast, Workspace, notifications::NotificationId};
 
-pub fn init(
-    fs: Arc<dyn Fs>,
-    prompt_builder: Arc<PromptBuilder>,
-    telemetry: Arc<Telemetry>,
-    cx: &mut App,
-) {
-    cx.set_global(TerminalInlineAssistant::new(fs, prompt_builder, telemetry));
+pub fn init(fs: Arc<dyn Fs>, prompt_builder: Arc<PromptBuilder>, cx: &mut App) {
+    cx.set_global(TerminalInlineAssistant::new(fs, prompt_builder));
 }
 
 const DEFAULT_CONTEXT_LINES: usize = 50;
@@ -44,7 +39,6 @@ pub struct TerminalInlineAssistant {
     next_assist_id: TerminalInlineAssistId,
     assists: HashMap<TerminalInlineAssistId, TerminalInlineAssist>,
     prompt_history: VecDeque<String>,
-    telemetry: Option<Arc<Telemetry>>,
     fs: Arc<dyn Fs>,
     prompt_builder: Arc<PromptBuilder>,
 }
@@ -52,16 +46,11 @@ pub struct TerminalInlineAssistant {
 impl Global for TerminalInlineAssistant {}
 
 impl TerminalInlineAssistant {
-    pub fn new(
-        fs: Arc<dyn Fs>,
-        prompt_builder: Arc<PromptBuilder>,
-        telemetry: Arc<Telemetry>,
-    ) -> Self {
+    pub fn new(fs: Arc<dyn Fs>, prompt_builder: Arc<PromptBuilder>) -> Self {
         Self {
             next_assist_id: TerminalInlineAssistId::default(),
             assists: HashMap::default(),
             prompt_history: VecDeque::default(),
-            telemetry: Some(telemetry),
             fs,
             prompt_builder,
         }
@@ -80,13 +69,14 @@ impl TerminalInlineAssistant {
     ) {
         let terminal = terminal_view.read(cx).terminal().clone();
         let assist_id = self.next_assist_id.post_inc();
+        let session_id = Uuid::new_v4();
         let prompt_buffer = cx.new(|cx| {
             MultiBuffer::singleton(
                 cx.new(|cx| Buffer::local(initial_prompt.unwrap_or_default(), cx)),
                 cx,
             )
         });
-        let codegen = cx.new(|_| TerminalCodegen::new(terminal, self.telemetry.clone()));
+        let codegen = cx.new(|_| TerminalCodegen::new(terminal, session_id));
 
         let prompt_editor = cx.new(|cx| {
             PromptEditor::new_terminal(
@@ -94,6 +84,7 @@ impl TerminalInlineAssistant {
                 self.prompt_history.clone(),
                 prompt_buffer.clone(),
                 codegen,
+                session_id,
                 self.fs.clone(),
                 thread_store.clone(),
                 prompt_store.clone(),
@@ -136,7 +127,7 @@ impl TerminalInlineAssistant {
         if let Some(prompt_editor) = assist.prompt_editor.as_ref() {
             prompt_editor.update(cx, |this, cx| {
                 this.editor.update(cx, |editor, cx| {
-                    window.focus(&editor.focus_handle(cx));
+                    window.focus(&editor.focus_handle(cx), cx);
                     editor.select_all(&SelectAll, window, cx);
                 });
             });
@@ -301,7 +292,7 @@ impl TerminalInlineAssistant {
                 .terminal
                 .update(cx, |this, cx| {
                     this.clear_block_below_cursor(cx);
-                    this.focus_handle(cx).focus(window);
+                    this.focus_handle(cx).focus(window, cx);
                 })
                 .log_err();
 
@@ -309,27 +300,45 @@ impl TerminalInlineAssistant {
                 LanguageModelRegistry::read_global(cx).inline_assistant_model()
             {
                 let codegen = assist.codegen.read(cx);
-                let executor = cx.background_executor().clone();
-                report_assistant_event(
-                    AssistantEventData {
-                        conversation_id: None,
-                        kind: AssistantKind::InlineTerminal,
-                        message_id: codegen.message_id.clone(),
-                        phase: if undo {
-                            AssistantPhase::Rejected
-                        } else {
-                            AssistantPhase::Accepted
-                        },
-                        model: model.telemetry_id(),
-                        model_provider: model.provider_id().to_string(),
-                        response_latency: None,
-                        error_message: None,
+                let session_id = codegen.session_id();
+                let message_id = codegen.message_id.clone();
+                let model_telemetry_id = model.telemetry_id();
+                let model_provider_id = model.provider_id().to_string();
+
+                let (phase, event_type, anthropic_event_type) = if undo {
+                    (
+                        "rejected",
+                        "Assistant Response Rejected",
+                        language_model::AnthropicEventType::Reject,
+                    )
+                } else {
+                    (
+                        "accepted",
+                        "Assistant Response Accepted",
+                        language_model::AnthropicEventType::Accept,
+                    )
+                };
+
+                // Fire Zed telemetry
+                telemetry::event!(
+                    event_type,
+                    kind = "inline_terminal",
+                    phase = phase,
+                    model = model_telemetry_id,
+                    model_provider = model_provider_id,
+                    message_id = message_id,
+                    session_id = session_id,
+                );
+
+                report_anthropic_event(
+                    &model,
+                    language_model::AnthropicEventData {
+                        completion_type: language_model::AnthropicCompletionType::Terminal,
+                        event: anthropic_event_type,
                         language_name: None,
+                        message_id,
                     },
-                    codegen.telemetry.clone(),
-                    cx.http_client(),
-                    model.api_key(cx),
-                    &executor,
+                    cx,
                 );
             }
 
@@ -360,7 +369,7 @@ impl TerminalInlineAssistant {
             .terminal
             .update(cx, |this, cx| {
                 this.clear_block_below_cursor(cx);
-                this.focus_handle(cx).focus(window);
+                this.focus_handle(cx).focus(window, cx);
             })
             .is_ok()
     }

crates/agent_ui/src/text_thread_editor.rs 🔗

@@ -1,6 +1,6 @@
 use crate::{
     language_model_selector::{LanguageModelSelector, language_model_selector},
-    ui::BurnModeTooltip,
+    ui::{BurnModeTooltip, ModelSelectorTooltip},
 };
 use agent_settings::CompletionMode;
 use anyhow::Result;
@@ -33,7 +33,8 @@ use language::{
     language_settings::{SoftWrap, all_language_settings},
 };
 use language_model::{
-    ConfigurationError, LanguageModelExt, LanguageModelImage, LanguageModelRegistry, Role,
+    ConfigurationError, IconOrSvg, LanguageModelExt, LanguageModelImage, LanguageModelRegistry,
+    Role,
 };
 use multi_buffer::MultiBufferRow;
 use picker::{Picker, popover_menu::PickerPopoverMenu};
@@ -71,7 +72,9 @@ use workspace::{
     pane,
     searchable::{SearchEvent, SearchableItem},
 };
-use zed_actions::agent::{AddSelectionToThread, ToggleModelSelector};
+use zed_actions::agent::{AddSelectionToThread, PasteRaw, ToggleModelSelector};
+
+use crate::CycleFavoriteModels;
 
 use crate::{slash_command::SlashCommandCompletionProvider, slash_command_picker};
 use assistant_text_thread::{
@@ -304,17 +307,31 @@ impl TextThreadEditor {
             language_model_selector: cx.new(|cx| {
                 language_model_selector(
                     |cx| LanguageModelRegistry::read_global(cx).default_model(),
-                    move |model, cx| {
-                        update_settings_file(fs.clone(), cx, move |settings, _| {
-                            let provider = model.provider_id().0.to_string();
-                            let model = model.id().0.to_string();
-                            settings.agent.get_or_insert_default().set_model(
-                                LanguageModelSelection {
-                                    provider: LanguageModelProviderSetting(provider),
-                                    model,
-                                },
-                            )
-                        });
+                    {
+                        let fs = fs.clone();
+                        move |model, cx| {
+                            update_settings_file(fs.clone(), cx, move |settings, _| {
+                                let provider = model.provider_id().0.to_string();
+                                let model = model.id().0.to_string();
+                                settings.agent.get_or_insert_default().set_model(
+                                    LanguageModelSelection {
+                                        provider: LanguageModelProviderSetting(provider),
+                                        model,
+                                    },
+                                )
+                            });
+                        }
+                    },
+                    {
+                        let fs = fs.clone();
+                        move |model, should_be_favorite, cx| {
+                            crate::favorite_models::toggle_in_settings(
+                                model,
+                                should_be_favorite,
+                                fs.clone(),
+                                cx,
+                            );
+                        }
                     },
                     true, // Use popover styles for picker
                     focus_handle,
@@ -1325,7 +1342,7 @@ impl TextThreadEditor {
         if let Some((text, _)) = Self::get_selection_or_code_block(&context_editor_view, cx) {
             active_editor_view.update(cx, |editor, cx| {
                 editor.insert(&text, window, cx);
-                editor.focus_handle(cx).focus(window);
+                editor.focus_handle(cx).focus(window, cx);
             })
         }
     }
@@ -1682,6 +1699,118 @@ impl TextThreadEditor {
         window: &mut Window,
         cx: &mut Context<Self>,
     ) {
+        let Some(workspace) = self.workspace.upgrade() else {
+            return;
+        };
+        let editor_clipboard_selections = cx
+            .read_from_clipboard()
+            .and_then(|item| item.entries().first().cloned())
+            .and_then(|entry| match entry {
+                ClipboardEntry::String(text) => {
+                    text.metadata_json::<Vec<editor::ClipboardSelection>>()
+                }
+                _ => None,
+            });
+
+        // Insert creases for pasted clipboard selections that:
+        // 1. Contain exactly one selection
+        // 2. Have an associated file path
+        // 3. Span multiple lines (not single-line selections)
+        // 4. Belong to a file that exists in the current project
+        let should_insert_creases = util::maybe!({
+            let selections = editor_clipboard_selections.as_ref()?;
+            if selections.len() > 1 {
+                return Some(false);
+            }
+            let selection = selections.first()?;
+            let file_path = selection.file_path.as_ref()?;
+            let line_range = selection.line_range.as_ref()?;
+
+            if line_range.start() == line_range.end() {
+                return Some(false);
+            }
+
+            Some(
+                workspace
+                    .read(cx)
+                    .project()
+                    .read(cx)
+                    .project_path_for_absolute_path(file_path, cx)
+                    .is_some(),
+            )
+        })
+        .unwrap_or(false);
+
+        if should_insert_creases && let Some(clipboard_item) = cx.read_from_clipboard() {
+            if let Some(ClipboardEntry::String(clipboard_text)) = clipboard_item.entries().first() {
+                if let Some(selections) = editor_clipboard_selections {
+                    cx.stop_propagation();
+
+                    let text = clipboard_text.text();
+                    self.editor.update(cx, |editor, cx| {
+                        let mut current_offset = 0;
+                        let weak_editor = cx.entity().downgrade();
+
+                        for selection in selections {
+                            if let (Some(file_path), Some(line_range)) =
+                                (selection.file_path, selection.line_range)
+                            {
+                                let selected_text =
+                                    &text[current_offset..current_offset + selection.len];
+                                let fence = assistant_slash_commands::codeblock_fence_for_path(
+                                    file_path.to_str(),
+                                    Some(line_range.clone()),
+                                );
+                                let formatted_text = format!("{fence}{selected_text}\n```");
+
+                                let insert_point = editor
+                                    .selections
+                                    .newest::<Point>(&editor.display_snapshot(cx))
+                                    .head();
+                                let start_row = MultiBufferRow(insert_point.row);
+
+                                editor.insert(&formatted_text, window, cx);
+
+                                let snapshot = editor.buffer().read(cx).snapshot(cx);
+                                let anchor_before = snapshot.anchor_after(insert_point);
+                                let anchor_after = editor
+                                    .selections
+                                    .newest_anchor()
+                                    .head()
+                                    .bias_left(&snapshot);
+
+                                editor.insert("\n", window, cx);
+
+                                let crease_text = acp_thread::selection_name(
+                                    Some(file_path.as_ref()),
+                                    &line_range,
+                                );
+
+                                let fold_placeholder = quote_selection_fold_placeholder(
+                                    crease_text,
+                                    weak_editor.clone(),
+                                );
+                                let crease = Crease::inline(
+                                    anchor_before..anchor_after,
+                                    fold_placeholder,
+                                    render_quote_selection_output_toggle,
+                                    |_, _, _, _| Empty.into_any(),
+                                );
+                                editor.insert_creases(vec![crease], cx);
+                                editor.fold_at(start_row, window, cx);
+
+                                current_offset += selection.len;
+                                if !selection.is_entire_line && current_offset < text.len() {
+                                    current_offset += 1;
+                                }
+                            }
+                        }
+                    });
+                    return;
+                }
+            }
+        }
+
         cx.stop_propagation();
 
         let mut images = if let Some(item) = cx.read_from_clipboard() {
@@ -1836,6 +1965,12 @@ impl TextThreadEditor {
         }
     }
 
+    fn paste_raw(&mut self, _: &PasteRaw, window: &mut Window, cx: &mut Context<Self>) {
+        self.editor.update(cx, |editor, cx| {
+            editor.paste(&editor::actions::Paste, window, cx);
+        });
+    }
+
     fn update_image_blocks(&mut self, cx: &mut Context<Self>) {
         self.editor.update(cx, |editor, cx| {
             let buffer = editor.buffer().read(cx).snapshot(cx);
@@ -2097,18 +2232,41 @@ impl TextThreadEditor {
             .default_model()
             .map(|default| default.provider);
 
-        let provider_icon = match active_provider {
-            Some(provider) => provider.icon(),
-            None => IconName::Ai,
-        };
+        let provider_icon = active_provider
+            .as_ref()
+            .map(|p| p.icon())
+            .unwrap_or(IconOrSvg::Icon(IconName::Ai));
 
         let focus_handle = self.editor().focus_handle(cx);
+
         let (color, icon) = if self.language_model_selector_menu_handle.is_deployed() {
             (Color::Accent, IconName::ChevronUp)
         } else {
             (Color::Muted, IconName::ChevronDown)
         };
 
+        let provider_icon_element = match provider_icon {
+            IconOrSvg::Svg(path) => Icon::from_external_svg(path),
+            IconOrSvg::Icon(name) => Icon::new(name),
+        }
+        .color(color)
+        .size(IconSize::XSmall);
+
+        let show_cycle_row = self
+            .language_model_selector
+            .read(cx)
+            .delegate
+            .favorites_count()
+            > 1;
+
+        let tooltip = Tooltip::element({
+            move |_, _cx| {
+                ModelSelectorTooltip::new(focus_handle.clone())
+                    .show_cycle_row(show_cycle_row)
+                    .into_any_element()
+            }
+        });
+
         PickerPopoverMenu::new(
             self.language_model_selector.clone(),
             ButtonLike::new("active-model")
@@ -2116,7 +2274,7 @@ impl TextThreadEditor {
                 .child(
                     h_flex()
                         .gap_0p5()
-                        .child(Icon::new(provider_icon).color(color).size(IconSize::XSmall))
+                        .child(provider_icon_element)
                         .child(
                             Label::new(model_name)
                                 .color(color)
@@ -2125,9 +2283,7 @@ impl TextThreadEditor {
                         )
                         .child(Icon::new(icon).color(color).size(IconSize::XSmall)),
                 ),
-            move |_window, cx| {
-                Tooltip::for_action_in("Change Model", &ToggleModelSelector, &focus_handle, cx)
-            },
+            tooltip,
             gpui::Corner::BottomRight,
             cx,
         )
@@ -2480,6 +2636,7 @@ impl Render for TextThreadEditor {
             .capture_action(cx.listener(TextThreadEditor::copy))
             .capture_action(cx.listener(TextThreadEditor::cut))
             .capture_action(cx.listener(TextThreadEditor::paste))
+            .on_action(cx.listener(TextThreadEditor::paste_raw))
             .capture_action(cx.listener(TextThreadEditor::cycle_message_role))
             .capture_action(cx.listener(TextThreadEditor::confirm_command))
             .on_action(cx.listener(TextThreadEditor::assist))
@@ -2487,6 +2644,11 @@ impl Render for TextThreadEditor {
             .on_action(move |_: &ToggleModelSelector, window, cx| {
                 language_model_selector.toggle(window, cx);
             })
+            .on_action(cx.listener(|this, _: &CycleFavoriteModels, window, cx| {
+                this.language_model_selector.update(cx, |selector, cx| {
+                    selector.delegate.cycle_favorite_models(window, cx);
+                });
+            }))
             .size_full()
             .child(
                 div()
@@ -2622,11 +2784,13 @@ impl SearchableItem for TextThreadEditor {
     fn update_matches(
         &mut self,
         matches: &[Self::Match],
+        active_match_index: Option<usize>,
         window: &mut Window,
         cx: &mut Context<Self>,
     ) {
-        self.editor
-            .update(cx, |editor, cx| editor.update_matches(matches, window, cx));
+        self.editor.update(cx, |editor, cx| {
+            editor.update_matches(matches, active_match_index, window, cx)
+        });
     }
 
     fn query_suggestion(&mut self, window: &mut Window, cx: &mut Context<Self>) -> String {
@@ -3230,7 +3394,6 @@ mod tests {
             let mut text_thread = TextThread::local(
                 registry,
                 None,
-                None,
                 prompt_builder.clone(),
                 Arc::new(SlashCommandWorkingSet::default()),
                 cx,

crates/agent_ui/src/ui.rs 🔗

@@ -4,8 +4,8 @@ mod burn_mode_tooltip;
 mod claude_code_onboarding_modal;
 mod end_trial_upsell;
 mod hold_for_default;
+mod model_selector_components;
 mod onboarding_modal;
-mod unavailable_editing_tooltip;
 mod usage_callout;
 
 pub use acp_onboarding_modal::*;
@@ -14,6 +14,6 @@ pub use burn_mode_tooltip::*;
 pub use claude_code_onboarding_modal::*;
 pub use end_trial_upsell::*;
 pub use hold_for_default::*;
+pub use model_selector_components::*;
 pub use onboarding_modal::*;
-pub use unavailable_editing_tooltip::*;
 pub use usage_callout::*;

crates/agent_ui/src/ui/acp_onboarding_modal.rs 🔗

@@ -222,8 +222,8 @@ impl Render for AcpOnboardingModal {
                 acp_onboarding_event!("Canceled", trigger = "Action");
                 cx.emit(DismissEvent);
             }))
-            .on_any_mouse_down(cx.listener(|this, _: &MouseDownEvent, window, _cx| {
-                this.focus_handle.focus(window);
+            .on_any_mouse_down(cx.listener(|this, _: &MouseDownEvent, window, cx| {
+                this.focus_handle.focus(window, cx);
             }))
             .child(illustration)
             .child(

crates/agent_ui/src/ui/agent_notification.rs 🔗

@@ -106,9 +106,6 @@ impl Render for AgentNotification {
             .font(ui_font)
             .border_color(cx.theme().colors().border)
             .rounded_xl()
-            .on_click(cx.listener(|_, _, _, cx| {
-                cx.emit(AgentNotificationEvent::Accepted);
-            }))
             .child(
                 h_flex()
                     .items_start()

crates/agent_ui/src/ui/claude_code_onboarding_modal.rs 🔗

@@ -230,8 +230,8 @@ impl Render for ClaudeCodeOnboardingModal {
                 claude_code_onboarding_event!("Canceled", trigger = "Action");
                 cx.emit(DismissEvent);
             }))
-            .on_any_mouse_down(cx.listener(|this, _: &MouseDownEvent, window, _cx| {
-                this.focus_handle.focus(window);
+            .on_any_mouse_down(cx.listener(|this, _: &MouseDownEvent, window, cx| {
+                this.focus_handle.focus(window, cx);
             }))
             .child(illustration)
             .child(

crates/agent_ui/src/ui/hold_for_default.rs 🔗

@@ -27,7 +27,7 @@ impl RenderOnce for HoldForDefault {
                 PlatformStyle::platform(),
                 None,
                 Some(TextSize::Default.rems(cx).into()),
-                true,
+                false,
             )))
             .child(div().map(|this| {
                 if self.is_default {

crates/agent_ui/src/ui/model_selector_components.rs 🔗

@@ -0,0 +1,249 @@
+use gpui::{Action, ClickEvent, FocusHandle, prelude::*};
+use ui::{ElevationIndex, KeyBinding, ListItem, ListItemSpacing, Tooltip, prelude::*};
+use zed_actions::agent::ToggleModelSelector;
+
+use crate::CycleFavoriteModels;
+
+enum ModelIcon {
+    Name(IconName),
+    Path(SharedString),
+}
+
+#[derive(IntoElement)]
+pub struct ModelSelectorHeader {
+    title: SharedString,
+    has_border: bool,
+}
+
+impl ModelSelectorHeader {
+    pub fn new(title: impl Into<SharedString>, has_border: bool) -> Self {
+        Self {
+            title: title.into(),
+            has_border,
+        }
+    }
+}
+
+impl RenderOnce for ModelSelectorHeader {
+    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
+        div()
+            .px_2()
+            .pb_1()
+            .when(self.has_border, |this| {
+                this.mt_1()
+                    .pt_2()
+                    .border_t_1()
+                    .border_color(cx.theme().colors().border_variant)
+            })
+            .child(
+                Label::new(self.title)
+                    .size(LabelSize::XSmall)
+                    .color(Color::Muted),
+            )
+    }
+}
+
+#[derive(IntoElement)]
+pub struct ModelSelectorListItem {
+    index: usize,
+    title: SharedString,
+    icon: Option<ModelIcon>,
+    is_selected: bool,
+    is_focused: bool,
+    is_favorite: bool,
+    on_toggle_favorite: Option<Box<dyn Fn(&ClickEvent, &mut Window, &mut App) + 'static>>,
+}
+
+impl ModelSelectorListItem {
+    pub fn new(index: usize, title: impl Into<SharedString>) -> Self {
+        Self {
+            index,
+            title: title.into(),
+            icon: None,
+            is_selected: false,
+            is_focused: false,
+            is_favorite: false,
+            on_toggle_favorite: None,
+        }
+    }
+
+    pub fn icon(mut self, icon: IconName) -> Self {
+        self.icon = Some(ModelIcon::Name(icon));
+        self
+    }
+
+    pub fn icon_path(mut self, path: SharedString) -> Self {
+        self.icon = Some(ModelIcon::Path(path));
+        self
+    }
+
+    pub fn is_selected(mut self, is_selected: bool) -> Self {
+        self.is_selected = is_selected;
+        self
+    }
+
+    pub fn is_focused(mut self, is_focused: bool) -> Self {
+        self.is_focused = is_focused;
+        self
+    }
+
+    pub fn is_favorite(mut self, is_favorite: bool) -> Self {
+        self.is_favorite = is_favorite;
+        self
+    }
+
+    pub fn on_toggle_favorite(
+        mut self,
+        handler: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
+    ) -> Self {
+        self.on_toggle_favorite = Some(Box::new(handler));
+        self
+    }
+}
+
+impl RenderOnce for ModelSelectorListItem {
+    fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement {
+        let model_icon_color = if self.is_selected {
+            Color::Accent
+        } else {
+            Color::Muted
+        };
+
+        let is_favorite = self.is_favorite;
+
+        ListItem::new(self.index)
+            .inset(true)
+            .spacing(ListItemSpacing::Sparse)
+            .toggle_state(self.is_focused)
+            .child(
+                h_flex()
+                    .w_full()
+                    .gap_1p5()
+                    .when_some(self.icon, |this, icon| {
+                        this.child(
+                            match icon {
+                                ModelIcon::Name(icon_name) => Icon::new(icon_name),
+                                ModelIcon::Path(icon_path) => Icon::from_external_svg(icon_path),
+                            }
+                            .color(model_icon_color)
+                            .size(IconSize::Small),
+                        )
+                    })
+                    .child(Label::new(self.title).truncate()),
+            )
+            .end_slot(div().pr_2().when(self.is_selected, |this| {
+                this.child(Icon::new(IconName::Check).color(Color::Accent))
+            }))
+            .end_hover_slot(div().pr_1p5().when_some(self.on_toggle_favorite, {
+                |this, handle_click| {
+                    let (icon, color, tooltip) = if is_favorite {
+                        (IconName::StarFilled, Color::Accent, "Unfavorite Model")
+                    } else {
+                        (IconName::Star, Color::Default, "Favorite Model")
+                    };
+                    this.child(
+                        IconButton::new(("toggle-favorite", self.index), icon)
+                            .layer(ElevationIndex::ElevatedSurface)
+                            .icon_color(color)
+                            .icon_size(IconSize::Small)
+                            .tooltip(Tooltip::text(tooltip))
+                            .on_click(move |event, window, cx| (handle_click)(event, window, cx)),
+                    )
+                }
+            }))
+    }
+}
+
+#[derive(IntoElement)]
+pub struct ModelSelectorFooter {
+    action: Box<dyn Action>,
+    focus_handle: FocusHandle,
+}
+
+impl ModelSelectorFooter {
+    pub fn new(action: Box<dyn Action>, focus_handle: FocusHandle) -> Self {
+        Self {
+            action,
+            focus_handle,
+        }
+    }
+}
+
+impl RenderOnce for ModelSelectorFooter {
+    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
+        let action = self.action;
+        let focus_handle = self.focus_handle;
+
+        h_flex()
+            .w_full()
+            .p_1p5()
+            .border_t_1()
+            .border_color(cx.theme().colors().border_variant)
+            .child(
+                Button::new("configure", "Configure")
+                    .full_width()
+                    .style(ButtonStyle::Outlined)
+                    .key_binding(
+                        KeyBinding::for_action_in(action.as_ref(), &focus_handle, cx)
+                            .map(|kb| kb.size(rems_from_px(12.))),
+                    )
+                    .on_click(move |_, window, cx| {
+                        window.dispatch_action(action.boxed_clone(), cx);
+                    }),
+            )
+    }
+}
+
+#[derive(IntoElement)]
+pub struct ModelSelectorTooltip {
+    focus_handle: FocusHandle,
+    show_cycle_row: bool,
+}
+
+impl ModelSelectorTooltip {
+    pub fn new(focus_handle: FocusHandle) -> Self {
+        Self {
+            focus_handle,
+            show_cycle_row: true,
+        }
+    }
+
+    pub fn show_cycle_row(mut self, show: bool) -> Self {
+        self.show_cycle_row = show;
+        self
+    }
+}
+
+impl RenderOnce for ModelSelectorTooltip {
+    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
+        v_flex()
+            .gap_1()
+            .child(
+                h_flex()
+                    .gap_2()
+                    .justify_between()
+                    .child(Label::new("Change Model"))
+                    .child(KeyBinding::for_action_in(
+                        &ToggleModelSelector,
+                        &self.focus_handle,
+                        cx,
+                    )),
+            )
+            .when(self.show_cycle_row, |this| {
+                this.child(
+                    h_flex()
+                        .pt_1()
+                        .gap_2()
+                        .border_t_1()
+                        .border_color(cx.theme().colors().border_variant)
+                        .justify_between()
+                        .child(Label::new("Cycle Favorited Models"))
+                        .child(KeyBinding::for_action_in(
+                            &CycleFavoriteModels,
+                            &self.focus_handle,
+                            cx,
+                        )),
+                )
+            })
+    }
+}

crates/agent_ui/src/ui/onboarding_modal.rs 🔗

@@ -83,8 +83,8 @@ impl Render for AgentOnboardingModal {
                 agent_onboarding_event!("Canceled", trigger = "Action");
                 cx.emit(DismissEvent);
             }))
-            .on_any_mouse_down(cx.listener(|this, _: &MouseDownEvent, window, _cx| {
-                this.focus_handle.focus(window);
+            .on_any_mouse_down(cx.listener(|this, _: &MouseDownEvent, window, cx| {
+                this.focus_handle.focus(window, cx);
             }))
             .child(
                 div()

crates/agent_ui/src/ui/unavailable_editing_tooltip.rs 🔗

@@ -1,29 +0,0 @@
-use gpui::{Context, IntoElement, Render, Window};
-use ui::{prelude::*, tooltip_container};
-
-pub struct UnavailableEditingTooltip {
-    agent_name: SharedString,
-}
-
-impl UnavailableEditingTooltip {
-    pub fn new(agent_name: SharedString) -> Self {
-        Self { agent_name }
-    }
-}
-
-impl Render for UnavailableEditingTooltip {
-    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
-        tooltip_container(cx, |this, _| {
-            this.child(Label::new("Unavailable Editing")).child(
-                div().max_w_64().child(
-                    Label::new(format!(
-                        "Editing previous messages is not available for {} yet.",
-                        self.agent_name
-                    ))
-                    .size(LabelSize::Small)
-                    .color(Color::Muted),
-                ),
-            )
-        })
-    }
-}

crates/agent_ui_v2/Cargo.toml 🔗

@@ -0,0 +1,47 @@
+[package]
+name = "agent_ui_v2"
+version = "0.1.0"
+edition.workspace = true
+publish.workspace = true
+license = "GPL-3.0-or-later"
+
+[lints]
+workspace = true
+
+[lib]
+path = "src/agent_ui_v2.rs"
+doctest = false
+
+[features]
+test-support = ["agent/test-support"]
+
+
+[dependencies]
+agent.workspace = true
+agent_servers.workspace = true
+agent_settings.workspace = true
+agent_ui.workspace = true
+anyhow.workspace = true
+assistant_text_thread.workspace = true
+chrono.workspace = true
+db.workspace = true
+editor.workspace = true
+feature_flags.workspace = true
+fs.workspace = true
+fuzzy.workspace = true
+gpui.workspace = true
+menu.workspace = true
+project.workspace = true
+prompt_store.workspace = true
+serde.workspace = true
+serde_json.workspace = true
+settings.workspace = true
+text.workspace = true
+time.workspace = true
+time_format.workspace = true
+ui.workspace = true
+util.workspace = true
+workspace.workspace = true
+
+[dev-dependencies]
+agent = { workspace = true, features = ["test-support"] }

crates/agent_ui_v2/src/agent_thread_pane.rs 🔗

@@ -0,0 +1,287 @@
+use agent::{HistoryEntry, HistoryEntryId, HistoryStore, NativeAgentServer};
+use agent_servers::AgentServer;
+use agent_settings::AgentSettings;
+use agent_ui::acp::AcpThreadView;
+use fs::Fs;
+use gpui::{
+    Entity, EventEmitter, Focusable, Pixels, SharedString, Subscription, WeakEntity, prelude::*,
+};
+use project::Project;
+use prompt_store::PromptStore;
+use serde::{Deserialize, Serialize};
+use settings::DockSide;
+use settings::Settings as _;
+use std::rc::Rc;
+use std::sync::Arc;
+use ui::{Tab, Tooltip, prelude::*};
+use workspace::{
+    Workspace,
+    dock::{ClosePane, MinimizePane, UtilityPane, UtilityPanePosition},
+    utility_pane::UtilityPaneSlot,
+};
+
+pub const DEFAULT_UTILITY_PANE_WIDTH: Pixels = gpui::px(400.0);
+
+#[derive(Serialize, Deserialize, Debug, Clone)]
+pub enum SerializedHistoryEntryId {
+    AcpThread(String),
+    TextThread(String),
+}
+
+impl From<HistoryEntryId> for SerializedHistoryEntryId {
+    fn from(id: HistoryEntryId) -> Self {
+        match id {
+            HistoryEntryId::AcpThread(session_id) => {
+                SerializedHistoryEntryId::AcpThread(session_id.0.to_string())
+            }
+            HistoryEntryId::TextThread(path) => {
+                SerializedHistoryEntryId::TextThread(path.to_string_lossy().to_string())
+            }
+        }
+    }
+}
+
+#[derive(Serialize, Deserialize, Debug)]
+pub struct SerializedAgentThreadPane {
+    pub expanded: bool,
+    pub width: Option<Pixels>,
+    pub thread_id: Option<SerializedHistoryEntryId>,
+}
+
+pub enum AgentsUtilityPaneEvent {
+    StateChanged,
+}
+
+impl EventEmitter<AgentsUtilityPaneEvent> for AgentThreadPane {}
+impl EventEmitter<MinimizePane> for AgentThreadPane {}
+impl EventEmitter<ClosePane> for AgentThreadPane {}
+
+struct ActiveThreadView {
+    view: Entity<AcpThreadView>,
+    thread_id: HistoryEntryId,
+    _notify: Subscription,
+}
+
+pub struct AgentThreadPane {
+    focus_handle: gpui::FocusHandle,
+    expanded: bool,
+    width: Option<Pixels>,
+    thread_view: Option<ActiveThreadView>,
+    workspace: WeakEntity<Workspace>,
+}
+
+impl AgentThreadPane {
+    pub fn new(workspace: WeakEntity<Workspace>, cx: &mut ui::Context<Self>) -> Self {
+        let focus_handle = cx.focus_handle();
+        Self {
+            focus_handle,
+            expanded: false,
+            width: None,
+            thread_view: None,
+            workspace,
+        }
+    }
+
+    pub fn thread_id(&self) -> Option<HistoryEntryId> {
+        self.thread_view.as_ref().map(|tv| tv.thread_id.clone())
+    }
+
+    pub fn serialize(&self) -> SerializedAgentThreadPane {
+        SerializedAgentThreadPane {
+            expanded: self.expanded,
+            width: self.width,
+            thread_id: self.thread_id().map(SerializedHistoryEntryId::from),
+        }
+    }
+
+    pub fn open_thread(
+        &mut self,
+        entry: HistoryEntry,
+        fs: Arc<dyn Fs>,
+        workspace: WeakEntity<Workspace>,
+        project: Entity<Project>,
+        history_store: Entity<HistoryStore>,
+        prompt_store: Option<Entity<PromptStore>>,
+        window: &mut Window,
+        cx: &mut Context<Self>,
+    ) {
+        let thread_id = entry.id();
+
+        let resume_thread = match &entry {
+            HistoryEntry::AcpThread(thread) => Some(thread.clone()),
+            HistoryEntry::TextThread(_) => None,
+        };
+
+        let agent: Rc<dyn AgentServer> = Rc::new(NativeAgentServer::new(fs, history_store.clone()));
+
+        let thread_view = cx.new(|cx| {
+            AcpThreadView::new(
+                agent,
+                resume_thread,
+                None,
+                workspace,
+                project,
+                history_store,
+                prompt_store,
+                true,
+                window,
+                cx,
+            )
+        });
+
+        let notify = cx.observe(&thread_view, |_, _, cx| {
+            cx.notify();
+        });
+
+        self.thread_view = Some(ActiveThreadView {
+            view: thread_view,
+            thread_id,
+            _notify: notify,
+        });
+
+        cx.notify();
+    }
+
+    fn title(&self, cx: &App) -> SharedString {
+        if let Some(active_thread_view) = &self.thread_view {
+            let thread_view = active_thread_view.view.read(cx);
+            if let Some(thread) = thread_view.thread() {
+                let title = thread.read(cx).title();
+                if !title.is_empty() {
+                    return title;
+                }
+            }
+            thread_view.title(cx)
+        } else {
+            "Thread".into()
+        }
+    }
+
+    fn render_header(&self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
+        let position = self.position(window, cx);
+        let slot = match position {
+            UtilityPanePosition::Left => UtilityPaneSlot::Left,
+            UtilityPanePosition::Right => UtilityPaneSlot::Right,
+        };
+
+        let workspace = self.workspace.clone();
+        let toggle_icon = self.toggle_icon(cx);
+        let title = self.title(cx);
+
+        let pane_toggle_button = |workspace: WeakEntity<Workspace>| {
+            IconButton::new("toggle_utility_pane", toggle_icon)
+                .icon_size(IconSize::Small)
+                .tooltip(Tooltip::text("Toggle Agent Pane"))
+                .on_click(move |_, window, cx| {
+                    workspace
+                        .update(cx, |workspace, cx| {
+                            workspace.toggle_utility_pane(slot, window, cx)
+                        })
+                        .ok();
+                })
+        };
+
+        h_flex()
+            .id("utility-pane-header")
+            .w_full()
+            .h(Tab::container_height(cx))
+            .px_1p5()
+            .gap(DynamicSpacing::Base06.rems(cx))
+            .when(slot == UtilityPaneSlot::Right, |this| {
+                this.flex_row_reverse()
+            })
+            .flex_none()
+            .border_b_1()
+            .border_color(cx.theme().colors().border)
+            .child(pane_toggle_button(workspace))
+            .child(
+                h_flex()
+                    .size_full()
+                    .min_w_0()
+                    .gap_1()
+                    .map(|this| {
+                        if slot == UtilityPaneSlot::Right {
+                            this.flex_row_reverse().justify_start()
+                        } else {
+                            this.justify_between()
+                        }
+                    })
+                    .child(Label::new(title).truncate())
+                    .child(
+                        IconButton::new("close_btn", IconName::Close)
+                            .icon_size(IconSize::Small)
+                            .tooltip(Tooltip::text("Close Agent Pane"))
+                            .on_click(cx.listener(|this, _: &gpui::ClickEvent, _window, cx| {
+                                cx.emit(ClosePane);
+                                this.thread_view = None;
+                                cx.notify()
+                            })),
+                    ),
+            )
+    }
+}
+
+impl Focusable for AgentThreadPane {
+    fn focus_handle(&self, cx: &ui::App) -> gpui::FocusHandle {
+        if let Some(thread_view) = &self.thread_view {
+            thread_view.view.focus_handle(cx)
+        } else {
+            self.focus_handle.clone()
+        }
+    }
+}
+
+impl UtilityPane for AgentThreadPane {
+    fn position(&self, _window: &Window, cx: &App) -> UtilityPanePosition {
+        match AgentSettings::get_global(cx).agents_panel_dock {
+            DockSide::Left => UtilityPanePosition::Left,
+            DockSide::Right => UtilityPanePosition::Right,
+        }
+    }
+
+    fn toggle_icon(&self, _cx: &App) -> IconName {
+        IconName::Thread
+    }
+
+    fn expanded(&self, _cx: &App) -> bool {
+        self.expanded
+    }
+
+    fn set_expanded(&mut self, expanded: bool, cx: &mut Context<Self>) {
+        self.expanded = expanded;
+        cx.emit(AgentsUtilityPaneEvent::StateChanged);
+        cx.notify();
+    }
+
+    fn width(&self, _cx: &App) -> Pixels {
+        self.width.unwrap_or(DEFAULT_UTILITY_PANE_WIDTH)
+    }
+
+    fn set_width(&mut self, width: Option<Pixels>, cx: &mut Context<Self>) {
+        self.width = width;
+        cx.emit(AgentsUtilityPaneEvent::StateChanged);
+        cx.notify();
+    }
+}
+
+impl Render for AgentThreadPane {
+    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
+        let content = if let Some(thread_view) = &self.thread_view {
+            div().size_full().child(thread_view.view.clone())
+        } else {
+            div()
+                .size_full()
+                .flex()
+                .items_center()
+                .justify_center()
+                .child(Label::new("Select a thread to view details").size(LabelSize::Default))
+        };
+
+        div()
+            .size_full()
+            .flex()
+            .flex_col()
+            .child(self.render_header(window, cx))
+            .child(content)
+    }
+}

crates/agent_ui_v2/src/agents_panel.rs 🔗

@@ -0,0 +1,437 @@
+use agent::{HistoryEntry, HistoryEntryId, HistoryStore};
+use agent_settings::AgentSettings;
+use anyhow::Result;
+use assistant_text_thread::TextThreadStore;
+use db::kvp::KEY_VALUE_STORE;
+use feature_flags::{AgentV2FeatureFlag, FeatureFlagAppExt};
+use fs::Fs;
+use gpui::{
+    Action, AsyncWindowContext, Entity, EventEmitter, Focusable, Pixels, Subscription, Task,
+    WeakEntity, actions, prelude::*,
+};
+use project::Project;
+use prompt_store::{PromptBuilder, PromptStore};
+use serde::{Deserialize, Serialize};
+use settings::{Settings as _, update_settings_file};
+use std::sync::Arc;
+use ui::{App, Context, IconName, IntoElement, ParentElement, Render, Styled, Window};
+use util::ResultExt;
+use workspace::{
+    Panel, Workspace,
+    dock::{ClosePane, DockPosition, PanelEvent, UtilityPane},
+    utility_pane::{UtilityPaneSlot, utility_slot_for_dock_position},
+};
+
+use crate::agent_thread_pane::{
+    AgentThreadPane, AgentsUtilityPaneEvent, SerializedAgentThreadPane, SerializedHistoryEntryId,
+};
+use crate::thread_history::{AcpThreadHistory, ThreadHistoryEvent};
+
+const AGENTS_PANEL_KEY: &str = "agents_panel";
+
+#[derive(Serialize, Deserialize, Debug)]
+struct SerializedAgentsPanel {
+    width: Option<Pixels>,
+    pane: Option<SerializedAgentThreadPane>,
+}
+
+actions!(
+    agents,
+    [
+        /// Toggle the visibility of the agents panel.
+        ToggleAgentsPanel
+    ]
+);
+
+pub fn init(cx: &mut App) {
+    cx.observe_new(|workspace: &mut Workspace, _, _| {
+        workspace.register_action(|workspace, _: &ToggleAgentsPanel, window, cx| {
+            workspace.toggle_panel_focus::<AgentsPanel>(window, cx);
+        });
+    })
+    .detach();
+}
+
+pub struct AgentsPanel {
+    focus_handle: gpui::FocusHandle,
+    workspace: WeakEntity<Workspace>,
+    project: Entity<Project>,
+    agent_thread_pane: Option<Entity<AgentThreadPane>>,
+    history: Entity<AcpThreadHistory>,
+    history_store: Entity<HistoryStore>,
+    prompt_store: Option<Entity<PromptStore>>,
+    fs: Arc<dyn Fs>,
+    width: Option<Pixels>,
+    pending_serialization: Task<Option<()>>,
+    _subscriptions: Vec<Subscription>,
+}
+
+impl AgentsPanel {
+    pub fn load(
+        workspace: WeakEntity<Workspace>,
+        cx: AsyncWindowContext,
+    ) -> Task<Result<Entity<Self>, anyhow::Error>> {
+        cx.spawn(async move |cx| {
+            let serialized_panel = cx
+                .background_spawn(async move {
+                    KEY_VALUE_STORE
+                        .read_kvp(AGENTS_PANEL_KEY)
+                        .ok()
+                        .flatten()
+                        .and_then(|panel| {
+                            serde_json::from_str::<SerializedAgentsPanel>(&panel).ok()
+                        })
+                })
+                .await;
+
+            let (fs, project, prompt_builder) = workspace.update(cx, |workspace, cx| {
+                let fs = workspace.app_state().fs.clone();
+                let project = workspace.project().clone();
+                let prompt_builder = PromptBuilder::load(fs.clone(), false, cx);
+                (fs, project, prompt_builder)
+            })?;
+
+            let text_thread_store = workspace
+                .update(cx, |_, cx| {
+                    TextThreadStore::new(
+                        project.clone(),
+                        prompt_builder.clone(),
+                        Default::default(),
+                        cx,
+                    )
+                })?
+                .await?;
+
+            let prompt_store = workspace
+                .update(cx, |_, cx| PromptStore::global(cx))?
+                .await
+                .log_err();
+
+            workspace.update_in(cx, |_, window, cx| {
+                cx.new(|cx| {
+                    let mut panel = Self::new(
+                        workspace.clone(),
+                        fs,
+                        project,
+                        prompt_store,
+                        text_thread_store,
+                        window,
+                        cx,
+                    );
+                    if let Some(serialized_panel) = serialized_panel {
+                        panel.width = serialized_panel.width;
+                        if let Some(serialized_pane) = serialized_panel.pane {
+                            panel.restore_utility_pane(serialized_pane, window, cx);
+                        }
+                    }
+                    panel
+                })
+            })
+        })
+    }
+
+    fn new(
+        workspace: WeakEntity<Workspace>,
+        fs: Arc<dyn Fs>,
+        project: Entity<Project>,
+        prompt_store: Option<Entity<PromptStore>>,
+        text_thread_store: Entity<TextThreadStore>,
+        window: &mut Window,
+        cx: &mut ui::Context<Self>,
+    ) -> Self {
+        let focus_handle = cx.focus_handle();
+
+        let history_store = cx.new(|cx| HistoryStore::new(text_thread_store, cx));
+        let history = cx.new(|cx| AcpThreadHistory::new(history_store.clone(), window, cx));
+
+        let this = cx.weak_entity();
+        let subscriptions = vec![
+            cx.subscribe_in(&history, window, Self::handle_history_event),
+            cx.on_flags_ready(move |_, cx| {
+                this.update(cx, |_, cx| {
+                    cx.notify();
+                })
+                .ok();
+            }),
+        ];
+
+        Self {
+            focus_handle,
+            workspace,
+            project,
+            agent_thread_pane: None,
+            history,
+            history_store,
+            prompt_store,
+            fs,
+            width: None,
+            pending_serialization: Task::ready(None),
+            _subscriptions: subscriptions,
+        }
+    }
+
+    fn restore_utility_pane(
+        &mut self,
+        serialized_pane: SerializedAgentThreadPane,
+        window: &mut Window,
+        cx: &mut Context<Self>,
+    ) {
+        let Some(thread_id) = &serialized_pane.thread_id else {
+            return;
+        };
+
+        let entry = self
+            .history_store
+            .read(cx)
+            .entries()
+            .find(|e| match (&e.id(), thread_id) {
+                (
+                    HistoryEntryId::AcpThread(session_id),
+                    SerializedHistoryEntryId::AcpThread(id),
+                ) => session_id.to_string() == *id,
+                (HistoryEntryId::TextThread(path), SerializedHistoryEntryId::TextThread(id)) => {
+                    path.to_string_lossy() == *id
+                }
+                _ => false,
+            });
+
+        if let Some(entry) = entry {
+            self.open_thread(
+                entry,
+                serialized_pane.expanded,
+                serialized_pane.width,
+                window,
+                cx,
+            );
+        }
+    }
+
+    fn handle_utility_pane_event(
+        &mut self,
+        _utility_pane: Entity<AgentThreadPane>,
+        event: &AgentsUtilityPaneEvent,
+        cx: &mut Context<Self>,
+    ) {
+        match event {
+            AgentsUtilityPaneEvent::StateChanged => {
+                self.serialize(cx);
+                cx.notify();
+            }
+        }
+    }
+
+    fn handle_close_pane_event(
+        &mut self,
+        _utility_pane: Entity<AgentThreadPane>,
+        _event: &ClosePane,
+        cx: &mut Context<Self>,
+    ) {
+        self.agent_thread_pane = None;
+        self.serialize(cx);
+        cx.notify();
+    }
+
+    fn handle_history_event(
+        &mut self,
+        _history: &Entity<AcpThreadHistory>,
+        event: &ThreadHistoryEvent,
+        window: &mut Window,
+        cx: &mut Context<Self>,
+    ) {
+        match event {
+            ThreadHistoryEvent::Open(entry) => {
+                self.open_thread(entry.clone(), true, None, window, cx);
+            }
+        }
+    }
+
+    fn open_thread(
+        &mut self,
+        entry: HistoryEntry,
+        expanded: bool,
+        width: Option<Pixels>,
+        window: &mut Window,
+        cx: &mut Context<Self>,
+    ) {
+        let entry_id = entry.id();
+
+        if let Some(existing_pane) = &self.agent_thread_pane {
+            if existing_pane.read(cx).thread_id() == Some(entry_id) {
+                existing_pane.update(cx, |pane, cx| {
+                    pane.set_expanded(true, cx);
+                });
+                return;
+            }
+        }
+
+        let fs = self.fs.clone();
+        let workspace = self.workspace.clone();
+        let project = self.project.clone();
+        let history_store = self.history_store.clone();
+        let prompt_store = self.prompt_store.clone();
+
+        let agent_thread_pane = cx.new(|cx| {
+            let mut pane = AgentThreadPane::new(workspace.clone(), cx);
+            pane.open_thread(
+                entry,
+                fs,
+                workspace.clone(),
+                project,
+                history_store,
+                prompt_store,
+                window,
+                cx,
+            );
+            if let Some(width) = width {
+                pane.set_width(Some(width), cx);
+            }
+            pane.set_expanded(expanded, cx);
+            pane
+        });
+
+        let state_subscription = cx.subscribe(&agent_thread_pane, Self::handle_utility_pane_event);
+        let close_subscription = cx.subscribe(&agent_thread_pane, Self::handle_close_pane_event);
+
+        self._subscriptions.push(state_subscription);
+        self._subscriptions.push(close_subscription);
+
+        let slot = self.utility_slot(window, cx);
+        let panel_id = cx.entity_id();
+
+        if let Some(workspace) = self.workspace.upgrade() {
+            workspace.update(cx, |workspace, cx| {
+                workspace.register_utility_pane(slot, panel_id, agent_thread_pane.clone(), cx);
+            });
+        }
+
+        self.agent_thread_pane = Some(agent_thread_pane);
+        self.serialize(cx);
+        cx.notify();
+    }
+
+    fn utility_slot(&self, window: &Window, cx: &App) -> UtilityPaneSlot {
+        let position = self.position(window, cx);
+        utility_slot_for_dock_position(position)
+    }
+
+    fn re_register_utility_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) {
+        if let Some(pane) = &self.agent_thread_pane {
+            let slot = self.utility_slot(window, cx);
+            let panel_id = cx.entity_id();
+            let pane = pane.clone();
+
+            if let Some(workspace) = self.workspace.upgrade() {
+                workspace.update(cx, |workspace, cx| {
+                    workspace.register_utility_pane(slot, panel_id, pane, cx);
+                });
+            }
+        }
+    }
+
+    fn serialize(&mut self, cx: &mut Context<Self>) {
+        let width = self.width;
+        let pane = self
+            .agent_thread_pane
+            .as_ref()
+            .map(|pane| pane.read(cx).serialize());
+
+        self.pending_serialization = cx.background_spawn(async move {
+            KEY_VALUE_STORE
+                .write_kvp(
+                    AGENTS_PANEL_KEY.into(),
+                    serde_json::to_string(&SerializedAgentsPanel { width, pane }).unwrap(),
+                )
+                .await
+                .log_err()
+        });
+    }
+}
+
+impl EventEmitter<PanelEvent> for AgentsPanel {}
+
+impl Focusable for AgentsPanel {
+    fn focus_handle(&self, _cx: &ui::App) -> gpui::FocusHandle {
+        self.focus_handle.clone()
+    }
+}
+
+impl Panel for AgentsPanel {
+    fn persistent_name() -> &'static str {
+        "AgentsPanel"
+    }
+
+    fn panel_key() -> &'static str {
+        AGENTS_PANEL_KEY
+    }
+
+    fn position(&self, _window: &Window, cx: &App) -> DockPosition {
+        match AgentSettings::get_global(cx).agents_panel_dock {
+            settings::DockSide::Left => DockPosition::Left,
+            settings::DockSide::Right => DockPosition::Right,
+        }
+    }
+
+    fn position_is_valid(&self, position: DockPosition) -> bool {
+        position != DockPosition::Bottom
+    }
+
+    fn set_position(
+        &mut self,
+        position: DockPosition,
+        window: &mut Window,
+        cx: &mut Context<Self>,
+    ) {
+        update_settings_file(self.fs.clone(), cx, move |settings, _| {
+            settings.agent.get_or_insert_default().agents_panel_dock = Some(match position {
+                DockPosition::Left => settings::DockSide::Left,
+                DockPosition::Right | DockPosition::Bottom => settings::DockSide::Right,
+            });
+        });
+        self.re_register_utility_pane(window, cx);
+    }
+
+    fn size(&self, window: &Window, cx: &App) -> Pixels {
+        let settings = AgentSettings::get_global(cx);
+        match self.position(window, cx) {
+            DockPosition::Left | DockPosition::Right => {
+                self.width.unwrap_or(settings.default_width)
+            }
+            DockPosition::Bottom => self.width.unwrap_or(settings.default_height),
+        }
+    }
+
+    fn set_size(&mut self, size: Option<Pixels>, window: &mut Window, cx: &mut Context<Self>) {
+        match self.position(window, cx) {
+            DockPosition::Left | DockPosition::Right => self.width = size,
+            DockPosition::Bottom => {}
+        }
+        self.serialize(cx);
+        cx.notify();
+    }
+
+    fn icon(&self, _window: &Window, cx: &App) -> Option<IconName> {
+        (self.enabled(cx) && AgentSettings::get_global(cx).button).then_some(IconName::ZedAgentTwo)
+    }
+
+    fn icon_tooltip(&self, _window: &Window, _cx: &App) -> Option<&'static str> {
+        Some("Agents Panel")
+    }
+
+    fn toggle_action(&self) -> Box<dyn Action> {
+        Box::new(ToggleAgentsPanel)
+    }
+
+    fn activation_priority(&self) -> u32 {
+        4
+    }
+
+    fn enabled(&self, cx: &App) -> bool {
+        AgentSettings::get_global(cx).enabled(cx) && cx.has_flag::<AgentV2FeatureFlag>()
+    }
+}
+
+impl Render for AgentsPanel {
+    fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
+        gpui::div().size_full().child(self.history.clone())
+    }
+}

crates/agent_ui_v2/src/thread_history.rs 🔗

@@ -0,0 +1,753 @@
+use agent::{HistoryEntry, HistoryStore};
+use chrono::{Datelike as _, Local, NaiveDate, TimeDelta, Utc};
+use editor::{Editor, EditorEvent};
+use fuzzy::StringMatchCandidate;
+use gpui::{
+    App, Entity, EventEmitter, FocusHandle, Focusable, ScrollStrategy, Task,
+    UniformListScrollHandle, Window, actions, uniform_list,
+};
+use std::{fmt::Display, ops::Range};
+use text::Bias;
+use time::{OffsetDateTime, UtcOffset};
+use ui::{
+    HighlightedLabel, IconButtonShape, ListItem, ListItemSpacing, Tab, Tooltip, WithScrollbar,
+    prelude::*,
+};
+
+actions!(
+    agents,
+    [
+        /// Removes all thread history.
+        RemoveHistory,
+        /// Removes the currently selected thread.
+        RemoveSelectedThread,
+    ]
+);
+
+pub struct AcpThreadHistory {
+    pub(crate) history_store: Entity<HistoryStore>,
+    scroll_handle: UniformListScrollHandle,
+    selected_index: usize,
+    hovered_index: Option<usize>,
+    search_editor: Entity<Editor>,
+    search_query: SharedString,
+    visible_items: Vec<ListItemType>,
+    local_timezone: UtcOffset,
+    confirming_delete_history: bool,
+    _update_task: Task<()>,
+    _subscriptions: Vec<gpui::Subscription>,
+}
+
+enum ListItemType {
+    BucketSeparator(TimeBucket),
+    Entry {
+        entry: HistoryEntry,
+        format: EntryTimeFormat,
+    },
+    SearchResult {
+        entry: HistoryEntry,
+        positions: Vec<usize>,
+    },
+}
+
+impl ListItemType {
+    fn history_entry(&self) -> Option<&HistoryEntry> {
+        match self {
+            ListItemType::Entry { entry, .. } => Some(entry),
+            ListItemType::SearchResult { entry, .. } => Some(entry),
+            _ => None,
+        }
+    }
+}
+
+#[allow(dead_code)]
+pub enum ThreadHistoryEvent {
+    Open(HistoryEntry),
+}
+
+impl EventEmitter<ThreadHistoryEvent> for AcpThreadHistory {}
+
+impl AcpThreadHistory {
+    pub fn new(
+        history_store: Entity<agent::HistoryStore>,
+        window: &mut Window,
+        cx: &mut Context<Self>,
+    ) -> Self {
+        let search_editor = cx.new(|cx| {
+            let mut editor = Editor::single_line(window, cx);
+            editor.set_placeholder_text("Search threads...", window, cx);
+            editor
+        });
+
+        let search_editor_subscription =
+            cx.subscribe(&search_editor, |this, search_editor, event, cx| {
+                if let EditorEvent::BufferEdited = event {
+                    let query = search_editor.read(cx).text(cx);
+                    if this.search_query != query {
+                        this.search_query = query.into();
+                        this.update_visible_items(false, cx);
+                    }
+                }
+            });
+
+        let history_store_subscription = cx.observe(&history_store, |this, _, cx| {
+            this.update_visible_items(true, cx);
+        });
+
+        let scroll_handle = UniformListScrollHandle::default();
+
+        let mut this = Self {
+            history_store,
+            scroll_handle,
+            selected_index: 0,
+            hovered_index: None,
+            visible_items: Default::default(),
+            search_editor,
+            local_timezone: UtcOffset::from_whole_seconds(
+                chrono::Local::now().offset().local_minus_utc(),
+            )
+            .unwrap(),
+            search_query: SharedString::default(),
+            confirming_delete_history: false,
+            _subscriptions: vec![search_editor_subscription, history_store_subscription],
+            _update_task: Task::ready(()),
+        };
+        this.update_visible_items(false, cx);
+        this
+    }
+
+    fn update_visible_items(&mut self, preserve_selected_item: bool, cx: &mut Context<Self>) {
+        let entries = self
+            .history_store
+            .update(cx, |store, _| store.entries().collect());
+        let new_list_items = if self.search_query.is_empty() {
+            self.add_list_separators(entries, cx)
+        } else {
+            self.filter_search_results(entries, cx)
+        };
+        let selected_history_entry = if preserve_selected_item {
+            self.selected_history_entry().cloned()
+        } else {
+            None
+        };
+
+        self._update_task = cx.spawn(async move |this, cx| {
+            let new_visible_items = new_list_items.await;
+            this.update(cx, |this, cx| {
+                let new_selected_index = if let Some(history_entry) = selected_history_entry {
+                    let history_entry_id = history_entry.id();
+                    new_visible_items
+                        .iter()
+                        .position(|visible_entry| {
+                            visible_entry
+                                .history_entry()
+                                .is_some_and(|entry| entry.id() == history_entry_id)
+                        })
+                        .unwrap_or(0)
+                } else {
+                    0
+                };
+
+                this.visible_items = new_visible_items;
+                this.set_selected_index(new_selected_index, Bias::Right, cx);
+                cx.notify();
+            })
+            .ok();
+        });
+    }
+
+    fn add_list_separators(&self, entries: Vec<HistoryEntry>, cx: &App) -> Task<Vec<ListItemType>> {
+        cx.background_spawn(async move {
+            let mut items = Vec::with_capacity(entries.len() + 1);
+            let mut bucket = None;
+            let today = Local::now().naive_local().date();
+
+            for entry in entries.into_iter() {
+                let entry_date = entry
+                    .updated_at()
+                    .with_timezone(&Local)
+                    .naive_local()
+                    .date();
+                let entry_bucket = TimeBucket::from_dates(today, entry_date);
+
+                if Some(entry_bucket) != bucket {
+                    bucket = Some(entry_bucket);
+                    items.push(ListItemType::BucketSeparator(entry_bucket));
+                }
+
+                items.push(ListItemType::Entry {
+                    entry,
+                    format: entry_bucket.into(),
+                });
+            }
+            items
+        })
+    }
+
+    fn filter_search_results(
+        &self,
+        entries: Vec<HistoryEntry>,
+        cx: &App,
+    ) -> Task<Vec<ListItemType>> {
+        let query = self.search_query.clone();
+        cx.background_spawn({
+            let executor = cx.background_executor().clone();
+            async move {
+                let mut candidates = Vec::with_capacity(entries.len());
+
+                for (idx, entry) in entries.iter().enumerate() {
+                    candidates.push(StringMatchCandidate::new(idx, entry.title()));
+                }
+
+                const MAX_MATCHES: usize = 100;
+
+                let matches = fuzzy::match_strings(
+                    &candidates,
+                    &query,
+                    false,
+                    true,
+                    MAX_MATCHES,
+                    &Default::default(),
+                    executor,
+                )
+                .await;
+
+                matches
+                    .into_iter()
+                    .map(|search_match| ListItemType::SearchResult {
+                        entry: entries[search_match.candidate_id].clone(),
+                        positions: search_match.positions,
+                    })
+                    .collect()
+            }
+        })
+    }
+
+    fn search_produced_no_matches(&self) -> bool {
+        self.visible_items.is_empty() && !self.search_query.is_empty()
+    }
+
+    fn selected_history_entry(&self) -> Option<&HistoryEntry> {
+        self.get_history_entry(self.selected_index)
+    }
+
+    fn get_history_entry(&self, visible_items_ix: usize) -> Option<&HistoryEntry> {
+        self.visible_items.get(visible_items_ix)?.history_entry()
+    }
+
+    fn set_selected_index(&mut self, mut index: usize, bias: Bias, cx: &mut Context<Self>) {
+        if self.visible_items.is_empty() {
+            self.selected_index = 0;
+            return;
+        }
+        while matches!(
+            self.visible_items.get(index),
+            None | Some(ListItemType::BucketSeparator(..))
+        ) {
+            index = match bias {
+                Bias::Left => {
+                    if index == 0 {
+                        self.visible_items.len() - 1
+                    } else {
+                        index - 1
+                    }
+                }
+                Bias::Right => {
+                    if index >= self.visible_items.len() - 1 {
+                        0
+                    } else {
+                        index + 1
+                    }
+                }
+            };
+        }
+        self.selected_index = index;
+        self.scroll_handle
+            .scroll_to_item(index, ScrollStrategy::Top);
+        cx.notify()
+    }
+
+    pub fn select_previous(
+        &mut self,
+        _: &menu::SelectPrevious,
+        _window: &mut Window,
+        cx: &mut Context<Self>,
+    ) {
+        if self.selected_index == 0 {
+            self.set_selected_index(self.visible_items.len() - 1, Bias::Left, cx);
+        } else {
+            self.set_selected_index(self.selected_index - 1, Bias::Left, cx);
+        }
+    }
+
+    pub fn select_next(
+        &mut self,
+        _: &menu::SelectNext,
+        _window: &mut Window,
+        cx: &mut Context<Self>,
+    ) {
+        if self.selected_index == self.visible_items.len() - 1 {
+            self.set_selected_index(0, Bias::Right, cx);
+        } else {
+            self.set_selected_index(self.selected_index + 1, Bias::Right, cx);
+        }
+    }
+
+    fn select_first(
+        &mut self,
+        _: &menu::SelectFirst,
+        _window: &mut Window,
+        cx: &mut Context<Self>,
+    ) {
+        self.set_selected_index(0, Bias::Right, cx);
+    }
+
+    fn select_last(&mut self, _: &menu::SelectLast, _window: &mut Window, cx: &mut Context<Self>) {
+        self.set_selected_index(self.visible_items.len() - 1, Bias::Left, cx);
+    }
+
+    fn confirm(&mut self, _: &menu::Confirm, _window: &mut Window, cx: &mut Context<Self>) {
+        self.confirm_entry(self.selected_index, cx);
+    }
+
+    fn confirm_entry(&mut self, ix: usize, cx: &mut Context<Self>) {
+        let Some(entry) = self.get_history_entry(ix) else {
+            return;
+        };
+        cx.emit(ThreadHistoryEvent::Open(entry.clone()));
+    }
+
+    fn remove_selected_thread(
+        &mut self,
+        _: &RemoveSelectedThread,
+        _window: &mut Window,
+        cx: &mut Context<Self>,
+    ) {
+        self.remove_thread(self.selected_index, cx)
+    }
+
+    fn remove_thread(&mut self, visible_item_ix: usize, cx: &mut Context<Self>) {
+        let Some(entry) = self.get_history_entry(visible_item_ix) else {
+            return;
+        };
+
+        let task = match entry {
+            HistoryEntry::AcpThread(thread) => self
+                .history_store
+                .update(cx, |this, cx| this.delete_thread(thread.id.clone(), cx)),
+            HistoryEntry::TextThread(text_thread) => self.history_store.update(cx, |this, cx| {
+                this.delete_text_thread(text_thread.path.clone(), cx)
+            }),
+        };
+        task.detach_and_log_err(cx);
+    }
+
+    fn remove_history(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
+        self.history_store.update(cx, |store, cx| {
+            store.delete_threads(cx).detach_and_log_err(cx)
+        });
+        self.confirming_delete_history = false;
+        cx.notify();
+    }
+
+    fn prompt_delete_history(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
+        self.confirming_delete_history = true;
+        cx.notify();
+    }
+
+    fn cancel_delete_history(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
+        self.confirming_delete_history = false;
+        cx.notify();
+    }
+
+    fn render_list_items(
+        &mut self,
+        range: Range<usize>,
+        _window: &mut Window,
+        cx: &mut Context<Self>,
+    ) -> Vec<AnyElement> {
+        self.visible_items
+            .get(range.clone())
+            .into_iter()
+            .flatten()
+            .enumerate()
+            .map(|(ix, item)| self.render_list_item(item, range.start + ix, cx))
+            .collect()
+    }
+
+    fn render_list_item(&self, item: &ListItemType, ix: usize, cx: &Context<Self>) -> AnyElement {
+        match item {
+            ListItemType::Entry { entry, format } => self
+                .render_history_entry(entry, *format, ix, Vec::default(), cx)
+                .into_any(),
+            ListItemType::SearchResult { entry, positions } => self.render_history_entry(
+                entry,
+                EntryTimeFormat::DateAndTime,
+                ix,
+                positions.clone(),
+                cx,
+            ),
+            ListItemType::BucketSeparator(bucket) => div()
+                .px(DynamicSpacing::Base06.rems(cx))
+                .pt_2()
+                .pb_1()
+                .child(
+                    Label::new(bucket.to_string())
+                        .size(LabelSize::XSmall)
+                        .color(Color::Muted),
+                )
+                .into_any_element(),
+        }
+    }
+
+    fn render_history_entry(
+        &self,
+        entry: &HistoryEntry,
+        format: EntryTimeFormat,
+        ix: usize,
+        highlight_positions: Vec<usize>,
+        cx: &Context<Self>,
+    ) -> AnyElement {
+        let selected = ix == self.selected_index;
+        let hovered = Some(ix) == self.hovered_index;
+        let timestamp = entry.updated_at().timestamp();
+
+        let display_text = match format {
+            EntryTimeFormat::DateAndTime => {
+                let entry_time = entry.updated_at();
+                let now = Utc::now();
+                let duration = now.signed_duration_since(entry_time);
+                let days = duration.num_days();
+
+                format!("{}d", days)
+            }
+            EntryTimeFormat::TimeOnly => format.format_timestamp(timestamp, self.local_timezone),
+        };
+
+        let title = entry.title().clone();
+        let full_date =
+            EntryTimeFormat::DateAndTime.format_timestamp(timestamp, self.local_timezone);
+
+        h_flex()
+            .w_full()
+            .pb_1()
+            .child(
+                ListItem::new(ix)
+                    .rounded()
+                    .toggle_state(selected)
+                    .spacing(ListItemSpacing::Sparse)
+                    .start_slot(
+                        h_flex()
+                            .w_full()
+                            .gap_2()
+                            .justify_between()
+                            .child(
+                                HighlightedLabel::new(entry.title(), highlight_positions)
+                                    .size(LabelSize::Small)
+                                    .truncate(),
+                            )
+                            .child(
+                                Label::new(display_text)
+                                    .color(Color::Muted)
+                                    .size(LabelSize::XSmall),
+                            ),
+                    )
+                    .tooltip(move |_, cx| {
+                        Tooltip::with_meta(title.clone(), None, full_date.clone(), cx)
+                    })
+                    .on_hover(cx.listener(move |this, is_hovered, _window, cx| {
+                        if *is_hovered {
+                            this.hovered_index = Some(ix);
+                        } else if this.hovered_index == Some(ix) {
+                            this.hovered_index = None;
+                        }
+
+                        cx.notify();
+                    }))
+                    .end_slot::<IconButton>(if hovered {
+                        Some(
+                            IconButton::new("delete", IconName::Trash)
+                                .shape(IconButtonShape::Square)
+                                .icon_size(IconSize::XSmall)
+                                .icon_color(Color::Muted)
+                                .tooltip(move |_window, cx| {
+                                    Tooltip::for_action("Delete", &RemoveSelectedThread, cx)
+                                })
+                                .on_click(cx.listener(move |this, _, _, cx| {
+                                    this.remove_thread(ix, cx);
+                                    cx.stop_propagation()
+                                })),
+                        )
+                    } else {
+                        None
+                    })
+                    .on_click(cx.listener(move |this, _, _, cx| this.confirm_entry(ix, cx))),
+            )
+            .into_any_element()
+    }
+}
+
+impl Focusable for AcpThreadHistory {
+    fn focus_handle(&self, cx: &App) -> FocusHandle {
+        self.search_editor.focus_handle(cx)
+    }
+}
+
+impl Render for AcpThreadHistory {
+    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
+        let has_no_history = self.history_store.read(cx).is_empty(cx);
+
+        v_flex()
+            .key_context("ThreadHistory")
+            .size_full()
+            .bg(cx.theme().colors().panel_background)
+            .on_action(cx.listener(Self::select_previous))
+            .on_action(cx.listener(Self::select_next))
+            .on_action(cx.listener(Self::select_first))
+            .on_action(cx.listener(Self::select_last))
+            .on_action(cx.listener(Self::confirm))
+            .on_action(cx.listener(Self::remove_selected_thread))
+            .on_action(cx.listener(|this, _: &RemoveHistory, window, cx| {
+                this.remove_history(window, cx);
+            }))
+            .child(
+                h_flex()
+                    .h(Tab::container_height(cx))
+                    .w_full()
+                    .py_1()
+                    .px_2()
+                    .gap_2()
+                    .justify_between()
+                    .border_b_1()
+                    .border_color(cx.theme().colors().border)
+                    .child(
+                        Icon::new(IconName::MagnifyingGlass)
+                            .color(Color::Muted)
+                            .size(IconSize::Small),
+                    )
+                    .child(self.search_editor.clone()),
+            )
+            .child({
+                let view = v_flex()
+                    .id("list-container")
+                    .relative()
+                    .overflow_hidden()
+                    .flex_grow();
+
+                if has_no_history {
+                    view.justify_center().items_center().child(
+                        Label::new("You don't have any past threads yet.")
+                            .size(LabelSize::Small)
+                            .color(Color::Muted),
+                    )
+                } else if self.search_produced_no_matches() {
+                    view.justify_center()
+                        .items_center()
+                        .child(Label::new("No threads match your search.").size(LabelSize::Small))
+                } else {
+                    view.child(
+                        uniform_list(
+                            "thread-history",
+                            self.visible_items.len(),
+                            cx.processor(|this, range: Range<usize>, window, cx| {
+                                this.render_list_items(range, window, cx)
+                            }),
+                        )
+                        .p_1()
+                        .pr_4()
+                        .track_scroll(&self.scroll_handle)
+                        .flex_grow(),
+                    )
+                    .vertical_scrollbar_for(&self.scroll_handle, window, cx)
+                }
+            })
+            .when(!has_no_history, |this| {
+                this.child(
+                    h_flex()
+                        .p_2()
+                        .border_t_1()
+                        .border_color(cx.theme().colors().border_variant)
+                        .when(!self.confirming_delete_history, |this| {
+                            this.child(
+                                Button::new("delete_history", "Delete All History")
+                                    .full_width()
+                                    .style(ButtonStyle::Outlined)
+                                    .label_size(LabelSize::Small)
+                                    .on_click(cx.listener(|this, _, window, cx| {
+                                        this.prompt_delete_history(window, cx);
+                                    })),
+                            )
+                        })
+                        .when(self.confirming_delete_history, |this| {
+                            this.w_full()
+                                .gap_2()
+                                .flex_wrap()
+                                .justify_between()
+                                .child(
+                                    h_flex()
+                                        .flex_wrap()
+                                        .gap_1()
+                                        .child(
+                                            Label::new("Delete all threads?")
+                                                .size(LabelSize::Small),
+                                        )
+                                        .child(
+                                            Label::new("You won't be able to recover them later.")
+                                                .size(LabelSize::Small)
+                                                .color(Color::Muted),
+                                        ),
+                                )
+                                .child(
+                                    h_flex()
+                                        .gap_1()
+                                        .child(
+                                            Button::new("cancel_delete", "Cancel")
+                                                .label_size(LabelSize::Small)
+                                                .on_click(cx.listener(|this, _, window, cx| {
+                                                    this.cancel_delete_history(window, cx);
+                                                })),
+                                        )
+                                        .child(
+                                            Button::new("confirm_delete", "Delete")
+                                                .style(ButtonStyle::Tinted(ui::TintColor::Error))
+                                                .color(Color::Error)
+                                                .label_size(LabelSize::Small)
+                                                .on_click(cx.listener(|_, _, window, cx| {
+                                                    window.dispatch_action(
+                                                        Box::new(RemoveHistory),
+                                                        cx,
+                                                    );
+                                                })),
+                                        ),
+                                )
+                        }),
+                )
+            })
+    }
+}
+
+#[derive(Clone, Copy)]
+pub enum EntryTimeFormat {
+    DateAndTime,
+    TimeOnly,
+}
+
+impl EntryTimeFormat {
+    fn format_timestamp(&self, timestamp: i64, timezone: UtcOffset) -> String {
+        let timestamp = OffsetDateTime::from_unix_timestamp(timestamp).unwrap();
+
+        match self {
+            EntryTimeFormat::DateAndTime => time_format::format_localized_timestamp(
+                timestamp,
+                OffsetDateTime::now_utc(),
+                timezone,
+                time_format::TimestampFormat::EnhancedAbsolute,
+            ),
+            EntryTimeFormat::TimeOnly => time_format::format_time(timestamp.to_offset(timezone)),
+        }
+    }
+}
+
+impl From<TimeBucket> for EntryTimeFormat {
+    fn from(bucket: TimeBucket) -> Self {
+        match bucket {
+            TimeBucket::Today => EntryTimeFormat::TimeOnly,
+            TimeBucket::Yesterday => EntryTimeFormat::TimeOnly,
+            TimeBucket::ThisWeek => EntryTimeFormat::DateAndTime,
+            TimeBucket::PastWeek => EntryTimeFormat::DateAndTime,
+            TimeBucket::All => EntryTimeFormat::DateAndTime,
+        }
+    }
+}
+
+#[derive(PartialEq, Eq, Clone, Copy, Debug)]
+enum TimeBucket {
+    Today,
+    Yesterday,
+    ThisWeek,
+    PastWeek,
+    All,
+}
+
+impl TimeBucket {
+    fn from_dates(reference: NaiveDate, date: NaiveDate) -> Self {
+        if date == reference {
+            return TimeBucket::Today;
+        }
+
+        if date == reference - TimeDelta::days(1) {
+            return TimeBucket::Yesterday;
+        }
+
+        let week = date.iso_week();
+
+        if reference.iso_week() == week {
+            return TimeBucket::ThisWeek;
+        }
+
+        let last_week = (reference - TimeDelta::days(7)).iso_week();
+
+        if week == last_week {
+            return TimeBucket::PastWeek;
+        }
+
+        TimeBucket::All
+    }
+}
+
+impl Display for TimeBucket {
+    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+        match self {
+            TimeBucket::Today => write!(f, "Today"),
+            TimeBucket::Yesterday => write!(f, "Yesterday"),
+            TimeBucket::ThisWeek => write!(f, "This Week"),
+            TimeBucket::PastWeek => write!(f, "Past Week"),
+            TimeBucket::All => write!(f, "All"),
+        }
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use chrono::NaiveDate;
+
+    #[test]
+    fn test_time_bucket_from_dates() {
+        let today = NaiveDate::from_ymd_opt(2023, 1, 15).unwrap();
+
+        let date = today;
+        assert_eq!(TimeBucket::from_dates(today, date), TimeBucket::Today);
+
+        let date = NaiveDate::from_ymd_opt(2023, 1, 14).unwrap();
+        assert_eq!(TimeBucket::from_dates(today, date), TimeBucket::Yesterday);
+
+        let date = NaiveDate::from_ymd_opt(2023, 1, 13).unwrap();
+        assert_eq!(TimeBucket::from_dates(today, date), TimeBucket::ThisWeek);
+
+        let date = NaiveDate::from_ymd_opt(2023, 1, 11).unwrap();
+        assert_eq!(TimeBucket::from_dates(today, date), TimeBucket::ThisWeek);
+
+        let date = NaiveDate::from_ymd_opt(2023, 1, 8).unwrap();
+        assert_eq!(TimeBucket::from_dates(today, date), TimeBucket::PastWeek);
+
+        let date = NaiveDate::from_ymd_opt(2023, 1, 5).unwrap();
+        assert_eq!(TimeBucket::from_dates(today, date), TimeBucket::PastWeek);
+
+        // All: not in this week or last week
+        let date = NaiveDate::from_ymd_opt(2023, 1, 1).unwrap();
+        assert_eq!(TimeBucket::from_dates(today, date), TimeBucket::All);
+
+        // Test year boundary cases
+        let new_year = NaiveDate::from_ymd_opt(2023, 1, 1).unwrap();
+
+        let date = NaiveDate::from_ymd_opt(2022, 12, 31).unwrap();
+        assert_eq!(
+            TimeBucket::from_dates(new_year, date),
+            TimeBucket::Yesterday
+        );
+
+        let date = NaiveDate::from_ymd_opt(2022, 12, 28).unwrap();
+        assert_eq!(TimeBucket::from_dates(new_year, date), TimeBucket::ThisWeek);
+    }
+}

crates/ai_onboarding/src/agent_api_keys_onboarding.rs 🔗

@@ -1,9 +1,9 @@
 use gpui::{Action, IntoElement, ParentElement, RenderOnce, point};
-use language_model::{LanguageModelRegistry, ZED_CLOUD_PROVIDER_ID};
+use language_model::{IconOrSvg, LanguageModelRegistry, ZED_CLOUD_PROVIDER_ID};
 use ui::{Divider, List, ListBulletItem, prelude::*};
 
 pub struct ApiKeysWithProviders {
-    configured_providers: Vec<(IconName, SharedString)>,
+    configured_providers: Vec<(IconOrSvg, SharedString)>,
 }
 
 impl ApiKeysWithProviders {
@@ -13,7 +13,8 @@ impl ApiKeysWithProviders {
             |this: &mut Self, _registry, event: &language_model::Event, cx| match event {
                 language_model::Event::ProviderStateChanged(_)
                 | language_model::Event::AddedProvider(_)
-                | language_model::Event::RemovedProvider(_) => {
+                | language_model::Event::RemovedProvider(_)
+                | language_model::Event::ProvidersChanged => {
                     this.configured_providers = Self::compute_configured_providers(cx)
                 }
                 _ => {}
@@ -26,9 +27,9 @@ impl ApiKeysWithProviders {
         }
     }
 
-    fn compute_configured_providers(cx: &App) -> Vec<(IconName, SharedString)> {
+    fn compute_configured_providers(cx: &App) -> Vec<(IconOrSvg, SharedString)> {
         LanguageModelRegistry::read_global(cx)
-            .providers()
+            .visible_providers()
             .iter()
             .filter(|provider| {
                 provider.is_authenticated(cx) && provider.id() != ZED_CLOUD_PROVIDER_ID
@@ -47,7 +48,14 @@ impl Render for ApiKeysWithProviders {
                 .map(|(icon, name)| {
                     h_flex()
                         .gap_1p5()
-                        .child(Icon::new(icon).size(IconSize::XSmall).color(Color::Muted))
+                        .child(
+                            match icon {
+                                IconOrSvg::Icon(icon_name) => Icon::new(icon_name),
+                                IconOrSvg::Svg(icon_path) => Icon::from_external_svg(icon_path),
+                            }
+                            .size(IconSize::XSmall)
+                            .color(Color::Muted),
+                        )
                         .child(Label::new(name))
                 });
         div()

crates/ai_onboarding/src/agent_panel_onboarding_content.rs 🔗

@@ -11,7 +11,7 @@ use crate::{AgentPanelOnboardingCard, ApiKeysWithoutProviders, ZedAiOnboarding};
 pub struct AgentPanelOnboarding {
     user_store: Entity<UserStore>,
     client: Arc<Client>,
-    configured_providers: Vec<(IconName, SharedString)>,
+    has_configured_providers: bool,
     continue_with_zed_ai: Arc<dyn Fn(&mut Window, &mut App)>,
 }
 
@@ -27,8 +27,9 @@ impl AgentPanelOnboarding {
             |this: &mut Self, _registry, event: &language_model::Event, cx| match event {
                 language_model::Event::ProviderStateChanged(_)
                 | language_model::Event::AddedProvider(_)
-                | language_model::Event::RemovedProvider(_) => {
-                    this.configured_providers = Self::compute_available_providers(cx)
+                | language_model::Event::RemovedProvider(_)
+                | language_model::Event::ProvidersChanged => {
+                    this.has_configured_providers = Self::has_configured_providers(cx)
                 }
                 _ => {}
             },
@@ -38,20 +39,16 @@ impl AgentPanelOnboarding {
         Self {
             user_store,
             client,
-            configured_providers: Self::compute_available_providers(cx),
+            has_configured_providers: Self::has_configured_providers(cx),
             continue_with_zed_ai: Arc::new(continue_with_zed_ai),
         }
     }
 
-    fn compute_available_providers(cx: &App) -> Vec<(IconName, SharedString)> {
+    fn has_configured_providers(cx: &App) -> bool {
         LanguageModelRegistry::read_global(cx)
-            .providers()
+            .visible_providers()
             .iter()
-            .filter(|provider| {
-                provider.is_authenticated(cx) && provider.id() != ZED_CLOUD_PROVIDER_ID
-            })
-            .map(|provider| (provider.icon(), provider.name().0))
-            .collect()
+            .any(|provider| provider.is_authenticated(cx) && provider.id() != ZED_CLOUD_PROVIDER_ID)
     }
 }
 
@@ -81,7 +78,7 @@ impl Render for AgentPanelOnboarding {
                 }),
             )
             .map(|this| {
-                if enrolled_in_trial || is_pro_user || !self.configured_providers.is_empty() {
+                if enrolled_in_trial || is_pro_user || self.has_configured_providers {
                     this
                 } else {
                     this.child(ApiKeysWithoutProviders::new())

crates/anthropic/src/anthropic.rs 🔗

@@ -12,6 +12,8 @@ pub use settings::{AnthropicAvailableModel as AvailableModel, ModelMode};
 use strum::{EnumIter, EnumString};
 use thiserror::Error;
 
+pub mod batches;
+
 pub const ANTHROPIC_API_URL: &str = "https://api.anthropic.com";
 
 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
@@ -427,10 +429,24 @@ impl Model {
         let mut headers = vec![];
 
         match self {
+            Self::ClaudeOpus4
+            | Self::ClaudeOpus4_1
+            | Self::ClaudeOpus4_5
+            | Self::ClaudeSonnet4
+            | Self::ClaudeSonnet4_5
+            | Self::ClaudeOpus4Thinking
+            | Self::ClaudeOpus4_1Thinking
+            | Self::ClaudeOpus4_5Thinking
+            | Self::ClaudeSonnet4Thinking
+            | Self::ClaudeSonnet4_5Thinking => {
+                // Fine-grained tool streaming for newer models
+                headers.push("fine-grained-tool-streaming-2025-05-14".to_string());
+            }
             Self::Claude3_7Sonnet | Self::Claude3_7SonnetThinking => {
                 // Try beta token-efficient tool use (supported in Claude 3.7 Sonnet only)
                 // https://docs.anthropic.com/en/docs/build-with-claude/tool-use/token-efficient-tool-use
                 headers.push("token-efficient-tools-2025-02-19".to_string());
+                headers.push("fine-grained-tool-streaming-2025-05-14".to_string());
             }
             Self::Custom {
                 extra_beta_headers, ..
@@ -465,6 +481,7 @@ impl Model {
     }
 }
 
+/// Generate completion with streaming.
 pub async fn stream_completion(
     client: &dyn HttpClient,
     api_url: &str,
@@ -477,6 +494,101 @@ pub async fn stream_completion(
         .map(|output| output.0)
 }
 
+/// Generate completion without streaming.
+pub async fn non_streaming_completion(
+    client: &dyn HttpClient,
+    api_url: &str,
+    api_key: &str,
+    request: Request,
+    beta_headers: Option<String>,
+) -> Result<Response, AnthropicError> {
+    let (mut response, rate_limits) =
+        send_request(client, api_url, api_key, &request, beta_headers).await?;
+
+    if response.status().is_success() {
+        let mut body = String::new();
+        response
+            .body_mut()
+            .read_to_string(&mut body)
+            .await
+            .map_err(AnthropicError::ReadResponse)?;
+
+        serde_json::from_str(&body).map_err(AnthropicError::DeserializeResponse)
+    } else {
+        Err(handle_error_response(response, rate_limits).await)
+    }
+}
+
+async fn send_request(
+    client: &dyn HttpClient,
+    api_url: &str,
+    api_key: &str,
+    request: impl Serialize,
+    beta_headers: Option<String>,
+) -> Result<(http::Response<AsyncBody>, RateLimitInfo), AnthropicError> {
+    let uri = format!("{api_url}/v1/messages");
+
+    let mut request_builder = HttpRequest::builder()
+        .method(Method::POST)
+        .uri(uri)
+        .header("Anthropic-Version", "2023-06-01")
+        .header("X-Api-Key", api_key.trim())
+        .header("Content-Type", "application/json");
+
+    if let Some(beta_headers) = beta_headers {
+        request_builder = request_builder.header("Anthropic-Beta", beta_headers);
+    }
+
+    let serialized_request =
+        serde_json::to_string(&request).map_err(AnthropicError::SerializeRequest)?;
+    let request = request_builder
+        .body(AsyncBody::from(serialized_request))
+        .map_err(AnthropicError::BuildRequestBody)?;
+
+    let response = client
+        .send(request)
+        .await
+        .map_err(AnthropicError::HttpSend)?;
+
+    let rate_limits = RateLimitInfo::from_headers(response.headers());
+
+    Ok((response, rate_limits))
+}
+
+async fn handle_error_response(
+    mut response: http::Response<AsyncBody>,
+    rate_limits: RateLimitInfo,
+) -> AnthropicError {
+    if response.status().as_u16() == 529 {
+        return AnthropicError::ServerOverloaded {
+            retry_after: rate_limits.retry_after,
+        };
+    }
+
+    if let Some(retry_after) = rate_limits.retry_after {
+        return AnthropicError::RateLimit { retry_after };
+    }
+
+    let mut body = String::new();
+    let read_result = response
+        .body_mut()
+        .read_to_string(&mut body)
+        .await
+        .map_err(AnthropicError::ReadResponse);
+
+    if let Err(err) = read_result {
+        return err;
+    }
+
+    match serde_json::from_str::<Event>(&body) {
+        Ok(Event::Error { error }) => AnthropicError::ApiError(error),
+        Ok(_) | Err(_) => AnthropicError::HttpResponseError {
+            status_code: response.status(),
+            message: body,
+        },
+    }
+}
+
 /// An individual rate limit.
 #[derive(Debug)]
 pub struct RateLimit {
@@ -580,30 +692,10 @@ pub async fn stream_completion_with_rate_limit_info(
         base: request,
         stream: true,
     };
-    let uri = format!("{api_url}/v1/messages");
 
-    let mut request_builder = HttpRequest::builder()
-        .method(Method::POST)
-        .uri(uri)
-        .header("Anthropic-Version", "2023-06-01")
-        .header("X-Api-Key", api_key.trim())
-        .header("Content-Type", "application/json");
-
-    if let Some(beta_headers) = beta_headers {
-        request_builder = request_builder.header("Anthropic-Beta", beta_headers);
-    }
+    let (response, rate_limits) =
+        send_request(client, api_url, api_key, &request, beta_headers).await?;
 
-    let serialized_request =
-        serde_json::to_string(&request).map_err(AnthropicError::SerializeRequest)?;
-    let request = request_builder
-        .body(AsyncBody::from(serialized_request))
-        .map_err(AnthropicError::BuildRequestBody)?;
-
-    let mut response = client
-        .send(request)
-        .await
-        .map_err(AnthropicError::HttpSend)?;
-    let rate_limits = RateLimitInfo::from_headers(response.headers());
     if response.status().is_success() {
         let reader = BufReader::new(response.into_body());
         let stream = reader
@@ -622,27 +714,8 @@ pub async fn stream_completion_with_rate_limit_info(
             })
             .boxed();
         Ok((stream, Some(rate_limits)))
-    } else if response.status().as_u16() == 529 {
-        Err(AnthropicError::ServerOverloaded {
-            retry_after: rate_limits.retry_after,
-        })
-    } else if let Some(retry_after) = rate_limits.retry_after {
-        Err(AnthropicError::RateLimit { retry_after })
     } else {
-        let mut body = String::new();
-        response
-            .body_mut()
-            .read_to_string(&mut body)
-            .await
-            .map_err(AnthropicError::ReadResponse)?;
-
-        match serde_json::from_str::<Event>(&body) {
-            Ok(Event::Error { error }) => Err(AnthropicError::ApiError(error)),
-            Ok(_) | Err(_) => Err(AnthropicError::HttpResponseError {
-                status_code: response.status(),
-                message: body,
-            }),
-        }
+        Err(handle_error_response(response, rate_limits).await)
     }
 }
 
@@ -979,6 +1052,71 @@ pub fn parse_prompt_too_long(message: &str) -> Option<u64> {
         .ok()
 }
 
+/// Request body for the token counting API.
+/// Similar to `Request` but without `max_tokens` since it's not needed for counting.
+#[derive(Debug, Serialize)]
+pub struct CountTokensRequest {
+    pub model: String,
+    pub messages: Vec<Message>,
+    #[serde(default, skip_serializing_if = "Option::is_none")]
+    pub system: Option<StringOrContents>,
+    #[serde(default, skip_serializing_if = "Vec::is_empty")]
+    pub tools: Vec<Tool>,
+    #[serde(default, skip_serializing_if = "Option::is_none")]
+    pub thinking: Option<Thinking>,
+    #[serde(default, skip_serializing_if = "Option::is_none")]
+    pub tool_choice: Option<ToolChoice>,
+}
+
+/// Response from the token counting API.
+#[derive(Debug, Deserialize)]
+pub struct CountTokensResponse {
+    pub input_tokens: u64,
+}
+
+/// Count the number of tokens in a message without creating it.
+pub async fn count_tokens(
+    client: &dyn HttpClient,
+    api_url: &str,
+    api_key: &str,
+    request: CountTokensRequest,
+) -> Result<CountTokensResponse, AnthropicError> {
+    let uri = format!("{api_url}/v1/messages/count_tokens");
+
+    let request_builder = HttpRequest::builder()
+        .method(Method::POST)
+        .uri(uri)
+        .header("Anthropic-Version", "2023-06-01")
+        .header("X-Api-Key", api_key.trim())
+        .header("Content-Type", "application/json");
+
+    let serialized_request =
+        serde_json::to_string(&request).map_err(AnthropicError::SerializeRequest)?;
+    let http_request = request_builder
+        .body(AsyncBody::from(serialized_request))
+        .map_err(AnthropicError::BuildRequestBody)?;
+
+    let mut response = client
+        .send(http_request)
+        .await
+        .map_err(AnthropicError::HttpSend)?;
+
+    let rate_limits = RateLimitInfo::from_headers(response.headers());
+
+    if response.status().is_success() {
+        let mut body = String::new();
+        response
+            .body_mut()
+            .read_to_string(&mut body)
+            .await
+            .map_err(AnthropicError::ReadResponse)?;
+
+        serde_json::from_str(&body).map_err(AnthropicError::DeserializeResponse)
+    } else {
+        Err(handle_error_response(response, rate_limits).await)
+    }
+}
+
 #[test]
 fn test_match_window_exceeded() {
     let error = ApiError {

crates/anthropic/src/batches.rs 🔗

@@ -0,0 +1,190 @@
+use anyhow::Result;
+use futures::AsyncReadExt;
+use http_client::{AsyncBody, HttpClient, Method, Request as HttpRequest};
+use serde::{Deserialize, Serialize};
+
+use crate::{AnthropicError, ApiError, RateLimitInfo, Request, Response};
+
+#[derive(Debug, Serialize, Deserialize)]
+pub struct BatchRequest {
+    pub custom_id: String,
+    pub params: Request,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+pub struct CreateBatchRequest {
+    pub requests: Vec<BatchRequest>,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+pub struct MessageBatchRequestCounts {
+    pub processing: u64,
+    pub succeeded: u64,
+    pub errored: u64,
+    pub canceled: u64,
+    pub expired: u64,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+pub struct MessageBatch {
+    pub id: String,
+    #[serde(rename = "type")]
+    pub batch_type: String,
+    pub processing_status: String,
+    pub request_counts: MessageBatchRequestCounts,
+    pub ended_at: Option<String>,
+    pub created_at: String,
+    pub expires_at: String,
+    pub archived_at: Option<String>,
+    pub cancel_initiated_at: Option<String>,
+    pub results_url: Option<String>,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(tag = "type")]
+pub enum BatchResult {
+    #[serde(rename = "succeeded")]
+    Succeeded { message: Response },
+    #[serde(rename = "errored")]
+    Errored { error: ApiError },
+    #[serde(rename = "canceled")]
+    Canceled,
+    #[serde(rename = "expired")]
+    Expired,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+pub struct BatchIndividualResponse {
+    pub custom_id: String,
+    pub result: BatchResult,
+}
+
+pub async fn create_batch(
+    client: &dyn HttpClient,
+    api_url: &str,
+    api_key: &str,
+    request: CreateBatchRequest,
+) -> Result<MessageBatch, AnthropicError> {
+    let uri = format!("{api_url}/v1/messages/batches");
+
+    let request_builder = HttpRequest::builder()
+        .method(Method::POST)
+        .uri(uri)
+        .header("Anthropic-Version", "2023-06-01")
+        .header("X-Api-Key", api_key.trim())
+        .header("Content-Type", "application/json");
+
+    let serialized_request =
+        serde_json::to_string(&request).map_err(AnthropicError::SerializeRequest)?;
+    let http_request = request_builder
+        .body(AsyncBody::from(serialized_request))
+        .map_err(AnthropicError::BuildRequestBody)?;
+
+    let mut response = client
+        .send(http_request)
+        .await
+        .map_err(AnthropicError::HttpSend)?;
+
+    let rate_limits = RateLimitInfo::from_headers(response.headers());
+
+    if response.status().is_success() {
+        let mut body = String::new();
+        response
+            .body_mut()
+            .read_to_string(&mut body)
+            .await
+            .map_err(AnthropicError::ReadResponse)?;
+
+        serde_json::from_str(&body).map_err(AnthropicError::DeserializeResponse)
+    } else {
+        Err(crate::handle_error_response(response, rate_limits).await)
+    }
+}
+
+pub async fn retrieve_batch(
+    client: &dyn HttpClient,
+    api_url: &str,
+    api_key: &str,
+    message_batch_id: &str,
+) -> Result<MessageBatch, AnthropicError> {
+    let uri = format!("{api_url}/v1/messages/batches/{message_batch_id}");
+
+    let request_builder = HttpRequest::builder()
+        .method(Method::GET)
+        .uri(uri)
+        .header("Anthropic-Version", "2023-06-01")
+        .header("X-Api-Key", api_key.trim());
+
+    let http_request = request_builder
+        .body(AsyncBody::default())
+        .map_err(AnthropicError::BuildRequestBody)?;
+
+    let mut response = client
+        .send(http_request)
+        .await
+        .map_err(AnthropicError::HttpSend)?;
+
+    let rate_limits = RateLimitInfo::from_headers(response.headers());
+
+    if response.status().is_success() {
+        let mut body = String::new();
+        response
+            .body_mut()
+            .read_to_string(&mut body)
+            .await
+            .map_err(AnthropicError::ReadResponse)?;
+
+        serde_json::from_str(&body).map_err(AnthropicError::DeserializeResponse)
+    } else {
+        Err(crate::handle_error_response(response, rate_limits).await)
+    }
+}
+
+pub async fn retrieve_batch_results(
+    client: &dyn HttpClient,
+    api_url: &str,
+    api_key: &str,
+    message_batch_id: &str,
+) -> Result<Vec<BatchIndividualResponse>, AnthropicError> {
+    let uri = format!("{api_url}/v1/messages/batches/{message_batch_id}/results");
+
+    let request_builder = HttpRequest::builder()
+        .method(Method::GET)
+        .uri(uri)
+        .header("Anthropic-Version", "2023-06-01")
+        .header("X-Api-Key", api_key.trim());
+
+    let http_request = request_builder
+        .body(AsyncBody::default())
+        .map_err(AnthropicError::BuildRequestBody)?;
+
+    let mut response = client
+        .send(http_request)
+        .await
+        .map_err(AnthropicError::HttpSend)?;
+
+    let rate_limits = RateLimitInfo::from_headers(response.headers());
+
+    if response.status().is_success() {
+        let mut body = String::new();
+        response
+            .body_mut()
+            .read_to_string(&mut body)
+            .await
+            .map_err(AnthropicError::ReadResponse)?;
+
+        let mut results = Vec::new();
+        for line in body.lines() {
+            if line.trim().is_empty() {
+                continue;
+            }
+            let result: BatchIndividualResponse =
+                serde_json::from_str(line).map_err(AnthropicError::DeserializeResponse)?;
+            results.push(result);
+        }
+
+        Ok(results)
+    } else {
+        Err(crate::handle_error_response(response, rate_limits).await)
+    }
+}

crates/assistant_slash_commands/Cargo.toml 🔗

@@ -22,7 +22,6 @@ feature_flags.workspace = true
 fs.workspace = true
 futures.workspace = true
 fuzzy.workspace = true
-globset.workspace = true
 gpui.workspace = true
 html_to_markdown.workspace = true
 http_client.workspace = true

crates/assistant_slash_commands/src/file_command.rs 🔗

@@ -226,10 +226,10 @@ fn collect_files(
     let Ok(matchers) = glob_inputs
         .iter()
         .map(|glob_input| {
-            custom_path_matcher::PathMatcher::new(&[glob_input.to_owned()])
+            util::paths::PathMatcher::new(&[glob_input.to_owned()], project.read(cx).path_style(cx))
                 .with_context(|| format!("invalid path {glob_input}"))
         })
-        .collect::<anyhow::Result<Vec<custom_path_matcher::PathMatcher>>>()
+        .collect::<anyhow::Result<Vec<util::paths::PathMatcher>>>()
     else {
         return futures::stream::once(async {
             anyhow::bail!("invalid path");
@@ -250,6 +250,7 @@ fn collect_files(
             let worktree_id = snapshot.id();
             let path_style = snapshot.path_style();
             let mut directory_stack: Vec<Arc<RelPath>> = Vec::new();
+            let mut folded_directory_path: Option<Arc<RelPath>> = None;
             let mut folded_directory_names: Arc<RelPath> = RelPath::empty().into();
             let mut is_top_level_directory = true;
 
@@ -277,6 +278,16 @@ fn collect_files(
                     )))?;
                 }
 
+                if let Some(folded_path) = &folded_directory_path {
+                    if !entry.path.starts_with(folded_path) {
+                        folded_directory_names = RelPath::empty().into();
+                        folded_directory_path = None;
+                        if directory_stack.is_empty() {
+                            is_top_level_directory = true;
+                        }
+                    }
+                }
+
                 let filename = entry.path.file_name().unwrap_or_default().to_string();
 
                 if entry.is_dir() {
@@ -292,13 +303,17 @@ fn collect_files(
                                 folded_directory_names =
                                     folded_directory_names.join(RelPath::unix(&filename).unwrap());
                             }
+                            folded_directory_path = Some(entry.path.clone());
                             continue;
                         }
                     } else {
                         // Skip empty directories
                         folded_directory_names = RelPath::empty().into();
+                        folded_directory_path = None;
                         continue;
                     }
+
+                    // Render the directory (either folded or normal)
                     if folded_directory_names.is_empty() {
                         let label = if is_top_level_directory {
                             is_top_level_directory = false;
@@ -334,6 +349,8 @@ fn collect_files(
                             },
                         )))?;
                         directory_stack.push(entry.path.clone());
+                        folded_directory_names = RelPath::empty().into();
+                        folded_directory_path = None;
                     }
                     events_tx.unbounded_send(Ok(SlashCommandEvent::Content(
                         SlashCommandContent::Text {
@@ -447,87 +464,6 @@ pub fn build_entry_output_section(
     }
 }
 
-/// This contains a small fork of the util::paths::PathMatcher, that is stricter about the prefix
-/// check. Only subpaths pass the prefix check, rather than any prefix.
-mod custom_path_matcher {
-    use globset::{Glob, GlobSet, GlobSetBuilder};
-    use std::fmt::Debug as _;
-    use util::{paths::SanitizedPath, rel_path::RelPath};
-
-    #[derive(Clone, Debug, Default)]
-    pub struct PathMatcher {
-        sources: Vec<String>,
-        sources_with_trailing_slash: Vec<String>,
-        glob: GlobSet,
-    }
-
-    impl std::fmt::Display for PathMatcher {
-        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
-            self.sources.fmt(f)
-        }
-    }
-
-    impl PartialEq for PathMatcher {
-        fn eq(&self, other: &Self) -> bool {
-            self.sources.eq(&other.sources)
-        }
-    }
-
-    impl Eq for PathMatcher {}
-
-    impl PathMatcher {
-        pub fn new(globs: &[String]) -> Result<Self, globset::Error> {
-            let globs = globs
-                .iter()
-                .map(|glob| Glob::new(&SanitizedPath::new(glob).to_string()))
-                .collect::<Result<Vec<_>, _>>()?;
-            let sources = globs.iter().map(|glob| glob.glob().to_owned()).collect();
-            let sources_with_trailing_slash = globs
-                .iter()
-                .map(|glob| glob.glob().to_string() + "/")
-                .collect();
-            let mut glob_builder = GlobSetBuilder::new();
-            for single_glob in globs {
-                glob_builder.add(single_glob);
-            }
-            let glob = glob_builder.build()?;
-            Ok(PathMatcher {
-                glob,
-                sources,
-                sources_with_trailing_slash,
-            })
-        }
-
-        pub fn is_match(&self, other: &RelPath) -> bool {
-            self.sources
-                .iter()
-                .zip(self.sources_with_trailing_slash.iter())
-                .any(|(source, with_slash)| {
-                    let as_bytes = other.as_unix_str().as_bytes();
-                    let with_slash = if source.ends_with('/') {
-                        source.as_bytes()
-                    } else {
-                        with_slash.as_bytes()
-                    };
-
-                    as_bytes.starts_with(with_slash) || as_bytes.ends_with(source.as_bytes())
-                })
-                || self.glob.is_match(other.as_std_path())
-                || self.check_with_end_separator(other)
-        }
-
-        fn check_with_end_separator(&self, path: &RelPath) -> bool {
-            let path_str = path.as_unix_str();
-            let separator = "/";
-            if path_str.ends_with(separator) {
-                false
-            } else {
-                self.glob.is_match(path_str.to_string() + separator)
-            }
-        }
-    }
-}
-
 pub fn append_buffer_to_output(
     buffer: &BufferSnapshot,
     path: Option<&str>,

crates/assistant_text_thread/Cargo.toml 🔗

@@ -46,7 +46,7 @@ serde_json.workspace = true
 settings.workspace = true
 smallvec.workspace = true
 smol.workspace = true
-telemetry_events.workspace = true
+telemetry.workspace = true
 text.workspace = true
 ui.workspace = true
 util.workspace = true

crates/assistant_text_thread/src/assistant_text_thread_tests.rs 🔗

@@ -50,7 +50,6 @@ fn test_inserting_and_removing_messages(cx: &mut App) {
         TextThread::local(
             registry,
             None,
-            None,
             prompt_builder.clone(),
             Arc::new(SlashCommandWorkingSet::default()),
             cx,
@@ -189,7 +188,6 @@ fn test_message_splitting(cx: &mut App) {
         TextThread::local(
             registry.clone(),
             None,
-            None,
             prompt_builder.clone(),
             Arc::new(SlashCommandWorkingSet::default()),
             cx,
@@ -294,7 +292,6 @@ fn test_messages_for_offsets(cx: &mut App) {
         TextThread::local(
             registry,
             None,
-            None,
             prompt_builder.clone(),
             Arc::new(SlashCommandWorkingSet::default()),
             cx,
@@ -405,7 +402,6 @@ async fn test_slash_commands(cx: &mut TestAppContext) {
         TextThread::local(
             registry.clone(),
             None,
-            None,
             prompt_builder.clone(),
             Arc::new(SlashCommandWorkingSet::default()),
             cx,
@@ -677,7 +673,6 @@ async fn test_serialization(cx: &mut TestAppContext) {
         TextThread::local(
             registry.clone(),
             None,
-            None,
             prompt_builder.clone(),
             Arc::new(SlashCommandWorkingSet::default()),
             cx,
@@ -724,7 +719,6 @@ async fn test_serialization(cx: &mut TestAppContext) {
             prompt_builder.clone(),
             Arc::new(SlashCommandWorkingSet::default()),
             None,
-            None,
             cx,
         )
     });
@@ -780,7 +774,6 @@ async fn test_random_context_collaboration(cx: &mut TestAppContext, mut rng: Std
                 prompt_builder.clone(),
                 Arc::new(SlashCommandWorkingSet::default()),
                 None,
-                None,
                 cx,
             )
         });
@@ -1041,7 +1034,6 @@ fn test_mark_cache_anchors(cx: &mut App) {
         TextThread::local(
             registry,
             None,
-            None,
             prompt_builder.clone(),
             Arc::new(SlashCommandWorkingSet::default()),
             cx,
@@ -1368,7 +1360,6 @@ fn setup_context_editor_with_fake_model(
         TextThread::local(
             registry,
             None,
-            None,
             prompt_builder.clone(),
             Arc::new(SlashCommandWorkingSet::default()),
             cx,

crates/assistant_text_thread/src/text_thread.rs 🔗

@@ -5,7 +5,7 @@ use assistant_slash_command::{
     SlashCommandResult, SlashCommandWorkingSet,
 };
 use assistant_slash_commands::FileCommandMetadata;
-use client::{self, ModelRequestUsage, RequestUsage, proto, telemetry::Telemetry};
+use client::{self, ModelRequestUsage, RequestUsage, proto};
 use clock::ReplicaId;
 use cloud_llm_client::{CompletionIntent, UsageLimit};
 use collections::{HashMap, HashSet};
@@ -14,15 +14,16 @@ use fs::{Fs, RenameOptions};
 use futures::{FutureExt, StreamExt, future::Shared};
 use gpui::{
     App, AppContext as _, Context, Entity, EventEmitter, RenderImage, SharedString, Subscription,
-    Task,
+    Task, WeakEntity,
 };
 use itertools::Itertools as _;
 use language::{AnchorRangeExt, Bias, Buffer, LanguageRegistry, OffsetRangeExt, Point, ToOffset};
 use language_model::{
-    LanguageModel, LanguageModelCacheConfiguration, LanguageModelCompletionEvent,
-    LanguageModelImage, LanguageModelRegistry, LanguageModelRequest, LanguageModelRequestMessage,
+    AnthropicCompletionType, AnthropicEventData, AnthropicEventType, LanguageModel,
+    LanguageModelCacheConfiguration, LanguageModelCompletionEvent, LanguageModelImage,
+    LanguageModelRegistry, LanguageModelRequest, LanguageModelRequestMessage,
     LanguageModelToolUseId, MessageContent, PaymentRequiredError, Role, StopReason,
-    report_assistant_event,
+    report_anthropic_event,
 };
 use open_ai::Model as OpenAiModel;
 use paths::text_threads_dir;
@@ -40,7 +41,7 @@ use std::{
     sync::Arc,
     time::{Duration, Instant},
 };
-use telemetry_events::{AssistantEventData, AssistantKind, AssistantPhase};
+
 use text::{BufferSnapshot, ToPoint};
 use ui::IconName;
 use util::{ResultExt, TryFutureExt, post_inc};
@@ -686,9 +687,8 @@ pub struct TextThread {
     pending_cache_warming_task: Task<Option<()>>,
     path: Option<Arc<Path>>,
     _subscriptions: Vec<Subscription>,
-    telemetry: Option<Arc<Telemetry>>,
     language_registry: Arc<LanguageRegistry>,
-    project: Option<Entity<Project>>,
+    project: Option<WeakEntity<Project>>,
     prompt_builder: Arc<PromptBuilder>,
     completion_mode: agent_settings::CompletionMode,
 }
@@ -708,8 +708,7 @@ impl EventEmitter<TextThreadEvent> for TextThread {}
 impl TextThread {
     pub fn local(
         language_registry: Arc<LanguageRegistry>,
-        project: Option<Entity<Project>>,
-        telemetry: Option<Arc<Telemetry>>,
+        project: Option<WeakEntity<Project>>,
         prompt_builder: Arc<PromptBuilder>,
         slash_commands: Arc<SlashCommandWorkingSet>,
         cx: &mut Context<Self>,
@@ -722,7 +721,6 @@ impl TextThread {
             prompt_builder,
             slash_commands,
             project,
-            telemetry,
             cx,
         )
     }
@@ -742,8 +740,7 @@ impl TextThread {
         language_registry: Arc<LanguageRegistry>,
         prompt_builder: Arc<PromptBuilder>,
         slash_commands: Arc<SlashCommandWorkingSet>,
-        project: Option<Entity<Project>>,
-        telemetry: Option<Arc<Telemetry>>,
+        project: Option<WeakEntity<Project>>,
         cx: &mut Context<Self>,
     ) -> Self {
         let buffer = cx.new(|_cx| {
@@ -784,7 +781,6 @@ impl TextThread {
             completion_mode: AgentSettings::get_global(cx).preferred_completion_mode,
             path: None,
             buffer,
-            telemetry,
             project,
             language_registry,
             slash_commands,
@@ -873,8 +869,7 @@ impl TextThread {
         language_registry: Arc<LanguageRegistry>,
         prompt_builder: Arc<PromptBuilder>,
         slash_commands: Arc<SlashCommandWorkingSet>,
-        project: Option<Entity<Project>>,
-        telemetry: Option<Arc<Telemetry>>,
+        project: Option<WeakEntity<Project>>,
         cx: &mut Context<Self>,
     ) -> Self {
         let id = saved_context.id.clone().unwrap_or_else(TextThreadId::new);
@@ -886,7 +881,6 @@ impl TextThread {
             prompt_builder,
             slash_commands,
             project,
-            telemetry,
             cx,
         );
         this.path = Some(path);
@@ -1167,10 +1161,6 @@ impl TextThread {
         self.language_registry.clone()
     }
 
-    pub fn project(&self) -> Option<Entity<Project>> {
-        self.project.clone()
-    }
-
     pub fn prompt_builder(&self) -> Arc<PromptBuilder> {
         self.prompt_builder.clone()
     }
@@ -2216,24 +2206,26 @@ impl TextThread {
                         .read(cx)
                         .language()
                         .map(|language| language.name());
-                    report_assistant_event(
-                        AssistantEventData {
-                            conversation_id: Some(this.id.0.clone()),
-                            kind: AssistantKind::Panel,
-                            phase: AssistantPhase::Response,
-                            message_id: None,
-                            model: model.telemetry_id(),
-                            model_provider: model.provider_id().to_string(),
-                            response_latency,
-                            error_message,
-                            language_name: language_name.map(|name| name.to_proto()),
-                        },
-                        this.telemetry.clone(),
-                        cx.http_client(),
-                        model.api_key(cx),
-                        cx.background_executor(),
+
+                    telemetry::event!(
+                        "Assistant Responded",
+                        conversation_id = this.id.0.clone(),
+                        kind = "panel",
+                        phase = "response",
+                        model =  model.telemetry_id(),
+                        model_provider = model.provider_id().to_string(),
+                        response_latency,
+                        error_message,
+                        language_name = language_name.as_ref().map(|name| name.to_proto()),
                     );
 
+                    report_anthropic_event(&model, AnthropicEventData {
+                        completion_type: AnthropicCompletionType::Panel,
+                        event: AnthropicEventType::Response,
+                        language_name: language_name.map(|name| name.to_proto()),
+                        message_id: None,
+                    }, cx);
+
                     if let Ok(stop_reason) = result {
                         match stop_reason {
                             StopReason::ToolUse => {}
@@ -2967,7 +2959,7 @@ impl TextThread {
     }
 
     fn update_model_request_usage(&self, amount: u32, limit: UsageLimit, cx: &mut App) {
-        let Some(project) = &self.project else {
+        let Some(project) = self.project.as_ref().and_then(|project| project.upgrade()) else {
             return;
         };
         project.read(cx).user_store().update(cx, |user_store, cx| {

crates/assistant_text_thread/src/text_thread_store.rs 🔗

@@ -4,7 +4,7 @@ use crate::{
 };
 use anyhow::{Context as _, Result};
 use assistant_slash_command::{SlashCommandId, SlashCommandWorkingSet};
-use client::{Client, TypedEnvelope, proto, telemetry::Telemetry};
+use client::{Client, TypedEnvelope, proto};
 use clock::ReplicaId;
 use collections::HashMap;
 use context_server::ContextServerId;
@@ -48,10 +48,9 @@ pub struct TextThreadStore {
     fs: Arc<dyn Fs>,
     languages: Arc<LanguageRegistry>,
     slash_commands: Arc<SlashCommandWorkingSet>,
-    telemetry: Arc<Telemetry>,
     _watch_updates: Task<Option<()>>,
     client: Arc<Client>,
-    project: Entity<Project>,
+    project: WeakEntity<Project>,
     project_is_shared: bool,
     client_subscription: Option<client::Subscription>,
     _project_subscriptions: Vec<gpui::Subscription>,
@@ -88,7 +87,6 @@ impl TextThreadStore {
     ) -> Task<Result<Entity<Self>>> {
         let fs = project.read(cx).fs().clone();
         let languages = project.read(cx).languages().clone();
-        let telemetry = project.read(cx).client().telemetry().clone();
         cx.spawn(async move |cx| {
             const CONTEXT_WATCH_DURATION: Duration = Duration::from_millis(100);
             let (mut events, _) = fs.watch(text_threads_dir(), CONTEXT_WATCH_DURATION).await;
@@ -102,7 +100,6 @@ impl TextThreadStore {
                     fs,
                     languages,
                     slash_commands,
-                    telemetry,
                     _watch_updates: cx.spawn(async move |this, cx| {
                         async move {
                             while events.next().await.is_some() {
@@ -119,10 +116,10 @@ impl TextThreadStore {
                     ],
                     project_is_shared: false,
                     client: project.read(cx).client(),
-                    project: project.clone(),
+                    project: project.downgrade(),
                     prompt_builder,
                 };
-                this.handle_project_shared(project.clone(), cx);
+                this.handle_project_shared(cx);
                 this.synchronize_contexts(cx);
                 this.register_context_server_handlers(cx);
                 this.reload(cx).detach_and_log_err(cx);
@@ -143,10 +140,9 @@ impl TextThreadStore {
             fs: project.read(cx).fs().clone(),
             languages: project.read(cx).languages().clone(),
             slash_commands: Arc::default(),
-            telemetry: project.read(cx).client().telemetry().clone(),
             _watch_updates: Task::ready(None),
             client: project.read(cx).client(),
-            project,
+            project: project.downgrade(),
             project_is_shared: false,
             client_subscription: None,
             _project_subscriptions: Default::default(),
@@ -180,8 +176,10 @@ impl TextThreadStore {
     ) -> Result<proto::OpenContextResponse> {
         let context_id = TextThreadId::from_proto(envelope.payload.context_id);
         let operations = this.update(&mut cx, |this, cx| {
+            let project = this.project.upgrade().context("project not found")?;
+
             anyhow::ensure!(
-                !this.project.read(cx).is_via_collab(),
+                !project.read(cx).is_via_collab(),
                 "only the host contexts can be opened"
             );
 
@@ -211,8 +209,9 @@ impl TextThreadStore {
         mut cx: AsyncApp,
     ) -> Result<proto::CreateContextResponse> {
         let (context_id, operations) = this.update(&mut cx, |this, cx| {
+            let project = this.project.upgrade().context("project not found")?;
             anyhow::ensure!(
-                !this.project.read(cx).is_via_collab(),
+                !project.read(cx).is_via_collab(),
                 "can only create contexts as the host"
             );
 
@@ -255,8 +254,9 @@ impl TextThreadStore {
         mut cx: AsyncApp,
     ) -> Result<proto::SynchronizeContextsResponse> {
         this.update(&mut cx, |this, cx| {
+            let project = this.project.upgrade().context("project not found")?;
             anyhow::ensure!(
-                !this.project.read(cx).is_via_collab(),
+                !project.read(cx).is_via_collab(),
                 "only the host can synchronize contexts"
             );
 
@@ -293,8 +293,12 @@ impl TextThreadStore {
         })?
     }
 
-    fn handle_project_shared(&mut self, _: Entity<Project>, cx: &mut Context<Self>) {
-        let is_shared = self.project.read(cx).is_shared();
+    fn handle_project_shared(&mut self, cx: &mut Context<Self>) {
+        let Some(project) = self.project.upgrade() else {
+            return;
+        };
+
+        let is_shared = project.read(cx).is_shared();
         let was_shared = mem::replace(&mut self.project_is_shared, is_shared);
         if is_shared == was_shared {
             return;
@@ -309,7 +313,7 @@ impl TextThreadStore {
                     false
                 }
             });
-            let remote_id = self.project.read(cx).remote_id().unwrap();
+            let remote_id = project.read(cx).remote_id().unwrap();
             self.client_subscription = self
                 .client
                 .subscribe_to_entity(remote_id)
@@ -323,13 +327,13 @@ impl TextThreadStore {
 
     fn handle_project_event(
         &mut self,
-        project: Entity<Project>,
+        _project: Entity<Project>,
         event: &project::Event,
         cx: &mut Context<Self>,
     ) {
         match event {
             project::Event::RemoteIdChanged(_) => {
-                self.handle_project_shared(project, cx);
+                self.handle_project_shared(cx);
             }
             project::Event::Reshared => {
                 self.advertise_contexts(cx);
@@ -371,7 +375,6 @@ impl TextThreadStore {
             TextThread::local(
                 self.languages.clone(),
                 Some(self.project.clone()),
-                Some(self.telemetry.clone()),
                 self.prompt_builder.clone(),
                 self.slash_commands.clone(),
                 cx,
@@ -382,7 +385,10 @@ impl TextThreadStore {
     }
 
     pub fn create_remote(&mut self, cx: &mut Context<Self>) -> Task<Result<Entity<TextThread>>> {
-        let project = self.project.read(cx);
+        let Some(project) = self.project.upgrade() else {
+            return Task::ready(Err(anyhow::anyhow!("project was dropped")));
+        };
+        let project = project.read(cx);
         let Some(project_id) = project.remote_id() else {
             return Task::ready(Err(anyhow::anyhow!("project was not remote")));
         };
@@ -391,7 +397,7 @@ impl TextThreadStore {
         let capability = project.capability();
         let language_registry = self.languages.clone();
         let project = self.project.clone();
-        let telemetry = self.telemetry.clone();
+
         let prompt_builder = self.prompt_builder.clone();
         let slash_commands = self.slash_commands.clone();
         let request = self.client.request(proto::CreateContext { project_id });
@@ -408,7 +414,6 @@ impl TextThreadStore {
                     prompt_builder,
                     slash_commands,
                     Some(project),
-                    Some(telemetry),
                     cx,
                 )
             })?;
@@ -446,7 +451,6 @@ impl TextThreadStore {
         let fs = self.fs.clone();
         let languages = self.languages.clone();
         let project = self.project.clone();
-        let telemetry = self.telemetry.clone();
         let load = cx.background_spawn({
             let path = path.clone();
             async move {
@@ -467,7 +471,6 @@ impl TextThreadStore {
                     prompt_builder,
                     slash_commands,
                     Some(project),
-                    Some(telemetry),
                     cx,
                 )
             })?;
@@ -541,7 +544,10 @@ impl TextThreadStore {
         text_thread_id: TextThreadId,
         cx: &mut Context<Self>,
     ) -> Task<Result<Entity<TextThread>>> {
-        let project = self.project.read(cx);
+        let Some(project) = self.project.upgrade() else {
+            return Task::ready(Err(anyhow::anyhow!("project was dropped")));
+        };
+        let project = project.read(cx);
         let Some(project_id) = project.remote_id() else {
             return Task::ready(Err(anyhow::anyhow!("project was not remote")));
         };
@@ -554,7 +560,6 @@ impl TextThreadStore {
         let capability = project.capability();
         let language_registry = self.languages.clone();
         let project = self.project.clone();
-        let telemetry = self.telemetry.clone();
         let request = self.client.request(proto::OpenContext {
             project_id,
             context_id: text_thread_id.to_proto(),
@@ -573,7 +578,6 @@ impl TextThreadStore {
                     prompt_builder,
                     slash_commands,
                     Some(project),
-                    Some(telemetry),
                     cx,
                 )
             })?;
@@ -618,7 +622,10 @@ impl TextThreadStore {
         event: &TextThreadEvent,
         cx: &mut Context<Self>,
     ) {
-        let Some(project_id) = self.project.read(cx).remote_id() else {
+        let Some(project) = self.project.upgrade() else {
+            return;
+        };
+        let Some(project_id) = project.read(cx).remote_id() else {
             return;
         };
 
@@ -652,12 +659,14 @@ impl TextThreadStore {
     }
 
     fn advertise_contexts(&self, cx: &App) {
-        let Some(project_id) = self.project.read(cx).remote_id() else {
+        let Some(project) = self.project.upgrade() else {
+            return;
+        };
+        let Some(project_id) = project.read(cx).remote_id() else {
             return;
         };
-
         // For now, only the host can advertise their open contexts.
-        if self.project.read(cx).is_via_collab() {
+        if project.read(cx).is_via_collab() {
             return;
         }
 
@@ -689,7 +698,10 @@ impl TextThreadStore {
     }
 
     fn synchronize_contexts(&mut self, cx: &mut Context<Self>) {
-        let Some(project_id) = self.project.read(cx).remote_id() else {
+        let Some(project) = self.project.upgrade() else {
+            return;
+        };
+        let Some(project_id) = project.read(cx).remote_id() else {
             return;
         };
 
@@ -828,7 +840,10 @@ impl TextThreadStore {
     }
 
     fn register_context_server_handlers(&self, cx: &mut Context<Self>) {
-        let context_server_store = self.project.read(cx).context_server_store();
+        let Some(project) = self.project.upgrade() else {
+            return;
+        };
+        let context_server_store = project.read(cx).context_server_store();
         cx.subscribe(&context_server_store, Self::handle_context_server_event)
             .detach();
 

crates/bedrock/src/bedrock.rs 🔗

@@ -87,7 +87,7 @@ pub async fn stream_completion(
                 Ok(None) => None,
                 Err(err) => Some((
                     Err(BedrockError::ClientError(anyhow!(
-                        "{:?}",
+                        "{}",
                         aws_sdk_bedrockruntime::error::DisplayErrorContext(err)
                     ))),
                     stream,

crates/bedrock/src/models.rs 🔗

@@ -584,41 +584,100 @@ impl Model {
         }
     }
 
-    pub fn cross_region_inference_id(&self, region: &str) -> anyhow::Result<String> {
+    pub fn cross_region_inference_id(
+        &self,
+        region: &str,
+        allow_global: bool,
+    ) -> anyhow::Result<String> {
+        // List derived from here:
+        // https://docs.aws.amazon.com/bedrock/latest/userguide/inference-profiles-support.html#inference-profiles-support-system
+        let model_id = self.request_id();
+
+        let supports_global = matches!(
+            self,
+            Model::ClaudeOpus4_5
+                | Model::ClaudeOpus4_5Thinking
+                | Model::ClaudeHaiku4_5
+                | Model::ClaudeSonnet4
+                | Model::ClaudeSonnet4Thinking
+                | Model::ClaudeSonnet4_5
+                | Model::ClaudeSonnet4_5Thinking
+        );
+
         let region_group = if region.starts_with("us-gov-") {
             "us-gov"
-        } else if region.starts_with("us-") {
-            "us"
+        } else if region.starts_with("us-")
+            || region.starts_with("ca-")
+            || region.starts_with("sa-")
+        {
+            if allow_global && supports_global {
+                "global"
+            } else {
+                "us"
+            }
         } else if region.starts_with("eu-") {
-            "eu"
+            if allow_global && supports_global {
+                "global"
+            } else {
+                "eu"
+            }
         } else if region.starts_with("ap-") || region == "me-central-1" || region == "me-south-1" {
-            "apac"
-        } else if region.starts_with("ca-") || region.starts_with("sa-") {
-            // Canada and South America regions - default to US profiles
-            "us"
+            if allow_global && supports_global {
+                "global"
+            } else {
+                "apac"
+            }
         } else {
             anyhow::bail!("Unsupported Region {region}");
         };
 
-        let model_id = self.request_id();
+        match (self, region_group, region) {
+            (Model::Custom { .. }, _, _) => Ok(self.request_id().into()),
 
-        match (self, region_group) {
-            // Custom models can't have CRI IDs
-            (Model::Custom { .. }, _) => Ok(self.request_id().into()),
+            (
+                Model::ClaudeOpus4_5
+                | Model::ClaudeOpus4_5Thinking
+                | Model::ClaudeHaiku4_5
+                | Model::ClaudeSonnet4
+                | Model::ClaudeSonnet4Thinking
+                | Model::ClaudeSonnet4_5
+                | Model::ClaudeSonnet4_5Thinking,
+                "global",
+                _,
+            ) => Ok(format!("{}.{}", region_group, model_id)),
 
-            // Models with US Gov only
-            (Model::Claude3_5Sonnet, "us-gov") | (Model::Claude3Haiku, "us-gov") => {
-                Ok(format!("{}.{}", region_group, model_id))
-            }
+            (
+                Model::Claude3Haiku
+                | Model::Claude3_5Sonnet
+                | Model::Claude3_7Sonnet
+                | Model::Claude3_7SonnetThinking
+                | Model::ClaudeSonnet4_5
+                | Model::ClaudeSonnet4_5Thinking,
+                "us-gov",
+                _,
+            ) => Ok(format!("{}.{}", region_group, model_id)),
 
-            // Available everywhere
-            (Model::AmazonNovaLite | Model::AmazonNovaMicro | Model::AmazonNovaPro, _) => {
-                Ok(format!("{}.{}", region_group, model_id))
+            (
+                Model::ClaudeHaiku4_5 | Model::ClaudeSonnet4_5 | Model::ClaudeSonnet4_5Thinking,
+                "apac",
+                "ap-southeast-2" | "ap-southeast-4",
+            ) => Ok(format!("au.{}", model_id)),
+
+            (
+                Model::ClaudeHaiku4_5 | Model::ClaudeSonnet4_5 | Model::ClaudeSonnet4_5Thinking,
+                "apac",
+                "ap-northeast-1" | "ap-northeast-3",
+            ) => Ok(format!("jp.{}", model_id)),
+
+            (Model::AmazonNovaLite, "us", r) if r.starts_with("ca-") => {
+                Ok(format!("ca.{}", model_id))
             }
 
-            // Models in US
             (
                 Model::AmazonNovaPremier
+                | Model::AmazonNovaLite
+                | Model::AmazonNovaMicro
+                | Model::AmazonNovaPro
                 | Model::Claude3_5Haiku
                 | Model::ClaudeHaiku4_5
                 | Model::Claude3_5Sonnet
@@ -655,16 +714,18 @@ impl Model {
                 | Model::PalmyraWriterX4
                 | Model::PalmyraWriterX5,
                 "us",
+                _,
             ) => Ok(format!("{}.{}", region_group, model_id)),
 
-            // Models available in EU
             (
-                Model::Claude3_5Sonnet
+                Model::AmazonNovaLite
+                | Model::AmazonNovaMicro
+                | Model::AmazonNovaPro
+                | Model::Claude3_5Sonnet
                 | Model::ClaudeHaiku4_5
                 | Model::Claude3_7Sonnet
                 | Model::Claude3_7SonnetThinking
                 | Model::ClaudeSonnet4
-                | Model::ClaudeSonnet4Thinking
                 | Model::ClaudeSonnet4_5
                 | Model::ClaudeSonnet4_5Thinking
                 | Model::Claude3Haiku
@@ -673,26 +734,26 @@ impl Model {
                 | Model::MetaLlama323BInstructV1
                 | Model::MistralPixtralLarge2502V1,
                 "eu",
+                _,
             ) => Ok(format!("{}.{}", region_group, model_id)),
 
-            // Models available in APAC
             (
-                Model::Claude3_5Sonnet
+                Model::AmazonNovaLite
+                | Model::AmazonNovaMicro
+                | Model::AmazonNovaPro
+                | Model::Claude3_5Sonnet
                 | Model::Claude3_5SonnetV2
                 | Model::ClaudeHaiku4_5
-                | Model::Claude3Haiku
-                | Model::Claude3Sonnet
                 | Model::Claude3_7Sonnet
                 | Model::Claude3_7SonnetThinking
                 | Model::ClaudeSonnet4
-                | Model::ClaudeSonnet4Thinking
-                | Model::ClaudeSonnet4_5
-                | Model::ClaudeSonnet4_5Thinking,
+                | Model::Claude3Haiku
+                | Model::Claude3Sonnet,
                 "apac",
+                _,
             ) => Ok(format!("{}.{}", region_group, model_id)),
 
-            // Any other combination is not supported
-            _ => Ok(self.request_id().into()),
+            _ => Ok(model_id.into()),
         }
     }
 }
@@ -705,15 +766,15 @@ mod tests {
     fn test_us_region_inference_ids() -> anyhow::Result<()> {
         // Test US regions
         assert_eq!(
-            Model::Claude3_5SonnetV2.cross_region_inference_id("us-east-1")?,
+            Model::Claude3_5SonnetV2.cross_region_inference_id("us-east-1", false)?,
             "us.anthropic.claude-3-5-sonnet-20241022-v2:0"
         );
         assert_eq!(
-            Model::Claude3_5SonnetV2.cross_region_inference_id("us-west-2")?,
+            Model::Claude3_5SonnetV2.cross_region_inference_id("us-west-2", false)?,
             "us.anthropic.claude-3-5-sonnet-20241022-v2:0"
         );
         assert_eq!(
-            Model::AmazonNovaPro.cross_region_inference_id("us-east-2")?,
+            Model::AmazonNovaPro.cross_region_inference_id("us-east-2", false)?,
             "us.amazon.nova-pro-v1:0"
         );
         Ok(())
@@ -723,19 +784,19 @@ mod tests {
     fn test_eu_region_inference_ids() -> anyhow::Result<()> {
         // Test European regions
         assert_eq!(
-            Model::ClaudeSonnet4.cross_region_inference_id("eu-west-1")?,
+            Model::ClaudeSonnet4.cross_region_inference_id("eu-west-1", false)?,
             "eu.anthropic.claude-sonnet-4-20250514-v1:0"
         );
         assert_eq!(
-            Model::ClaudeSonnet4_5.cross_region_inference_id("eu-west-1")?,
+            Model::ClaudeSonnet4_5.cross_region_inference_id("eu-west-1", false)?,
             "eu.anthropic.claude-sonnet-4-5-20250929-v1:0"
         );
         assert_eq!(
-            Model::Claude3Sonnet.cross_region_inference_id("eu-west-1")?,
+            Model::Claude3Sonnet.cross_region_inference_id("eu-west-1", false)?,
             "eu.anthropic.claude-3-sonnet-20240229-v1:0"
         );
         assert_eq!(
-            Model::AmazonNovaMicro.cross_region_inference_id("eu-north-1")?,
+            Model::AmazonNovaMicro.cross_region_inference_id("eu-north-1", false)?,
             "eu.amazon.nova-micro-v1:0"
         );
         Ok(())
@@ -745,15 +806,15 @@ mod tests {
     fn test_apac_region_inference_ids() -> anyhow::Result<()> {
         // Test Asia-Pacific regions
         assert_eq!(
-            Model::Claude3_5SonnetV2.cross_region_inference_id("ap-northeast-1")?,
+            Model::Claude3_5SonnetV2.cross_region_inference_id("ap-northeast-1", false)?,
             "apac.anthropic.claude-3-5-sonnet-20241022-v2:0"
         );
         assert_eq!(
-            Model::Claude3_5SonnetV2.cross_region_inference_id("ap-southeast-2")?,
+            Model::Claude3_5SonnetV2.cross_region_inference_id("ap-southeast-2", false)?,
             "apac.anthropic.claude-3-5-sonnet-20241022-v2:0"
         );
         assert_eq!(
-            Model::AmazonNovaLite.cross_region_inference_id("ap-south-1")?,
+            Model::AmazonNovaLite.cross_region_inference_id("ap-south-1", false)?,
             "apac.amazon.nova-lite-v1:0"
         );
         Ok(())
@@ -763,11 +824,11 @@ mod tests {
     fn test_gov_region_inference_ids() -> anyhow::Result<()> {
         // Test Government regions
         assert_eq!(
-            Model::Claude3_5Sonnet.cross_region_inference_id("us-gov-east-1")?,
+            Model::Claude3_5Sonnet.cross_region_inference_id("us-gov-east-1", false)?,
             "us-gov.anthropic.claude-3-5-sonnet-20240620-v1:0"
         );
         assert_eq!(
-            Model::Claude3Haiku.cross_region_inference_id("us-gov-west-1")?,
+            Model::Claude3Haiku.cross_region_inference_id("us-gov-west-1", false)?,
             "us-gov.anthropic.claude-3-haiku-20240307-v1:0"
         );
         Ok(())
@@ -777,15 +838,15 @@ mod tests {
     fn test_meta_models_inference_ids() -> anyhow::Result<()> {
         // Test Meta models
         assert_eq!(
-            Model::MetaLlama370BInstructV1.cross_region_inference_id("us-east-1")?,
+            Model::MetaLlama370BInstructV1.cross_region_inference_id("us-east-1", false)?,
             "meta.llama3-70b-instruct-v1:0"
         );
         assert_eq!(
-            Model::MetaLlama3170BInstructV1.cross_region_inference_id("us-east-1")?,
+            Model::MetaLlama3170BInstructV1.cross_region_inference_id("us-east-1", false)?,
             "us.meta.llama3-1-70b-instruct-v1:0"
         );
         assert_eq!(
-            Model::MetaLlama321BInstructV1.cross_region_inference_id("eu-west-1")?,
+            Model::MetaLlama321BInstructV1.cross_region_inference_id("eu-west-1", false)?,
             "eu.meta.llama3-2-1b-instruct-v1:0"
         );
         Ok(())
@@ -796,11 +857,11 @@ mod tests {
         // Mistral models don't follow the regional prefix pattern,
         // so they should return their original IDs
         assert_eq!(
-            Model::MistralMistralLarge2402V1.cross_region_inference_id("us-east-1")?,
+            Model::MistralMistralLarge2402V1.cross_region_inference_id("us-east-1", false)?,
             "mistral.mistral-large-2402-v1:0"
         );
         assert_eq!(
-            Model::MistralMixtral8x7BInstructV0.cross_region_inference_id("eu-west-1")?,
+            Model::MistralMixtral8x7BInstructV0.cross_region_inference_id("eu-west-1", false)?,
             "mistral.mixtral-8x7b-instruct-v0:1"
         );
         Ok(())
@@ -811,11 +872,11 @@ mod tests {
         // AI21 models don't follow the regional prefix pattern,
         // so they should return their original IDs
         assert_eq!(
-            Model::AI21J2UltraV1.cross_region_inference_id("us-east-1")?,
+            Model::AI21J2UltraV1.cross_region_inference_id("us-east-1", false)?,
             "ai21.j2-ultra-v1"
         );
         assert_eq!(
-            Model::AI21JambaInstructV1.cross_region_inference_id("eu-west-1")?,
+            Model::AI21JambaInstructV1.cross_region_inference_id("eu-west-1", false)?,
             "ai21.jamba-instruct-v1:0"
         );
         Ok(())
@@ -826,11 +887,11 @@ mod tests {
         // Cohere models don't follow the regional prefix pattern,
         // so they should return their original IDs
         assert_eq!(
-            Model::CohereCommandRV1.cross_region_inference_id("us-east-1")?,
+            Model::CohereCommandRV1.cross_region_inference_id("us-east-1", false)?,
             "cohere.command-r-v1:0"
         );
         assert_eq!(
-            Model::CohereCommandTextV14_4k.cross_region_inference_id("ap-southeast-1")?,
+            Model::CohereCommandTextV14_4k.cross_region_inference_id("ap-southeast-1", false)?,
             "cohere.command-text-v14:7:4k"
         );
         Ok(())
@@ -850,10 +911,17 @@ mod tests {
 
         // Custom model should return its name unchanged
         assert_eq!(
-            custom_model.cross_region_inference_id("us-east-1")?,
+            custom_model.cross_region_inference_id("us-east-1", false)?,
             "custom.my-model-v1:0"
         );
 
+        // Test that models without global support fall back to regional when allow_global is true
+        assert_eq!(
+            Model::AmazonNovaPro.cross_region_inference_id("us-east-1", true)?,
+            "us.amazon.nova-pro-v1:0",
+            "Nova Pro should fall back to regional profile even when allow_global is true"
+        );
+
         Ok(())
     }
 
@@ -892,3 +960,28 @@ mod tests {
         );
     }
 }
+
+#[test]
+fn test_global_inference_ids() -> anyhow::Result<()> {
+    // Test global inference for models that support it when allow_global is true
+    assert_eq!(
+        Model::ClaudeSonnet4.cross_region_inference_id("us-east-1", true)?,
+        "global.anthropic.claude-sonnet-4-20250514-v1:0"
+    );
+    assert_eq!(
+        Model::ClaudeSonnet4_5.cross_region_inference_id("eu-west-1", true)?,
+        "global.anthropic.claude-sonnet-4-5-20250929-v1:0"
+    );
+    assert_eq!(
+        Model::ClaudeHaiku4_5.cross_region_inference_id("ap-south-1", true)?,
+        "global.anthropic.claude-haiku-4-5-20251001-v1:0"
+    );
+
+    // Test that regional prefix is used when allow_global is false
+    assert_eq!(
+        Model::ClaudeSonnet4.cross_region_inference_id("us-east-1", false)?,
+        "us.anthropic.claude-sonnet-4-20250514-v1:0"
+    );
+
+    Ok(())
+}

crates/buffer_diff/src/buffer_diff.rs 🔗

@@ -212,6 +212,12 @@ impl BufferDiffSnapshot {
         self.inner.hunks.is_empty()
     }
 
+    pub fn base_text_string(&self) -> Option<String> {
+        self.inner
+            .base_text_exists
+            .then(|| self.inner.base_text.text())
+    }
+
     pub fn secondary_diff(&self) -> Option<&BufferDiffSnapshot> {
         self.secondary_diff.as_deref()
     }
@@ -1206,6 +1212,34 @@ impl BufferDiff {
         new_index_text
     }
 
+    pub fn stage_or_unstage_all_hunks(
+        &mut self,
+        stage: bool,
+        buffer: &text::BufferSnapshot,
+        file_exists: bool,
+        cx: &mut Context<Self>,
+    ) {
+        let hunks = self
+            .snapshot(cx)
+            .hunks_intersecting_range(Anchor::MIN..Anchor::MAX, buffer)
+            .collect::<Vec<_>>();
+        let Some(secondary) = self.secondary_diff.clone() else {
+            return;
+        };
+        let secondary = secondary.read(cx).inner.clone();
+        self.inner
+            .stage_or_unstage_hunks_impl(&secondary, stage, &hunks, buffer, file_exists, cx);
+        if let Some((first, last)) = hunks.first().zip(hunks.last()) {
+            let changed_range = first.buffer_range.start..last.buffer_range.end;
+            let base_text_changed_range =
+                first.diff_base_byte_range.start..last.diff_base_byte_range.end;
+            cx.emit(BufferDiffEvent::DiffChanged {
+                changed_range: Some(changed_range),
+                base_text_changed_range: Some(base_text_changed_range),
+            });
+        }
+    }
+
     pub fn update_diff(
         &self,
         buffer: text::BufferSnapshot,
@@ -2164,7 +2198,7 @@ mod tests {
             Point::new(0, 0)..Point::new(10, 0)
         );
 
-        // Edit does not affect the diff.
+        // Edit does affects the diff because it recalculates word diffs.
         buffer.edit_via_marked_text(
             &"
                 one
@@ -2179,9 +2213,15 @@ mod tests {
             .unindent(),
         );
         let diff_2 = BufferDiffSnapshot::new_sync(buffer.clone(), base_text.clone(), cx);
+        let (range, base_text_range) =
+            compare_hunks(&diff_1.inner.hunks, &empty_diff.inner.hunks, &buffer);
+        assert_eq!(
+            range.unwrap().to_point(&buffer),
+            Point::new(4, 0)..Point::new(5, 0),
+        );
         assert_eq!(
-            (None, None),
-            compare_hunks(&diff_2.inner.hunks, &diff_1.inner.hunks, &buffer)
+            base_text_range.unwrap().to_point(diff_2.base_text()),
+            Point::new(0, 0)..Point::new(0, 0),
         );
 
         // Edit turns a deletion hunk into a modification.

crates/call/src/call_impl/room.rs 🔗

@@ -305,6 +305,7 @@ impl Room {
 
     pub(crate) fn leave(&mut self, cx: &mut Context<Self>) -> Task<Result<()>> {
         cx.notify();
+        self.emit_video_track_unsubscribed_events(cx);
         self.leave_internal(cx)
     }
 
@@ -352,6 +353,14 @@ impl Room {
         self.maintain_connection.take();
     }
 
+    fn emit_video_track_unsubscribed_events(&self, cx: &mut Context<Self>) {
+        for participant in self.remote_participants.values() {
+            for sid in participant.video_tracks.keys() {
+                cx.emit(Event::RemoteVideoTrackUnsubscribed { sid: sid.clone() });
+            }
+        }
+    }
+
     async fn maintain_connection(
         this: WeakEntity<Self>,
         client: Arc<Client>,
@@ -882,6 +891,9 @@ impl Room {
                                     project_id: project.id,
                                 });
                             }
+                            for sid in participant.video_tracks.keys() {
+                                cx.emit(Event::RemoteVideoTrackUnsubscribed { sid: sid.clone() });
+                            }
                             false
                         }
                     });

crates/cli/src/main.rs 🔗

@@ -32,7 +32,7 @@ struct Detect;
 
 trait InstalledApp {
     fn zed_version_string(&self) -> String;
-    fn launch(&self, ipc_url: String) -> anyhow::Result<()>;
+    fn launch(&self, ipc_url: String, user_data_dir: Option<&str>) -> anyhow::Result<()>;
     fn run_foreground(
         &self,
         ipc_url: String,
@@ -61,6 +61,8 @@ Examples:
 )]
 struct Args {
     /// Wait for all of the given paths to be opened/closed before exiting.
+    ///
+    /// When opening a directory, waits until the created window is closed.
     #[arg(short, long)]
     wait: bool,
     /// Add files to the currently open workspace
@@ -588,7 +590,7 @@ fn main() -> Result<()> {
     if args.foreground {
         app.run_foreground(url, user_data_dir.as_deref())?;
     } else {
-        app.launch(url)?;
+        app.launch(url, user_data_dir.as_deref())?;
         sender.join().unwrap()?;
         if let Some(handle) = stdin_pipe_handle {
             handle.join().unwrap()?;
@@ -709,14 +711,18 @@ mod linux {
             )
         }
 
-        fn launch(&self, ipc_url: String) -> anyhow::Result<()> {
-            let sock_path = paths::data_dir().join(format!(
+        fn launch(&self, ipc_url: String, user_data_dir: Option<&str>) -> anyhow::Result<()> {
+            let data_dir = user_data_dir
+                .map(PathBuf::from)
+                .unwrap_or_else(|| paths::data_dir().clone());
+
+            let sock_path = data_dir.join(format!(
                 "zed-{}.sock",
                 *release_channel::RELEASE_CHANNEL_NAME
             ));
             let sock = UnixDatagram::unbound()?;
             if sock.connect(&sock_path).is_err() {
-                self.boot_background(ipc_url)?;
+                self.boot_background(ipc_url, user_data_dir)?;
             } else {
                 sock.send(ipc_url.as_bytes())?;
             }
@@ -742,7 +748,11 @@ mod linux {
     }
 
     impl App {
-        fn boot_background(&self, ipc_url: String) -> anyhow::Result<()> {
+        fn boot_background(
+            &self,
+            ipc_url: String,
+            user_data_dir: Option<&str>,
+        ) -> anyhow::Result<()> {
             let path = &self.0;
 
             match fork::fork() {
@@ -756,8 +766,13 @@ mod linux {
                     if fork::close_fd().is_err() {
                         eprintln!("failed to close_fd: {}", std::io::Error::last_os_error());
                     }
-                    let error =
-                        exec::execvp(path.clone(), &[path.as_os_str(), &OsString::from(ipc_url)]);
+                    let mut args: Vec<OsString> =
+                        vec![path.as_os_str().to_owned(), OsString::from(ipc_url)];
+                    if let Some(dir) = user_data_dir {
+                        args.push(OsString::from("--user-data-dir"));
+                        args.push(OsString::from(dir));
+                    }
+                    let error = exec::execvp(path.clone(), &args);
                     // if exec succeeded, we never get here.
                     eprintln!("failed to exec {:?}: {}", path, error);
                     process::exit(1)
@@ -943,11 +958,14 @@ mod windows {
             )
         }
 
-        fn launch(&self, ipc_url: String) -> anyhow::Result<()> {
+        fn launch(&self, ipc_url: String, user_data_dir: Option<&str>) -> anyhow::Result<()> {
             if check_single_instance() {
-                std::process::Command::new(self.0.clone())
-                    .arg(ipc_url)
-                    .spawn()?;
+                let mut cmd = std::process::Command::new(self.0.clone());
+                cmd.arg(ipc_url);
+                if let Some(dir) = user_data_dir {
+                    cmd.arg("--user-data-dir").arg(dir);
+                }
+                cmd.spawn()?;
             } else {
                 unsafe {
                     let pipe = CreateFileW(
@@ -1096,7 +1114,7 @@ mod mac_os {
             format!("Zed {} – {}", self.version(), self.path().display(),)
         }
 
-        fn launch(&self, url: String) -> anyhow::Result<()> {
+        fn launch(&self, url: String, user_data_dir: Option<&str>) -> anyhow::Result<()> {
             match self {
                 Self::App { app_bundle, .. } => {
                     let app_path = app_bundle;
@@ -1146,8 +1164,11 @@ mod mac_os {
                             format!("Cloning descriptor for file {subprocess_stdout_file:?}")
                         })?;
                     let mut command = std::process::Command::new(executable);
-                    let command = command
-                        .env(FORCE_CLI_MODE_ENV_VAR_NAME, "")
+                    command.env(FORCE_CLI_MODE_ENV_VAR_NAME, "");
+                    if let Some(dir) = user_data_dir {
+                        command.arg("--user-data-dir").arg(dir);
+                    }
+                    command
                         .stderr(subprocess_stdout_file)
                         .stdout(subprocess_stdin_file)
                         .arg(url);

crates/client/Cargo.toml 🔗

@@ -53,7 +53,7 @@ text.workspace = true
 thiserror.workspace = true
 time.workspace = true
 tiny_http.workspace = true
-tokio-socks = { version = "0.5.2", default-features = false, features = ["futures-io"] }
+tokio-socks.workspace = true
 tokio.workspace = true
 url.workspace = true
 util.workspace = true

crates/client/src/client.rs 🔗

@@ -150,9 +150,8 @@ pub fn init(client: &Arc<Client>, cx: &mut App) {
                     .detach_and_log_err(cx);
             }
         }
-    });
-
-    cx.on_action({
+    })
+    .on_action({
         let client = client.clone();
         move |_: &SignOut, cx| {
             if let Some(client) = client.upgrade() {
@@ -162,9 +161,8 @@ pub fn init(client: &Arc<Client>, cx: &mut App) {
                 .detach();
             }
         }
-    });
-
-    cx.on_action({
+    })
+    .on_action({
         let client = client;
         move |_: &Reconnect, cx| {
             if let Some(client) = client.upgrade() {
@@ -1723,28 +1721,68 @@ impl ProtoClient for Client {
     fn is_via_collab(&self) -> bool {
         true
     }
+
+    fn has_wsl_interop(&self) -> bool {
+        false
+    }
 }
 
 /// prefix for the zed:// url scheme
 pub const ZED_URL_SCHEME: &str = "zed";
 
+/// A parsed Zed link that can be handled internally by the application.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum ZedLink {
+    /// Join a channel: `zed.dev/channel/channel-name-123` or `zed://channel/channel-name-123`
+    Channel { channel_id: u64 },
+    /// Open channel notes: `zed.dev/channel/channel-name-123/notes` or with heading `notes#heading`
+    ChannelNotes {
+        channel_id: u64,
+        heading: Option<String>,
+    },
+}
+
 /// Parses the given link into a Zed link.
 ///
-/// Returns a [`Some`] containing the unprefixed link if the link is a Zed link.
-/// Returns [`None`] otherwise.
-pub fn parse_zed_link<'a>(link: &'a str, cx: &App) -> Option<&'a str> {
+/// Returns a [`Some`] containing the parsed link if the link is a recognized Zed link
+/// that should be handled internally by the application.
+/// Returns [`None`] for links that should be opened in the browser.
+pub fn parse_zed_link(link: &str, cx: &App) -> Option<ZedLink> {
     let server_url = &ClientSettings::get_global(cx).server_url;
-    if let Some(stripped) = link
+    let path = link
         .strip_prefix(server_url)
         .and_then(|result| result.strip_prefix('/'))
-    {
-        return Some(stripped);
+        .or_else(|| {
+            link.strip_prefix(ZED_URL_SCHEME)
+                .and_then(|result| result.strip_prefix("://"))
+        })?;
+
+    let mut parts = path.split('/');
+
+    if parts.next() != Some("channel") {
+        return None;
     }
-    if let Some(stripped) = link
-        .strip_prefix(ZED_URL_SCHEME)
-        .and_then(|result| result.strip_prefix("://"))
-    {
-        return Some(stripped);
+
+    let slug = parts.next()?;
+    let id_str = slug.split('-').next_back()?;
+    let channel_id = id_str.parse::<u64>().ok()?;
+
+    let Some(next) = parts.next() else {
+        return Some(ZedLink::Channel { channel_id });
+    };
+
+    if let Some(heading) = next.strip_prefix("notes#") {
+        return Some(ZedLink::ChannelNotes {
+            channel_id,
+            heading: Some(heading.to_string()),
+        });
+    }
+
+    if next == "notes" {
+        return Some(ZedLink::ChannelNotes {
+            channel_id,
+            heading: None,
+        });
     }
 
     None

crates/cloud_llm_client/src/cloud_llm_client.rs 🔗

@@ -371,6 +371,8 @@ pub struct LanguageModel {
     pub supports_images: bool,
     pub supports_thinking: bool,
     pub supports_max_mode: bool,
+    #[serde(default)]
+    pub supports_streaming_tools: bool,
     // only used by OpenAI and xAI
     #[serde(default)]
     pub supports_parallel_tool_calls: bool,

crates/cloud_llm_client/src/predict_edits_v3.rs 🔗

@@ -31,18 +31,10 @@ pub struct PredictEditsRequest {
     /// Within `signatures`
     pub excerpt_parent: Option<usize>,
     #[serde(skip_serializing_if = "Vec::is_empty", default)]
-    pub included_files: Vec<IncludedFile>,
-    #[serde(skip_serializing_if = "Vec::is_empty", default)]
-    pub signatures: Vec<Signature>,
-    #[serde(skip_serializing_if = "Vec::is_empty", default)]
-    pub referenced_declarations: Vec<ReferencedDeclaration>,
+    pub related_files: Vec<RelatedFile>,
     pub events: Vec<Arc<Event>>,
     #[serde(default)]
     pub can_collect_data: bool,
-    #[serde(skip_serializing_if = "Vec::is_empty", default)]
-    pub diagnostic_groups: Vec<DiagnosticGroup>,
-    #[serde(skip_serializing_if = "is_default", default)]
-    pub diagnostic_groups_truncated: bool,
     /// Info about the git repository state, only present when can_collect_data is true.
     #[serde(skip_serializing_if = "Option::is_none", default)]
     pub git_info: Option<PredictEditsGitInfo>,
@@ -58,7 +50,7 @@ pub struct PredictEditsRequest {
 }
 
 #[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct IncludedFile {
+pub struct RelatedFile {
     pub path: Arc<Path>,
     pub max_row: Line,
     pub excerpts: Vec<Excerpt>,
@@ -72,11 +64,9 @@ pub struct Excerpt {
 
 #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, EnumIter)]
 pub enum PromptFormat {
-    MarkedExcerpt,
-    LabeledSections,
-    NumLinesUniDiff,
+    /// XML old_tex/new_text
     OldTextNewText,
-    /// Prompt format intended for use via zeta_cli
+    /// Prompt format intended for use via edit_prediction_cli
     OnlySnippets,
     /// One-sentence instructions used in fine-tuned models
     Minimal,
@@ -87,7 +77,7 @@ pub enum PromptFormat {
 }
 
 impl PromptFormat {
-    pub const DEFAULT: PromptFormat = PromptFormat::NumLinesUniDiff;
+    pub const DEFAULT: PromptFormat = PromptFormat::Minimal;
 }
 
 impl Default for PromptFormat {
@@ -105,10 +95,7 @@ impl PromptFormat {
 impl std::fmt::Display for PromptFormat {
     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
         match self {
-            PromptFormat::MarkedExcerpt => write!(f, "Marked Excerpt"),
-            PromptFormat::LabeledSections => write!(f, "Labeled Sections"),
             PromptFormat::OnlySnippets => write!(f, "Only Snippets"),
-            PromptFormat::NumLinesUniDiff => write!(f, "Numbered Lines / Unified Diff"),
             PromptFormat::OldTextNewText => write!(f, "Old Text / New Text"),
             PromptFormat::Minimal => write!(f, "Minimal"),
             PromptFormat::MinimalQwen => write!(f, "Minimal + Qwen FIM"),
@@ -178,67 +165,6 @@ impl<'a> std::fmt::Display for DiffPathFmt<'a> {
     }
 }
 
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct Signature {
-    pub text: String,
-    pub text_is_truncated: bool,
-    #[serde(skip_serializing_if = "Option::is_none", default)]
-    pub parent_index: Option<usize>,
-    /// Range of `text` within the file, possibly truncated according to `text_is_truncated`. The
-    /// file is implicitly the file that contains the descendant declaration or excerpt.
-    pub range: Range<Line>,
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct ReferencedDeclaration {
-    pub path: Arc<Path>,
-    pub text: String,
-    pub text_is_truncated: bool,
-    /// Range of `text` within file, possibly truncated according to `text_is_truncated`
-    pub range: Range<Line>,
-    /// Range within `text`
-    pub signature_range: Range<usize>,
-    /// Index within `signatures`.
-    #[serde(skip_serializing_if = "Option::is_none", default)]
-    pub parent_index: Option<usize>,
-    pub score_components: DeclarationScoreComponents,
-    pub signature_score: f32,
-    pub declaration_score: f32,
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct DeclarationScoreComponents {
-    pub is_same_file: bool,
-    pub is_referenced_nearby: bool,
-    pub is_referenced_in_breadcrumb: bool,
-    pub reference_count: usize,
-    pub same_file_declaration_count: usize,
-    pub declaration_count: usize,
-    pub reference_line_distance: u32,
-    pub declaration_line_distance: u32,
-    pub excerpt_vs_item_jaccard: f32,
-    pub excerpt_vs_signature_jaccard: f32,
-    pub adjacent_vs_item_jaccard: f32,
-    pub adjacent_vs_signature_jaccard: f32,
-    pub excerpt_vs_item_weighted_overlap: f32,
-    pub excerpt_vs_signature_weighted_overlap: f32,
-    pub adjacent_vs_item_weighted_overlap: f32,
-    pub adjacent_vs_signature_weighted_overlap: f32,
-    pub path_import_match_count: usize,
-    pub wildcard_path_import_match_count: usize,
-    pub import_similarity: f32,
-    pub max_import_similarity: f32,
-    pub normalized_import_similarity: f32,
-    pub wildcard_import_similarity: f32,
-    pub normalized_wildcard_import_similarity: f32,
-    pub included_by_others: usize,
-    pub includes_others: usize,
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize)]
-#[serde(transparent)]
-pub struct DiagnosticGroup(pub Box<serde_json::value::RawValue>);
-
 #[derive(Debug, Clone, Serialize, Deserialize)]
 pub struct PredictEditsResponse {
     pub request_id: Uuid,
@@ -262,10 +188,6 @@ pub struct Edit {
     pub content: String,
 }
 
-fn is_default<T: Default + PartialEq>(value: &T) -> bool {
-    *value == T::default()
-}
-
 #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, PartialOrd, Eq, Ord)]
 pub struct Point {
     pub line: Line,

crates/cloud_zeta2_prompt/Cargo.toml 🔗

@@ -1,23 +0,0 @@
-[package]
-name = "cloud_zeta2_prompt"
-version = "0.1.0"
-publish.workspace = true
-edition.workspace = true
-license = "GPL-3.0-or-later"
-
-[lints]
-workspace = true
-
-[lib]
-path = "src/cloud_zeta2_prompt.rs"
-
-[dependencies]
-anyhow.workspace = true
-cloud_llm_client.workspace = true
-indoc.workspace = true
-ordered-float.workspace = true
-rustc-hash.workspace = true
-schemars.workspace = true
-serde.workspace = true
-serde_json.workspace = true
-strum.workspace = true

crates/cloud_zeta2_prompt/src/cloud_zeta2_prompt.rs 🔗

@@ -1,1075 +0,0 @@
-//! Zeta2 prompt planning and generation code shared with cloud.
-pub mod retrieval_prompt;
-
-use anyhow::{Context as _, Result, anyhow};
-use cloud_llm_client::predict_edits_v3::{
-    self, DiffPathFmt, Event, Excerpt, IncludedFile, Line, Point, PromptFormat,
-    ReferencedDeclaration,
-};
-use indoc::indoc;
-use ordered_float::OrderedFloat;
-use rustc_hash::{FxHashMap, FxHashSet};
-use serde::Serialize;
-use std::cmp;
-use std::fmt::Write;
-use std::sync::Arc;
-use std::{cmp::Reverse, collections::BinaryHeap, ops::Range, path::Path};
-use strum::{EnumIter, IntoEnumIterator};
-
-pub const DEFAULT_MAX_PROMPT_BYTES: usize = 10 * 1024;
-
-pub const CURSOR_MARKER: &str = "<|user_cursor|>";
-/// NOTE: Differs from zed version of constant - includes a newline
-pub const EDITABLE_REGION_START_MARKER_WITH_NEWLINE: &str = "<|editable_region_start|>\n";
-/// NOTE: Differs from zed version of constant - includes a newline
-pub const EDITABLE_REGION_END_MARKER_WITH_NEWLINE: &str = "<|editable_region_end|>\n";
-
-// TODO: use constants for markers?
-const MARKED_EXCERPT_INSTRUCTIONS: &str = indoc! {"
-    You are a code completion assistant and your task is to analyze user edits and then rewrite an excerpt that the user provides, suggesting the appropriate edits within the excerpt, taking into account the cursor location.
-
-    The excerpt to edit will be wrapped in markers <|editable_region_start|> and <|editable_region_end|>. The cursor position is marked with <|user_cursor|>.  Please respond with edited code for that region.
-
-    Other code is provided for context, and `…` indicates when code has been skipped.
-
-    ## Edit History
-
-"};
-
-const LABELED_SECTIONS_INSTRUCTIONS: &str = indoc! {r#"
-    You are a code completion assistant and your task is to analyze user edits, and suggest an edit to one of the provided sections of code.
-
-    Sections of code are grouped by file and then labeled by `<|section_N|>` (e.g `<|section_8|>`).
-
-    The cursor position is marked with `<|user_cursor|>` and it will appear within a special section labeled `<|current_section|>`. Prefer editing the current section until no more changes are needed within it.
-
-    Respond ONLY with the name of the section to edit on a single line, followed by all of the code that should replace that section. For example:
-
-    <|current_section|>
-    for i in 0..16 {
-        println!("{i}");
-    }
-
-    ## Edit History
-
-"#};
-
-const NUMBERED_LINES_INSTRUCTIONS: &str = indoc! {r#"
-    # Instructions
-
-    You are an edit prediction agent in a code editor.
-    Your job is to predict the next edit that the user will make,
-    based on their last few edits and their current cursor location.
-
-    ## Output Format
-
-    You must briefly explain your understanding of the user's goal, in one
-    or two sentences, and then specify their next edit in the form of a
-    unified diff, like this:
-
-    ```
-    --- a/src/myapp/cli.py
-    +++ b/src/myapp/cli.py
-    @@ ... @@
-     import os
-     import time
-     import sys
-    +from constants import LOG_LEVEL_WARNING
-    @@ ... @@
-     config.headless()
-     config.set_interactive(false)
-    -config.set_log_level(LOG_L)
-    +config.set_log_level(LOG_LEVEL_WARNING)
-     config.set_use_color(True)
-    ```
-
-    ## Edit History
-
-"#};
-
-const STUDENT_MODEL_INSTRUCTIONS: &str = indoc! {r#"
-    You are a code completion assistant that analyzes edit history to identify and systematically complete incomplete refactorings or patterns across the entire codebase.
-
-    ## Edit History
-
-    "#};
-
-const UNIFIED_DIFF_REMINDER: &str = indoc! {"
-    ---
-
-    Analyze the edit history and the files, then provide the unified diff for your predicted edits.
-    Do not include the cursor marker in your output.
-    Your diff should include edited file paths in its file headers (lines beginning with `---` and `+++`).
-    Do not include line numbers in the hunk headers, use `@@ ... @@`.
-    Removed lines begin with `-`.
-    Added lines begin with `+`.
-    Context lines begin with an extra space.
-    Context and removed lines are used to match the target edit location, so make sure to include enough of them
-    to uniquely identify it amongst all excerpts of code provided.
-"};
-
-const MINIMAL_PROMPT_REMINDER: &str = indoc! {"
-    ---
-
-    Please analyze the edit history and the files, then provide the unified diff for your predicted edits.
-    Do not include the cursor marker in your output.
-    If you're editing multiple files, be sure to reflect filename in the hunk's header.
-    "};
-
-const XML_TAGS_INSTRUCTIONS: &str = indoc! {r#"
-    # Instructions
-
-    You are an edit prediction agent in a code editor.
-
-    Analyze the history of edits made by the user in order to infer what they are currently trying to accomplish.
-    Then complete the remainder of the current change if it is incomplete, or predict the next edit the user intends to make.
-    Always continue along the user's current trajectory, rather than changing course.
-
-    ## Output Format
-
-    You should briefly explain your understanding of the user's overall goal in one sentence, then explain what the next change
-    along the users current trajectory will be in another, and finally specify the next edit using the following XML-like format:
-
-    <edits path="my-project/src/myapp/cli.py">
-    <old_text>
-    OLD TEXT 1 HERE
-    </old_text>
-    <new_text>
-    NEW TEXT 1 HERE
-    </new_text>
-
-    <old_text>
-    OLD TEXT 1 HERE
-    </old_text>
-    <new_text>
-    NEW TEXT 1 HERE
-    </new_text>
-    </edits>
-
-    - Specify the file to edit using the `path` attribute.
-    - Use `<old_text>` and `<new_text>` tags to replace content
-    - `<old_text>` must exactly match existing file content, including indentation
-    - `<old_text>` cannot be empty
-    - Do not escape quotes, newlines, or other characters within tags
-    - Always close all tags properly
-    - Don't include the <|user_cursor|> marker in your output.
-
-    ## Edit History
-
-"#};
-
-const OLD_TEXT_NEW_TEXT_REMINDER: &str = indoc! {r#"
-    ---
-
-    Remember that the edits in the edit history have already been applied.
-"#};
-
-pub fn build_prompt(
-    request: &predict_edits_v3::PredictEditsRequest,
-) -> Result<(String, SectionLabels)> {
-    let mut section_labels = Default::default();
-
-    let prompt_data = PromptData {
-        events: request.events.clone(),
-        cursor_point: request.cursor_point,
-        cursor_path: request.excerpt_path.clone(),
-        included_files: request.included_files.clone(),
-    };
-    match request.prompt_format {
-        PromptFormat::MinimalQwen => {
-            return Ok((MinimalQwenPrompt.render(&prompt_data), section_labels));
-        }
-        PromptFormat::SeedCoder1120 => {
-            return Ok((SeedCoder1120Prompt.render(&prompt_data), section_labels));
-        }
-        _ => (),
-    };
-
-    let mut insertions = match request.prompt_format {
-        PromptFormat::MarkedExcerpt => vec![
-            (
-                Point {
-                    line: request.excerpt_line_range.start,
-                    column: 0,
-                },
-                EDITABLE_REGION_START_MARKER_WITH_NEWLINE,
-            ),
-            (request.cursor_point, CURSOR_MARKER),
-            (
-                Point {
-                    line: request.excerpt_line_range.end,
-                    column: 0,
-                },
-                EDITABLE_REGION_END_MARKER_WITH_NEWLINE,
-            ),
-        ],
-        PromptFormat::LabeledSections
-        | PromptFormat::NumLinesUniDiff
-        | PromptFormat::Minimal
-        | PromptFormat::OldTextNewText => {
-            vec![(request.cursor_point, CURSOR_MARKER)]
-        }
-        PromptFormat::OnlySnippets => vec![],
-        PromptFormat::MinimalQwen => unreachable!(),
-        PromptFormat::SeedCoder1120 => unreachable!(),
-    };
-
-    let mut prompt = match request.prompt_format {
-        PromptFormat::MarkedExcerpt => MARKED_EXCERPT_INSTRUCTIONS.to_string(),
-        PromptFormat::LabeledSections => LABELED_SECTIONS_INSTRUCTIONS.to_string(),
-        PromptFormat::NumLinesUniDiff => NUMBERED_LINES_INSTRUCTIONS.to_string(),
-        PromptFormat::OldTextNewText => XML_TAGS_INSTRUCTIONS.to_string(),
-        PromptFormat::OnlySnippets => String::new(),
-        PromptFormat::Minimal => STUDENT_MODEL_INSTRUCTIONS.to_string(),
-        PromptFormat::MinimalQwen => unreachable!(),
-        PromptFormat::SeedCoder1120 => unreachable!(),
-    };
-
-    if request.events.is_empty() {
-        prompt.push_str("(No edit history)\n\n");
-    } else {
-        let edit_preamble = if request.prompt_format == PromptFormat::Minimal {
-            "The following are the latest edits made by the user, from earlier to later.\n\n"
-        } else {
-            "Here are the latest edits made by the user, from earlier to later.\n\n"
-        };
-        prompt.push_str(edit_preamble);
-        push_events(&mut prompt, &request.events);
-    }
-
-    let excerpts_preamble = match request.prompt_format {
-        PromptFormat::Minimal => indoc! {"
-             ## Part of the file under the cursor
-
-             (The cursor marker <|user_cursor|> indicates the current user cursor position.
-             The file is in current state, edits from edit history has been applied.
-             We only show part of the file around the cursor.
-             You can only edit exactly this part of the file.
-             We prepend line numbers (e.g., `123|<actual line>`); they are not part of the file.)
-             "},
-        PromptFormat::NumLinesUniDiff | PromptFormat::OldTextNewText => indoc! {"
-            ## Code Excerpts
-
-            Here is some excerpts of code that you should take into account to predict the next edit.
-
-            The cursor position is marked by `<|user_cursor|>` as it stands after the last edit in the history.
-
-            In addition other excerpts are included to better understand what the edit will be, including the declaration
-            or references of symbols around the cursor, or other similar code snippets that may need to be updated
-            following patterns that appear in the edit history.
-
-            Consider each of them carefully in relation to the edit history, and that the user may not have navigated
-            to the next place they want to edit yet.
-
-            Lines starting with `…` indicate omitted line ranges. These may appear inside multi-line code constructs.
-        "},
-        _ => indoc! {"
-            ## Code Excerpts
-
-            The cursor marker <|user_cursor|> indicates the current user cursor position.
-            The file is in current state, edits from edit history have been applied.
-        "},
-    };
-
-    prompt.push_str(excerpts_preamble);
-    prompt.push('\n');
-
-    if !request.referenced_declarations.is_empty() || !request.signatures.is_empty() {
-        let syntax_based_prompt = SyntaxBasedPrompt::populate(request)?;
-        section_labels = syntax_based_prompt.write(&mut insertions, &mut prompt)?;
-    } else {
-        if request.prompt_format == PromptFormat::LabeledSections {
-            anyhow::bail!("PromptFormat::LabeledSections cannot be used with ContextMode::Llm");
-        }
-
-        let include_line_numbers = matches!(
-            request.prompt_format,
-            PromptFormat::NumLinesUniDiff | PromptFormat::Minimal
-        );
-        for related_file in &request.included_files {
-            if request.prompt_format == PromptFormat::Minimal {
-                write_codeblock_with_filename(
-                    &related_file.path,
-                    &related_file.excerpts,
-                    if related_file.path == request.excerpt_path {
-                        &insertions
-                    } else {
-                        &[]
-                    },
-                    related_file.max_row,
-                    include_line_numbers,
-                    &mut prompt,
-                );
-            } else {
-                write_codeblock(
-                    &related_file.path,
-                    &related_file.excerpts,
-                    if related_file.path == request.excerpt_path {
-                        &insertions
-                    } else {
-                        &[]
-                    },
-                    related_file.max_row,
-                    include_line_numbers,
-                    &mut prompt,
-                );
-            }
-        }
-    }
-
-    match request.prompt_format {
-        PromptFormat::NumLinesUniDiff => {
-            prompt.push_str(UNIFIED_DIFF_REMINDER);
-        }
-        PromptFormat::OldTextNewText => {
-            prompt.push_str(OLD_TEXT_NEW_TEXT_REMINDER);
-        }
-        PromptFormat::Minimal => {
-            prompt.push_str(MINIMAL_PROMPT_REMINDER);
-        }
-        _ => {}
-    }
-
-    Ok((prompt, section_labels))
-}
-
-pub fn generation_params(prompt_format: PromptFormat) -> GenerationParams {
-    match prompt_format {
-        PromptFormat::SeedCoder1120 => SeedCoder1120Prompt::generation_params(),
-        _ => GenerationParams::default(),
-    }
-}
-
-pub fn write_codeblock<'a>(
-    path: &Path,
-    excerpts: impl IntoIterator<Item = &'a Excerpt>,
-    sorted_insertions: &[(Point, &str)],
-    file_line_count: Line,
-    include_line_numbers: bool,
-    output: &'a mut String,
-) {
-    writeln!(output, "`````{}", DiffPathFmt(path)).unwrap();
-
-    write_excerpts(
-        excerpts,
-        sorted_insertions,
-        file_line_count,
-        include_line_numbers,
-        output,
-    );
-    write!(output, "`````\n\n").unwrap();
-}
-
-fn write_codeblock_with_filename<'a>(
-    path: &Path,
-    excerpts: impl IntoIterator<Item = &'a Excerpt>,
-    sorted_insertions: &[(Point, &str)],
-    file_line_count: Line,
-    include_line_numbers: bool,
-    output: &'a mut String,
-) {
-    writeln!(output, "`````filename={}", DiffPathFmt(path)).unwrap();
-
-    write_excerpts(
-        excerpts,
-        sorted_insertions,
-        file_line_count,
-        include_line_numbers,
-        output,
-    );
-    write!(output, "`````\n\n").unwrap();
-}
-
-pub fn write_excerpts<'a>(
-    excerpts: impl IntoIterator<Item = &'a Excerpt>,
-    sorted_insertions: &[(Point, &str)],
-    file_line_count: Line,
-    include_line_numbers: bool,
-    output: &mut String,
-) {
-    let mut current_row = Line(0);
-    let mut sorted_insertions = sorted_insertions.iter().peekable();
-
-    for excerpt in excerpts {
-        if excerpt.start_line > current_row {
-            writeln!(output, "…").unwrap();
-        }
-        if excerpt.text.is_empty() {
-            return;
-        }
-
-        current_row = excerpt.start_line;
-
-        for mut line in excerpt.text.lines() {
-            if include_line_numbers {
-                write!(output, "{}|", current_row.0 + 1).unwrap();
-            }
-
-            while let Some((insertion_location, insertion_marker)) = sorted_insertions.peek() {
-                match current_row.cmp(&insertion_location.line) {
-                    cmp::Ordering::Equal => {
-                        let (prefix, suffix) = line.split_at(insertion_location.column as usize);
-                        output.push_str(prefix);
-                        output.push_str(insertion_marker);
-                        line = suffix;
-                        sorted_insertions.next();
-                    }
-                    cmp::Ordering::Less => break,
-                    cmp::Ordering::Greater => {
-                        sorted_insertions.next();
-                        break;
-                    }
-                }
-            }
-            output.push_str(line);
-            output.push('\n');
-            current_row.0 += 1;
-        }
-    }
-
-    if current_row < file_line_count {
-        writeln!(output, "…").unwrap();
-    }
-}
-
-pub fn push_events(output: &mut String, events: &[Arc<predict_edits_v3::Event>]) {
-    if events.is_empty() {
-        return;
-    };
-
-    writeln!(output, "`````diff").unwrap();
-    for event in events {
-        writeln!(output, "{}", event).unwrap();
-    }
-    writeln!(output, "`````\n").unwrap();
-}
-
-pub struct SyntaxBasedPrompt<'a> {
-    request: &'a predict_edits_v3::PredictEditsRequest,
-    /// Snippets to include in the prompt. These may overlap - they are merged / deduplicated in
-    /// `to_prompt_string`.
-    snippets: Vec<PlannedSnippet<'a>>,
-    budget_used: usize,
-}
-
-#[derive(Clone, Debug)]
-pub struct PlannedSnippet<'a> {
-    path: Arc<Path>,
-    range: Range<Line>,
-    text: &'a str,
-    // TODO: Indicate this in the output
-    #[allow(dead_code)]
-    text_is_truncated: bool,
-}
-
-#[derive(EnumIter, Clone, Copy, PartialEq, Eq, Hash, Debug, PartialOrd, Ord)]
-pub enum DeclarationStyle {
-    Signature,
-    Declaration,
-}
-
-#[derive(Default, Clone, Debug, Serialize)]
-pub struct SectionLabels {
-    pub excerpt_index: usize,
-    pub section_ranges: Vec<(Arc<Path>, Range<Line>)>,
-}
-
-impl<'a> SyntaxBasedPrompt<'a> {
-    /// Greedy one-pass knapsack algorithm to populate the prompt plan. Does the following:
-    ///
-    /// Initializes a priority queue by populating it with each snippet, finding the
-    /// DeclarationStyle that minimizes `score_density = score / snippet.range(style).len()`. When a
-    /// "signature" snippet is popped, insert an entry for the "declaration" variant that reflects
-    /// the cost of upgrade.
-    ///
-    /// TODO: Implement an early halting condition. One option might be to have another priority
-    /// queue where the score is the size, and update it accordingly. Another option might be to
-    /// have some simpler heuristic like bailing after N failed insertions, or based on how much
-    /// budget is left.
-    ///
-    /// TODO: Has the current known sources of imprecision:
-    ///
-    /// * Does not consider snippet overlap when ranking. For example, it might add a field to the
-    /// plan even though the containing struct is already included.
-    ///
-    /// * Does not consider cost of signatures when ranking snippets - this is tricky since
-    /// signatures may be shared by multiple snippets.
-    ///
-    /// * Does not include file paths / other text when considering max_bytes.
-    pub fn populate(request: &'a predict_edits_v3::PredictEditsRequest) -> Result<Self> {
-        let mut this = Self {
-            request,
-            snippets: Vec::new(),
-            budget_used: request.excerpt.len(),
-        };
-        let mut included_parents = FxHashSet::default();
-        let additional_parents = this.additional_parent_signatures(
-            &request.excerpt_path,
-            request.excerpt_parent,
-            &included_parents,
-        )?;
-        this.add_parents(&mut included_parents, additional_parents);
-
-        let max_bytes = request.prompt_max_bytes.unwrap_or(DEFAULT_MAX_PROMPT_BYTES);
-
-        if this.budget_used > max_bytes {
-            return Err(anyhow!(
-                "Excerpt + signatures size of {} already exceeds budget of {}",
-                this.budget_used,
-                max_bytes
-            ));
-        }
-
-        #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
-        struct QueueEntry {
-            score_density: OrderedFloat<f32>,
-            declaration_index: usize,
-            style: DeclarationStyle,
-        }
-
-        // Initialize priority queue with the best score for each snippet.
-        let mut queue: BinaryHeap<QueueEntry> = BinaryHeap::new();
-        for (declaration_index, declaration) in request.referenced_declarations.iter().enumerate() {
-            let (style, score_density) = DeclarationStyle::iter()
-                .map(|style| {
-                    (
-                        style,
-                        OrderedFloat(declaration_score_density(&declaration, style)),
-                    )
-                })
-                .max_by_key(|(_, score_density)| *score_density)
-                .unwrap();
-            queue.push(QueueEntry {
-                score_density,
-                declaration_index,
-                style,
-            });
-        }
-
-        // Knapsack selection loop
-        while let Some(queue_entry) = queue.pop() {
-            let Some(declaration) = request
-                .referenced_declarations
-                .get(queue_entry.declaration_index)
-            else {
-                return Err(anyhow!(
-                    "Invalid declaration index {}",
-                    queue_entry.declaration_index
-                ));
-            };
-
-            let mut additional_bytes = declaration_size(declaration, queue_entry.style);
-            if this.budget_used + additional_bytes > max_bytes {
-                continue;
-            }
-
-            let additional_parents = this.additional_parent_signatures(
-                &declaration.path,
-                declaration.parent_index,
-                &mut included_parents,
-            )?;
-            additional_bytes += additional_parents
-                .iter()
-                .map(|(_, snippet)| snippet.text.len())
-                .sum::<usize>();
-            if this.budget_used + additional_bytes > max_bytes {
-                continue;
-            }
-
-            this.budget_used += additional_bytes;
-            this.add_parents(&mut included_parents, additional_parents);
-            let planned_snippet = match queue_entry.style {
-                DeclarationStyle::Signature => {
-                    let Some(text) = declaration.text.get(declaration.signature_range.clone())
-                    else {
-                        return Err(anyhow!(
-                            "Invalid declaration signature_range {:?} with text.len() = {}",
-                            declaration.signature_range,
-                            declaration.text.len()
-                        ));
-                    };
-                    let signature_start_line = declaration.range.start
-                        + Line(
-                            declaration.text[..declaration.signature_range.start]
-                                .lines()
-                                .count() as u32,
-                        );
-                    let signature_end_line = signature_start_line
-                        + Line(
-                            declaration.text
-                                [declaration.signature_range.start..declaration.signature_range.end]
-                                .lines()
-                                .count() as u32,
-                        );
-                    let range = signature_start_line..signature_end_line;
-
-                    PlannedSnippet {
-                        path: declaration.path.clone(),
-                        range,
-                        text,
-                        text_is_truncated: declaration.text_is_truncated,
-                    }
-                }
-                DeclarationStyle::Declaration => PlannedSnippet {
-                    path: declaration.path.clone(),
-                    range: declaration.range.clone(),
-                    text: &declaration.text,
-                    text_is_truncated: declaration.text_is_truncated,
-                },
-            };
-            this.snippets.push(planned_snippet);
-
-            // When a Signature is consumed, insert an entry for Definition style.
-            if queue_entry.style == DeclarationStyle::Signature {
-                let signature_size = declaration_size(&declaration, DeclarationStyle::Signature);
-                let declaration_size =
-                    declaration_size(&declaration, DeclarationStyle::Declaration);
-                let signature_score = declaration_score(&declaration, DeclarationStyle::Signature);
-                let declaration_score =
-                    declaration_score(&declaration, DeclarationStyle::Declaration);
-
-                let score_diff = declaration_score - signature_score;
-                let size_diff = declaration_size.saturating_sub(signature_size);
-                if score_diff > 0.0001 && size_diff > 0 {
-                    queue.push(QueueEntry {
-                        declaration_index: queue_entry.declaration_index,
-                        score_density: OrderedFloat(score_diff / (size_diff as f32)),
-                        style: DeclarationStyle::Declaration,
-                    });
-                }
-            }
-        }
-
-        anyhow::Ok(this)
-    }
-
-    fn add_parents(
-        &mut self,
-        included_parents: &mut FxHashSet<usize>,
-        snippets: Vec<(usize, PlannedSnippet<'a>)>,
-    ) {
-        for (parent_index, snippet) in snippets {
-            included_parents.insert(parent_index);
-            self.budget_used += snippet.text.len();
-            self.snippets.push(snippet);
-        }
-    }
-
-    fn additional_parent_signatures(
-        &self,
-        path: &Arc<Path>,
-        parent_index: Option<usize>,
-        included_parents: &FxHashSet<usize>,
-    ) -> Result<Vec<(usize, PlannedSnippet<'a>)>> {
-        let mut results = Vec::new();
-        self.additional_parent_signatures_impl(path, parent_index, included_parents, &mut results)?;
-        Ok(results)
-    }
-
-    fn additional_parent_signatures_impl(
-        &self,
-        path: &Arc<Path>,
-        parent_index: Option<usize>,
-        included_parents: &FxHashSet<usize>,
-        results: &mut Vec<(usize, PlannedSnippet<'a>)>,
-    ) -> Result<()> {
-        let Some(parent_index) = parent_index else {
-            return Ok(());
-        };
-        if included_parents.contains(&parent_index) {
-            return Ok(());
-        }
-        let Some(parent_signature) = self.request.signatures.get(parent_index) else {
-            return Err(anyhow!("Invalid parent index {}", parent_index));
-        };
-        results.push((
-            parent_index,
-            PlannedSnippet {
-                path: path.clone(),
-                range: parent_signature.range.clone(),
-                text: &parent_signature.text,
-                text_is_truncated: parent_signature.text_is_truncated,
-            },
-        ));
-        self.additional_parent_signatures_impl(
-            path,
-            parent_signature.parent_index,
-            included_parents,
-            results,
-        )
-    }
-
-    /// Renders the planned context. Each file starts with "```FILE_PATH\n` and ends with triple
-    /// backticks, with a newline after each file. Outputs a line with "..." between nonconsecutive
-    /// chunks.
-    pub fn write(
-        &'a self,
-        excerpt_file_insertions: &mut Vec<(Point, &'static str)>,
-        prompt: &mut String,
-    ) -> Result<SectionLabels> {
-        let mut file_to_snippets: FxHashMap<&'a std::path::Path, Vec<&PlannedSnippet<'a>>> =
-            FxHashMap::default();
-        for snippet in &self.snippets {
-            file_to_snippets
-                .entry(&snippet.path)
-                .or_default()
-                .push(snippet);
-        }
-
-        // Reorder so that file with cursor comes last
-        let mut file_snippets = Vec::new();
-        let mut excerpt_file_snippets = Vec::new();
-        for (file_path, snippets) in file_to_snippets {
-            if file_path == self.request.excerpt_path.as_ref() {
-                excerpt_file_snippets = snippets;
-            } else {
-                file_snippets.push((file_path, snippets, false));
-            }
-        }
-        let excerpt_snippet = PlannedSnippet {
-            path: self.request.excerpt_path.clone(),
-            range: self.request.excerpt_line_range.clone(),
-            text: &self.request.excerpt,
-            text_is_truncated: false,
-        };
-        excerpt_file_snippets.push(&excerpt_snippet);
-        file_snippets.push((&self.request.excerpt_path, excerpt_file_snippets, true));
-
-        let section_labels =
-            self.push_file_snippets(prompt, excerpt_file_insertions, file_snippets)?;
-
-        Ok(section_labels)
-    }
-
-    fn push_file_snippets(
-        &self,
-        output: &mut String,
-        excerpt_file_insertions: &mut Vec<(Point, &'static str)>,
-        file_snippets: Vec<(&'a Path, Vec<&'a PlannedSnippet>, bool)>,
-    ) -> Result<SectionLabels> {
-        let mut section_ranges = Vec::new();
-        let mut excerpt_index = None;
-
-        for (file_path, mut snippets, is_excerpt_file) in file_snippets {
-            snippets.sort_by_key(|s| (s.range.start, Reverse(s.range.end)));
-
-            // TODO: What if the snippets get expanded too large to be editable?
-            let mut current_snippet: Option<(&PlannedSnippet, Range<Line>)> = None;
-            let mut disjoint_snippets: Vec<(&PlannedSnippet, Range<Line>)> = Vec::new();
-            for snippet in snippets {
-                if let Some((_, current_snippet_range)) = current_snippet.as_mut()
-                    && snippet.range.start <= current_snippet_range.end
-                {
-                    current_snippet_range.end = current_snippet_range.end.max(snippet.range.end);
-                    continue;
-                }
-                if let Some(current_snippet) = current_snippet.take() {
-                    disjoint_snippets.push(current_snippet);
-                }
-                current_snippet = Some((snippet, snippet.range.clone()));
-            }
-            if let Some(current_snippet) = current_snippet.take() {
-                disjoint_snippets.push(current_snippet);
-            }
-
-            writeln!(output, "`````path={}", file_path.display()).ok();
-            let mut skipped_last_snippet = false;
-            for (snippet, range) in disjoint_snippets {
-                let section_index = section_ranges.len();
-
-                match self.request.prompt_format {
-                    PromptFormat::MarkedExcerpt
-                    | PromptFormat::OnlySnippets
-                    | PromptFormat::OldTextNewText
-                    | PromptFormat::Minimal
-                    | PromptFormat::NumLinesUniDiff => {
-                        if range.start.0 > 0 && !skipped_last_snippet {
-                            output.push_str("…\n");
-                        }
-                    }
-                    PromptFormat::LabeledSections => {
-                        if is_excerpt_file
-                            && range.start <= self.request.excerpt_line_range.start
-                            && range.end >= self.request.excerpt_line_range.end
-                        {
-                            writeln!(output, "<|current_section|>").ok();
-                        } else {
-                            writeln!(output, "<|section_{}|>", section_index).ok();
-                        }
-                    }
-                    PromptFormat::MinimalQwen => unreachable!(),
-                    PromptFormat::SeedCoder1120 => unreachable!(),
-                }
-
-                let push_full_snippet = |output: &mut String| {
-                    if self.request.prompt_format == PromptFormat::NumLinesUniDiff {
-                        for (i, line) in snippet.text.lines().enumerate() {
-                            writeln!(output, "{}|{}", i as u32 + range.start.0 + 1, line)?;
-                        }
-                    } else {
-                        output.push_str(&snippet.text);
-                    }
-                    anyhow::Ok(())
-                };
-
-                if is_excerpt_file {
-                    if self.request.prompt_format == PromptFormat::OnlySnippets {
-                        if range.start >= self.request.excerpt_line_range.start
-                            && range.end <= self.request.excerpt_line_range.end
-                        {
-                            skipped_last_snippet = true;
-                        } else {
-                            skipped_last_snippet = false;
-                            output.push_str(snippet.text);
-                        }
-                    } else if !excerpt_file_insertions.is_empty() {
-                        let lines = snippet.text.lines().collect::<Vec<_>>();
-                        let push_line = |output: &mut String, line_ix: usize| {
-                            if self.request.prompt_format == PromptFormat::NumLinesUniDiff {
-                                write!(output, "{}|", line_ix as u32 + range.start.0 + 1)?;
-                            }
-                            anyhow::Ok(writeln!(output, "{}", lines[line_ix])?)
-                        };
-                        let mut last_line_ix = 0;
-                        let mut insertion_ix = 0;
-                        while insertion_ix < excerpt_file_insertions.len() {
-                            let (point, insertion) = &excerpt_file_insertions[insertion_ix];
-                            let found = point.line >= range.start && point.line <= range.end;
-                            if found {
-                                excerpt_index = Some(section_index);
-                                let insertion_line_ix = (point.line.0 - range.start.0) as usize;
-                                for line_ix in last_line_ix..insertion_line_ix {
-                                    push_line(output, line_ix)?;
-                                }
-                                if let Some(next_line) = lines.get(insertion_line_ix) {
-                                    if self.request.prompt_format == PromptFormat::NumLinesUniDiff {
-                                        write!(
-                                            output,
-                                            "{}|",
-                                            insertion_line_ix as u32 + range.start.0 + 1
-                                        )?
-                                    }
-                                    output.push_str(&next_line[..point.column as usize]);
-                                    output.push_str(insertion);
-                                    writeln!(output, "{}", &next_line[point.column as usize..])?;
-                                } else {
-                                    writeln!(output, "{}", insertion)?;
-                                }
-                                last_line_ix = insertion_line_ix + 1;
-                                excerpt_file_insertions.remove(insertion_ix);
-                                continue;
-                            }
-                            insertion_ix += 1;
-                        }
-                        skipped_last_snippet = false;
-                        for line_ix in last_line_ix..lines.len() {
-                            push_line(output, line_ix)?;
-                        }
-                    } else {
-                        skipped_last_snippet = false;
-                        push_full_snippet(output)?;
-                    }
-                } else {
-                    skipped_last_snippet = false;
-                    push_full_snippet(output)?;
-                }
-
-                section_ranges.push((snippet.path.clone(), range));
-            }
-
-            output.push_str("`````\n\n");
-        }
-
-        Ok(SectionLabels {
-            // TODO: Clean this up
-            excerpt_index: match self.request.prompt_format {
-                PromptFormat::OnlySnippets => 0,
-                _ => excerpt_index.context("bug: no snippet found for excerpt")?,
-            },
-            section_ranges,
-        })
-    }
-}
-
-fn declaration_score_density(declaration: &ReferencedDeclaration, style: DeclarationStyle) -> f32 {
-    declaration_score(declaration, style) / declaration_size(declaration, style) as f32
-}
-
-fn declaration_score(declaration: &ReferencedDeclaration, style: DeclarationStyle) -> f32 {
-    match style {
-        DeclarationStyle::Signature => declaration.signature_score,
-        DeclarationStyle::Declaration => declaration.declaration_score,
-    }
-}
-
-fn declaration_size(declaration: &ReferencedDeclaration, style: DeclarationStyle) -> usize {
-    match style {
-        DeclarationStyle::Signature => declaration.signature_range.len(),
-        DeclarationStyle::Declaration => declaration.text.len(),
-    }
-}
-
-struct PromptData {
-    events: Vec<Arc<Event>>,
-    cursor_point: Point,
-    cursor_path: Arc<Path>, // TODO: make a common struct with cursor_point
-    included_files: Vec<IncludedFile>,
-}
-
-#[derive(Default)]
-pub struct GenerationParams {
-    pub temperature: Option<f32>,
-    pub top_p: Option<f32>,
-    pub stop: Option<Vec<String>>,
-}
-
-trait PromptFormatter {
-    fn render(&self, data: &PromptData) -> String;
-
-    fn generation_params() -> GenerationParams {
-        return GenerationParams::default();
-    }
-}
-
-struct MinimalQwenPrompt;
-
-impl PromptFormatter for MinimalQwenPrompt {
-    fn render(&self, data: &PromptData) -> String {
-        let edit_history = self.fmt_edit_history(data);
-        let context = self.fmt_context(data);
-
-        format!(
-            "{instructions}\n\n{edit_history}\n\n{context}",
-            instructions = MinimalQwenPrompt::INSTRUCTIONS,
-            edit_history = edit_history,
-            context = context
-        )
-    }
-}
-
-impl MinimalQwenPrompt {
-    const INSTRUCTIONS: &str = "You are a code completion assistant that analyzes edit history to identify and systematically complete incomplete refactorings or patterns across the entire codebase.\n";
-
-    fn fmt_edit_history(&self, data: &PromptData) -> String {
-        if data.events.is_empty() {
-            "(No edit history)\n\n".to_string()
-        } else {
-            let mut events_str = String::new();
-            push_events(&mut events_str, &data.events);
-            format!(
-                "The following are the latest edits made by the user, from earlier to later.\n\n{}",
-                events_str
-            )
-        }
-    }
-
-    fn fmt_context(&self, data: &PromptData) -> String {
-        let mut context = String::new();
-        let include_line_numbers = true;
-
-        for related_file in &data.included_files {
-            writeln!(context, "<|file_sep|>{}", DiffPathFmt(&related_file.path)).unwrap();
-
-            if related_file.path == data.cursor_path {
-                write!(context, "<|fim_prefix|>").unwrap();
-                write_excerpts(
-                    &related_file.excerpts,
-                    &[(data.cursor_point, "<|fim_suffix|>")],
-                    related_file.max_row,
-                    include_line_numbers,
-                    &mut context,
-                );
-                writeln!(context, "<|fim_middle|>").unwrap();
-            } else {
-                write_excerpts(
-                    &related_file.excerpts,
-                    &[],
-                    related_file.max_row,
-                    include_line_numbers,
-                    &mut context,
-                );
-            }
-        }
-        context
-    }
-}
-
-struct SeedCoder1120Prompt;
-
-impl PromptFormatter for SeedCoder1120Prompt {
-    fn render(&self, data: &PromptData) -> String {
-        let edit_history = self.fmt_edit_history(data);
-        let context = self.fmt_context(data);
-
-        format!(
-            "# Edit History:\n{edit_history}\n\n{context}",
-            edit_history = edit_history,
-            context = context
-        )
-    }
-
-    fn generation_params() -> GenerationParams {
-        GenerationParams {
-            temperature: Some(0.2),
-            top_p: Some(0.9),
-            stop: Some(vec!["<[end_of_sentence]>".into()]),
-        }
-    }
-}
-
-impl SeedCoder1120Prompt {
-    fn fmt_edit_history(&self, data: &PromptData) -> String {
-        if data.events.is_empty() {
-            "(No edit history)\n\n".to_string()
-        } else {
-            let mut events_str = String::new();
-            push_events(&mut events_str, &data.events);
-            events_str
-        }
-    }
-
-    fn fmt_context(&self, data: &PromptData) -> String {
-        let mut context = String::new();
-        let include_line_numbers = true;
-
-        for related_file in &data.included_files {
-            writeln!(context, "# Path: {}\n", DiffPathFmt(&related_file.path)).unwrap();
-
-            if related_file.path == data.cursor_path {
-                let fim_prompt = self.fmt_fim(&related_file, data.cursor_point);
-                context.push_str(&fim_prompt);
-            } else {
-                write_excerpts(
-                    &related_file.excerpts,
-                    &[],
-                    related_file.max_row,
-                    include_line_numbers,
-                    &mut context,
-                );
-            }
-        }
-        context
-    }
-
-    fn fmt_fim(&self, file: &IncludedFile, cursor_point: Point) -> String {
-        let mut buf = String::new();
-        const FIM_SUFFIX: &str = "<[fim-suffix]>";
-        const FIM_PREFIX: &str = "<[fim-prefix]>";
-        const FIM_MIDDLE: &str = "<[fim-middle]>";
-        write!(buf, "{}", FIM_PREFIX).unwrap();
-        write_excerpts(
-            &file.excerpts,
-            &[(cursor_point, FIM_SUFFIX)],
-            file.max_row,
-            true,
-            &mut buf,
-        );
-
-        // Swap prefix and suffix parts
-        let index = buf.find(FIM_SUFFIX).unwrap();
-        let prefix = &buf[..index];
-        let suffix = &buf[index..];
-
-        format!("{}{}{}", suffix, prefix, FIM_MIDDLE)
-    }
-}

crates/cloud_zeta2_prompt/src/retrieval_prompt.rs 🔗

@@ -1,244 +0,0 @@
-use anyhow::Result;
-use cloud_llm_client::predict_edits_v3::{self, Excerpt};
-use indoc::indoc;
-use schemars::JsonSchema;
-use serde::{Deserialize, Serialize};
-use std::fmt::Write;
-
-use crate::{push_events, write_codeblock};
-
-pub fn build_prompt(request: predict_edits_v3::PlanContextRetrievalRequest) -> Result<String> {
-    let mut prompt = SEARCH_INSTRUCTIONS.to_string();
-
-    if !request.events.is_empty() {
-        writeln!(&mut prompt, "\n## User Edits\n\n")?;
-        push_events(&mut prompt, &request.events);
-    }
-
-    writeln!(&mut prompt, "## Cursor context\n")?;
-    write_codeblock(
-        &request.excerpt_path,
-        &[Excerpt {
-            start_line: request.excerpt_line_range.start,
-            text: request.excerpt.into(),
-        }],
-        &[],
-        request.cursor_file_max_row,
-        true,
-        &mut prompt,
-    );
-
-    writeln!(&mut prompt, "{TOOL_USE_REMINDER}")?;
-
-    Ok(prompt)
-}
-
-/// Search for relevant code
-///
-/// For the best results, run multiple queries at once with a single invocation of this tool.
-#[derive(Clone, Deserialize, Serialize, JsonSchema)]
-pub struct SearchToolInput {
-    /// An array of queries to run for gathering context relevant to the next prediction
-    #[schemars(length(max = 3))]
-    #[serde(deserialize_with = "deserialize_queries")]
-    pub queries: Box<[SearchToolQuery]>,
-}
-
-fn deserialize_queries<'de, D>(deserializer: D) -> Result<Box<[SearchToolQuery]>, D::Error>
-where
-    D: serde::Deserializer<'de>,
-{
-    use serde::de::Error;
-
-    #[derive(Deserialize)]
-    #[serde(untagged)]
-    enum QueryCollection {
-        Array(Box<[SearchToolQuery]>),
-        DoubleArray(Box<[Box<[SearchToolQuery]>]>),
-        Single(SearchToolQuery),
-    }
-
-    #[derive(Deserialize)]
-    #[serde(untagged)]
-    enum MaybeDoubleEncoded {
-        SingleEncoded(QueryCollection),
-        DoubleEncoded(String),
-    }
-
-    let result = MaybeDoubleEncoded::deserialize(deserializer)?;
-
-    let normalized = match result {
-        MaybeDoubleEncoded::SingleEncoded(value) => value,
-        MaybeDoubleEncoded::DoubleEncoded(value) => {
-            serde_json::from_str(&value).map_err(D::Error::custom)?
-        }
-    };
-
-    Ok(match normalized {
-        QueryCollection::Array(items) => items,
-        QueryCollection::Single(search_tool_query) => Box::new([search_tool_query]),
-        QueryCollection::DoubleArray(double_array) => double_array.into_iter().flatten().collect(),
-    })
-}
-
-/// Search for relevant code by path, syntax hierarchy, and content.
-#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, Hash)]
-pub struct SearchToolQuery {
-    /// 1. A glob pattern to match file paths in the codebase to search in.
-    pub glob: String,
-    /// 2. Regular expressions to match syntax nodes **by their first line** and hierarchy.
-    ///
-    /// Subsequent regexes match nodes within the full content of the nodes matched by the previous regexes.
-    ///
-    /// Example: Searching for a `User` class
-    ///     ["class\s+User"]
-    ///
-    /// Example: Searching for a `get_full_name` method under a `User` class
-    ///     ["class\s+User", "def\sget_full_name"]
-    ///
-    /// Skip this field to match on content alone.
-    #[schemars(length(max = 3))]
-    #[serde(default)]
-    pub syntax_node: Vec<String>,
-    /// 3. An optional regular expression to match the final content that should appear in the results.
-    ///
-    /// - Content will be matched within all lines of the matched syntax nodes.
-    /// - If syntax node regexes are provided, this field can be skipped to include as much of the node itself as possible.
-    /// - If no syntax node regexes are provided, the content will be matched within the entire file.
-    pub content: Option<String>,
-}
-
-pub const TOOL_NAME: &str = "search";
-
-const SEARCH_INSTRUCTIONS: &str = indoc! {r#"
-    You are part of an edit prediction system in a code editor.
-    Your role is to search for code that will serve as context for predicting the next edit.
-
-    - Analyze the user's recent edits and current cursor context
-    - Use the `search` tool to find code that is relevant for predicting the next edit
-    - Focus on finding:
-       - Code patterns that might need similar changes based on the recent edits
-       - Functions, variables, types, and constants referenced in the current cursor context
-       - Related implementations, usages, or dependencies that may require consistent updates
-       - How items defined in the cursor excerpt are used or altered
-    - You will not be able to filter results or perform subsequent queries, so keep searches as targeted as possible
-    - Use `syntax_node` parameter whenever you're looking for a particular type, class, or function
-    - Avoid using wildcard globs if you already know the file path of the content you're looking for
-"#};
-
-const TOOL_USE_REMINDER: &str = indoc! {"
-    --
-    Analyze the user's intent in one to two sentences, then call the `search` tool.
-"};
-
-#[cfg(test)]
-mod tests {
-    use serde_json::json;
-
-    use super::*;
-
-    #[test]
-    fn test_deserialize_queries() {
-        let single_query_json = indoc! {r#"{
-            "queries": {
-                "glob": "**/*.rs",
-                "syntax_node": ["fn test"],
-                "content": "assert"
-            }
-        }"#};
-
-        let flat_input: SearchToolInput = serde_json::from_str(single_query_json).unwrap();
-        assert_eq!(flat_input.queries.len(), 1);
-        assert_eq!(flat_input.queries[0].glob, "**/*.rs");
-        assert_eq!(flat_input.queries[0].syntax_node, vec!["fn test"]);
-        assert_eq!(flat_input.queries[0].content, Some("assert".to_string()));
-
-        let flat_json = indoc! {r#"{
-            "queries": [
-                {
-                    "glob": "**/*.rs",
-                    "syntax_node": ["fn test"],
-                    "content": "assert"
-                },
-                {
-                    "glob": "**/*.ts",
-                    "syntax_node": [],
-                    "content": null
-                }
-            ]
-        }"#};
-
-        let flat_input: SearchToolInput = serde_json::from_str(flat_json).unwrap();
-        assert_eq!(flat_input.queries.len(), 2);
-        assert_eq!(flat_input.queries[0].glob, "**/*.rs");
-        assert_eq!(flat_input.queries[0].syntax_node, vec!["fn test"]);
-        assert_eq!(flat_input.queries[0].content, Some("assert".to_string()));
-        assert_eq!(flat_input.queries[1].glob, "**/*.ts");
-        assert_eq!(flat_input.queries[1].syntax_node.len(), 0);
-        assert_eq!(flat_input.queries[1].content, None);
-
-        let nested_json = indoc! {r#"{
-            "queries": [
-                [
-                    {
-                        "glob": "**/*.rs",
-                        "syntax_node": ["fn test"],
-                        "content": "assert"
-                    }
-                ],
-                [
-                    {
-                        "glob": "**/*.ts",
-                        "syntax_node": [],
-                        "content": null
-                    }
-                ]
-            ]
-        }"#};
-
-        let nested_input: SearchToolInput = serde_json::from_str(nested_json).unwrap();
-
-        assert_eq!(nested_input.queries.len(), 2);
-
-        assert_eq!(nested_input.queries[0].glob, "**/*.rs");
-        assert_eq!(nested_input.queries[0].syntax_node, vec!["fn test"]);
-        assert_eq!(nested_input.queries[0].content, Some("assert".to_string()));
-        assert_eq!(nested_input.queries[1].glob, "**/*.ts");
-        assert_eq!(nested_input.queries[1].syntax_node.len(), 0);
-        assert_eq!(nested_input.queries[1].content, None);
-
-        let double_encoded_queries = serde_json::to_string(&json!({
-            "queries": serde_json::to_string(&json!([
-                {
-                    "glob": "**/*.rs",
-                    "syntax_node": ["fn test"],
-                    "content": "assert"
-                },
-                {
-                    "glob": "**/*.ts",
-                    "syntax_node": [],
-                    "content": null
-                }
-            ])).unwrap()
-        }))
-        .unwrap();
-
-        let double_encoded_input: SearchToolInput =
-            serde_json::from_str(&double_encoded_queries).unwrap();
-
-        assert_eq!(double_encoded_input.queries.len(), 2);
-
-        assert_eq!(double_encoded_input.queries[0].glob, "**/*.rs");
-        assert_eq!(double_encoded_input.queries[0].syntax_node, vec!["fn test"]);
-        assert_eq!(
-            double_encoded_input.queries[0].content,
-            Some("assert".to_string())
-        );
-        assert_eq!(double_encoded_input.queries[1].glob, "**/*.ts");
-        assert_eq!(double_encoded_input.queries[1].syntax_node.len(), 0);
-        assert_eq!(double_encoded_input.queries[1].content, None);
-
-        // ### ERROR Switching from var declarations to lexical declarations [RUN 073]
-        // invalid search json {"queries": ["express/lib/response.js", "var\\s+[a-zA-Z_][a-zA-Z0-9_]*\\s*=.*;", "function.*\\(.*\\).*\\{.*\\}"]}
-    }
-}

crates/codestral/Cargo.toml 🔗

@@ -10,7 +10,7 @@ path = "src/codestral.rs"
 
 [dependencies]
 anyhow.workspace = true
-edit_prediction.workspace = true
+edit_prediction_types.workspace = true
 edit_prediction_context.workspace = true
 futures.workspace = true
 gpui.workspace = true

crates/codestral/src/codestral.rs 🔗

@@ -1,6 +1,6 @@
 use anyhow::{Context as _, Result};
-use edit_prediction::{Direction, EditPrediction, EditPredictionProvider};
 use edit_prediction_context::{EditPredictionExcerpt, EditPredictionExcerptOptions};
+use edit_prediction_types::{EditPrediction, EditPredictionDelegate};
 use futures::AsyncReadExt;
 use gpui::{App, Context, Entity, Task};
 use http_client::HttpClient;
@@ -43,17 +43,17 @@ impl CurrentCompletion {
     /// Attempts to adjust the edits based on changes made to the buffer since the completion was generated.
     /// Returns None if the user's edits conflict with the predicted edits.
     fn interpolate(&self, new_snapshot: &BufferSnapshot) -> Option<Vec<(Range<Anchor>, Arc<str>)>> {
-        edit_prediction::interpolate_edits(&self.snapshot, new_snapshot, &self.edits)
+        edit_prediction_types::interpolate_edits(&self.snapshot, new_snapshot, &self.edits)
     }
 }
 
-pub struct CodestralCompletionProvider {
+pub struct CodestralEditPredictionDelegate {
     http_client: Arc<dyn HttpClient>,
     pending_request: Option<Task<Result<()>>>,
     current_completion: Option<CurrentCompletion>,
 }
 
-impl CodestralCompletionProvider {
+impl CodestralEditPredictionDelegate {
     pub fn new(http_client: Arc<dyn HttpClient>) -> Self {
         Self {
             http_client,
@@ -165,7 +165,7 @@ impl CodestralCompletionProvider {
     }
 }
 
-impl EditPredictionProvider for CodestralCompletionProvider {
+impl EditPredictionDelegate for CodestralEditPredictionDelegate {
     fn name() -> &'static str {
         "codestral"
     }
@@ -174,7 +174,7 @@ impl EditPredictionProvider for CodestralCompletionProvider {
         "Codestral"
     }
 
-    fn show_completions_in_menu() -> bool {
+    fn show_predictions_in_menu() -> bool {
         true
     }
 
@@ -239,7 +239,6 @@ impl EditPredictionProvider for CodestralCompletionProvider {
                 cursor_point,
                 &snapshot,
                 &EXCERPT_OPTIONS,
-                None,
             )
             .context("Line containing cursor doesn't fit in excerpt max bytes")?;
 
@@ -301,16 +300,6 @@ impl EditPredictionProvider for CodestralCompletionProvider {
         }));
     }
 
-    fn cycle(
-        &mut self,
-        _buffer: Entity<Buffer>,
-        _cursor_position: Anchor,
-        _direction: Direction,
-        _cx: &mut Context<Self>,
-    ) {
-        // Codestral doesn't support multiple completions, so cycling does nothing
-    }
-
     fn accept(&mut self, _cx: &mut Context<Self>) {
         log::debug!("Codestral: Completion accepted");
         self.pending_request = None;

crates/collab/Cargo.toml 🔗

@@ -65,7 +65,7 @@ tokio = { workspace = true, features = ["full"] }
 toml.workspace = true
 tower = "0.4"
 tower-http = { workspace = true, features = ["trace"] }
-tracing = "0.1.40"
+tracing.workspace = true
 tracing-subscriber = { version = "0.3.18", features = ["env-filter", "json", "registry", "tracing-log"] } # workaround for https://github.com/tokio-rs/tracing/issues/2927
 util.workspace = true
 uuid.workspace = true

crates/collab/README.md 🔗

@@ -63,15 +63,3 @@ Deployment is triggered by pushing to the `collab-staging` (or `collab-productio
 - `./script/deploy-collab production`
 
 You can tell what is currently deployed with `./script/what-is-deployed`.
-
-# Database Migrations
-
-To create a new migration:
-
-```sh
-./script/create-migration <name>
-```
-
-Migrations are run automatically on service start, so run `foreman start` again. The service will crash if the migrations fail.
-
-When you create a new migration, you also need to update the [SQLite schema](./migrations.sqlite/20221109000000_test_schema.sql) that is used for testing.

crates/collab/k8s/migrate.template.yml 🔗

@@ -1,21 +0,0 @@
-apiVersion: batch/v1
-kind: Job
-metadata:
-  namespace: ${ZED_KUBE_NAMESPACE}
-  name: ${ZED_MIGRATE_JOB_NAME}
-spec:
-  template:
-    spec:
-      restartPolicy: Never
-      containers:
-        - name: migrator
-          imagePullPolicy: Always
-          image: ${ZED_IMAGE_ID}
-          args:
-            - migrate
-          env:
-            - name: DATABASE_URL
-              valueFrom:
-                secretKeyRef:
-                  name: database
-                  key: url

crates/collab/migrations/20210527024318_initial_schema.sql 🔗

@@ -1,20 +0,0 @@
-CREATE TABLE IF NOT EXISTS "sessions" (
-    "id" VARCHAR NOT NULL PRIMARY KEY,
-    "expires" TIMESTAMP WITH TIME ZONE NULL,
-    "session" TEXT NOT NULL
-);
-
-CREATE TABLE IF NOT EXISTS "users" (
-    "id" SERIAL PRIMARY KEY,
-    "github_login" VARCHAR,
-    "admin" BOOLEAN
-);
-
-CREATE UNIQUE INDEX "index_users_github_login" ON "users" ("github_login");
-
-CREATE TABLE IF NOT EXISTS "signups" (
-    "id" SERIAL PRIMARY KEY,
-    "github_login" VARCHAR,
-    "email_address" VARCHAR,
-    "about" TEXT
-);

crates/collab/migrations/20210805175147_create_chat_tables.sql 🔗

@@ -1,46 +0,0 @@
-CREATE TABLE IF NOT EXISTS "orgs" (
-    "id" SERIAL PRIMARY KEY,
-    "name" VARCHAR NOT NULL,
-    "slug" VARCHAR NOT NULL
-);
-
-CREATE UNIQUE INDEX "index_orgs_slug" ON "orgs" ("slug");
-
-CREATE TABLE IF NOT EXISTS "org_memberships" (
-    "id" SERIAL PRIMARY KEY,
-    "org_id" INTEGER REFERENCES orgs (id) NOT NULL,
-    "user_id" INTEGER REFERENCES users (id) NOT NULL,
-    "admin" BOOLEAN NOT NULL
-);
-
-CREATE INDEX "index_org_memberships_user_id" ON "org_memberships" ("user_id");
-CREATE UNIQUE INDEX "index_org_memberships_org_id_and_user_id" ON "org_memberships" ("org_id", "user_id");
-
-CREATE TABLE IF NOT EXISTS "channels" (
-    "id" SERIAL PRIMARY KEY,
-    "owner_id" INTEGER NOT NULL,
-    "owner_is_user" BOOLEAN NOT NULL,
-    "name" VARCHAR NOT NULL
-);
-
-CREATE UNIQUE INDEX "index_channels_owner_and_name" ON "channels" ("owner_is_user", "owner_id", "name");
-
-CREATE TABLE IF NOT EXISTS "channel_memberships" (
-    "id" SERIAL PRIMARY KEY,
-    "channel_id" INTEGER REFERENCES channels (id) NOT NULL,
-    "user_id" INTEGER REFERENCES users (id) NOT NULL,
-    "admin" BOOLEAN NOT NULL
-);
-
-CREATE INDEX "index_channel_memberships_user_id" ON "channel_memberships" ("user_id");
-CREATE UNIQUE INDEX "index_channel_memberships_channel_id_and_user_id" ON "channel_memberships" ("channel_id", "user_id");
-
-CREATE TABLE IF NOT EXISTS "channel_messages" (
-    "id" SERIAL PRIMARY KEY,
-    "channel_id" INTEGER REFERENCES channels (id) NOT NULL,
-    "sender_id" INTEGER REFERENCES users (id) NOT NULL,
-    "body" TEXT NOT NULL,
-    "sent_at" TIMESTAMP
-);
-
-CREATE INDEX "index_channel_messages_channel_id" ON "channel_messages" ("channel_id");

crates/collab/migrations/20220506130724_create_contacts.sql 🔗

@@ -1,11 +0,0 @@
-CREATE TABLE IF NOT EXISTS "contacts" (
-    "id" SERIAL PRIMARY KEY,
-    "user_id_a" INTEGER REFERENCES users (id) NOT NULL,
-    "user_id_b" INTEGER REFERENCES users (id) NOT NULL,
-    "a_to_b" BOOLEAN NOT NULL,
-    "should_notify" BOOLEAN NOT NULL,
-    "accepted" BOOLEAN NOT NULL
-);
-
-CREATE UNIQUE INDEX "index_contacts_user_ids" ON "contacts" ("user_id_a", "user_id_b");
-CREATE INDEX "index_contacts_user_id_b" ON "contacts" ("user_id_b");

crates/collab/migrations/20220518151305_add_invites_to_users.sql 🔗

@@ -1,9 +0,0 @@
-ALTER TABLE users
-ADD email_address VARCHAR(255) DEFAULT NULL,
-ADD invite_code VARCHAR(64),
-ADD invite_count INTEGER NOT NULL DEFAULT 0,
-ADD inviter_id INTEGER REFERENCES users (id),
-ADD connected_once BOOLEAN NOT NULL DEFAULT false,
-ADD created_at TIMESTAMP NOT NULL DEFAULT NOW();
-
-CREATE UNIQUE INDEX "index_invite_code_users" ON "users" ("invite_code");

crates/collab/migrations/20220523232954_allow_user_deletes.sql 🔗

@@ -1,6 +0,0 @@
-ALTER TABLE contacts DROP CONSTRAINT contacts_user_id_a_fkey;
-ALTER TABLE contacts DROP CONSTRAINT contacts_user_id_b_fkey;
-ALTER TABLE contacts ADD CONSTRAINT contacts_user_id_a_fkey FOREIGN KEY (user_id_a) REFERENCES users(id) ON DELETE CASCADE;
-ALTER TABLE contacts ADD CONSTRAINT contacts_user_id_b_fkey FOREIGN KEY (user_id_b) REFERENCES users(id) ON DELETE CASCADE;
-ALTER TABLE users DROP CONSTRAINT users_inviter_id_fkey;
-ALTER TABLE users ADD CONSTRAINT users_inviter_id_fkey FOREIGN KEY (inviter_id) REFERENCES users(id) ON DELETE SET NULL;

crates/collab/migrations/20220620211403_create_projects.sql 🔗

@@ -1,24 +0,0 @@
-CREATE TABLE IF NOT EXISTS "projects" (
-    "id" SERIAL PRIMARY KEY,
-    "host_user_id" INTEGER REFERENCES users (id) NOT NULL,
-    "unregistered" BOOLEAN NOT NULL DEFAULT false
-);
-
-CREATE TABLE IF NOT EXISTS "worktree_extensions" (
-    "id" SERIAL PRIMARY KEY,
-    "project_id" INTEGER REFERENCES projects (id) NOT NULL,
-    "worktree_id" INTEGER NOT NULL,
-    "extension" VARCHAR(255),
-    "count" INTEGER NOT NULL
-);
-
-CREATE TABLE IF NOT EXISTS "project_activity_periods" (
-    "id" SERIAL PRIMARY KEY,
-    "duration_millis" INTEGER NOT NULL,
-    "ended_at" TIMESTAMP NOT NULL,
-    "user_id" INTEGER REFERENCES users (id) NOT NULL,
-    "project_id" INTEGER REFERENCES projects (id) NOT NULL
-);
-
-CREATE INDEX "index_project_activity_periods_on_ended_at" ON "project_activity_periods" ("ended_at");
-CREATE UNIQUE INDEX "index_worktree_extensions_on_project_id_and_worktree_id_and_extension" ON "worktree_extensions" ("project_id", "worktree_id", "extension");

crates/collab/migrations/20220913211150_create_signups.sql 🔗

@@ -1,27 +0,0 @@
-CREATE TABLE IF NOT EXISTS "signups" (
-    "id" SERIAL PRIMARY KEY,
-    "email_address" VARCHAR NOT NULL,
-    "email_confirmation_code" VARCHAR(64) NOT NULL,
-    "email_confirmation_sent" BOOLEAN NOT NULL,
-    "created_at" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
-    "device_id" VARCHAR,
-    "user_id" INTEGER REFERENCES users (id) ON DELETE CASCADE,
-    "inviting_user_id" INTEGER REFERENCES users (id) ON DELETE SET NULL,
-
-    "platform_mac" BOOLEAN NOT NULL,
-    "platform_linux" BOOLEAN NOT NULL,
-    "platform_windows" BOOLEAN NOT NULL,
-    "platform_unknown" BOOLEAN NOT NULL,
-
-    "editor_features" VARCHAR[],
-    "programming_languages" VARCHAR[]
-);
-
-CREATE UNIQUE INDEX "index_signups_on_email_address" ON "signups" ("email_address");
-CREATE INDEX "index_signups_on_email_confirmation_sent" ON "signups" ("email_confirmation_sent");
-
-ALTER TABLE "users"
-    ADD "github_user_id" INTEGER;
-
-CREATE INDEX "index_users_on_email_address" ON "users" ("email_address");
-CREATE INDEX "index_users_on_github_user_id" ON "users" ("github_user_id");

crates/collab/migrations/20221111092550_reconnection_support.sql 🔗

@@ -1,90 +0,0 @@
-CREATE TABLE IF NOT EXISTS "rooms" (
-    "id" SERIAL PRIMARY KEY,
-    "live_kit_room" VARCHAR NOT NULL
-);
-
-ALTER TABLE "projects"
-    ADD "room_id" INTEGER REFERENCES rooms (id),
-    ADD "host_connection_id" INTEGER,
-    ADD "host_connection_epoch" UUID;
-CREATE INDEX "index_projects_on_host_connection_epoch" ON "projects" ("host_connection_epoch");
-
-CREATE TABLE "worktrees" (
-    "project_id" INTEGER NOT NULL REFERENCES projects (id) ON DELETE CASCADE,
-    "id" INT8 NOT NULL,
-    "root_name" VARCHAR NOT NULL,
-    "abs_path" VARCHAR NOT NULL,
-    "visible" BOOL NOT NULL,
-    "scan_id" INT8 NOT NULL,
-    "is_complete" BOOL NOT NULL,
-    PRIMARY KEY(project_id, id)
-);
-CREATE INDEX "index_worktrees_on_project_id" ON "worktrees" ("project_id");
-
-CREATE TABLE "worktree_entries" (
-    "project_id" INTEGER NOT NULL,
-    "worktree_id" INT8 NOT NULL,
-    "id" INT8 NOT NULL,
-    "is_dir" BOOL NOT NULL,
-    "path" VARCHAR NOT NULL,
-    "inode" INT8 NOT NULL,
-    "mtime_seconds" INT8 NOT NULL,
-    "mtime_nanos" INTEGER NOT NULL,
-    "is_symlink" BOOL NOT NULL,
-    "is_ignored" BOOL NOT NULL,
-    PRIMARY KEY(project_id, worktree_id, id),
-    FOREIGN KEY(project_id, worktree_id) REFERENCES worktrees (project_id, id) ON DELETE CASCADE
-);
-CREATE INDEX "index_worktree_entries_on_project_id" ON "worktree_entries" ("project_id");
-CREATE INDEX "index_worktree_entries_on_project_id_and_worktree_id" ON "worktree_entries" ("project_id", "worktree_id");
-
-CREATE TABLE "worktree_diagnostic_summaries" (
-    "project_id" INTEGER NOT NULL,
-    "worktree_id" INT8 NOT NULL,
-    "path" VARCHAR NOT NULL,
-    "language_server_id" INT8 NOT NULL,
-    "error_count" INTEGER NOT NULL,
-    "warning_count" INTEGER NOT NULL,
-    PRIMARY KEY(project_id, worktree_id, path),
-    FOREIGN KEY(project_id, worktree_id) REFERENCES worktrees (project_id, id) ON DELETE CASCADE
-);
-CREATE INDEX "index_worktree_diagnostic_summaries_on_project_id" ON "worktree_diagnostic_summaries" ("project_id");
-CREATE INDEX "index_worktree_diagnostic_summaries_on_project_id_and_worktree_id" ON "worktree_diagnostic_summaries" ("project_id", "worktree_id");
-
-CREATE TABLE "language_servers" (
-    "project_id" INTEGER NOT NULL REFERENCES projects (id) ON DELETE CASCADE,
-    "id" INT8 NOT NULL,
-    "name" VARCHAR NOT NULL,
-    PRIMARY KEY(project_id, id)
-);
-CREATE INDEX "index_language_servers_on_project_id" ON "language_servers" ("project_id");
-
-CREATE TABLE "project_collaborators" (
-    "id" SERIAL PRIMARY KEY,
-    "project_id" INTEGER NOT NULL REFERENCES projects (id) ON DELETE CASCADE,
-    "connection_id" INTEGER NOT NULL,
-    "connection_epoch" UUID NOT NULL,
-    "user_id" INTEGER NOT NULL,
-    "replica_id" INTEGER NOT NULL,
-    "is_host" BOOLEAN NOT NULL
-);
-CREATE INDEX "index_project_collaborators_on_project_id" ON "project_collaborators" ("project_id");
-CREATE UNIQUE INDEX "index_project_collaborators_on_project_id_and_replica_id" ON "project_collaborators" ("project_id", "replica_id");
-CREATE INDEX "index_project_collaborators_on_connection_epoch" ON "project_collaborators" ("connection_epoch");
-
-CREATE TABLE "room_participants" (
-    "id" SERIAL PRIMARY KEY,
-    "room_id" INTEGER NOT NULL REFERENCES rooms (id),
-    "user_id" INTEGER NOT NULL REFERENCES users (id),
-    "answering_connection_id" INTEGER,
-    "answering_connection_epoch" UUID,
-    "location_kind" INTEGER,
-    "location_project_id" INTEGER,
-    "initial_project_id" INTEGER,
-    "calling_user_id" INTEGER NOT NULL REFERENCES users (id),
-    "calling_connection_id" INTEGER NOT NULL,
-    "calling_connection_epoch" UUID NOT NULL
-);
-CREATE UNIQUE INDEX "index_room_participants_on_user_id" ON "room_participants" ("user_id");
-CREATE INDEX "index_room_participants_on_answering_connection_epoch" ON "room_participants" ("answering_connection_epoch");
-CREATE INDEX "index_room_participants_on_calling_connection_epoch" ON "room_participants" ("calling_connection_epoch");

crates/collab/migrations/20221207165001_add_connection_lost_to_room_participants.sql 🔗

@@ -1,7 +0,0 @@
-ALTER TABLE "room_participants"
-    ADD "answering_connection_lost" BOOLEAN NOT NULL DEFAULT FALSE;
-
-CREATE INDEX "index_project_collaborators_on_connection_id" ON "project_collaborators" ("connection_id");
-CREATE UNIQUE INDEX "index_project_collaborators_on_project_id_connection_id_and_epoch" ON "project_collaborators" ("project_id", "connection_id", "connection_epoch");
-CREATE INDEX "index_room_participants_on_answering_connection_id" ON "room_participants" ("answering_connection_id");
-CREATE UNIQUE INDEX "index_room_participants_on_answering_connection_id_and_answering_connection_epoch" ON "room_participants" ("answering_connection_id", "answering_connection_epoch");

crates/collab/migrations/20221214144346_change_epoch_from_uuid_to_integer.sql 🔗

@@ -1,30 +0,0 @@
-CREATE TABLE servers (
-    id SERIAL PRIMARY KEY,
-    environment VARCHAR NOT NULL
-);
-
-DROP TABLE worktree_extensions;
-DROP TABLE project_activity_periods;
-DELETE from projects;
-ALTER TABLE projects
-    DROP COLUMN host_connection_epoch,
-    ADD COLUMN host_connection_server_id INTEGER REFERENCES servers (id) ON DELETE CASCADE;
-CREATE INDEX "index_projects_on_host_connection_server_id" ON "projects" ("host_connection_server_id");
-CREATE INDEX "index_projects_on_host_connection_id_and_host_connection_server_id" ON "projects" ("host_connection_id", "host_connection_server_id");
-
-DELETE FROM project_collaborators;
-ALTER TABLE project_collaborators
-    DROP COLUMN connection_epoch,
-    ADD COLUMN connection_server_id INTEGER NOT NULL REFERENCES servers (id) ON DELETE CASCADE;
-CREATE INDEX "index_project_collaborators_on_connection_server_id" ON "project_collaborators" ("connection_server_id");
-CREATE UNIQUE INDEX "index_project_collaborators_on_project_id_connection_id_and_server_id" ON "project_collaborators" ("project_id", "connection_id", "connection_server_id");
-
-DELETE FROM room_participants;
-ALTER TABLE room_participants
-    DROP COLUMN answering_connection_epoch,
-    DROP COLUMN calling_connection_epoch,
-    ADD COLUMN answering_connection_server_id INTEGER REFERENCES servers (id) ON DELETE CASCADE,
-    ADD COLUMN calling_connection_server_id INTEGER REFERENCES servers (id) ON DELETE SET NULL;
-CREATE INDEX "index_room_participants_on_answering_connection_server_id" ON "room_participants" ("answering_connection_server_id");
-CREATE INDEX "index_room_participants_on_calling_connection_server_id" ON "room_participants" ("calling_connection_server_id");
-CREATE UNIQUE INDEX "index_room_participants_on_answering_connection_id_and_answering_connection_server_id" ON "room_participants" ("answering_connection_id", "answering_connection_server_id");

crates/collab/migrations/20230202155735_followers.sql 🔗

@@ -1,15 +0,0 @@
-CREATE TABLE IF NOT EXISTS "followers" (
-    "id" SERIAL PRIMARY KEY,
-    "room_id" INTEGER NOT NULL REFERENCES rooms (id) ON DELETE CASCADE,
-    "project_id" INTEGER NOT NULL REFERENCES projects (id) ON DELETE CASCADE,
-    "leader_connection_server_id" INTEGER NOT NULL REFERENCES servers (id) ON DELETE CASCADE,
-    "leader_connection_id" INTEGER NOT NULL,
-    "follower_connection_server_id" INTEGER NOT NULL REFERENCES servers (id) ON DELETE CASCADE,
-    "follower_connection_id" INTEGER NOT NULL
-);
-
-CREATE UNIQUE INDEX 
-    "index_followers_on_project_id_and_leader_connection_server_id_and_leader_connection_id_and_follower_connection_server_id_and_follower_connection_id"
-ON "followers" ("project_id", "leader_connection_server_id", "leader_connection_id", "follower_connection_server_id", "follower_connection_id");
-
-CREATE INDEX "index_followers_on_room_id" ON "followers" ("room_id");

crates/collab/migrations/20230508211523_add-repository-entries.sql 🔗

@@ -1,13 +0,0 @@
-CREATE TABLE "worktree_repositories" (
-    "project_id" INTEGER NOT NULL,
-    "worktree_id" INT8 NOT NULL,
-    "work_directory_id" INT8 NOT NULL,
-    "scan_id" INT8 NOT NULL,
-    "branch" VARCHAR,
-    "is_deleted" BOOL NOT NULL,
-    PRIMARY KEY(project_id, worktree_id, work_directory_id),
-    FOREIGN KEY(project_id, worktree_id) REFERENCES worktrees (project_id, id) ON DELETE CASCADE,
-    FOREIGN KEY(project_id, worktree_id, work_directory_id) REFERENCES worktree_entries (project_id, worktree_id, id) ON DELETE CASCADE
-);
-CREATE INDEX "index_worktree_repositories_on_project_id" ON "worktree_repositories" ("project_id");
-CREATE INDEX "index_worktree_repositories_on_project_id_and_worktree_id" ON "worktree_repositories" ("project_id", "worktree_id");

crates/collab/migrations/20230511004019_add_repository_statuses.sql 🔗

@@ -1,15 +0,0 @@
-CREATE TABLE "worktree_repository_statuses" (
-    "project_id" INTEGER NOT NULL,
-    "worktree_id" INT8 NOT NULL,
-    "work_directory_id" INT8 NOT NULL,
-    "repo_path" VARCHAR NOT NULL,
-    "status" INT8 NOT NULL,
-    "scan_id" INT8 NOT NULL,
-    "is_deleted" BOOL NOT NULL,
-    PRIMARY KEY(project_id, worktree_id, work_directory_id, repo_path),
-    FOREIGN KEY(project_id, worktree_id) REFERENCES worktrees (project_id, id) ON DELETE CASCADE,
-    FOREIGN KEY(project_id, worktree_id, work_directory_id) REFERENCES worktree_entries (project_id, worktree_id, id) ON DELETE CASCADE
-);
-CREATE INDEX "index_wt_repos_statuses_on_project_id" ON "worktree_repository_statuses" ("project_id");
-CREATE INDEX "index_wt_repos_statuses_on_project_id_and_wt_id" ON "worktree_repository_statuses" ("project_id", "worktree_id");
-CREATE INDEX "index_wt_repos_statuses_on_project_id_and_wt_id_and_wd_id" ON "worktree_repository_statuses" ("project_id", "worktree_id", "work_directory_id");

crates/collab/migrations/20230529164700_add_worktree_settings_files.sql 🔗

@@ -1,10 +0,0 @@
-CREATE TABLE "worktree_settings_files" (
-    "project_id" INTEGER NOT NULL,
-    "worktree_id" INT8 NOT NULL,
-    "path" VARCHAR NOT NULL,
-    "content" TEXT NOT NULL,
-    PRIMARY KEY(project_id, worktree_id, path),
-    FOREIGN KEY(project_id, worktree_id) REFERENCES worktrees (project_id, id) ON DELETE CASCADE
-);
-CREATE INDEX "index_settings_files_on_project_id" ON "worktree_settings_files" ("project_id");
-CREATE INDEX "index_settings_files_on_project_id_and_wt_id" ON "worktree_settings_files" ("project_id", "worktree_id");

crates/collab/migrations/20230727150500_add_channels.sql 🔗

@@ -1,30 +0,0 @@
-DROP TABLE "channel_messages";
-DROP TABLE "channel_memberships";
-DROP TABLE "org_memberships";
-DROP TABLE "orgs";
-DROP TABLE "channels";
-
-CREATE TABLE "channels" (
-    "id" SERIAL PRIMARY KEY,
-    "name" VARCHAR NOT NULL,
-    "created_at" TIMESTAMP NOT NULL DEFAULT now()
-);
-
-CREATE TABLE "channel_paths" (
-    "id_path" VARCHAR NOT NULL PRIMARY KEY,
-    "channel_id" INTEGER NOT NULL REFERENCES channels (id) ON DELETE CASCADE
-);
-CREATE INDEX "index_channel_paths_on_channel_id" ON "channel_paths" ("channel_id");
-
-CREATE TABLE "channel_members" (
-    "id" SERIAL PRIMARY KEY,
-    "channel_id" INTEGER NOT NULL REFERENCES channels (id) ON DELETE CASCADE,
-    "user_id" INTEGER NOT NULL REFERENCES users (id) ON DELETE CASCADE,
-    "admin" BOOLEAN NOT NULL DEFAULT false,
-    "accepted" BOOLEAN NOT NULL DEFAULT false,
-    "updated_at" TIMESTAMP NOT NULL DEFAULT now()
-);
-
-CREATE UNIQUE INDEX "index_channel_members_on_channel_id_and_user_id" ON "channel_members" ("channel_id", "user_id");
-
-ALTER TABLE rooms ADD COLUMN "channel_id" INTEGER REFERENCES channels (id) ON DELETE CASCADE;

crates/collab/migrations/20230819154600_add_channel_buffers.sql 🔗

@@ -1,40 +0,0 @@
-CREATE TABLE "buffers" (
-    "id" SERIAL PRIMARY KEY,
-    "channel_id" INTEGER NOT NULL REFERENCES channels (id) ON DELETE CASCADE,
-    "epoch" INTEGER NOT NULL DEFAULT 0
-);
-
-CREATE INDEX "index_buffers_on_channel_id" ON "buffers" ("channel_id");
-
-CREATE TABLE "buffer_operations" (
-    "buffer_id" INTEGER NOT NULL REFERENCES buffers (id) ON DELETE CASCADE,
-    "epoch" INTEGER NOT NULL,
-    "replica_id" INTEGER NOT NULL,
-    "lamport_timestamp" INTEGER NOT NULL,
-    "value" BYTEA NOT NULL,
-    PRIMARY KEY(buffer_id, epoch, lamport_timestamp, replica_id)
-);
-
-CREATE TABLE "buffer_snapshots" (
-    "buffer_id" INTEGER NOT NULL REFERENCES buffers (id) ON DELETE CASCADE,
-    "epoch" INTEGER NOT NULL,
-    "text" TEXT NOT NULL,
-    "operation_serialization_version" INTEGER NOT NULL,
-    PRIMARY KEY(buffer_id, epoch)
-);
-
-CREATE TABLE "channel_buffer_collaborators" (
-    "id" SERIAL PRIMARY KEY,
-    "channel_id" INTEGER NOT NULL REFERENCES channels (id) ON DELETE CASCADE,
-    "connection_id" INTEGER NOT NULL,
-    "connection_server_id" INTEGER NOT NULL REFERENCES servers (id) ON DELETE CASCADE,
-    "connection_lost" BOOLEAN NOT NULL DEFAULT FALSE,
-    "user_id" INTEGER NOT NULL REFERENCES users (id) ON DELETE CASCADE,
-    "replica_id" INTEGER NOT NULL
-);
-
-CREATE INDEX "index_channel_buffer_collaborators_on_channel_id" ON "channel_buffer_collaborators" ("channel_id");
-CREATE UNIQUE INDEX "index_channel_buffer_collaborators_on_channel_id_and_replica_id" ON "channel_buffer_collaborators" ("channel_id", "replica_id");
-CREATE INDEX "index_channel_buffer_collaborators_on_connection_server_id" ON "channel_buffer_collaborators" ("connection_server_id");
-CREATE INDEX "index_channel_buffer_collaborators_on_connection_id" ON "channel_buffer_collaborators" ("connection_id");
-CREATE UNIQUE INDEX "index_channel_buffer_collaborators_on_channel_id_connection_id_and_server_id" ON "channel_buffer_collaborators" ("channel_id", "connection_id", "connection_server_id");

crates/collab/migrations/20230825190322_add_server_feature_flags.sql 🔗

@@ -1,16 +0,0 @@
-CREATE TABLE "feature_flags" (
-    "id" SERIAL PRIMARY KEY,
-    "flag" VARCHAR(255) NOT NULL UNIQUE
-);
-
-CREATE UNIQUE INDEX "index_feature_flags" ON "feature_flags" ("id");
-
-CREATE TABLE "user_features" (
-    "user_id" INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
-    "feature_id" INTEGER NOT NULL REFERENCES feature_flags(id) ON DELETE CASCADE,
-    PRIMARY KEY (user_id, feature_id)
-);
-
-CREATE UNIQUE INDEX "index_user_features_user_id_and_feature_id" ON "user_features" ("user_id", "feature_id");
-CREATE INDEX "index_user_features_on_user_id" ON "user_features" ("user_id");
-CREATE INDEX "index_user_features_on_feature_id" ON "user_features" ("feature_id");

crates/collab/migrations/20230907114200_add_channel_messages.sql 🔗

@@ -1,19 +0,0 @@
-CREATE TABLE IF NOT EXISTS "channel_messages" (
-    "id" SERIAL PRIMARY KEY,
-    "channel_id" INTEGER NOT NULL REFERENCES channels (id) ON DELETE CASCADE,
-    "sender_id" INTEGER NOT NULL REFERENCES users (id),
-    "body" TEXT NOT NULL,
-    "sent_at" TIMESTAMP,
-    "nonce" UUID NOT NULL
-);
-CREATE INDEX "index_channel_messages_on_channel_id" ON "channel_messages" ("channel_id");
-CREATE UNIQUE INDEX "index_channel_messages_on_nonce" ON "channel_messages" ("nonce");
-
-CREATE TABLE IF NOT EXISTS "channel_chat_participants" (
-    "id" SERIAL PRIMARY KEY,
-    "user_id" INTEGER NOT NULL REFERENCES users (id),
-    "channel_id" INTEGER NOT NULL REFERENCES channels (id) ON DELETE CASCADE,
-    "connection_id" INTEGER NOT NULL,
-    "connection_server_id" INTEGER NOT NULL REFERENCES servers (id) ON DELETE CASCADE
-);
-CREATE INDEX "index_channel_chat_participants_on_channel_id" ON "channel_chat_participants" ("channel_id");

crates/collab/migrations/20230925210437_add_channel_changes.sql 🔗

@@ -1,19 +0,0 @@
-CREATE TABLE IF NOT EXISTS "observed_buffer_edits" (
-    "user_id" INTEGER NOT NULL REFERENCES users (id) ON DELETE CASCADE,
-    "buffer_id" INTEGER NOT NULL REFERENCES buffers (id) ON DELETE CASCADE,
-    "epoch" INTEGER NOT NULL,
-    "lamport_timestamp" INTEGER NOT NULL,
-    "replica_id" INTEGER NOT NULL,
-    PRIMARY KEY (user_id, buffer_id)
-);
-
-CREATE UNIQUE INDEX "index_observed_buffer_user_and_buffer_id" ON "observed_buffer_edits" ("user_id", "buffer_id");
-
-CREATE TABLE IF NOT EXISTS "observed_channel_messages" (
-    "user_id" INTEGER NOT NULL REFERENCES users (id) ON DELETE CASCADE,
-    "channel_id" INTEGER NOT NULL REFERENCES channels (id) ON DELETE CASCADE,
-    "channel_message_id" INTEGER NOT NULL,
-    PRIMARY KEY (user_id, channel_id)
-);
-
-CREATE UNIQUE INDEX "index_observed_channel_messages_user_and_channel_id" ON "observed_channel_messages" ("user_id", "channel_id");

crates/collab/migrations/20231004130100_create_notifications.sql 🔗

@@ -1,22 +0,0 @@
-CREATE TABLE "notification_kinds" (
-    "id" SERIAL PRIMARY KEY,
-    "name" VARCHAR NOT NULL
-);
-
-CREATE UNIQUE INDEX "index_notification_kinds_on_name" ON "notification_kinds" ("name");
-
-CREATE TABLE notifications (
-    "id" SERIAL PRIMARY KEY,
-    "created_at" TIMESTAMP NOT NULL DEFAULT now(),
-    "recipient_id" INTEGER NOT NULL REFERENCES users (id) ON DELETE CASCADE,
-    "kind" INTEGER NOT NULL REFERENCES notification_kinds (id),
-    "entity_id" INTEGER,
-    "content" TEXT,
-    "is_read" BOOLEAN NOT NULL DEFAULT FALSE,
-    "response" BOOLEAN
-);
-
-CREATE INDEX
-    "index_notifications_on_recipient_id_is_read_kind_entity_id"
-    ON "notifications"
-    ("recipient_id", "is_read", "kind", "entity_id");

crates/collab/migrations/20231018102700_create_mentions.sql 🔗

@@ -1,11 +0,0 @@
-CREATE TABLE "channel_message_mentions" (
-    "message_id" INTEGER NOT NULL REFERENCES channel_messages (id) ON DELETE CASCADE,
-    "start_offset" INTEGER NOT NULL,
-    "end_offset" INTEGER NOT NULL,
-    "user_id" INTEGER NOT NULL REFERENCES users (id) ON DELETE CASCADE,
-    PRIMARY KEY(message_id, start_offset)
-);
-
--- We use 'on conflict update' with this index, so it should be per-user.
-CREATE UNIQUE INDEX "index_channel_messages_on_sender_id_nonce" ON "channel_messages" ("sender_id", "nonce");
-DROP INDEX "index_channel_messages_on_nonce";

crates/collab/migrations/20231024085546_move_channel_paths_to_channels_table.sql 🔗

@@ -1,12 +0,0 @@
-ALTER TABLE channels ADD COLUMN parent_path TEXT;
-
-UPDATE channels
-SET parent_path = substr(
-    channel_paths.id_path,
-    2,
-    length(channel_paths.id_path) - length('/' || channel_paths.channel_id::text || '/')
-)
-FROM channel_paths
-WHERE channel_paths.channel_id = channels.id;
-
-CREATE INDEX "index_channels_on_parent_path" ON "channels" ("parent_path");

crates/collab/migrations/20240214102900_add_extensions.sql 🔗

@@ -1,22 +0,0 @@
-CREATE TABLE IF NOT EXISTS extensions (
-    id SERIAL PRIMARY KEY,
-    name TEXT NOT NULL,
-    external_id TEXT NOT NULL,
-    latest_version TEXT NOT NULL,
-    total_download_count BIGINT NOT NULL DEFAULT 0
-);
-
-CREATE TABLE IF NOT EXISTS extension_versions (
-    extension_id INTEGER REFERENCES extensions(id),
-    version TEXT NOT NULL,
-    published_at TIMESTAMP NOT NULL DEFAULT now(),
-    authors TEXT NOT NULL,
-    repository TEXT NOT NULL,
-    description TEXT NOT NULL,
-    download_count BIGINT NOT NULL DEFAULT 0,
-    PRIMARY KEY(extension_id, version)
-);
-
-CREATE UNIQUE INDEX "index_extensions_external_id" ON "extensions" ("external_id");
-CREATE INDEX "trigram_index_extensions_name" ON "extensions" USING GIN(name gin_trgm_ops);
-CREATE INDEX "index_extensions_total_download_count" ON "extensions" ("total_download_count");

crates/collab/migrations/20240220234826_add_rate_buckets.sql 🔗

@@ -1,11 +0,0 @@
-CREATE TABLE IF NOT EXISTS rate_buckets (
-    user_id INT NOT NULL,
-    rate_limit_name VARCHAR(255) NOT NULL,
-    token_count INT NOT NULL,
-    last_refill TIMESTAMP WITHOUT TIME ZONE NOT NULL,
-    PRIMARY KEY (user_id, rate_limit_name),
-    CONSTRAINT fk_user
-        FOREIGN KEY (user_id) REFERENCES users(id)
-);
-
-CREATE INDEX idx_user_id_rate_limit ON rate_buckets (user_id, rate_limit_name);

crates/collab/migrations/20240226163408_hosted_projects.sql 🔗

@@ -1,11 +0,0 @@
--- Add migration script here
-
-CREATE TABLE hosted_projects (
-    id INT PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
-    channel_id INT NOT NULL REFERENCES channels(id),
-    name TEXT NOT NULL,
-    visibility TEXT NOT NULL,
-    deleted_at TIMESTAMP NULL
-);
-CREATE INDEX idx_hosted_projects_on_channel_id ON hosted_projects (channel_id);
-CREATE UNIQUE INDEX uix_hosted_projects_on_channel_id_and_name ON hosted_projects (channel_id, name) WHERE (deleted_at IS NULL);

crates/collab/migrations/20240307163119_denormalize_buffer_ops.sql 🔗

@@ -1,17 +0,0 @@
--- Add migration script here
-
-ALTER TABLE buffers ADD COLUMN latest_operation_epoch INTEGER;
-ALTER TABLE buffers ADD COLUMN latest_operation_lamport_timestamp INTEGER;
-ALTER TABLE buffers ADD COLUMN latest_operation_replica_id INTEGER;
-
-WITH ops AS (
-    SELECT DISTINCT ON (buffer_id) buffer_id, epoch, lamport_timestamp, replica_id
-    FROM buffer_operations
-    ORDER BY buffer_id, epoch DESC, lamport_timestamp DESC, replica_id DESC
-)
-UPDATE buffers
-SET latest_operation_epoch = ops.epoch,
-    latest_operation_lamport_timestamp = ops.lamport_timestamp,
-    latest_operation_replica_id = ops.replica_id
-FROM ops
-WHERE buffers.id = ops.buffer_id;

crates/collab/migrations/20240321162658_add_devservers.sql 🔗

@@ -1,7 +0,0 @@
-CREATE TABLE dev_servers (
-  id INT PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
-  channel_id INT NOT NULL REFERENCES channels(id),
-  name TEXT NOT NULL,
-  hashed_token TEXT NOT NULL
-);
-CREATE INDEX idx_dev_servers_on_channel_id ON dev_servers (channel_id);

crates/collab/migrations/20240402155003_add_dev_server_projects.sql 🔗

@@ -1,9 +0,0 @@
-CREATE TABLE remote_projects (
-    id INT PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
-    channel_id INT NOT NULL REFERENCES channels(id),
-    dev_server_id INT NOT NULL REFERENCES dev_servers(id),
-    name TEXT NOT NULL,
-    path TEXT NOT NULL
-);
-
-ALTER TABLE projects ADD COLUMN remote_project_id INTEGER REFERENCES remote_projects(id);

crates/collab/migrations/20240409082755_create_embeddings.sql 🔗

@@ -1,9 +0,0 @@
-CREATE TABLE IF NOT EXISTS "embeddings" (
-    "model" TEXT,
-    "digest" BYTEA,
-    "dimensions" FLOAT4[1536],
-    "retrieved_at" TIMESTAMP NOT NULL DEFAULT now(),
-    PRIMARY KEY ("model", "digest")
-);
-
-CREATE INDEX IF NOT EXISTS "idx_retrieved_at_on_embeddings" ON "embeddings" ("retrieved_at");

crates/collab/migrations/20240502150229_rename_to_dev_server_projects.sql 🔗

@@ -1,11 +0,0 @@
-CREATE TABLE dev_server_projects (
-    id INT PRIMARY KEY GENERATED ALWAYS AS IDENTITY (START WITH 100),
-    dev_server_id INT NOT NULL REFERENCES dev_servers(id) ON DELETE CASCADE,
-    path TEXT NOT NULL
-);
-INSERT INTO dev_server_projects OVERRIDING SYSTEM VALUE SELECT * FROM remote_projects;
-
-ALTER TABLE dev_server_projects ADD CONSTRAINT uix_dev_server_projects_dev_server_id_path UNIQUE(dev_server_id, path);
-
-ALTER TABLE projects ADD COLUMN dev_server_project_id INTEGER REFERENCES dev_server_projects(id);
-UPDATE projects SET dev_server_project_id = remote_project_id;

crates/collab/migrations/20240729170526_add_billing_subscription.sql 🔗

@@ -1,12 +0,0 @@
-CREATE TABLE IF NOT EXISTS billing_subscriptions (
-    id SERIAL PRIMARY KEY,
-    created_at TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT now(),
-    user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
-    stripe_customer_id TEXT NOT NULL,
-    stripe_subscription_id TEXT NOT NULL,
-    stripe_subscription_status TEXT NOT NULL
-);
-
-CREATE INDEX "ix_billing_subscriptions_on_user_id" ON billing_subscriptions (user_id);
-CREATE INDEX "ix_billing_subscriptions_on_stripe_customer_id" ON billing_subscriptions (stripe_customer_id);
-CREATE UNIQUE INDEX "uix_billing_subscriptions_on_stripe_subscription_id" ON billing_subscriptions (stripe_subscription_id);

crates/collab/migrations/20240730014107_add_billing_customer.sql 🔗

@@ -1,18 +0,0 @@
-CREATE TABLE IF NOT EXISTS billing_customers (
-    id SERIAL PRIMARY KEY,
-    created_at TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT now(),
-    user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
-    stripe_customer_id TEXT NOT NULL
-);
-
-CREATE UNIQUE INDEX "uix_billing_customers_on_user_id" ON billing_customers (user_id);
-CREATE UNIQUE INDEX "uix_billing_customers_on_stripe_customer_id" ON billing_customers (stripe_customer_id);
-
--- Make `billing_subscriptions` reference `billing_customers` instead of having its
--- own `user_id` and `stripe_customer_id`.
-DROP INDEX IF EXISTS "ix_billing_subscriptions_on_user_id";
-DROP INDEX IF EXISTS "ix_billing_subscriptions_on_stripe_customer_id";
-ALTER TABLE billing_subscriptions DROP COLUMN user_id;
-ALTER TABLE billing_subscriptions DROP COLUMN stripe_customer_id;
-ALTER TABLE billing_subscriptions ADD COLUMN billing_customer_id INTEGER NOT NULL REFERENCES billing_customers (id) ON DELETE CASCADE;
-CREATE INDEX "ix_billing_subscriptions_on_billing_customer_id" ON billing_subscriptions (billing_customer_id);

crates/collab/migrations/20240730182554_add_processed_stripe_events.sql 🔗

@@ -1,11 +0,0 @@
-ALTER TABLE billing_customers DROP COLUMN last_stripe_event_id;
-ALTER TABLE billing_subscriptions DROP COLUMN last_stripe_event_id;
-
-CREATE TABLE IF NOT EXISTS processed_stripe_events (
-    stripe_event_id TEXT PRIMARY KEY,
-    stripe_event_type TEXT NOT NULL,
-    stripe_event_created_timestamp BIGINT NOT NULL,
-    processed_at TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT now()
-);
-
-CREATE INDEX "ix_processed_stripe_events_on_stripe_event_created_timestamp" ON processed_stripe_events (stripe_event_created_timestamp);

crates/collab/migrations/20241009190639_add_billing_preferences.sql 🔗

@@ -1,8 +0,0 @@
-create table if not exists billing_preferences (
-    id serial primary key,
-    created_at timestamp without time zone not null default now(),
-    user_id integer not null references users(id) on delete cascade,
-    max_monthly_llm_usage_spending_in_cents integer not null
-);
-
-create unique index "uix_billing_preferences_on_user_id" on billing_preferences (user_id);

crates/collab/migrations/20241121185750_add_breakpoints.sql 🔗

@@ -1,11 +0,0 @@
-CREATE TABLE IF NOT EXISTS "breakpoints" (
-    "id" SERIAL PRIMARY KEY,
-    "project_id" INTEGER NOT NULL REFERENCES projects (id) ON DELETE CASCADE,
-    "position" INTEGER NOT NULL,
-    "log_message" TEXT NULL,
-    "worktree_id" BIGINT NOT NULL,
-    "path" TEXT NOT NULL,
-    "kind" VARCHAR NOT NULL
-);
-
-CREATE INDEX "index_breakpoints_on_project_id" ON "breakpoints" ("project_id");

crates/collab/migrations/20250113230049_expand_git_status_information.sql 🔗

@@ -1,13 +0,0 @@
-ALTER TABLE worktree_repository_statuses
-ADD COLUMN status_kind INTEGER,
-ADD COLUMN first_status INTEGER,
-ADD COLUMN second_status INTEGER;
-
-UPDATE worktree_repository_statuses
-SET
-    status_kind = 0;
-
-ALTER TABLE worktree_repository_statuses
-ALTER COLUMN status_kind
-SET
-    NOT NULL;

crates/collab/migrations/20250205192813_add_provides_fields_to_extension_versions.sql 🔗

@@ -1,10 +0,0 @@
-alter table extension_versions
-add column provides_themes bool not null default false,
-add column provides_icon_themes bool not null default false,
-add column provides_languages bool not null default false,
-add column provides_grammars bool not null default false,
-add column provides_language_servers bool not null default false,
-add column provides_context_servers bool not null default false,
-add column provides_slash_commands bool not null default false,
-add column provides_indexed_docs_providers bool not null default false,
-add column provides_snippets bool not null default false;

crates/collab/migrations/20250319182812_create_project_repositories.sql 🔗

@@ -1,32 +0,0 @@
-CREATE TABLE "project_repositories" (
-    "project_id" INTEGER NOT NULL,
-    "abs_path" VARCHAR,
-    "id" INT8 NOT NULL,
-    "legacy_worktree_id" INT8,
-    "entry_ids" VARCHAR,
-    "branch" VARCHAR,
-    "scan_id" INT8 NOT NULL,
-    "is_deleted" BOOL NOT NULL,
-    "current_merge_conflicts" VARCHAR,
-    "branch_summary" VARCHAR,
-    PRIMARY KEY (project_id, id)
-);
-
-CREATE INDEX "index_project_repositories_on_project_id" ON "project_repositories" ("project_id");
-
-CREATE TABLE "project_repository_statuses" (
-    "project_id" INTEGER NOT NULL,
-    "repository_id" INT8 NOT NULL,
-    "repo_path" VARCHAR NOT NULL,
-    "status" INT8 NOT NULL,
-    "status_kind" INT4 NOT NULL,
-    "first_status" INT4 NULL,
-    "second_status" INT4 NULL,
-    "scan_id" INT8 NOT NULL,
-    "is_deleted" BOOL NOT NULL,
-    PRIMARY KEY (project_id, repository_id, repo_path)
-);
-
-CREATE INDEX "index_project_repos_statuses_on_project_id" ON "project_repository_statuses" ("project_id");
-
-CREATE INDEX "index_project_repos_statuses_on_project_id_and_repo_id" ON "project_repository_statuses" ("project_id", "repository_id");

crates/collab/migrations/20250530175450_add_channel_order.sql 🔗

@@ -1,16 +0,0 @@
--- Add channel_order column to channels table with default value
-ALTER TABLE channels ADD COLUMN channel_order INTEGER NOT NULL DEFAULT 1;
-
--- Update channel_order for existing channels using ROW_NUMBER for deterministic ordering
-UPDATE channels
-SET channel_order = (
-    SELECT ROW_NUMBER() OVER (
-        PARTITION BY parent_path
-        ORDER BY name, id
-    )
-    FROM channels c2
-    WHERE c2.id = channels.id
-);
-
--- Create index for efficient ordering queries
-CREATE INDEX "index_channels_on_parent_path_and_order" ON "channels" ("parent_path", "channel_order");

crates/collab/migrations/20250702185129_add_cascading_delete_to_repository_entries.sql 🔗

@@ -1,25 +0,0 @@
-DELETE FROM project_repositories
-WHERE project_id NOT IN (SELECT id FROM projects);
-
-ALTER TABLE project_repositories
-    ADD CONSTRAINT fk_project_repositories_project_id
-        FOREIGN KEY (project_id)
-        REFERENCES projects (id)
-        ON DELETE CASCADE
-        NOT VALID;
-
-ALTER TABLE project_repositories
-    VALIDATE CONSTRAINT fk_project_repositories_project_id;
-
-DELETE FROM project_repository_statuses
-WHERE project_id NOT IN (SELECT id FROM projects);
-
-ALTER TABLE project_repository_statuses
-    ADD CONSTRAINT fk_project_repository_statuses_project_id
-        FOREIGN KEY (project_id)
-        REFERENCES projects (id)
-        ON DELETE CASCADE
-        NOT VALID;
-
-ALTER TABLE project_repository_statuses
-    VALIDATE CONSTRAINT fk_project_repository_statuses_project_id;

crates/collab/migrations/20251208000000_test_schema.sql 🔗

@@ -0,0 +1,899 @@
+CREATE EXTENSION IF NOT EXISTS pg_trgm WITH SCHEMA public;
+
+CREATE TABLE public.access_tokens (
+    id integer NOT NULL,
+    user_id integer,
+    hash character varying(128),
+    impersonated_user_id integer
+);
+
+CREATE SEQUENCE public.access_tokens_id_seq
+    AS integer
+    START WITH 1
+    INCREMENT BY 1
+    NO MINVALUE
+    NO MAXVALUE
+    CACHE 1;
+
+ALTER SEQUENCE public.access_tokens_id_seq OWNED BY public.access_tokens.id;
+
+CREATE TABLE public.breakpoints (
+    id integer NOT NULL,
+    project_id integer NOT NULL,
+    "position" integer NOT NULL,
+    log_message text,
+    worktree_id bigint NOT NULL,
+    path text NOT NULL,
+    kind character varying NOT NULL
+);
+
+CREATE SEQUENCE public.breakpoints_id_seq
+    AS integer
+    START WITH 1
+    INCREMENT BY 1
+    NO MINVALUE
+    NO MAXVALUE
+    CACHE 1;
+
+ALTER SEQUENCE public.breakpoints_id_seq OWNED BY public.breakpoints.id;
+
+CREATE TABLE public.buffer_operations (
+    buffer_id integer NOT NULL,
+    epoch integer NOT NULL,
+    replica_id integer NOT NULL,
+    lamport_timestamp integer NOT NULL,
+    value bytea NOT NULL
+);
+
+CREATE TABLE public.buffer_snapshots (
+    buffer_id integer NOT NULL,
+    epoch integer NOT NULL,
+    text text NOT NULL,
+    operation_serialization_version integer NOT NULL
+);
+
+CREATE TABLE public.buffers (
+    id integer NOT NULL,
+    channel_id integer NOT NULL,
+    epoch integer DEFAULT 0 NOT NULL,
+    latest_operation_epoch integer,
+    latest_operation_lamport_timestamp integer,
+    latest_operation_replica_id integer
+);
+
+CREATE SEQUENCE public.buffers_id_seq
+    AS integer
+    START WITH 1
+    INCREMENT BY 1
+    NO MINVALUE
+    NO MAXVALUE
+    CACHE 1;
+
+ALTER SEQUENCE public.buffers_id_seq OWNED BY public.buffers.id;
+
+CREATE TABLE public.channel_buffer_collaborators (
+    id integer NOT NULL,
+    channel_id integer NOT NULL,
+    connection_id integer NOT NULL,
+    connection_server_id integer NOT NULL,
+    connection_lost boolean DEFAULT false NOT NULL,
+    user_id integer NOT NULL,
+    replica_id integer NOT NULL
+);
+
+CREATE SEQUENCE public.channel_buffer_collaborators_id_seq
+    AS integer
+    START WITH 1
+    INCREMENT BY 1
+    NO MINVALUE
+    NO MAXVALUE
+    CACHE 1;
+
+ALTER SEQUENCE public.channel_buffer_collaborators_id_seq OWNED BY public.channel_buffer_collaborators.id;
+
+CREATE TABLE public.channel_chat_participants (
+    id integer NOT NULL,
+    user_id integer NOT NULL,
+    channel_id integer NOT NULL,
+    connection_id integer NOT NULL,
+    connection_server_id integer NOT NULL
+);
+
+CREATE SEQUENCE public.channel_chat_participants_id_seq
+    AS integer
+    START WITH 1
+    INCREMENT BY 1
+    NO MINVALUE
+    NO MAXVALUE
+    CACHE 1;
+
+ALTER SEQUENCE public.channel_chat_participants_id_seq OWNED BY public.channel_chat_participants.id;
+
+CREATE TABLE public.channel_members (
+    id integer NOT NULL,
+    channel_id integer NOT NULL,
+    user_id integer NOT NULL,
+    accepted boolean DEFAULT false NOT NULL,
+    updated_at timestamp without time zone DEFAULT now() NOT NULL,
+    role text NOT NULL
+);
+
+CREATE SEQUENCE public.channel_members_id_seq
+    AS integer
+    START WITH 1
+    INCREMENT BY 1
+    NO MINVALUE
+    NO MAXVALUE
+    CACHE 1;
+
+ALTER SEQUENCE public.channel_members_id_seq OWNED BY public.channel_members.id;
+
+CREATE TABLE public.channels (
+    id integer NOT NULL,
+    name character varying NOT NULL,
+    created_at timestamp without time zone DEFAULT now() NOT NULL,
+    visibility text DEFAULT 'members'::text NOT NULL,
+    parent_path text NOT NULL,
+    requires_zed_cla boolean DEFAULT false NOT NULL,
+    channel_order integer DEFAULT 1 NOT NULL
+);
+
+CREATE SEQUENCE public.channels_id_seq
+    AS integer
+    START WITH 1
+    INCREMENT BY 1
+    NO MINVALUE
+    NO MAXVALUE
+    CACHE 1;
+
+ALTER SEQUENCE public.channels_id_seq OWNED BY public.channels.id;
+
+CREATE TABLE public.contacts (
+    id integer NOT NULL,
+    user_id_a integer NOT NULL,
+    user_id_b integer NOT NULL,
+    a_to_b boolean NOT NULL,
+    should_notify boolean NOT NULL,
+    accepted boolean NOT NULL
+);
+
+CREATE SEQUENCE public.contacts_id_seq
+    AS integer
+    START WITH 1
+    INCREMENT BY 1
+    NO MINVALUE
+    NO MAXVALUE
+    CACHE 1;
+
+ALTER SEQUENCE public.contacts_id_seq OWNED BY public.contacts.id;
+
+CREATE TABLE public.contributors (
+    user_id integer NOT NULL,
+    signed_at timestamp without time zone DEFAULT now() NOT NULL
+);
+
+CREATE TABLE public.extension_versions (
+    extension_id integer NOT NULL,
+    version text NOT NULL,
+    published_at timestamp without time zone DEFAULT now() NOT NULL,
+    authors text NOT NULL,
+    repository text NOT NULL,
+    description text NOT NULL,
+    download_count bigint DEFAULT 0 NOT NULL,
+    schema_version integer DEFAULT 0 NOT NULL,
+    wasm_api_version text,
+    provides_themes boolean DEFAULT false NOT NULL,
+    provides_icon_themes boolean DEFAULT false NOT NULL,
+    provides_languages boolean DEFAULT false NOT NULL,
+    provides_grammars boolean DEFAULT false NOT NULL,
+    provides_language_servers boolean DEFAULT false NOT NULL,
+    provides_context_servers boolean DEFAULT false NOT NULL,
+    provides_slash_commands boolean DEFAULT false NOT NULL,
+    provides_indexed_docs_providers boolean DEFAULT false NOT NULL,
+    provides_snippets boolean DEFAULT false NOT NULL,
+    provides_debug_adapters boolean DEFAULT false NOT NULL,
+    provides_agent_servers boolean DEFAULT false NOT NULL
+);
+
+CREATE TABLE public.extensions (
+    id integer NOT NULL,
+    name text NOT NULL,
+    external_id text NOT NULL,
+    latest_version text NOT NULL,
+    total_download_count bigint DEFAULT 0 NOT NULL
+);
+
+CREATE SEQUENCE public.extensions_id_seq
+    AS integer
+    START WITH 1
+    INCREMENT BY 1
+    NO MINVALUE
+    NO MAXVALUE
+    CACHE 1;
+
+ALTER SEQUENCE public.extensions_id_seq OWNED BY public.extensions.id;
+
+CREATE TABLE public.feature_flags (
+    id integer NOT NULL,
+    flag character varying(255) NOT NULL,
+    enabled_for_all boolean DEFAULT false NOT NULL
+);
+
+CREATE SEQUENCE public.feature_flags_id_seq
+    AS integer
+    START WITH 1
+    INCREMENT BY 1
+    NO MINVALUE
+    NO MAXVALUE
+    CACHE 1;
+
+ALTER SEQUENCE public.feature_flags_id_seq OWNED BY public.feature_flags.id;
+
+CREATE TABLE public.followers (
+    id integer NOT NULL,
+    room_id integer NOT NULL,
+    project_id integer NOT NULL,
+    leader_connection_server_id integer NOT NULL,
+    leader_connection_id integer NOT NULL,
+    follower_connection_server_id integer NOT NULL,
+    follower_connection_id integer NOT NULL
+);
+
+CREATE SEQUENCE public.followers_id_seq
+    AS integer
+    START WITH 1
+    INCREMENT BY 1
+    NO MINVALUE
+    NO MAXVALUE
+    CACHE 1;
+
+ALTER SEQUENCE public.followers_id_seq OWNED BY public.followers.id;
+
+CREATE TABLE public.language_servers (
+    project_id integer NOT NULL,
+    id bigint NOT NULL,
+    name character varying NOT NULL,
+    capabilities text NOT NULL,
+    worktree_id bigint
+);
+
+CREATE TABLE public.notification_kinds (
+    id integer NOT NULL,
+    name character varying NOT NULL
+);
+
+CREATE SEQUENCE public.notification_kinds_id_seq
+    AS integer
+    START WITH 1
+    INCREMENT BY 1
+    NO MINVALUE
+    NO MAXVALUE
+    CACHE 1;
+
+ALTER SEQUENCE public.notification_kinds_id_seq OWNED BY public.notification_kinds.id;
+
+CREATE TABLE public.notifications (
+    id integer NOT NULL,
+    created_at timestamp without time zone DEFAULT now() NOT NULL,
+    recipient_id integer NOT NULL,
+    kind integer NOT NULL,
+    entity_id integer,
+    content text,
+    is_read boolean DEFAULT false NOT NULL,
+    response boolean
+);
+
+CREATE SEQUENCE public.notifications_id_seq
+    AS integer
+    START WITH 1
+    INCREMENT BY 1
+    NO MINVALUE
+    NO MAXVALUE
+    CACHE 1;
+
+ALTER SEQUENCE public.notifications_id_seq OWNED BY public.notifications.id;
+
+CREATE TABLE public.observed_buffer_edits (
+    user_id integer NOT NULL,
+    buffer_id integer NOT NULL,
+    epoch integer NOT NULL,
+    lamport_timestamp integer NOT NULL,
+    replica_id integer NOT NULL
+);
+
+CREATE TABLE public.project_collaborators (
+    id integer NOT NULL,
+    project_id integer NOT NULL,
+    connection_id integer NOT NULL,
+    user_id integer NOT NULL,
+    replica_id integer NOT NULL,
+    is_host boolean NOT NULL,
+    connection_server_id integer NOT NULL,
+    committer_name character varying,
+    committer_email character varying
+);
+
+CREATE SEQUENCE public.project_collaborators_id_seq
+    AS integer
+    START WITH 1
+    INCREMENT BY 1
+    NO MINVALUE
+    NO MAXVALUE
+    CACHE 1;
+
+ALTER SEQUENCE public.project_collaborators_id_seq OWNED BY public.project_collaborators.id;
+
+CREATE TABLE public.project_repositories (
+    project_id integer NOT NULL,
+    abs_path character varying,
+    id bigint NOT NULL,
+    legacy_worktree_id bigint,
+    entry_ids character varying,
+    branch character varying,
+    scan_id bigint NOT NULL,
+    is_deleted boolean NOT NULL,
+    current_merge_conflicts character varying,
+    branch_summary character varying,
+    head_commit_details character varying,
+    merge_message character varying
+);
+
+CREATE TABLE public.project_repository_statuses (
+    project_id integer NOT NULL,
+    repository_id bigint NOT NULL,
+    repo_path character varying NOT NULL,
+    status bigint NOT NULL,
+    status_kind integer NOT NULL,
+    first_status integer,
+    second_status integer,
+    scan_id bigint NOT NULL,
+    is_deleted boolean NOT NULL
+);
+
+CREATE TABLE public.projects (
+    id integer NOT NULL,
+    host_user_id integer,
+    unregistered boolean DEFAULT false NOT NULL,
+    room_id integer,
+    host_connection_id integer,
+    host_connection_server_id integer,
+    windows_paths boolean DEFAULT false
+);
+
+CREATE SEQUENCE public.projects_id_seq
+    AS integer
+    START WITH 1
+    INCREMENT BY 1
+    NO MINVALUE
+    NO MAXVALUE
+    CACHE 1;
+
+ALTER SEQUENCE public.projects_id_seq OWNED BY public.projects.id;
+
+CREATE TABLE public.room_participants (
+    id integer NOT NULL,
+    room_id integer NOT NULL,
+    user_id integer NOT NULL,
+    answering_connection_id integer,
+    location_kind integer,
+    location_project_id integer,
+    initial_project_id integer,
+    calling_user_id integer NOT NULL,
+    calling_connection_id integer NOT NULL,
+    answering_connection_lost boolean DEFAULT false NOT NULL,
+    answering_connection_server_id integer,
+    calling_connection_server_id integer,
+    participant_index integer,
+    role text
+);
+
+CREATE SEQUENCE public.room_participants_id_seq
+    AS integer
+    START WITH 1
+    INCREMENT BY 1
+    NO MINVALUE
+    NO MAXVALUE
+    CACHE 1;
+
+ALTER SEQUENCE public.room_participants_id_seq OWNED BY public.room_participants.id;
+
+CREATE TABLE public.rooms (
+    id integer NOT NULL,
+    live_kit_room character varying NOT NULL,
+    channel_id integer
+);
+
+CREATE SEQUENCE public.rooms_id_seq
+    AS integer
+    START WITH 1
+    INCREMENT BY 1
+    NO MINVALUE
+    NO MAXVALUE
+    CACHE 1;
+
+ALTER SEQUENCE public.rooms_id_seq OWNED BY public.rooms.id;
+
+CREATE TABLE public.servers (
+    id integer NOT NULL,
+    environment character varying NOT NULL
+);
+
+CREATE SEQUENCE public.servers_id_seq
+    AS integer
+    START WITH 1
+    INCREMENT BY 1
+    NO MINVALUE
+    NO MAXVALUE
+    CACHE 1;
+
+ALTER SEQUENCE public.servers_id_seq OWNED BY public.servers.id;
+
+CREATE TABLE public.user_features (
+    user_id integer NOT NULL,
+    feature_id integer NOT NULL
+);
+
+CREATE TABLE public.users (
+    id integer NOT NULL,
+    github_login character varying,
+    admin boolean NOT NULL,
+    email_address character varying(255) DEFAULT NULL::character varying,
+    invite_code character varying(64),
+    invite_count integer DEFAULT 0 NOT NULL,
+    inviter_id integer,
+    connected_once boolean DEFAULT false NOT NULL,
+    created_at timestamp without time zone DEFAULT now() NOT NULL,
+    github_user_id integer NOT NULL,
+    metrics_id uuid DEFAULT gen_random_uuid() NOT NULL,
+    accepted_tos_at timestamp without time zone,
+    github_user_created_at timestamp without time zone,
+    custom_llm_monthly_allowance_in_cents integer,
+    name text
+);
+
+CREATE SEQUENCE public.users_id_seq
+    AS integer
+    START WITH 1
+    INCREMENT BY 1
+    NO MINVALUE
+    NO MAXVALUE
+    CACHE 1;
+
+ALTER SEQUENCE public.users_id_seq OWNED BY public.users.id;
+
+CREATE TABLE public.worktree_diagnostic_summaries (
+    project_id integer NOT NULL,
+    worktree_id bigint NOT NULL,
+    path character varying NOT NULL,
+    language_server_id bigint NOT NULL,
+    error_count integer NOT NULL,
+    warning_count integer NOT NULL
+);
+
+CREATE TABLE public.worktree_entries (
+    project_id integer NOT NULL,
+    worktree_id bigint NOT NULL,
+    id bigint NOT NULL,
+    is_dir boolean NOT NULL,
+    path character varying NOT NULL,
+    inode bigint NOT NULL,
+    mtime_seconds bigint NOT NULL,
+    mtime_nanos integer NOT NULL,
+    is_symlink boolean DEFAULT false NOT NULL,
+    is_ignored boolean NOT NULL,
+    scan_id bigint,
+    is_deleted boolean,
+    git_status bigint,
+    is_external boolean DEFAULT false NOT NULL,
+    is_fifo boolean DEFAULT false NOT NULL,
+    canonical_path text,
+    is_hidden boolean DEFAULT false NOT NULL
+);
+
+CREATE TABLE public.worktree_settings_files (
+    project_id integer NOT NULL,
+    worktree_id bigint NOT NULL,
+    path character varying NOT NULL,
+    content text NOT NULL,
+    kind character varying
+);
+
+CREATE TABLE public.worktrees (
+    project_id integer NOT NULL,
+    id bigint NOT NULL,
+    root_name character varying NOT NULL,
+    abs_path character varying NOT NULL,
+    visible boolean NOT NULL,
+    scan_id bigint NOT NULL,
+    is_complete boolean DEFAULT false NOT NULL,
+    completed_scan_id bigint
+);
+
+ALTER TABLE ONLY public.access_tokens ALTER COLUMN id SET DEFAULT nextval('public.access_tokens_id_seq'::regclass);
+
+ALTER TABLE ONLY public.breakpoints ALTER COLUMN id SET DEFAULT nextval('public.breakpoints_id_seq'::regclass);
+
+ALTER TABLE ONLY public.buffers ALTER COLUMN id SET DEFAULT nextval('public.buffers_id_seq'::regclass);
+
+ALTER TABLE ONLY public.channel_buffer_collaborators ALTER COLUMN id SET DEFAULT nextval('public.channel_buffer_collaborators_id_seq'::regclass);
+
+ALTER TABLE ONLY public.channel_chat_participants ALTER COLUMN id SET DEFAULT nextval('public.channel_chat_participants_id_seq'::regclass);
+
+ALTER TABLE ONLY public.channel_members ALTER COLUMN id SET DEFAULT nextval('public.channel_members_id_seq'::regclass);
+
+ALTER TABLE ONLY public.channels ALTER COLUMN id SET DEFAULT nextval('public.channels_id_seq'::regclass);
+
+ALTER TABLE ONLY public.contacts ALTER COLUMN id SET DEFAULT nextval('public.contacts_id_seq'::regclass);
+
+ALTER TABLE ONLY public.extensions ALTER COLUMN id SET DEFAULT nextval('public.extensions_id_seq'::regclass);
+
+ALTER TABLE ONLY public.feature_flags ALTER COLUMN id SET DEFAULT nextval('public.feature_flags_id_seq'::regclass);
+
+ALTER TABLE ONLY public.followers ALTER COLUMN id SET DEFAULT nextval('public.followers_id_seq'::regclass);
+
+ALTER TABLE ONLY public.notification_kinds ALTER COLUMN id SET DEFAULT nextval('public.notification_kinds_id_seq'::regclass);
+
+ALTER TABLE ONLY public.notifications ALTER COLUMN id SET DEFAULT nextval('public.notifications_id_seq'::regclass);
+
+ALTER TABLE ONLY public.project_collaborators ALTER COLUMN id SET DEFAULT nextval('public.project_collaborators_id_seq'::regclass);
+
+ALTER TABLE ONLY public.projects ALTER COLUMN id SET DEFAULT nextval('public.projects_id_seq'::regclass);
+
+ALTER TABLE ONLY public.room_participants ALTER COLUMN id SET DEFAULT nextval('public.room_participants_id_seq'::regclass);
+
+ALTER TABLE ONLY public.rooms ALTER COLUMN id SET DEFAULT nextval('public.rooms_id_seq'::regclass);
+
+ALTER TABLE ONLY public.servers ALTER COLUMN id SET DEFAULT nextval('public.servers_id_seq'::regclass);
+
+ALTER TABLE ONLY public.users ALTER COLUMN id SET DEFAULT nextval('public.users_id_seq'::regclass);
+
+ALTER TABLE ONLY public.access_tokens
+    ADD CONSTRAINT access_tokens_pkey PRIMARY KEY (id);
+
+ALTER TABLE ONLY public.breakpoints
+    ADD CONSTRAINT breakpoints_pkey PRIMARY KEY (id);
+
+ALTER TABLE ONLY public.buffer_operations
+    ADD CONSTRAINT buffer_operations_pkey PRIMARY KEY (buffer_id, epoch, lamport_timestamp, replica_id);
+
+ALTER TABLE ONLY public.buffer_snapshots
+    ADD CONSTRAINT buffer_snapshots_pkey PRIMARY KEY (buffer_id, epoch);
+
+ALTER TABLE ONLY public.buffers
+    ADD CONSTRAINT buffers_pkey PRIMARY KEY (id);
+
+ALTER TABLE ONLY public.channel_buffer_collaborators
+    ADD CONSTRAINT channel_buffer_collaborators_pkey PRIMARY KEY (id);
+
+ALTER TABLE ONLY public.channel_chat_participants
+    ADD CONSTRAINT channel_chat_participants_pkey PRIMARY KEY (id);
+
+ALTER TABLE ONLY public.channel_members
+    ADD CONSTRAINT channel_members_pkey PRIMARY KEY (id);
+
+ALTER TABLE ONLY public.channels
+    ADD CONSTRAINT channels_pkey PRIMARY KEY (id);
+
+ALTER TABLE ONLY public.contacts
+    ADD CONSTRAINT contacts_pkey PRIMARY KEY (id);
+
+ALTER TABLE ONLY public.contributors
+    ADD CONSTRAINT contributors_pkey PRIMARY KEY (user_id);
+
+ALTER TABLE ONLY public.extension_versions
+    ADD CONSTRAINT extension_versions_pkey PRIMARY KEY (extension_id, version);
+
+ALTER TABLE ONLY public.extensions
+    ADD CONSTRAINT extensions_pkey PRIMARY KEY (id);
+
+ALTER TABLE ONLY public.feature_flags
+    ADD CONSTRAINT feature_flags_flag_key UNIQUE (flag);
+
+ALTER TABLE ONLY public.feature_flags
+    ADD CONSTRAINT feature_flags_pkey PRIMARY KEY (id);
+
+ALTER TABLE ONLY public.followers
+    ADD CONSTRAINT followers_pkey PRIMARY KEY (id);
+
+ALTER TABLE ONLY public.language_servers
+    ADD CONSTRAINT language_servers_pkey PRIMARY KEY (project_id, id);
+
+ALTER TABLE ONLY public.notification_kinds
+    ADD CONSTRAINT notification_kinds_pkey PRIMARY KEY (id);
+
+ALTER TABLE ONLY public.notifications
+    ADD CONSTRAINT notifications_pkey PRIMARY KEY (id);
+
+ALTER TABLE ONLY public.observed_buffer_edits
+    ADD CONSTRAINT observed_buffer_edits_pkey PRIMARY KEY (user_id, buffer_id);
+
+ALTER TABLE ONLY public.project_collaborators
+    ADD CONSTRAINT project_collaborators_pkey PRIMARY KEY (id);
+
+ALTER TABLE ONLY public.project_repositories
+    ADD CONSTRAINT project_repositories_pkey PRIMARY KEY (project_id, id);
+
+ALTER TABLE ONLY public.project_repository_statuses
+    ADD CONSTRAINT project_repository_statuses_pkey PRIMARY KEY (project_id, repository_id, repo_path);
+
+ALTER TABLE ONLY public.projects
+    ADD CONSTRAINT projects_pkey PRIMARY KEY (id);
+
+ALTER TABLE ONLY public.room_participants
+    ADD CONSTRAINT room_participants_pkey PRIMARY KEY (id);
+
+ALTER TABLE ONLY public.rooms
+    ADD CONSTRAINT rooms_pkey PRIMARY KEY (id);
+
+ALTER TABLE ONLY public.servers
+    ADD CONSTRAINT servers_pkey PRIMARY KEY (id);
+
+ALTER TABLE ONLY public.user_features
+    ADD CONSTRAINT user_features_pkey PRIMARY KEY (user_id, feature_id);
+
+ALTER TABLE ONLY public.users
+    ADD CONSTRAINT users_pkey PRIMARY KEY (id);
+
+ALTER TABLE ONLY public.worktree_diagnostic_summaries
+    ADD CONSTRAINT worktree_diagnostic_summaries_pkey PRIMARY KEY (project_id, worktree_id, path);
+
+ALTER TABLE ONLY public.worktree_entries
+    ADD CONSTRAINT worktree_entries_pkey PRIMARY KEY (project_id, worktree_id, id);
+
+ALTER TABLE ONLY public.worktree_settings_files
+    ADD CONSTRAINT worktree_settings_files_pkey PRIMARY KEY (project_id, worktree_id, path);
+
+ALTER TABLE ONLY public.worktrees
+    ADD CONSTRAINT worktrees_pkey PRIMARY KEY (project_id, id);
+
+CREATE INDEX index_access_tokens_user_id ON public.access_tokens USING btree (user_id);
+
+CREATE INDEX index_breakpoints_on_project_id ON public.breakpoints USING btree (project_id);
+
+CREATE INDEX index_buffers_on_channel_id ON public.buffers USING btree (channel_id);
+
+CREATE INDEX index_channel_buffer_collaborators_on_channel_id ON public.channel_buffer_collaborators USING btree (channel_id);
+
+CREATE UNIQUE INDEX index_channel_buffer_collaborators_on_channel_id_and_replica_id ON public.channel_buffer_collaborators USING btree (channel_id, replica_id);
+
+CREATE UNIQUE INDEX index_channel_buffer_collaborators_on_channel_id_connection_id_ ON public.channel_buffer_collaborators USING btree (channel_id, connection_id, connection_server_id);
+
+CREATE INDEX index_channel_buffer_collaborators_on_connection_id ON public.channel_buffer_collaborators USING btree (connection_id);
+
+CREATE INDEX index_channel_buffer_collaborators_on_connection_server_id ON public.channel_buffer_collaborators USING btree (connection_server_id);
+
+CREATE INDEX index_channel_chat_participants_on_channel_id ON public.channel_chat_participants USING btree (channel_id);
+
+CREATE UNIQUE INDEX index_channel_members_on_channel_id_and_user_id ON public.channel_members USING btree (channel_id, user_id);
+
+CREATE INDEX index_channels_on_parent_path ON public.channels USING btree (parent_path text_pattern_ops);
+
+CREATE INDEX index_channels_on_parent_path_and_order ON public.channels USING btree (parent_path, channel_order);
+
+CREATE INDEX index_contacts_user_id_b ON public.contacts USING btree (user_id_b);
+
+CREATE UNIQUE INDEX index_contacts_user_ids ON public.contacts USING btree (user_id_a, user_id_b);
+
+CREATE UNIQUE INDEX index_extensions_external_id ON public.extensions USING btree (external_id);
+
+CREATE INDEX index_extensions_total_download_count ON public.extensions USING btree (total_download_count);
+
+CREATE UNIQUE INDEX index_feature_flags ON public.feature_flags USING btree (id);
+
+CREATE UNIQUE INDEX index_followers_on_project_id_and_leader_connection_server_id_a ON public.followers USING btree (project_id, leader_connection_server_id, leader_connection_id, follower_connection_server_id, follower_connection_id);
+
+CREATE INDEX index_followers_on_room_id ON public.followers USING btree (room_id);
+
+CREATE UNIQUE INDEX index_invite_code_users ON public.users USING btree (invite_code);
+
+CREATE INDEX index_language_servers_on_project_id ON public.language_servers USING btree (project_id);
+
+CREATE UNIQUE INDEX index_notification_kinds_on_name ON public.notification_kinds USING btree (name);
+
+CREATE INDEX index_notifications_on_recipient_id_is_read_kind_entity_id ON public.notifications USING btree (recipient_id, is_read, kind, entity_id);
+
+CREATE UNIQUE INDEX index_observed_buffer_user_and_buffer_id ON public.observed_buffer_edits USING btree (user_id, buffer_id);
+
+CREATE INDEX index_project_collaborators_on_connection_id ON public.project_collaborators USING btree (connection_id);
+
+CREATE INDEX index_project_collaborators_on_connection_server_id ON public.project_collaborators USING btree (connection_server_id);
+
+CREATE INDEX index_project_collaborators_on_project_id ON public.project_collaborators USING btree (project_id);
+
+CREATE UNIQUE INDEX index_project_collaborators_on_project_id_and_replica_id ON public.project_collaborators USING btree (project_id, replica_id);
+
+CREATE UNIQUE INDEX index_project_collaborators_on_project_id_connection_id_and_ser ON public.project_collaborators USING btree (project_id, connection_id, connection_server_id);
+
+CREATE INDEX index_project_repos_statuses_on_project_id ON public.project_repository_statuses USING btree (project_id);
+
+CREATE INDEX index_project_repos_statuses_on_project_id_and_repo_id ON public.project_repository_statuses USING btree (project_id, repository_id);
+
+CREATE INDEX index_project_repositories_on_project_id ON public.project_repositories USING btree (project_id);
+
+CREATE INDEX index_projects_on_host_connection_id_and_host_connection_server ON public.projects USING btree (host_connection_id, host_connection_server_id);
+
+CREATE INDEX index_projects_on_host_connection_server_id ON public.projects USING btree (host_connection_server_id);
+
+CREATE INDEX index_room_participants_on_answering_connection_id ON public.room_participants USING btree (answering_connection_id);
+
+CREATE UNIQUE INDEX index_room_participants_on_answering_connection_id_and_answerin ON public.room_participants USING btree (answering_connection_id, answering_connection_server_id);
+
+CREATE INDEX index_room_participants_on_answering_connection_server_id ON public.room_participants USING btree (answering_connection_server_id);
+
+CREATE INDEX index_room_participants_on_calling_connection_server_id ON public.room_participants USING btree (calling_connection_server_id);
+
+CREATE INDEX index_room_participants_on_room_id ON public.room_participants USING btree (room_id);
+
+CREATE UNIQUE INDEX index_room_participants_on_user_id ON public.room_participants USING btree (user_id);
+
+CREATE UNIQUE INDEX index_rooms_on_channel_id ON public.rooms USING btree (channel_id);
+
+CREATE INDEX index_settings_files_on_project_id ON public.worktree_settings_files USING btree (project_id);
+
+CREATE INDEX index_settings_files_on_project_id_and_wt_id ON public.worktree_settings_files USING btree (project_id, worktree_id);
+
+CREATE INDEX index_user_features_on_feature_id ON public.user_features USING btree (feature_id);
+
+CREATE INDEX index_user_features_on_user_id ON public.user_features USING btree (user_id);
+
+CREATE UNIQUE INDEX index_user_features_user_id_and_feature_id ON public.user_features USING btree (user_id, feature_id);
+
+CREATE UNIQUE INDEX index_users_github_login ON public.users USING btree (github_login);
+
+CREATE INDEX index_users_on_email_address ON public.users USING btree (email_address);
+
+CREATE INDEX index_worktree_diagnostic_summaries_on_project_id ON public.worktree_diagnostic_summaries USING btree (project_id);
+
+CREATE INDEX index_worktree_diagnostic_summaries_on_project_id_and_worktree_ ON public.worktree_diagnostic_summaries USING btree (project_id, worktree_id);
+
+CREATE INDEX index_worktree_entries_on_project_id ON public.worktree_entries USING btree (project_id);
+
+CREATE INDEX index_worktree_entries_on_project_id_and_worktree_id ON public.worktree_entries USING btree (project_id, worktree_id);
+
+CREATE INDEX index_worktrees_on_project_id ON public.worktrees USING btree (project_id);
+
+CREATE INDEX trigram_index_extensions_name ON public.extensions USING gin (name public.gin_trgm_ops);
+
+CREATE INDEX trigram_index_users_on_github_login ON public.users USING gin (github_login public.gin_trgm_ops);
+
+CREATE UNIQUE INDEX uix_channels_parent_path_name ON public.channels USING btree (parent_path, name) WHERE ((parent_path IS NOT NULL) AND (parent_path <> ''::text));
+
+CREATE UNIQUE INDEX uix_users_on_github_user_id ON public.users USING btree (github_user_id);
+
+ALTER TABLE ONLY public.access_tokens
+    ADD CONSTRAINT access_tokens_user_id_fkey FOREIGN KEY (user_id) REFERENCES public.users(id) ON DELETE CASCADE;
+
+ALTER TABLE ONLY public.breakpoints
+    ADD CONSTRAINT breakpoints_project_id_fkey FOREIGN KEY (project_id) REFERENCES public.projects(id) ON DELETE CASCADE;
+
+ALTER TABLE ONLY public.buffer_operations
+    ADD CONSTRAINT buffer_operations_buffer_id_fkey FOREIGN KEY (buffer_id) REFERENCES public.buffers(id) ON DELETE CASCADE;
+
+ALTER TABLE ONLY public.buffer_snapshots
+    ADD CONSTRAINT buffer_snapshots_buffer_id_fkey FOREIGN KEY (buffer_id) REFERENCES public.buffers(id) ON DELETE CASCADE;
+
+ALTER TABLE ONLY public.buffers
+    ADD CONSTRAINT buffers_channel_id_fkey FOREIGN KEY (channel_id) REFERENCES public.channels(id) ON DELETE CASCADE;
+
+ALTER TABLE ONLY public.channel_buffer_collaborators
+    ADD CONSTRAINT channel_buffer_collaborators_channel_id_fkey FOREIGN KEY (channel_id) REFERENCES public.channels(id) ON DELETE CASCADE;
+
+ALTER TABLE ONLY public.channel_buffer_collaborators
+    ADD CONSTRAINT channel_buffer_collaborators_connection_server_id_fkey FOREIGN KEY (connection_server_id) REFERENCES public.servers(id) ON DELETE CASCADE;
+
+ALTER TABLE ONLY public.channel_buffer_collaborators
+    ADD CONSTRAINT channel_buffer_collaborators_user_id_fkey FOREIGN KEY (user_id) REFERENCES public.users(id) ON DELETE CASCADE;
+
+ALTER TABLE ONLY public.channel_chat_participants
+    ADD CONSTRAINT channel_chat_participants_channel_id_fkey FOREIGN KEY (channel_id) REFERENCES public.channels(id) ON DELETE CASCADE;
+
+ALTER TABLE ONLY public.channel_chat_participants
+    ADD CONSTRAINT channel_chat_participants_connection_server_id_fkey FOREIGN KEY (connection_server_id) REFERENCES public.servers(id) ON DELETE CASCADE;
+
+ALTER TABLE ONLY public.channel_chat_participants
+    ADD CONSTRAINT channel_chat_participants_user_id_fkey FOREIGN KEY (user_id) REFERENCES public.users(id);
+
+ALTER TABLE ONLY public.channel_members
+    ADD CONSTRAINT channel_members_channel_id_fkey FOREIGN KEY (channel_id) REFERENCES public.channels(id) ON DELETE CASCADE;
+
+ALTER TABLE ONLY public.channel_members
+    ADD CONSTRAINT channel_members_user_id_fkey FOREIGN KEY (user_id) REFERENCES public.users(id) ON DELETE CASCADE;
+
+ALTER TABLE ONLY public.contacts
+    ADD CONSTRAINT contacts_user_id_a_fkey FOREIGN KEY (user_id_a) REFERENCES public.users(id) ON DELETE CASCADE;
+
+ALTER TABLE ONLY public.contacts
+    ADD CONSTRAINT contacts_user_id_b_fkey FOREIGN KEY (user_id_b) REFERENCES public.users(id) ON DELETE CASCADE;
+
+ALTER TABLE ONLY public.contributors
+    ADD CONSTRAINT contributors_user_id_fkey FOREIGN KEY (user_id) REFERENCES public.users(id);
+
+ALTER TABLE ONLY public.extension_versions
+    ADD CONSTRAINT extension_versions_extension_id_fkey FOREIGN KEY (extension_id) REFERENCES public.extensions(id);
+
+ALTER TABLE ONLY public.project_repositories
+    ADD CONSTRAINT fk_project_repositories_project_id FOREIGN KEY (project_id) REFERENCES public.projects(id) ON DELETE CASCADE;
+
+ALTER TABLE ONLY public.project_repository_statuses
+    ADD CONSTRAINT fk_project_repository_statuses_project_id FOREIGN KEY (project_id) REFERENCES public.projects(id) ON DELETE CASCADE;
+
+ALTER TABLE ONLY public.followers
+    ADD CONSTRAINT followers_follower_connection_server_id_fkey FOREIGN KEY (follower_connection_server_id) REFERENCES public.servers(id) ON DELETE CASCADE;
+
+ALTER TABLE ONLY public.followers
+    ADD CONSTRAINT followers_leader_connection_server_id_fkey FOREIGN KEY (leader_connection_server_id) REFERENCES public.servers(id) ON DELETE CASCADE;
+
+ALTER TABLE ONLY public.followers
+    ADD CONSTRAINT followers_project_id_fkey FOREIGN KEY (project_id) REFERENCES public.projects(id) ON DELETE CASCADE;
+
+ALTER TABLE ONLY public.followers
+    ADD CONSTRAINT followers_room_id_fkey FOREIGN KEY (room_id) REFERENCES public.rooms(id) ON DELETE CASCADE;
+
+ALTER TABLE ONLY public.language_servers
+    ADD CONSTRAINT language_servers_project_id_fkey FOREIGN KEY (project_id) REFERENCES public.projects(id) ON DELETE CASCADE;
+
+ALTER TABLE ONLY public.notifications
+    ADD CONSTRAINT notifications_kind_fkey FOREIGN KEY (kind) REFERENCES public.notification_kinds(id);
+
+ALTER TABLE ONLY public.notifications
+    ADD CONSTRAINT notifications_recipient_id_fkey FOREIGN KEY (recipient_id) REFERENCES public.users(id) ON DELETE CASCADE;
+
+ALTER TABLE ONLY public.observed_buffer_edits
+    ADD CONSTRAINT observed_buffer_edits_buffer_id_fkey FOREIGN KEY (buffer_id) REFERENCES public.buffers(id) ON DELETE CASCADE;
+
+ALTER TABLE ONLY public.observed_buffer_edits
+    ADD CONSTRAINT observed_buffer_edits_user_id_fkey FOREIGN KEY (user_id) REFERENCES public.users(id) ON DELETE CASCADE;
+
+ALTER TABLE ONLY public.project_collaborators
+    ADD CONSTRAINT project_collaborators_connection_server_id_fkey FOREIGN KEY (connection_server_id) REFERENCES public.servers(id) ON DELETE CASCADE;
+
+ALTER TABLE ONLY public.project_collaborators
+    ADD CONSTRAINT project_collaborators_project_id_fkey FOREIGN KEY (project_id) REFERENCES public.projects(id) ON DELETE CASCADE;
+
+ALTER TABLE ONLY public.projects
+    ADD CONSTRAINT projects_host_connection_server_id_fkey FOREIGN KEY (host_connection_server_id) REFERENCES public.servers(id) ON DELETE CASCADE;
+
+ALTER TABLE ONLY public.projects
+    ADD CONSTRAINT projects_host_user_id_fkey FOREIGN KEY (host_user_id) REFERENCES public.users(id);
+
+ALTER TABLE ONLY public.projects
+    ADD CONSTRAINT projects_room_id_fkey FOREIGN KEY (room_id) REFERENCES public.rooms(id) ON DELETE CASCADE;
+
+ALTER TABLE ONLY public.room_participants
+    ADD CONSTRAINT room_participants_answering_connection_server_id_fkey FOREIGN KEY (answering_connection_server_id) REFERENCES public.servers(id) ON DELETE CASCADE;
+
+ALTER TABLE ONLY public.room_participants
+    ADD CONSTRAINT room_participants_calling_connection_server_id_fkey FOREIGN KEY (calling_connection_server_id) REFERENCES public.servers(id) ON DELETE SET NULL;
+
+ALTER TABLE ONLY public.room_participants
+    ADD CONSTRAINT room_participants_calling_user_id_fkey FOREIGN KEY (calling_user_id) REFERENCES public.users(id);
+
+ALTER TABLE ONLY public.room_participants
+    ADD CONSTRAINT room_participants_room_id_fkey FOREIGN KEY (room_id) REFERENCES public.rooms(id);
+
+ALTER TABLE ONLY public.room_participants
+    ADD CONSTRAINT room_participants_user_id_fkey FOREIGN KEY (user_id) REFERENCES public.users(id);
+
+ALTER TABLE ONLY public.rooms
+    ADD CONSTRAINT rooms_channel_id_fkey FOREIGN KEY (channel_id) REFERENCES public.channels(id) ON DELETE CASCADE;
+
+ALTER TABLE ONLY public.user_features
+    ADD CONSTRAINT user_features_feature_id_fkey FOREIGN KEY (feature_id) REFERENCES public.feature_flags(id) ON DELETE CASCADE;
+
+ALTER TABLE ONLY public.user_features
+    ADD CONSTRAINT user_features_user_id_fkey FOREIGN KEY (user_id) REFERENCES public.users(id) ON DELETE CASCADE;
+
+ALTER TABLE ONLY public.users
+    ADD CONSTRAINT users_inviter_id_fkey FOREIGN KEY (inviter_id) REFERENCES public.users(id) ON DELETE SET NULL;
+
+ALTER TABLE ONLY public.worktree_diagnostic_summaries
+    ADD CONSTRAINT worktree_diagnostic_summaries_project_id_worktree_id_fkey FOREIGN KEY (project_id, worktree_id) REFERENCES public.worktrees(project_id, id) ON DELETE CASCADE;
+
+ALTER TABLE ONLY public.worktree_entries
+    ADD CONSTRAINT worktree_entries_project_id_worktree_id_fkey FOREIGN KEY (project_id, worktree_id) REFERENCES public.worktrees(project_id, id) ON DELETE CASCADE;
+
+ALTER TABLE ONLY public.worktree_settings_files
+    ADD CONSTRAINT worktree_settings_files_project_id_worktree_id_fkey FOREIGN KEY (project_id, worktree_id) REFERENCES public.worktrees(project_id, id) ON DELETE CASCADE;
+
+ALTER TABLE ONLY public.worktrees
+    ADD CONSTRAINT worktrees_project_id_fkey FOREIGN KEY (project_id) REFERENCES public.projects(id) ON DELETE CASCADE;

crates/collab/migrations_llm/20240806182921_create_providers_and_models.sql 🔗

@@ -1,19 +0,0 @@
-create table if not exists providers (
-    id serial primary key,
-    name text not null
-);
-
-create unique index uix_providers_on_name on providers (name);
-
-create table if not exists models (
-    id serial primary key,
-    provider_id integer not null references providers (id) on delete cascade,
-    name text not null,
-    max_requests_per_minute integer not null,
-    max_tokens_per_minute integer not null,
-    max_tokens_per_day integer not null
-);
-
-create unique index uix_models_on_provider_id_name on models (provider_id, name);
-create index ix_models_on_provider_id on models (provider_id);
-create index ix_models_on_name on models (name);

crates/collab/migrations_llm/20240806213401_create_usages.sql 🔗

@@ -1,19 +0,0 @@
-create table usage_measures (
-    id serial primary key,
-    name text not null
-);
-
-create unique index uix_usage_measures_on_name on usage_measures (name);
-
-create table if not exists usages (
-    id serial primary key,
-    user_id integer not null,
-    model_id integer not null references models (id) on delete cascade,
-    measure_id integer not null references usage_measures (id) on delete cascade,
-    timestamp timestamp without time zone not null,
-    buckets bigint[] not null
-);
-
-create index ix_usages_on_user_id on usages (user_id);
-create index ix_usages_on_model_id on usages (model_id);
-create unique index uix_usages_on_user_id_model_id_measure_id on usages (user_id, model_id, measure_id);

crates/collab/migrations_llm/20240812225346_create_lifetime_usages.sql 🔗

@@ -1,9 +0,0 @@
-create table lifetime_usages (
-    id serial primary key,
-    user_id integer not null,
-    model_id integer not null references models (id) on delete cascade,
-    input_tokens bigint not null default 0,
-    output_tokens bigint not null default 0
-);
-
-create unique index uix_lifetime_usages_on_user_id_model_id on lifetime_usages (user_id, model_id);

crates/collab/migrations_llm/20241007173634_add_cache_token_counts.sql 🔗

@@ -1,11 +0,0 @@
-alter table models
-    add column price_per_million_cache_creation_input_tokens integer not null default 0,
-    add column price_per_million_cache_read_input_tokens integer not null default 0;
-
-alter table usages
-    add column cache_creation_input_tokens_this_month bigint not null default 0,
-    add column cache_read_input_tokens_this_month bigint not null default 0;
-
-alter table lifetime_usages
-    add column cache_creation_input_tokens bigint not null default 0,
-    add column cache_read_input_tokens bigint not null default 0;

crates/collab/migrations_llm/20241008155620_create_monthly_usages.sql 🔗

@@ -1,13 +0,0 @@
-create table monthly_usages (
-    id serial primary key,
-    user_id integer not null,
-    model_id integer not null references models (id) on delete cascade,
-    month integer not null,
-    year integer not null,
-    input_tokens bigint not null default 0,
-    cache_creation_input_tokens bigint not null default 0,
-    cache_read_input_tokens bigint not null default 0,
-    output_tokens bigint not null default 0
-);
-
-create unique index uix_monthly_usages_on_user_id_model_id_month_year on monthly_usages (user_id, model_id, month, year);

crates/collab/migrations_llm/20241010151249_create_billing_events.sql 🔗

@@ -1,12 +0,0 @@
-create table billing_events (
-    id serial primary key,
-    idempotency_key uuid not null default gen_random_uuid(),
-    user_id integer not null,
-    model_id integer not null references models (id) on delete cascade,
-    input_tokens bigint not null default 0,
-    input_cache_creation_tokens bigint not null default 0,
-    input_cache_read_tokens bigint not null default 0,
-    output_tokens bigint not null default 0
-);
-
-create index uix_billing_events_on_user_id_model_id on billing_events (user_id, model_id);

crates/collab/migrations_llm/20250415213005_add_subscription_usages.sql 🔗

@@ -1,10 +0,0 @@
-create table subscription_usages (
-    id serial primary key,
-    user_id integer not null,
-    period_start_at timestamp without time zone not null,
-    period_end_at timestamp without time zone not null,
-    model_requests int not null default 0,
-    edit_predictions int not null default 0
-);
-
-create unique index uix_subscription_usages_on_user_id_start_at_end_at on subscription_usages (user_id, period_start_at, period_end_at);

crates/collab/migrations_llm/20250425171838_add_subscription_usage_meters.sql 🔗

@@ -1,8 +0,0 @@
-create table subscription_usage_meters (
-    id serial primary key,
-    subscription_usage_id integer not null references subscription_usages (id) on delete cascade,
-    model_id integer not null references models (id) on delete cascade,
-    requests integer not null default 0
-);
-
-create unique index uix_subscription_usage_meters_on_subscription_usage_model on subscription_usage_meters (subscription_usage_id, model_id);

crates/collab/migrations_llm/20250503162708_add_v2_subscription_usage_and_meter_tables.sql 🔗

@@ -1,23 +0,0 @@
-create table subscription_usages_v2 (
-    id uuid primary key,
-    user_id integer not null,
-    period_start_at timestamp without time zone not null,
-    period_end_at timestamp without time zone not null,
-    plan text not null,
-    model_requests int not null default 0,
-    edit_predictions int not null default 0
-);
-
-create unique index uix_subscription_usages_v2_on_user_id_start_at_end_at on subscription_usages_v2 (user_id, period_start_at, period_end_at);
-
-create index ix_subscription_usages_v2_on_plan on subscription_usages_v2 (plan);
-
-create table subscription_usage_meters_v2 (
-    id uuid primary key,
-    subscription_usage_id uuid not null references subscription_usages_v2 (id) on delete cascade,
-    model_id integer not null references models (id) on delete cascade,
-    mode text not null,
-    requests integer not null default 0
-);
-
-create unique index uix_subscription_usage_meters_v2_on_usage_model_mode on subscription_usage_meters_v2 (subscription_usage_id, model_id, mode);

crates/collab/src/api/contributors.rs 🔗

@@ -54,6 +54,26 @@ async fn check_is_contributor(
 ) -> Result<Json<CheckIsContributorResponse>> {
     let params = params.into_contributor_selector()?;
 
+    if CopilotSweAgentBot::is_copilot_bot(&params) {
+        return Ok(Json(CheckIsContributorResponse {
+            signed_at: Some(
+                CopilotSweAgentBot::created_at()
+                    .and_utc()
+                    .to_rfc3339_opts(SecondsFormat::Millis, true),
+            ),
+        }));
+    }
+
+    if Dependabot::is_dependabot(&params) {
+        return Ok(Json(CheckIsContributorResponse {
+            signed_at: Some(
+                Dependabot::created_at()
+                    .and_utc()
+                    .to_rfc3339_opts(SecondsFormat::Millis, true),
+            ),
+        }));
+    }
+
     if RenovateBot::is_renovate_bot(&params) {
         return Ok(Json(CheckIsContributorResponse {
             signed_at: Some(
@@ -83,6 +103,71 @@ async fn check_is_contributor(
     }))
 }
 
+/// The Copilot bot GitHub user (`copilot-swe-agent[bot]`).
+///
+/// https://api.github.com/users/copilot-swe-agent[bot]
+struct CopilotSweAgentBot;
+
+impl CopilotSweAgentBot {
+    const LOGIN: &'static str = "copilot-swe-agent[bot]";
+    const USER_ID: i32 = 198982749;
+    /// The alias of the GitHub copilot user. Although https://api.github.com/users/copilot
+    /// yields a 404, GitHub still refers to the copilot bot user as @Copilot in some cases.
+    const NAME_ALIAS: &'static str = "Copilot";
+
+    /// Returns the `created_at` timestamp for the Dependabot bot user.
+    fn created_at() -> &'static NaiveDateTime {
+        static CREATED_AT: OnceLock<NaiveDateTime> = OnceLock::new();
+        CREATED_AT.get_or_init(|| {
+            chrono::DateTime::parse_from_rfc3339("2025-02-12T20:26:08Z")
+                .expect("failed to parse 'created_at' for 'copilot-swe-agent[bot]'")
+                .naive_utc()
+        })
+    }
+
+    /// Returns whether the given contributor selector corresponds to the Copilot bot user.
+    fn is_copilot_bot(contributor: &ContributorSelector) -> bool {
+        match contributor {
+            ContributorSelector::GitHubLogin { github_login } => {
+                github_login == Self::LOGIN || github_login == Self::NAME_ALIAS
+            }
+            ContributorSelector::GitHubUserId { github_user_id } => {
+                github_user_id == &Self::USER_ID
+            }
+        }
+    }
+}
+
+/// The Dependabot bot GitHub user (`dependabot[bot]`).
+///
+/// https://api.github.com/users/dependabot[bot]
+struct Dependabot;
+
+impl Dependabot {
+    const LOGIN: &'static str = "dependabot[bot]";
+    const USER_ID: i32 = 49699333;
+
+    /// Returns the `created_at` timestamp for the Dependabot bot user.
+    fn created_at() -> &'static NaiveDateTime {
+        static CREATED_AT: OnceLock<NaiveDateTime> = OnceLock::new();
+        CREATED_AT.get_or_init(|| {
+            chrono::DateTime::parse_from_rfc3339("2019-04-16T22:34:25Z")
+                .expect("failed to parse 'created_at' for 'dependabot[bot]'")
+                .naive_utc()
+        })
+    }
+
+    /// Returns whether the given contributor selector corresponds to the Dependabot bot user.
+    fn is_dependabot(contributor: &ContributorSelector) -> bool {
+        match contributor {
+            ContributorSelector::GitHubLogin { github_login } => github_login == Self::LOGIN,
+            ContributorSelector::GitHubUserId { github_user_id } => {
+                github_user_id == &Self::USER_ID
+            }
+        }
+    }
+}
+
 /// The Renovate bot GitHub user (`renovate[bot]`).
 ///
 /// https://api.github.com/users/renovate[bot]

crates/collab/src/db/queries/projects.rs 🔗

@@ -362,6 +362,8 @@ impl Database {
                                 entry_ids: ActiveValue::set("[]".into()),
                                 head_commit_details: ActiveValue::set(None),
                                 merge_message: ActiveValue::set(None),
+                                remote_upstream_url: ActiveValue::set(None),
+                                remote_origin_url: ActiveValue::set(None),
                             }
                         }),
                     )
@@ -511,6 +513,8 @@ impl Database {
                     serde_json::to_string(&update.current_merge_conflicts).unwrap(),
                 )),
                 merge_message: ActiveValue::set(update.merge_message.clone()),
+                remote_upstream_url: ActiveValue::set(update.remote_upstream_url.clone()),
+                remote_origin_url: ActiveValue::set(update.remote_origin_url.clone()),
             })
             .on_conflict(
                 OnConflict::columns([
@@ -1005,6 +1009,8 @@ impl Database {
                         is_last_update: true,
                         merge_message: db_repository_entry.merge_message,
                         stash_entries: Vec::new(),
+                        remote_upstream_url: db_repository_entry.remote_upstream_url.clone(),
+                        remote_origin_url: db_repository_entry.remote_origin_url.clone(),
                     });
                 }
             }

crates/collab/src/db/queries/rooms.rs 🔗

@@ -796,6 +796,8 @@ impl Database {
                             is_last_update: true,
                             merge_message: db_repository.merge_message,
                             stash_entries: Vec::new(),
+                            remote_upstream_url: db_repository.remote_upstream_url.clone(),
+                            remote_origin_url: db_repository.remote_origin_url.clone(),
                         });
                     }
                 }

crates/collab/src/db/tables.rs 🔗

@@ -22,7 +22,6 @@ pub mod project_repository_statuses;
 pub mod room;
 pub mod room_participant;
 pub mod server;
-pub mod signup;
 pub mod user;
 pub mod worktree;
 pub mod worktree_diagnostic_summary;

crates/collab/src/db/tables/project_repository.rs 🔗

@@ -22,6 +22,8 @@ pub struct Model {
     pub branch_summary: Option<String>,
     // A JSON object representing the current Head commit values
     pub head_commit_details: Option<String>,
+    pub remote_upstream_url: Option<String>,
+    pub remote_origin_url: Option<String>,
 }
 
 #[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]

crates/collab/src/db/tables/signup.rs 🔗

@@ -1,28 +0,0 @@
-use crate::db::{SignupId, UserId};
-use sea_orm::entity::prelude::*;
-
-#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
-#[sea_orm(table_name = "signups")]
-pub struct Model {
-    #[sea_orm(primary_key)]
-    pub id: SignupId,
-    pub email_address: String,
-    pub email_confirmation_code: String,
-    pub email_confirmation_sent: bool,
-    pub created_at: DateTime,
-    pub device_id: Option<String>,
-    pub user_id: Option<UserId>,
-    pub inviting_user_id: Option<UserId>,
-    pub platform_mac: bool,
-    pub platform_linux: bool,
-    pub platform_windows: bool,
-    pub platform_unknown: bool,
-    pub editor_features: Option<Vec<String>>,
-    pub programming_languages: Option<Vec<String>>,
-    pub added_to_mailing_list: bool,
-}
-
-#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
-pub enum Relation {}
-
-impl ActiveModelBehavior for ActiveModel {}

crates/collab/src/db/tests.rs 🔗

@@ -3,22 +3,21 @@ mod channel_tests;
 mod contributor_tests;
 mod db_tests;
 mod extension_tests;
+mod migrations;
 
-use crate::migrations::run_database_migrations;
+use std::sync::Arc;
+use std::sync::atomic::{AtomicI32, Ordering::SeqCst};
+use std::time::Duration;
 
-use super::*;
 use gpui::BackgroundExecutor;
 use parking_lot::Mutex;
 use rand::prelude::*;
 use sea_orm::ConnectionTrait;
 use sqlx::migrate::MigrateDatabase;
-use std::{
-    sync::{
-        Arc,
-        atomic::{AtomicI32, Ordering::SeqCst},
-    },
-    time::Duration,
-};
+
+use self::migrations::run_database_migrations;
+
+use super::*;
 
 pub struct TestDb {
     pub db: Option<Arc<Database>>,

crates/collab/src/lib.rs 🔗

@@ -3,8 +3,6 @@ pub mod auth;
 pub mod db;
 pub mod env;
 pub mod executor;
-pub mod llm;
-pub mod migrations;
 pub mod rpc;
 pub mod seed;
 

crates/collab/src/llm/db.rs 🔗

@@ -1,98 +0,0 @@
-use std::future::Future;
-use std::sync::Arc;
-
-use anyhow::Context;
-pub use sea_orm::ConnectOptions;
-use sea_orm::{DatabaseConnection, DatabaseTransaction, IsolationLevel, TransactionTrait};
-
-use crate::Result;
-use crate::db::TransactionHandle;
-use crate::executor::Executor;
-
-/// The database for the LLM service.
-pub struct LlmDatabase {
-    options: ConnectOptions,
-    pool: DatabaseConnection,
-    #[allow(unused)]
-    executor: Executor,
-    #[cfg(test)]
-    runtime: Option<tokio::runtime::Runtime>,
-}
-
-impl LlmDatabase {
-    /// Connects to the database with the given options
-    pub async fn new(options: ConnectOptions, executor: Executor) -> Result<Self> {
-        sqlx::any::install_default_drivers();
-        Ok(Self {
-            options: options.clone(),
-            pool: sea_orm::Database::connect(options).await?,
-            executor,
-            #[cfg(test)]
-            runtime: None,
-        })
-    }
-
-    pub fn options(&self) -> &ConnectOptions {
-        &self.options
-    }
-
-    pub async fn transaction<F, Fut, T>(&self, f: F) -> Result<T>
-    where
-        F: Send + Fn(TransactionHandle) -> Fut,
-        Fut: Send + Future<Output = Result<T>>,
-    {
-        let body = async {
-            let (tx, result) = self.with_transaction(&f).await?;
-            match result {
-                Ok(result) => match tx.commit().await.map_err(Into::into) {
-                    Ok(()) => Ok(result),
-                    Err(error) => Err(error),
-                },
-                Err(error) => {
-                    tx.rollback().await?;
-                    Err(error)
-                }
-            }
-        };
-
-        self.run(body).await
-    }
-
-    async fn with_transaction<F, Fut, T>(&self, f: &F) -> Result<(DatabaseTransaction, Result<T>)>
-    where
-        F: Send + Fn(TransactionHandle) -> Fut,
-        Fut: Send + Future<Output = Result<T>>,
-    {
-        let tx = self
-            .pool
-            .begin_with_config(Some(IsolationLevel::ReadCommitted), None)
-            .await?;
-
-        let mut tx = Arc::new(Some(tx));
-        let result = f(TransactionHandle(tx.clone())).await;
-        let tx = Arc::get_mut(&mut tx)
-            .and_then(|tx| tx.take())
-            .context("couldn't complete transaction because it's still in use")?;
-
-        Ok((tx, result))
-    }
-
-    async fn run<F, T>(&self, future: F) -> Result<T>
-    where
-        F: Future<Output = Result<T>>,
-    {
-        #[cfg(test)]
-        {
-            if let Executor::Deterministic(executor) = &self.executor {
-                executor.simulate_random_delay().await;
-            }
-
-            self.runtime.as_ref().unwrap().block_on(future)
-        }
-
-        #[cfg(not(test))]
-        {
-            future.await
-        }
-    }
-}

crates/collab/src/main.rs 🔗

@@ -1,4 +1,4 @@
-use anyhow::{Context as _, anyhow};
+use anyhow::anyhow;
 use axum::headers::HeaderMapExt;
 use axum::{
     Extension, Router,
@@ -9,8 +9,6 @@ use axum::{
 
 use collab::ServiceMode;
 use collab::api::CloudflareIpCountryHeader;
-use collab::llm::db::LlmDatabase;
-use collab::migrations::run_database_migrations;
 use collab::{
     AppState, Config, Result, api::fetch_extensions_from_blob_store_periodically, db, env,
     executor::Executor,
@@ -19,7 +17,6 @@ use db::Database;
 use std::{
     env::args,
     net::{SocketAddr, TcpListener},
-    path::Path,
     sync::Arc,
     time::Duration,
 };
@@ -49,10 +46,6 @@ async fn main() -> Result<()> {
         Some("version") => {
             println!("collab v{} ({})", VERSION, REVISION.unwrap_or("unknown"));
         }
-        Some("migrate") => {
-            let config = envy::from_env::<Config>().expect("error loading config");
-            setup_app_database(&config).await?;
-        }
         Some("seed") => {
             let config = envy::from_env::<Config>().expect("error loading config");
             let db_options = db::ConnectOptions::new(config.database_url.clone());
@@ -69,7 +62,7 @@ async fn main() -> Result<()> {
                 Some("all") => ServiceMode::All,
                 _ => {
                     return Err(anyhow!(
-                        "usage: collab <version | migrate | seed | serve <api|collab|all>>"
+                        "usage: collab <version | seed | serve <api|collab|all>>"
                     ))?;
                 }
             };
@@ -90,7 +83,6 @@ async fn main() -> Result<()> {
 
             if mode.is_collab() || mode.is_api() {
                 setup_app_database(&config).await?;
-                setup_llm_database(&config).await?;
 
                 let state = AppState::new(config, Executor::Production).await?;
 
@@ -211,25 +203,6 @@ async fn setup_app_database(config: &Config) -> Result<()> {
     let db_options = db::ConnectOptions::new(config.database_url.clone());
     let mut db = Database::new(db_options).await?;
 
-    let migrations_path = config.migrations_path.as_deref().unwrap_or_else(|| {
-        #[cfg(feature = "sqlite")]
-        let default_migrations = concat!(env!("CARGO_MANIFEST_DIR"), "/migrations.sqlite");
-        #[cfg(not(feature = "sqlite"))]
-        let default_migrations = concat!(env!("CARGO_MANIFEST_DIR"), "/migrations");
-
-        Path::new(default_migrations)
-    });
-
-    let migrations = run_database_migrations(db.options(), migrations_path).await?;
-    for (migration, duration) in migrations {
-        log::info!(
-            "Migrated {} {} {:?}",
-            migration.version,
-            migration.description,
-            duration
-        );
-    }
-
     db.initialize_notification_kinds().await?;
 
     if config.seed_path.is_some() {
@@ -239,37 +212,6 @@ async fn setup_app_database(config: &Config) -> Result<()> {
     Ok(())
 }
 
-async fn setup_llm_database(config: &Config) -> Result<()> {
-    let database_url = config
-        .llm_database_url
-        .as_ref()
-        .context("missing LLM_DATABASE_URL")?;
-
-    let db_options = db::ConnectOptions::new(database_url.clone());
-    let db = LlmDatabase::new(db_options, Executor::Production).await?;
-
-    let migrations_path = config
-        .llm_database_migrations_path
-        .as_deref()
-        .unwrap_or_else(|| {
-            let default_migrations = concat!(env!("CARGO_MANIFEST_DIR"), "/migrations_llm");
-
-            Path::new(default_migrations)
-        });
-
-    let migrations = run_database_migrations(db.options(), migrations_path).await?;
-    for (migration, duration) in migrations {
-        log::info!(
-            "Migrated {} {} {:?}",
-            migration.version,
-            migration.description,
-            duration
-        );
-    }
-
-    Ok(())
-}
-
 async fn handle_root(Extension(mode): Extension<ServiceMode>) -> String {
     format!("zed:{mode} v{VERSION} ({})", REVISION.unwrap_or("unknown"))
 }

crates/collab/src/rpc.rs 🔗

@@ -469,6 +469,8 @@ impl Server {
             .add_request_handler(forward_mutating_project_request::<proto::GetBlobContent>)
             .add_request_handler(forward_mutating_project_request::<proto::GitCreateBranch>)
             .add_request_handler(forward_mutating_project_request::<proto::GitChangeBranch>)
+            .add_request_handler(forward_mutating_project_request::<proto::GitCreateRemote>)
+            .add_request_handler(forward_mutating_project_request::<proto::GitRemoveRemote>)
             .add_request_handler(forward_mutating_project_request::<proto::CheckForPushedCommits>)
             .add_message_handler(broadcast_project_message_from_host::<proto::AdvertiseContexts>)
             .add_message_handler(update_context)

crates/collab/src/tests.rs 🔗

@@ -1,5 +1,3 @@
-use std::sync::Arc;
-
 use call::Room;
 use client::ChannelId;
 use gpui::{Entity, TestAppContext};
@@ -18,7 +16,6 @@ mod randomized_test_helpers;
 mod remote_editing_collaboration_tests;
 mod test_server;
 
-use language::{Language, LanguageConfig, LanguageMatcher, tree_sitter_rust};
 pub use randomized_test_helpers::{
     RandomizedTest, TestError, UserTestPlan, run_randomized_test, save_randomized_test_plan,
 };
@@ -51,17 +48,3 @@ fn room_participants(room: &Entity<Room>, cx: &mut TestAppContext) -> RoomPartic
 fn channel_id(room: &Entity<Room>, cx: &mut TestAppContext) -> Option<ChannelId> {
     cx.read(|cx| room.read(cx).channel_id())
 }
-
-fn rust_lang() -> Arc<Language> {
-    Arc::new(Language::new(
-        LanguageConfig {
-            name: "Rust".into(),
-            matcher: LanguageMatcher {
-                path_suffixes: vec!["rs".to_string()],
-                ..Default::default()
-            },
-            ..Default::default()
-        },
-        Some(tree_sitter_rust::LANGUAGE.into()),
-    ))
-}

crates/collab/src/tests/editor_tests.rs 🔗

@@ -1,7 +1,4 @@
-use crate::{
-    rpc::RECONNECT_TIMEOUT,
-    tests::{TestServer, rust_lang},
-};
+use crate::{rpc::RECONNECT_TIMEOUT, tests::TestServer};
 use call::ActiveCall;
 use editor::{
     DocumentColorsRenderMode, Editor, FETCH_COLORS_DEBOUNCE_TIMEOUT, MultiBufferOffset, RowInfo,
@@ -23,8 +20,9 @@ use gpui::{
     App, Rgba, SharedString, TestAppContext, UpdateGlobal, VisualContext, VisualTestContext,
 };
 use indoc::indoc;
-use language::FakeLspAdapter;
+use language::{FakeLspAdapter, rust_lang};
 use lsp::LSP_REQUEST_TIMEOUT;
+use pretty_assertions::assert_eq;
 use project::{
     ProgressToken, ProjectPath, SERVER_PROGRESS_THROTTLE_TIMEOUT,
     lsp_store::lsp_ext_command::{ExpandedMacro, LspExtExpandMacro},
@@ -314,6 +312,49 @@ async fn test_collaborating_with_completion(cx_a: &mut TestAppContext, cx_b: &mu
             "Rust",
             FakeLspAdapter {
                 capabilities: capabilities.clone(),
+                initializer: Some(Box::new(|fake_server| {
+                    fake_server.set_request_handler::<lsp::request::Completion, _, _>(
+                        |params, _| async move {
+                            assert_eq!(
+                                params.text_document_position.text_document.uri,
+                                lsp::Uri::from_file_path(path!("/a/main.rs")).unwrap(),
+                            );
+                            assert_eq!(
+                                params.text_document_position.position,
+                                lsp::Position::new(0, 14),
+                            );
+
+                            Ok(Some(lsp::CompletionResponse::Array(vec![
+                                lsp::CompletionItem {
+                                    label: "first_method(…)".into(),
+                                    detail: Some("fn(&mut self, B) -> C".into()),
+                                    text_edit: Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
+                                        new_text: "first_method($1)".to_string(),
+                                        range: lsp::Range::new(
+                                            lsp::Position::new(0, 14),
+                                            lsp::Position::new(0, 14),
+                                        ),
+                                    })),
+                                    insert_text_format: Some(lsp::InsertTextFormat::SNIPPET),
+                                    ..Default::default()
+                                },
+                                lsp::CompletionItem {
+                                    label: "second_method(…)".into(),
+                                    detail: Some("fn(&mut self, C) -> D<E>".into()),
+                                    text_edit: Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
+                                        new_text: "second_method()".to_string(),
+                                        range: lsp::Range::new(
+                                            lsp::Position::new(0, 14),
+                                            lsp::Position::new(0, 14),
+                                        ),
+                                    })),
+                                    insert_text_format: Some(lsp::InsertTextFormat::SNIPPET),
+                                    ..Default::default()
+                                },
+                            ])))
+                        },
+                    );
+                })),
                 ..FakeLspAdapter::default()
             },
         ),
@@ -322,6 +363,11 @@ async fn test_collaborating_with_completion(cx_a: &mut TestAppContext, cx_b: &mu
             FakeLspAdapter {
                 name: "fake-analyzer",
                 capabilities: capabilities.clone(),
+                initializer: Some(Box::new(|fake_server| {
+                    fake_server.set_request_handler::<lsp::request::Completion, _, _>(
+                        |_, _| async move { Ok(None) },
+                    );
+                })),
                 ..FakeLspAdapter::default()
             },
         ),
@@ -375,6 +421,7 @@ async fn test_collaborating_with_completion(cx_a: &mut TestAppContext, cx_b: &mu
     let fake_language_server = fake_language_servers[0].next().await.unwrap();
     let second_fake_language_server = fake_language_servers[1].next().await.unwrap();
     cx_a.background_executor.run_until_parked();
+    cx_b.background_executor.run_until_parked();
 
     buffer_b.read_with(cx_b, |buffer, _| {
         assert!(!buffer.completion_triggers().is_empty())
@@ -389,58 +436,9 @@ async fn test_collaborating_with_completion(cx_a: &mut TestAppContext, cx_b: &mu
     });
     cx_b.focus(&editor_b);
 
-    // Receive a completion request as the host's language server.
-    // Return some completions from the host's language server.
-    cx_a.executor().start_waiting();
-    fake_language_server
-        .set_request_handler::<lsp::request::Completion, _, _>(|params, _| async move {
-            assert_eq!(
-                params.text_document_position.text_document.uri,
-                lsp::Uri::from_file_path(path!("/a/main.rs")).unwrap(),
-            );
-            assert_eq!(
-                params.text_document_position.position,
-                lsp::Position::new(0, 14),
-            );
-
-            Ok(Some(lsp::CompletionResponse::Array(vec![
-                lsp::CompletionItem {
-                    label: "first_method(…)".into(),
-                    detail: Some("fn(&mut self, B) -> C".into()),
-                    text_edit: Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
-                        new_text: "first_method($1)".to_string(),
-                        range: lsp::Range::new(
-                            lsp::Position::new(0, 14),
-                            lsp::Position::new(0, 14),
-                        ),
-                    })),
-                    insert_text_format: Some(lsp::InsertTextFormat::SNIPPET),
-                    ..Default::default()
-                },
-                lsp::CompletionItem {
-                    label: "second_method(…)".into(),
-                    detail: Some("fn(&mut self, C) -> D<E>".into()),
-                    text_edit: Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
-                        new_text: "second_method()".to_string(),
-                        range: lsp::Range::new(
-                            lsp::Position::new(0, 14),
-                            lsp::Position::new(0, 14),
-                        ),
-                    })),
-                    insert_text_format: Some(lsp::InsertTextFormat::SNIPPET),
-                    ..Default::default()
-                },
-            ])))
-        })
-        .next()
-        .await
-        .unwrap();
-    second_fake_language_server
-        .set_request_handler::<lsp::request::Completion, _, _>(|_, _| async move { Ok(None) })
-        .next()
-        .await
-        .unwrap();
-    cx_a.executor().finish_waiting();
+    // Allow the completion request to propagate from guest to host to LSP.
+    cx_b.background_executor.run_until_parked();
+    cx_a.background_executor.run_until_parked();
 
     // Open the buffer on the host.
     let buffer_a = project_a
@@ -486,6 +484,7 @@ async fn test_collaborating_with_completion(cx_a: &mut TestAppContext, cx_b: &mu
 
     // The additional edit is applied.
     cx_a.executor().run_until_parked();
+    cx_b.executor().run_until_parked();
 
     buffer_a.read_with(cx_a, |buffer, _| {
         assert_eq!(
@@ -643,13 +642,11 @@ async fn test_collaborating_with_completion(cx_a: &mut TestAppContext, cx_b: &mu
                         ),
                     })),
                     insert_text_format: Some(lsp::InsertTextFormat::SNIPPET),
-                    ..Default::default()
+                    ..lsp::CompletionItem::default()
                 },
             ])))
         });
 
-    cx_b.executor().run_until_parked();
-
     // Await both language server responses
     first_lsp_completion.next().await.unwrap();
     second_lsp_completion.next().await.unwrap();
@@ -3192,13 +3189,12 @@ async fn test_lsp_pull_diagnostics(
             .collect::<Vec<_>>();
         let expected_messages = [
             expected_pull_diagnostic_lib_message,
-            // TODO bug: the pushed diagnostics are not being sent to the client when they open the corresponding buffer.
-            // expected_push_diagnostic_lib_message,
+            expected_push_diagnostic_lib_message,
         ];
         assert_eq!(
             all_diagnostics.len(),
-            1,
-            "Expected pull diagnostics, but got: {all_diagnostics:?}"
+            2,
+            "Expected pull and push diagnostics, but got: {all_diagnostics:?}"
         );
         for diagnostic in all_diagnostics {
             assert!(
@@ -3258,14 +3254,15 @@ async fn test_lsp_pull_diagnostics(
                 .diagnostics_in_range(MultiBufferOffset(0)..snapshot.len())
                 .collect::<Vec<_>>();
             let expected_messages = [
-                expected_workspace_pull_diagnostics_lib_message,
-                // TODO bug: the pushed diagnostics are not being sent to the client when they open the corresponding buffer.
-                // expected_push_diagnostic_lib_message,
+                // Despite workspace diagnostics provided,
+                // the currently open file's diagnostics should be preferred, as LSP suggests.
+                expected_pull_diagnostic_lib_message,
+                expected_push_diagnostic_lib_message,
             ];
             assert_eq!(
                 all_diagnostics.len(),
-                1,
-                "Expected pull diagnostics, but got: {all_diagnostics:?}"
+                2,
+                "Expected pull and push diagnostics, but got: {all_diagnostics:?}"
             );
             for diagnostic in all_diagnostics {
                 assert!(
@@ -3378,8 +3375,9 @@ async fn test_lsp_pull_diagnostics(
         "Another workspace diagnostics pull should happen after the diagnostics refresh server request"
     );
     {
-        assert!(
-            diagnostics_pulls_result_ids.lock().await.len() == diagnostic_pulls_result_ids,
+        assert_eq!(
+            diagnostics_pulls_result_ids.lock().await.len(),
+            diagnostic_pulls_result_ids,
             "Pulls should not happen hence no extra ids should appear"
         );
         assert!(
@@ -3397,7 +3395,7 @@ async fn test_lsp_pull_diagnostics(
             expected_pull_diagnostic_lib_message,
             expected_push_diagnostic_lib_message,
         ];
-        assert_eq!(all_diagnostics.len(), 1);
+        assert_eq!(all_diagnostics.len(), 2);
         for diagnostic in &all_diagnostics {
             assert!(
                 expected_messages.contains(&diagnostic.diagnostic.message.as_str()),
@@ -3516,7 +3514,6 @@ async fn test_git_blame_is_forwarded(cx_a: &mut TestAppContext, cx_b: &mut TestA
         .into_iter()
         .map(|(sha, message)| (sha.parse().unwrap(), message.into()))
         .collect(),
-        remote_url: Some("git@github.com:zed-industries/zed.git".to_string()),
     };
     client_a.fs().set_blame_for_repo(
         Path::new(path!("/my-repo/.git")),
@@ -3601,10 +3598,6 @@ async fn test_git_blame_is_forwarded(cx_a: &mut TestAppContext, cx_b: &mut TestA
             for (idx, (buffer, entry)) in entries.iter().flatten().enumerate() {
                 let details = blame.details_for_entry(*buffer, entry).unwrap();
                 assert_eq!(details.message, format!("message for idx-{}", idx));
-                assert_eq!(
-                    details.permalink.unwrap().to_string(),
-                    format!("https://github.com/zed-industries/zed/commit/{}", entry.sha)
-                );
             }
         });
     });

crates/collab/src/tests/integration_tests.rs 🔗

@@ -2,7 +2,7 @@ use crate::{
     rpc::{CLEANUP_TIMEOUT, RECONNECT_TIMEOUT},
     tests::{
         RoomParticipants, TestClient, TestServer, channel_id, following_tests::join_channel,
-        room_participants, rust_lang,
+        room_participants,
     },
 };
 use anyhow::{Result, anyhow};
@@ -26,7 +26,7 @@ use language::{
     Diagnostic, DiagnosticEntry, DiagnosticSourceKind, FakeLspAdapter, Language, LanguageConfig,
     LanguageMatcher, LineEnding, OffsetRangeExt, Point, Rope,
     language_settings::{Formatter, FormatterList},
-    tree_sitter_rust, tree_sitter_typescript,
+    rust_lang, tree_sitter_rust, tree_sitter_typescript,
 };
 use lsp::{LanguageServerId, OneOf};
 use parking_lot::Mutex;
@@ -6745,8 +6745,13 @@ async fn test_preview_tabs(cx: &mut TestAppContext) {
     });
 
     // Split pane to the right
-    pane.update(cx, |pane, cx| {
-        pane.split(workspace::SplitDirection::Right, cx);
+    pane.update_in(cx, |pane, window, cx| {
+        pane.split(
+            workspace::SplitDirection::Right,
+            workspace::SplitMode::default(),
+            window,
+            cx,
+        );
     });
     cx.run_until_parked();
     let right_pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());

crates/collab/src/tests/remote_editing_collaboration_tests.rs 🔗

@@ -4,6 +4,7 @@ use collections::{HashMap, HashSet};
 
 use dap::{Capabilities, adapters::DebugTaskDefinition, transport::RequestHandling};
 use debugger_ui::debugger_panel::DebugPanel;
+use editor::{Editor, EditorMode, MultiBuffer};
 use extension::ExtensionHostProxy;
 use fs::{FakeFs, Fs as _, RemoveOptions};
 use futures::StreamExt as _;
@@ -12,22 +13,30 @@ use http_client::BlockedHttpClient;
 use language::{
     FakeLspAdapter, Language, LanguageConfig, LanguageMatcher, LanguageRegistry,
     language_settings::{Formatter, FormatterList, language_settings},
-    tree_sitter_typescript,
+    rust_lang, tree_sitter_typescript,
 };
 use node_runtime::NodeRuntime;
 use project::{
     ProjectPath,
     debugger::session::ThreadId,
     lsp_store::{FormatTrigger, LspFormatTarget},
+    trusted_worktrees::{PathTrust, TrustedWorktrees},
 };
 use remote::RemoteClient;
 use remote_server::{HeadlessAppState, HeadlessProject};
 use rpc::proto;
 use serde_json::json;
-use settings::{LanguageServerFormatterSpecifier, PrettierSettingsContent, SettingsStore};
+use settings::{
+    InlayHintSettingsContent, LanguageServerFormatterSpecifier, PrettierSettingsContent,
+    SettingsStore,
+};
 use std::{
     path::Path,
-    sync::{Arc, atomic::AtomicUsize},
+    sync::{
+        Arc,
+        atomic::{AtomicUsize, Ordering},
+    },
+    time::Duration,
 };
 use task::TcpArgumentsTemplate;
 use util::{path, rel_path::rel_path};
@@ -90,13 +99,14 @@ async fn test_sharing_an_ssh_remote_project(
                 languages,
                 extension_host_proxy: Arc::new(ExtensionHostProxy::new()),
             },
+            false,
             cx,
         )
     });
 
     let client_ssh = RemoteClient::fake_client(opts, cx_a).await;
     let (project_a, worktree_id) = client_a
-        .build_ssh_project(path!("/code/project1"), client_ssh, cx_a)
+        .build_ssh_project(path!("/code/project1"), client_ssh, false, cx_a)
         .await;
 
     // While the SSH worktree is being scanned, user A shares the remote project.
@@ -250,13 +260,14 @@ async fn test_ssh_collaboration_git_branches(
                 languages,
                 extension_host_proxy: Arc::new(ExtensionHostProxy::new()),
             },
+            false,
             cx,
         )
     });
 
     let client_ssh = RemoteClient::fake_client(opts, cx_a).await;
     let (project_a, _) = client_a
-        .build_ssh_project("/project", client_ssh, cx_a)
+        .build_ssh_project("/project", client_ssh, false, cx_a)
         .await;
 
     // While the SSH worktree is being scanned, user A shares the remote project.
@@ -454,13 +465,14 @@ async fn test_ssh_collaboration_formatting_with_prettier(
                 languages,
                 extension_host_proxy: Arc::new(ExtensionHostProxy::new()),
             },
+            false,
             cx,
         )
     });
 
     let client_ssh = RemoteClient::fake_client(opts, cx_a).await;
     let (project_a, worktree_id) = client_a
-        .build_ssh_project(path!("/project"), client_ssh, cx_a)
+        .build_ssh_project(path!("/project"), client_ssh, false, cx_a)
         .await;
 
     // While the SSH worktree is being scanned, user A shares the remote project.
@@ -615,6 +627,7 @@ async fn test_remote_server_debugger(
                 languages,
                 extension_host_proxy: Arc::new(ExtensionHostProxy::new()),
             },
+            false,
             cx,
         )
     });
@@ -627,7 +640,7 @@ async fn test_remote_server_debugger(
         command_palette_hooks::init(cx);
     });
     let (project_a, _) = client_a
-        .build_ssh_project(path!("/code"), client_ssh.clone(), cx_a)
+        .build_ssh_project(path!("/code"), client_ssh.clone(), false, cx_a)
         .await;
 
     let (workspace, cx_a) = client_a.build_workspace(&project_a, cx_a);
@@ -723,6 +736,7 @@ async fn test_slow_adapter_startup_retries(
                 languages,
                 extension_host_proxy: Arc::new(ExtensionHostProxy::new()),
             },
+            false,
             cx,
         )
     });
@@ -735,7 +749,7 @@ async fn test_slow_adapter_startup_retries(
         command_palette_hooks::init(cx);
     });
     let (project_a, _) = client_a
-        .build_ssh_project(path!("/code"), client_ssh.clone(), cx_a)
+        .build_ssh_project(path!("/code"), client_ssh.clone(), false, cx_a)
         .await;
 
     let (workspace, cx_a) = client_a.build_workspace(&project_a, cx_a);
@@ -838,3 +852,261 @@ async fn test_slow_adapter_startup_retries(
 
     shutdown_session.await.unwrap();
 }
+
+#[gpui::test]
+async fn test_ssh_remote_worktree_trust(cx_a: &mut TestAppContext, server_cx: &mut TestAppContext) {
+    use project::trusted_worktrees::RemoteHostLocation;
+
+    cx_a.update(|cx| {
+        release_channel::init(semver::Version::new(0, 0, 0), cx);
+        project::trusted_worktrees::init(HashMap::default(), None, None, cx);
+    });
+    server_cx.update(|cx| {
+        release_channel::init(semver::Version::new(0, 0, 0), cx);
+        project::trusted_worktrees::init(HashMap::default(), None, None, cx);
+    });
+
+    let mut server = TestServer::start(cx_a.executor().clone()).await;
+    let client_a = server.create_client(cx_a, "user_a").await;
+
+    let server_name = "override-rust-analyzer";
+    let lsp_inlay_hint_request_count = Arc::new(AtomicUsize::new(0));
+
+    let (opts, server_ssh) = RemoteClient::fake_server(cx_a, server_cx);
+    let remote_fs = FakeFs::new(server_cx.executor());
+    remote_fs
+        .insert_tree(
+            path!("/projects"),
+            json!({
+                "project_a": {
+                    ".zed": {
+                        "settings.json": r#"{"languages":{"Rust":{"language_servers":["override-rust-analyzer"]}}}"#
+                    },
+                    "main.rs": "fn main() {}"
+                },
+                "project_b": { "lib.rs": "pub fn lib() {}" }
+            }),
+        )
+        .await;
+
+    server_cx.update(HeadlessProject::init);
+    let remote_http_client = Arc::new(BlockedHttpClient);
+    let node = NodeRuntime::unavailable();
+    let languages = Arc::new(LanguageRegistry::new(server_cx.executor()));
+    languages.add(rust_lang());
+
+    let capabilities = lsp::ServerCapabilities {
+        inlay_hint_provider: Some(lsp::OneOf::Left(true)),
+        ..lsp::ServerCapabilities::default()
+    };
+    let mut fake_language_servers = languages.register_fake_lsp(
+        "Rust",
+        FakeLspAdapter {
+            name: server_name,
+            capabilities: capabilities.clone(),
+            initializer: Some(Box::new({
+                let lsp_inlay_hint_request_count = lsp_inlay_hint_request_count.clone();
+                move |fake_server| {
+                    let lsp_inlay_hint_request_count = lsp_inlay_hint_request_count.clone();
+                    fake_server.set_request_handler::<lsp::request::InlayHintRequest, _, _>(
+                        move |_params, _| {
+                            lsp_inlay_hint_request_count.fetch_add(1, Ordering::Release);
+                            async move {
+                                Ok(Some(vec![lsp::InlayHint {
+                                    position: lsp::Position::new(0, 0),
+                                    label: lsp::InlayHintLabel::String("hint".to_string()),
+                                    kind: None,
+                                    text_edits: None,
+                                    tooltip: None,
+                                    padding_left: None,
+                                    padding_right: None,
+                                    data: None,
+                                }]))
+                            }
+                        },
+                    );
+                }
+            })),
+            ..FakeLspAdapter::default()
+        },
+    );
+
+    let _headless_project = server_cx.new(|cx| {
+        HeadlessProject::new(
+            HeadlessAppState {
+                session: server_ssh,
+                fs: remote_fs.clone(),
+                http_client: remote_http_client,
+                node_runtime: node,
+                languages,
+                extension_host_proxy: Arc::new(ExtensionHostProxy::new()),
+            },
+            true,
+            cx,
+        )
+    });
+
+    let client_ssh = RemoteClient::fake_client(opts, cx_a).await;
+    let (project_a, worktree_id_a) = client_a
+        .build_ssh_project(path!("/projects/project_a"), client_ssh.clone(), true, cx_a)
+        .await;
+
+    cx_a.update(|cx| {
+        release_channel::init(semver::Version::new(0, 0, 0), cx);
+
+        SettingsStore::update_global(cx, |store, cx| {
+            store.update_user_settings(cx, |settings| {
+                let language_settings = &mut settings.project.all_languages.defaults;
+                language_settings.inlay_hints = Some(InlayHintSettingsContent {
+                    enabled: Some(true),
+                    ..InlayHintSettingsContent::default()
+                })
+            });
+        });
+    });
+
+    project_a
+        .update(cx_a, |project, cx| {
+            project.languages().add(rust_lang());
+            project.languages().register_fake_lsp_adapter(
+                "Rust",
+                FakeLspAdapter {
+                    name: server_name,
+                    capabilities,
+                    ..FakeLspAdapter::default()
+                },
+            );
+            project.find_or_create_worktree(path!("/projects/project_b"), true, cx)
+        })
+        .await
+        .unwrap();
+
+    cx_a.run_until_parked();
+
+    let worktree_ids = project_a.read_with(cx_a, |project, cx| {
+        project
+            .worktrees(cx)
+            .map(|wt| wt.read(cx).id())
+            .collect::<Vec<_>>()
+    });
+    assert_eq!(worktree_ids.len(), 2);
+
+    let remote_host = project_a.read_with(cx_a, |project, cx| {
+        project
+            .remote_connection_options(cx)
+            .map(RemoteHostLocation::from)
+    });
+
+    let trusted_worktrees =
+        cx_a.update(|cx| TrustedWorktrees::try_get_global(cx).expect("trust global should exist"));
+
+    let can_trust_a =
+        trusted_worktrees.update(cx_a, |store, cx| store.can_trust(worktree_ids[0], cx));
+    let can_trust_b =
+        trusted_worktrees.update(cx_a, |store, cx| store.can_trust(worktree_ids[1], cx));
+    assert!(!can_trust_a, "project_a should be restricted initially");
+    assert!(!can_trust_b, "project_b should be restricted initially");
+
+    let worktree_store = project_a.read_with(cx_a, |project, _| project.worktree_store());
+    let has_restricted = trusted_worktrees.read_with(cx_a, |store, cx| {
+        store.has_restricted_worktrees(&worktree_store, cx)
+    });
+    assert!(has_restricted, "should have restricted worktrees");
+
+    let buffer_before_approval = project_a
+        .update(cx_a, |project, cx| {
+            project.open_buffer((worktree_id_a, rel_path("main.rs")), cx)
+        })
+        .await
+        .unwrap();
+
+    let (editor, cx_a) = cx_a.add_window_view(|window, cx| {
+        Editor::new(
+            EditorMode::full(),
+            cx.new(|cx| MultiBuffer::singleton(buffer_before_approval.clone(), cx)),
+            Some(project_a.clone()),
+            window,
+            cx,
+        )
+    });
+    cx_a.run_until_parked();
+    let fake_language_server = fake_language_servers.next();
+
+    cx_a.read(|cx| {
+        let file = buffer_before_approval.read(cx).file();
+        assert_eq!(
+            language_settings(Some("Rust".into()), file, cx).language_servers,
+            ["...".to_string()],
+            "remote .zed/settings.json must not sync before trust approval"
+        )
+    });
+
+    editor.update_in(cx_a, |editor, window, cx| {
+        editor.handle_input("1", window, cx);
+    });
+    cx_a.run_until_parked();
+    cx_a.executor().advance_clock(Duration::from_secs(1));
+    assert_eq!(
+        lsp_inlay_hint_request_count.load(Ordering::Acquire),
+        0,
+        "inlay hints must not be queried before trust approval"
+    );
+
+    trusted_worktrees.update(cx_a, |store, cx| {
+        store.trust(
+            HashSet::from_iter([PathTrust::Worktree(worktree_ids[0])]),
+            remote_host.clone(),
+            cx,
+        );
+    });
+    cx_a.run_until_parked();
+
+    cx_a.read(|cx| {
+        let file = buffer_before_approval.read(cx).file();
+        assert_eq!(
+            language_settings(Some("Rust".into()), file, cx).language_servers,
+            ["override-rust-analyzer".to_string()],
+            "remote .zed/settings.json should sync after trust approval"
+        )
+    });
+    let _fake_language_server = fake_language_server.await.unwrap();
+    editor.update_in(cx_a, |editor, window, cx| {
+        editor.handle_input("1", window, cx);
+    });
+    cx_a.run_until_parked();
+    cx_a.executor().advance_clock(Duration::from_secs(1));
+    assert!(
+        lsp_inlay_hint_request_count.load(Ordering::Acquire) > 0,
+        "inlay hints should be queried after trust approval"
+    );
+
+    let can_trust_a =
+        trusted_worktrees.update(cx_a, |store, cx| store.can_trust(worktree_ids[0], cx));
+    let can_trust_b =
+        trusted_worktrees.update(cx_a, |store, cx| store.can_trust(worktree_ids[1], cx));
+    assert!(can_trust_a, "project_a should be trusted after trust()");
+    assert!(!can_trust_b, "project_b should still be restricted");
+
+    trusted_worktrees.update(cx_a, |store, cx| {
+        store.trust(
+            HashSet::from_iter([PathTrust::Worktree(worktree_ids[1])]),
+            remote_host.clone(),
+            cx,
+        );
+    });
+
+    let can_trust_a =
+        trusted_worktrees.update(cx_a, |store, cx| store.can_trust(worktree_ids[0], cx));
+    let can_trust_b =
+        trusted_worktrees.update(cx_a, |store, cx| store.can_trust(worktree_ids[1], cx));
+    assert!(can_trust_a, "project_a should remain trusted");
+    assert!(can_trust_b, "project_b should now be trusted");
+
+    let has_restricted_after = trusted_worktrees.read_with(cx_a, |store, cx| {
+        store.has_restricted_worktrees(&worktree_store, cx)
+    });
+    assert!(
+        !has_restricted_after,
+        "should have no restricted worktrees after trusting both"
+    );
+}

crates/collab/src/tests/test_server.rs 🔗

@@ -761,6 +761,7 @@ impl TestClient {
         &self,
         root_path: impl AsRef<Path>,
         ssh: Entity<RemoteClient>,
+        init_worktree_trust: bool,
         cx: &mut TestAppContext,
     ) -> (Entity<Project>, WorktreeId) {
         let project = cx.update(|cx| {
@@ -771,6 +772,7 @@ impl TestClient {
                 self.app_state.user_store.clone(),
                 self.app_state.languages.clone(),
                 self.app_state.fs.clone(),
+                init_worktree_trust,
                 cx,
             )
         });
@@ -839,6 +841,7 @@ impl TestClient {
                 self.app_state.languages.clone(),
                 self.app_state.fs.clone(),
                 None,
+                false,
                 cx,
             )
         })

crates/collab_ui/src/collab_panel.rs 🔗

@@ -109,22 +109,8 @@ pub fn init(cx: &mut App) {
         });
         // TODO: make it possible to bind this one to a held key for push to talk?
         // how to make "toggle_on_modifiers_press" contextual?
-        workspace.register_action(|_, _: &Mute, window, cx| {
-            let room = ActiveCall::global(cx).read(cx).room().cloned();
-            if let Some(room) = room {
-                window.defer(cx, move |_window, cx| {
-                    room.update(cx, |room, cx| room.toggle_mute(cx))
-                });
-            }
-        });
-        workspace.register_action(|_, _: &Deafen, window, cx| {
-            let room = ActiveCall::global(cx).read(cx).room().cloned();
-            if let Some(room) = room {
-                window.defer(cx, move |_window, cx| {
-                    room.update(cx, |room, cx| room.toggle_deafen(cx))
-                });
-            }
-        });
+        workspace.register_action(|_, _: &Mute, _, cx| title_bar::collab::toggle_mute(cx));
+        workspace.register_action(|_, _: &Deafen, _, cx| title_bar::collab::toggle_deafen(cx));
         workspace.register_action(|_, _: &LeaveCall, window, cx| {
             CollabPanel::leave_call(window, cx);
         });
@@ -1266,7 +1252,7 @@ impl CollabPanel {
             context_menu
         });
 
-        window.focus(&context_menu.focus_handle(cx));
+        window.focus(&context_menu.focus_handle(cx), cx);
         let subscription = cx.subscribe_in(
             &context_menu,
             window,
@@ -1438,7 +1424,7 @@ impl CollabPanel {
             context_menu
         });
 
-        window.focus(&context_menu.focus_handle(cx));
+        window.focus(&context_menu.focus_handle(cx), cx);
         let subscription = cx.subscribe_in(
             &context_menu,
             window,
@@ -1501,7 +1487,7 @@ impl CollabPanel {
             })
         });
 
-        window.focus(&context_menu.focus_handle(cx));
+        window.focus(&context_menu.focus_handle(cx), cx);
         let subscription = cx.subscribe_in(
             &context_menu,
             window,
@@ -1535,9 +1521,9 @@ impl CollabPanel {
         if cx.stop_active_drag(window) {
             return;
         } else if self.take_editing_state(window, cx) {
-            window.focus(&self.filter_editor.focus_handle(cx));
+            window.focus(&self.filter_editor.focus_handle(cx), cx);
         } else if !self.reset_filter_editor_text(window, cx) {
-            self.focus_handle.focus(window);
+            self.focus_handle.focus(window, cx);
         }
 
         if self.context_menu.is_some() {
@@ -1840,7 +1826,7 @@ impl CollabPanel {
         });
         self.update_entries(false, cx);
         self.select_channel_editor();
-        window.focus(&self.channel_name_editor.focus_handle(cx));
+        window.focus(&self.channel_name_editor.focus_handle(cx), cx);
         cx.notify();
     }
 
@@ -1865,7 +1851,7 @@ impl CollabPanel {
         });
         self.update_entries(false, cx);
         self.select_channel_editor();
-        window.focus(&self.channel_name_editor.focus_handle(cx));
+        window.focus(&self.channel_name_editor.focus_handle(cx), cx);
         cx.notify();
     }
 
@@ -1914,7 +1900,7 @@ impl CollabPanel {
                 editor.set_text(channel.name.clone(), window, cx);
                 editor.select_all(&Default::default(), window, cx);
             });
-            window.focus(&self.channel_name_editor.focus_handle(cx));
+            window.focus(&self.channel_name_editor.focus_handle(cx), cx);
             self.update_entries(false, cx);
             self.select_channel_editor();
         }

crates/collab_ui/src/collab_panel/channel_modal.rs 🔗

@@ -642,7 +642,7 @@ impl ChannelModalDelegate {
             });
             menu
         });
-        window.focus(&context_menu.focus_handle(cx));
+        window.focus(&context_menu.focus_handle(cx), cx);
         let subscription = cx.subscribe_in(
             &context_menu,
             window,

crates/command_palette/src/command_palette.rs 🔗

@@ -2,7 +2,7 @@ mod persistence;
 
 use std::{
     cmp::{self, Reverse},
-    collections::HashMap,
+    collections::{HashMap, VecDeque},
     sync::Arc,
     time::Duration,
 };
@@ -19,6 +19,7 @@ use gpui::{
     ParentElement, Render, Styled, Task, WeakEntity, Window,
 };
 use persistence::COMMAND_PALETTE_HISTORY;
+use picker::Direction;
 use picker::{Picker, PickerDelegate};
 use postage::{sink::Sink, stream::Stream};
 use settings::Settings;
@@ -163,6 +164,7 @@ pub struct CommandPaletteDelegate {
         Task<()>,
         postage::dispatch::Receiver<(Vec<Command>, Vec<StringMatch>, CommandInterceptResult)>,
     )>,
+    query_history: QueryHistory,
 }
 
 struct Command {
@@ -170,6 +172,91 @@ struct Command {
     action: Box<dyn Action>,
 }
 
+#[derive(Default)]
+struct QueryHistory {
+    history: Option<VecDeque<String>>,
+    cursor: Option<usize>,
+    prefix: Option<String>,
+}
+
+impl QueryHistory {
+    fn history(&mut self) -> &mut VecDeque<String> {
+        self.history.get_or_insert_with(|| {
+            COMMAND_PALETTE_HISTORY
+                .list_recent_queries()
+                .unwrap_or_default()
+                .into_iter()
+                .collect()
+        })
+    }
+
+    fn add(&mut self, query: String) {
+        if let Some(pos) = self.history().iter().position(|h| h == &query) {
+            self.history().remove(pos);
+        }
+        self.history().push_back(query);
+        self.cursor = None;
+        self.prefix = None;
+    }
+
+    fn validate_cursor(&mut self, current_query: &str) -> Option<usize> {
+        if let Some(pos) = self.cursor {
+            if self.history().get(pos).map(|s| s.as_str()) != Some(current_query) {
+                self.cursor = None;
+                self.prefix = None;
+            }
+        }
+        self.cursor
+    }
+
+    fn previous(&mut self, current_query: &str) -> Option<&str> {
+        if self.validate_cursor(current_query).is_none() {
+            self.prefix = Some(current_query.to_string());
+        }
+
+        let prefix = self.prefix.clone().unwrap_or_default();
+        let start_index = self.cursor.unwrap_or(self.history().len());
+
+        for i in (0..start_index).rev() {
+            if self
+                .history()
+                .get(i)
+                .is_some_and(|e| e.starts_with(&prefix))
+            {
+                self.cursor = Some(i);
+                return self.history().get(i).map(|s| s.as_str());
+            }
+        }
+        None
+    }
+
+    fn next(&mut self, current_query: &str) -> Option<&str> {
+        let selected = self.validate_cursor(current_query)?;
+        let prefix = self.prefix.clone().unwrap_or_default();
+
+        for i in (selected + 1)..self.history().len() {
+            if self
+                .history()
+                .get(i)
+                .is_some_and(|e| e.starts_with(&prefix))
+            {
+                self.cursor = Some(i);
+                return self.history().get(i).map(|s| s.as_str());
+            }
+        }
+        None
+    }
+
+    fn reset_cursor(&mut self) {
+        self.cursor = None;
+        self.prefix = None;
+    }
+
+    fn is_navigating(&self) -> bool {
+        self.cursor.is_some()
+    }
+}
+
 impl Clone for Command {
     fn clone(&self) -> Self {
         Self {
@@ -196,6 +283,7 @@ impl CommandPaletteDelegate {
             previous_focus_handle,
             latest_query: String::new(),
             updating_matches: None,
+            query_history: Default::default(),
         }
     }
 
@@ -271,6 +359,11 @@ impl CommandPaletteDelegate {
         // so we need to return an Option here
         self.commands.get(action_ix)
     }
+
+    #[cfg(any(test, feature = "test-support"))]
+    pub fn seed_history(&mut self, queries: &[&str]) {
+        self.query_history.history = Some(queries.iter().map(|s| s.to_string()).collect());
+    }
 }
 
 impl PickerDelegate for CommandPaletteDelegate {
@@ -280,6 +373,38 @@ impl PickerDelegate for CommandPaletteDelegate {
         "Execute a command...".into()
     }
 
+    fn select_history(
+        &mut self,
+        direction: Direction,
+        query: &str,
+        _window: &mut Window,
+        _cx: &mut App,
+    ) -> Option<String> {
+        match direction {
+            Direction::Up => {
+                let should_use_history =
+                    self.selected_ix == 0 || self.query_history.is_navigating();
+                if should_use_history {
+                    if let Some(query) = self.query_history.previous(query).map(|s| s.to_string()) {
+                        return Some(query);
+                    }
+                }
+            }
+            Direction::Down => {
+                if self.query_history.is_navigating() {
+                    if let Some(query) = self.query_history.next(query).map(|s| s.to_string()) {
+                        return Some(query);
+                    } else {
+                        let prefix = self.query_history.prefix.take().unwrap_or_default();
+                        self.query_history.reset_cursor();
+                        return Some(prefix);
+                    }
+                }
+            }
+        }
+        None
+    }
+
     fn match_count(&self) -> usize {
         self.matches.len()
     }
@@ -439,6 +564,12 @@ impl PickerDelegate for CommandPaletteDelegate {
             self.dismissed(window, cx);
             return;
         }
+
+        if !self.latest_query.is_empty() {
+            self.query_history.add(self.latest_query.clone());
+            self.query_history.reset_cursor();
+        }
+
         let action_ix = self.matches[self.selected_ix].candidate_id;
         let command = self.commands.swap_remove(action_ix);
         telemetry::event!(
@@ -457,7 +588,7 @@ impl PickerDelegate for CommandPaletteDelegate {
         })
         .detach_and_log_err(cx);
         let action = command.action;
-        window.focus(&self.previous_focus_handle);
+        window.focus(&self.previous_focus_handle, cx);
         self.dismissed(window, cx);
         window.dispatch_action(action, cx);
     }
@@ -588,7 +719,7 @@ mod tests {
     use super::*;
     use editor::Editor;
     use go_to_line::GoToLine;
-    use gpui::TestAppContext;
+    use gpui::{TestAppContext, VisualTestContext};
     use language::Point;
     use project::Project;
     use settings::KeymapFile;
@@ -653,7 +784,7 @@ mod tests {
 
         workspace.update_in(cx, |workspace, window, cx| {
             workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
-            editor.update(cx, |editor, cx| window.focus(&editor.focus_handle(cx)))
+            editor.update(cx, |editor, cx| window.focus(&editor.focus_handle(cx), cx))
         });
 
         cx.simulate_keystrokes("cmd-shift-p");
@@ -724,7 +855,7 @@ mod tests {
 
         workspace.update_in(cx, |workspace, window, cx| {
             workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
-            editor.update(cx, |editor, cx| window.focus(&editor.focus_handle(cx)))
+            editor.update(cx, |editor, cx| window.focus(&editor.focus_handle(cx), cx))
         });
 
         // Test normalize (trimming whitespace and double colons)
@@ -799,7 +930,9 @@ mod tests {
                         "bindings": {
                             "cmd-n": "workspace::NewFile",
                             "enter": "menu::Confirm",
-                            "cmd-shift-p": "command_palette::Toggle"
+                            "cmd-shift-p": "command_palette::Toggle",
+                            "up": "menu::SelectPrevious",
+                            "down": "menu::SelectNext"
                         }
                     }
                 ]"#,
@@ -808,4 +941,264 @@ mod tests {
             app_state
         })
     }
+
+    fn open_palette_with_history(
+        workspace: &Entity<Workspace>,
+        history: &[&str],
+        cx: &mut VisualTestContext,
+    ) -> Entity<Picker<CommandPaletteDelegate>> {
+        cx.simulate_keystrokes("cmd-shift-p");
+        cx.run_until_parked();
+
+        let palette = workspace.update(cx, |workspace, cx| {
+            workspace
+                .active_modal::<CommandPalette>(cx)
+                .unwrap()
+                .read(cx)
+                .picker
+                .clone()
+        });
+
+        palette.update(cx, |palette, _cx| {
+            palette.delegate.seed_history(history);
+        });
+
+        palette
+    }
+
+    #[gpui::test]
+    async fn test_history_navigation_basic(cx: &mut TestAppContext) {
+        let app_state = init_test(cx);
+        let project = Project::test(app_state.fs.clone(), [], cx).await;
+        let (workspace, cx) =
+            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
+
+        let palette = open_palette_with_history(&workspace, &["backspace", "select all"], cx);
+
+        // Query should be empty initially
+        palette.read_with(cx, |palette, cx| {
+            assert_eq!(palette.query(cx), "");
+        });
+
+        // Press up - should load most recent query "select all"
+        cx.simulate_keystrokes("up");
+        cx.background_executor.run_until_parked();
+        palette.read_with(cx, |palette, cx| {
+            assert_eq!(palette.query(cx), "select all");
+        });
+
+        // Press up again - should load "backspace"
+        cx.simulate_keystrokes("up");
+        cx.background_executor.run_until_parked();
+        palette.read_with(cx, |palette, cx| {
+            assert_eq!(palette.query(cx), "backspace");
+        });
+
+        // Press down - should go back to "select all"
+        cx.simulate_keystrokes("down");
+        cx.background_executor.run_until_parked();
+        palette.read_with(cx, |palette, cx| {
+            assert_eq!(palette.query(cx), "select all");
+        });
+
+        // Press down again - should clear query (exit history mode)
+        cx.simulate_keystrokes("down");
+        cx.background_executor.run_until_parked();
+        palette.read_with(cx, |palette, cx| {
+            assert_eq!(palette.query(cx), "");
+        });
+    }
+
+    #[gpui::test]
+    async fn test_history_mode_exit_on_typing(cx: &mut TestAppContext) {
+        let app_state = init_test(cx);
+        let project = Project::test(app_state.fs.clone(), [], cx).await;
+        let (workspace, cx) =
+            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
+
+        let palette = open_palette_with_history(&workspace, &["backspace"], cx);
+
+        // Press up to enter history mode
+        cx.simulate_keystrokes("up");
+        cx.background_executor.run_until_parked();
+        palette.read_with(cx, |palette, cx| {
+            assert_eq!(palette.query(cx), "backspace");
+        });
+
+        // Type something - should append to the history query
+        cx.simulate_input("x");
+        cx.background_executor.run_until_parked();
+        palette.read_with(cx, |palette, cx| {
+            assert_eq!(palette.query(cx), "backspacex");
+        });
+    }
+
+    #[gpui::test]
+    async fn test_history_navigation_with_suggestions(cx: &mut TestAppContext) {
+        let app_state = init_test(cx);
+        let project = Project::test(app_state.fs.clone(), [], cx).await;
+        let (workspace, cx) =
+            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
+
+        let palette = open_palette_with_history(&workspace, &["editor: close", "editor: open"], cx);
+
+        // Open palette with a query that has multiple matches
+        cx.simulate_input("editor");
+        cx.background_executor.run_until_parked();
+
+        // Should have multiple matches, selected_ix should be 0
+        palette.read_with(cx, |palette, _| {
+            assert!(palette.delegate.matches.len() > 1);
+            assert_eq!(palette.delegate.selected_ix, 0);
+        });
+
+        // Press down - should navigate to next suggestion (not history)
+        cx.simulate_keystrokes("down");
+        cx.background_executor.run_until_parked();
+        palette.read_with(cx, |palette, _| {
+            assert_eq!(palette.delegate.selected_ix, 1);
+        });
+
+        // Press up - should go back to first suggestion
+        cx.simulate_keystrokes("up");
+        cx.background_executor.run_until_parked();
+        palette.read_with(cx, |palette, _| {
+            assert_eq!(palette.delegate.selected_ix, 0);
+        });
+
+        // Press up again at top - should enter history mode and show previous query
+        // that matches the "editor" prefix
+        cx.simulate_keystrokes("up");
+        cx.background_executor.run_until_parked();
+        palette.read_with(cx, |palette, cx| {
+            assert_eq!(palette.query(cx), "editor: open");
+        });
+    }
+
+    #[gpui::test]
+    async fn test_history_prefix_search(cx: &mut TestAppContext) {
+        let app_state = init_test(cx);
+        let project = Project::test(app_state.fs.clone(), [], cx).await;
+        let (workspace, cx) =
+            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
+
+        let palette = open_palette_with_history(
+            &workspace,
+            &["open file", "select all", "select line", "backspace"],
+            cx,
+        );
+
+        // Type "sel" as a prefix
+        cx.simulate_input("sel");
+        cx.background_executor.run_until_parked();
+
+        // Press up - should get "select line" (most recent matching "sel")
+        cx.simulate_keystrokes("up");
+        cx.background_executor.run_until_parked();
+        palette.read_with(cx, |palette, cx| {
+            assert_eq!(palette.query(cx), "select line");
+        });
+
+        // Press up again - should get "select all" (next matching "sel")
+        cx.simulate_keystrokes("up");
+        cx.background_executor.run_until_parked();
+        palette.read_with(cx, |palette, cx| {
+            assert_eq!(palette.query(cx), "select all");
+        });
+
+        // Press up again - should stay at "select all" (no more matches for "sel")
+        cx.simulate_keystrokes("up");
+        cx.background_executor.run_until_parked();
+        palette.read_with(cx, |palette, cx| {
+            assert_eq!(palette.query(cx), "select all");
+        });
+
+        // Press down - should go back to "select line"
+        cx.simulate_keystrokes("down");
+        cx.background_executor.run_until_parked();
+        palette.read_with(cx, |palette, cx| {
+            assert_eq!(palette.query(cx), "select line");
+        });
+
+        // Press down again - should return to original prefix "sel"
+        cx.simulate_keystrokes("down");
+        cx.background_executor.run_until_parked();
+        palette.read_with(cx, |palette, cx| {
+            assert_eq!(palette.query(cx), "sel");
+        });
+    }
+
+    #[gpui::test]
+    async fn test_history_prefix_search_no_matches(cx: &mut TestAppContext) {
+        let app_state = init_test(cx);
+        let project = Project::test(app_state.fs.clone(), [], cx).await;
+        let (workspace, cx) =
+            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
+
+        let palette =
+            open_palette_with_history(&workspace, &["open file", "backspace", "select all"], cx);
+
+        // Type "xyz" as a prefix that doesn't match anything
+        cx.simulate_input("xyz");
+        cx.background_executor.run_until_parked();
+
+        // Press up - should stay at "xyz" (no matches)
+        cx.simulate_keystrokes("up");
+        cx.background_executor.run_until_parked();
+        palette.read_with(cx, |palette, cx| {
+            assert_eq!(palette.query(cx), "xyz");
+        });
+    }
+
+    #[gpui::test]
+    async fn test_history_empty_prefix_searches_all(cx: &mut TestAppContext) {
+        let app_state = init_test(cx);
+        let project = Project::test(app_state.fs.clone(), [], cx).await;
+        let (workspace, cx) =
+            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
+
+        let palette = open_palette_with_history(&workspace, &["alpha", "beta", "gamma"], cx);
+
+        // With empty query, press up - should get "gamma" (most recent)
+        cx.simulate_keystrokes("up");
+        cx.background_executor.run_until_parked();
+        palette.read_with(cx, |palette, cx| {
+            assert_eq!(palette.query(cx), "gamma");
+        });
+
+        // Press up - should get "beta"
+        cx.simulate_keystrokes("up");
+        cx.background_executor.run_until_parked();
+        palette.read_with(cx, |palette, cx| {
+            assert_eq!(palette.query(cx), "beta");
+        });
+
+        // Press up - should get "alpha"
+        cx.simulate_keystrokes("up");
+        cx.background_executor.run_until_parked();
+        palette.read_with(cx, |palette, cx| {
+            assert_eq!(palette.query(cx), "alpha");
+        });
+
+        // Press down - should get "beta"
+        cx.simulate_keystrokes("down");
+        cx.background_executor.run_until_parked();
+        palette.read_with(cx, |palette, cx| {
+            assert_eq!(palette.query(cx), "beta");
+        });
+
+        // Press down - should get "gamma"
+        cx.simulate_keystrokes("down");
+        cx.background_executor.run_until_parked();
+        palette.read_with(cx, |palette, cx| {
+            assert_eq!(palette.query(cx), "gamma");
+        });
+
+        // Press down - should return to empty string (exit history mode)
+        cx.simulate_keystrokes("down");
+        cx.background_executor.run_until_parked();
+        palette.read_with(cx, |palette, cx| {
+            assert_eq!(palette.query(cx), "");
+        });
+    }
 }

crates/command_palette/src/persistence.rs 🔗

@@ -123,6 +123,16 @@ impl CommandPaletteDB {
             ORDER BY COUNT(1) DESC
         }
     }
+
+    query! {
+        pub fn list_recent_queries() -> Result<Vec<String>> {
+            SELECT user_query
+            FROM command_invocations
+            WHERE user_query != ""
+            GROUP BY user_query
+            ORDER BY MAX(last_invoked) ASC
+        }
+    }
 }
 
 #[cfg(test)]

crates/component_preview/Cargo.toml 🔗

@@ -0,0 +1,45 @@
+[package]
+name = "component_preview"
+version = "0.1.0"
+edition.workspace = true
+publish.workspace = true
+license = "GPL-3.0-or-later"
+
+[lints]
+workspace = true
+
+[lib]
+path = "src/component_preview.rs"
+
+[features]
+default = []
+preview = []
+test-support = ["db/test-support"]
+
+[dependencies]
+anyhow.workspace = true
+client.workspace = true
+collections.workspace = true
+component.workspace = true
+db.workspace = true
+fs.workspace = true
+gpui.workspace = true
+language.workspace = true
+log.workspace = true
+node_runtime.workspace = true
+notifications.workspace = true
+project.workspace = true
+release_channel.workspace = true
+reqwest_client.workspace = true
+session.workspace = true
+settings.workspace = true
+theme.workspace = true
+ui.workspace = true
+ui_input.workspace = true
+uuid.workspace = true
+workspace.workspace = true
+
+[[example]]
+name = "component_preview"
+path = "examples/component_preview.rs"
+required-features = ["preview"]

crates/component_preview/examples/component_preview.rs 🔗

@@ -0,0 +1,18 @@
+//! Component Preview Example
+//!
+//! Run with: `cargo run -p component_preview --example component_preview --features="preview"`
+//!
+//! To use this in other projects, add the following to your `Cargo.toml`:
+//!
+//! ```toml
+//! [dependencies]
+//! component_preview = { path = "../component_preview", features = ["preview"] }
+//!
+//! [[example]]
+//! name = "component_preview"
+//! path = "examples/component_preview.rs"
+//! ```
+
+fn main() {
+    component_preview::run_component_preview();
+}

crates/zed/src/zed/component_preview.rs → crates/component_preview/src/component_preview.rs 🔗

@@ -1,7 +1,4 @@
-//! # Component Preview
-//!
-//! A view for exploring Zed components.
-
+mod component_preview_example;
 mod persistence;
 
 use client::UserStore;
@@ -11,18 +8,21 @@ use gpui::{
     App, Entity, EventEmitter, FocusHandle, Focusable, Task, WeakEntity, Window, list, prelude::*,
 };
 use gpui::{ListState, ScrollHandle, ScrollStrategy, UniformListScrollHandle};
-use languages::LanguageRegistry;
+use language::LanguageRegistry;
 use notifications::status_toast::{StatusToast, ToastIcon};
 use persistence::COMPONENT_PREVIEW_DB;
 use project::Project;
 use std::{iter::Iterator, ops::Range, sync::Arc};
 use ui::{ButtonLike, Divider, HighlightedLabel, ListItem, ListSubHeader, Tooltip, prelude::*};
 use ui_input::InputField;
+use workspace::AppState;
 use workspace::{
-    AppState, Item, ItemId, SerializableItem, Workspace, WorkspaceId, delete_unloaded_items,
-    item::ItemEvent,
+    Item, ItemId, SerializableItem, Workspace, WorkspaceId, delete_unloaded_items, item::ItemEvent,
 };
 
+#[allow(unused_imports)]
+pub use component_preview_example::*;
+
 pub fn init(app_state: Arc<AppState>, cx: &mut App) {
     workspace::register_serializable_item::<ComponentPreview>(cx);
 
@@ -161,7 +161,7 @@ impl ComponentPreview {
         component_preview.update_component_list(cx);
 
         let focus_handle = component_preview.filter_editor.read(cx).focus_handle(cx);
-        window.focus(&focus_handle);
+        window.focus(&focus_handle, cx);
 
         Ok(component_preview)
     }
@@ -770,7 +770,7 @@ impl Item for ComponentPreview {
         self.workspace_id = workspace.database_id();
 
         let focus_handle = self.filter_editor.read(cx).focus_handle(cx);
-        window.focus(&focus_handle);
+        window.focus(&focus_handle, cx);
     }
 }
 

crates/component_preview/src/component_preview_example.rs 🔗

@@ -0,0 +1,145 @@
+/// Run the component preview application.
+///
+/// This initializes the application with minimal required infrastructure
+/// and opens a workspace with the ComponentPreview item.
+#[cfg(feature = "preview")]
+pub fn run_component_preview() {
+    use fs::RealFs;
+    use gpui::{
+        AppContext as _, Application, Bounds, KeyBinding, WindowBounds, WindowOptions, actions,
+        size,
+    };
+
+    use client::{Client, UserStore};
+    use language::LanguageRegistry;
+    use node_runtime::NodeRuntime;
+    use project::Project;
+    use reqwest_client::ReqwestClient;
+    use session::{AppSession, Session};
+    use std::sync::Arc;
+    use ui::{App, px};
+    use workspace::{AppState, Workspace, WorkspaceStore};
+
+    use crate::{ComponentPreview, init};
+
+    actions!(zed, [Quit]);
+
+    fn quit(_: &Quit, cx: &mut App) {
+        cx.quit();
+    }
+
+    Application::new().run(|cx| {
+        component::init();
+
+        cx.on_action(quit);
+        cx.bind_keys([KeyBinding::new("cmd-q", Quit, None)]);
+        let version = release_channel::AppVersion::load(env!("CARGO_PKG_VERSION"), None, None);
+        release_channel::init(version, cx);
+
+        let http_client =
+            ReqwestClient::user_agent("component_preview").expect("Failed to create HTTP client");
+        cx.set_http_client(Arc::new(http_client));
+
+        let fs = Arc::new(RealFs::new(None, cx.background_executor().clone()));
+        <dyn fs::Fs>::set_global(fs.clone(), cx);
+
+        settings::init(cx);
+        theme::init(theme::LoadThemes::JustBase, cx);
+
+        let languages = Arc::new(LanguageRegistry::new(cx.background_executor().clone()));
+        let client = Client::production(cx);
+        client::init(&client, cx);
+
+        let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
+        let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
+        let session_id = uuid::Uuid::new_v4().to_string();
+        let session = cx.background_executor().block(Session::new(session_id));
+        let session = cx.new(|cx| AppSession::new(session, cx));
+        let node_runtime = NodeRuntime::unavailable();
+
+        let app_state = Arc::new(AppState {
+            languages,
+            client,
+            user_store,
+            workspace_store,
+            fs,
+            build_window_options: |_, _| Default::default(),
+            node_runtime,
+            session,
+        });
+        AppState::set_global(Arc::downgrade(&app_state), cx);
+
+        workspace::init(app_state.clone(), cx);
+        init(app_state.clone(), cx);
+
+        let size = size(px(1200.), px(800.));
+        let bounds = Bounds::centered(None, size, cx);
+
+        cx.open_window(
+            WindowOptions {
+                window_bounds: Some(WindowBounds::Windowed(bounds)),
+                ..Default::default()
+            },
+            {
+                move |window, cx| {
+                    let app_state = app_state;
+                    theme::setup_ui_font(window, cx);
+
+                    let project = Project::local(
+                        app_state.client.clone(),
+                        app_state.node_runtime.clone(),
+                        app_state.user_store.clone(),
+                        app_state.languages.clone(),
+                        app_state.fs.clone(),
+                        None,
+                        false,
+                        cx,
+                    );
+
+                    let workspace = cx.new(|cx| {
+                        Workspace::new(
+                            Default::default(),
+                            project.clone(),
+                            app_state.clone(),
+                            window,
+                            cx,
+                        )
+                    });
+
+                    workspace.update(cx, |workspace, cx| {
+                        let weak_workspace = cx.entity().downgrade();
+                        let language_registry = app_state.languages.clone();
+                        let user_store = app_state.user_store.clone();
+
+                        let component_preview = cx.new(|cx| {
+                            ComponentPreview::new(
+                                weak_workspace,
+                                project,
+                                language_registry,
+                                user_store,
+                                None,
+                                None,
+                                window,
+                                cx,
+                            )
+                            .expect("Failed to create component preview")
+                        });
+
+                        workspace.add_item_to_active_pane(
+                            Box::new(component_preview),
+                            None,
+                            true,
+                            window,
+                            cx,
+                        );
+                    });
+
+                    workspace
+                }
+            },
+        )
+        .expect("Failed to open component preview window");
+
+        cx.activate(true);
+    });
+}

crates/context_server/Cargo.toml 🔗

@@ -29,10 +29,12 @@ schemars.workspace = true
 serde_json.workspace = true
 serde.workspace = true
 settings.workspace = true
+slotmap.workspace = true
 smol.workspace = true
 tempfile.workspace = true
 url = { workspace = true, features = ["serde"] }
 util.workspace = true
+terminal.workspace = true
 
 [dev-dependencies]
 gpui = { workspace = true, features = ["test-support"] }

crates/context_server/src/client.rs 🔗

@@ -6,6 +6,7 @@ use parking_lot::Mutex;
 use postage::barrier;
 use serde::{Deserialize, Serialize, de::DeserializeOwned};
 use serde_json::{Value, value::RawValue};
+use slotmap::SlotMap;
 use smol::channel;
 use std::{
     fmt,
@@ -50,7 +51,7 @@ pub(crate) struct Client {
     next_id: AtomicI32,
     outbound_tx: channel::Sender<String>,
     name: Arc<str>,
-    notification_handlers: Arc<Mutex<HashMap<&'static str, NotificationHandler>>>,
+    subscription_set: Arc<Mutex<NotificationSubscriptionSet>>,
     response_handlers: Arc<Mutex<Option<HashMap<RequestId, ResponseHandler>>>>,
     #[allow(clippy::type_complexity)]
     #[allow(dead_code)]
@@ -191,21 +192,20 @@ impl Client {
         let (outbound_tx, outbound_rx) = channel::unbounded::<String>();
         let (output_done_tx, output_done_rx) = barrier::channel();
 
-        let notification_handlers =
-            Arc::new(Mutex::new(HashMap::<_, NotificationHandler>::default()));
+        let subscription_set = Arc::new(Mutex::new(NotificationSubscriptionSet::default()));
         let response_handlers =
             Arc::new(Mutex::new(Some(HashMap::<_, ResponseHandler>::default())));
         let request_handlers = Arc::new(Mutex::new(HashMap::<_, RequestHandler>::default()));
 
         let receive_input_task = cx.spawn({
-            let notification_handlers = notification_handlers.clone();
+            let subscription_set = subscription_set.clone();
             let response_handlers = response_handlers.clone();
             let request_handlers = request_handlers.clone();
             let transport = transport.clone();
             async move |cx| {
                 Self::handle_input(
                     transport,
-                    notification_handlers,
+                    subscription_set,
                     request_handlers,
                     response_handlers,
                     cx,
@@ -236,7 +236,7 @@ impl Client {
 
         Ok(Self {
             server_id,
-            notification_handlers,
+            subscription_set,
             response_handlers,
             name: server_name,
             next_id: Default::default(),
@@ -257,7 +257,7 @@ impl Client {
     /// to pending requests) and notifications (which trigger registered handlers).
     async fn handle_input(
         transport: Arc<dyn Transport>,
-        notification_handlers: Arc<Mutex<HashMap<&'static str, NotificationHandler>>>,
+        subscription_set: Arc<Mutex<NotificationSubscriptionSet>>,
         request_handlers: Arc<Mutex<HashMap<&'static str, RequestHandler>>>,
         response_handlers: Arc<Mutex<Option<HashMap<RequestId, ResponseHandler>>>>,
         cx: &mut AsyncApp,
@@ -282,10 +282,11 @@ impl Client {
                     handler(Ok(message.to_string()));
                 }
             } else if let Ok(notification) = serde_json::from_str::<AnyNotification>(&message) {
-                let mut notification_handlers = notification_handlers.lock();
-                if let Some(handler) = notification_handlers.get_mut(notification.method.as_str()) {
-                    handler(notification.params.unwrap_or(Value::Null), cx.clone());
-                }
+                subscription_set.lock().notify(
+                    &notification.method,
+                    notification.params.unwrap_or(Value::Null),
+                    cx,
+                )
             } else {
                 log::error!("Unhandled JSON from context_server: {}", message);
             }
@@ -451,12 +452,18 @@ impl Client {
         Ok(())
     }
 
+    #[must_use]
     pub fn on_notification(
         &self,
         method: &'static str,
         f: Box<dyn 'static + Send + FnMut(Value, AsyncApp)>,
-    ) {
-        self.notification_handlers.lock().insert(method, f);
+    ) -> NotificationSubscription {
+        let mut notification_subscriptions = self.subscription_set.lock();
+
+        NotificationSubscription {
+            id: notification_subscriptions.add_handler(method, f),
+            set: self.subscription_set.clone(),
+        }
     }
 }
 
@@ -485,3 +492,73 @@ impl fmt::Debug for Client {
             .finish_non_exhaustive()
     }
 }
+
+slotmap::new_key_type! {
+    struct NotificationSubscriptionId;
+}
+
+#[derive(Default)]
+pub struct NotificationSubscriptionSet {
+    // we have very few subscriptions at the moment
+    methods: Vec<(&'static str, Vec<NotificationSubscriptionId>)>,
+    handlers: SlotMap<NotificationSubscriptionId, NotificationHandler>,
+}
+
+impl NotificationSubscriptionSet {
+    #[must_use]
+    fn add_handler(
+        &mut self,
+        method: &'static str,
+        handler: NotificationHandler,
+    ) -> NotificationSubscriptionId {
+        let id = self.handlers.insert(handler);
+        if let Some((_, handler_ids)) = self
+            .methods
+            .iter_mut()
+            .find(|(probe_method, _)| method == *probe_method)
+        {
+            debug_assert!(
+                handler_ids.len() < 20,
+                "Too many MCP handlers for {}. Consider using a different data structure.",
+                method
+            );
+
+            handler_ids.push(id);
+        } else {
+            self.methods.push((method, vec![id]));
+        };
+        id
+    }
+
+    fn notify(&mut self, method: &str, payload: Value, cx: &mut AsyncApp) {
+        let Some((_, handler_ids)) = self
+            .methods
+            .iter_mut()
+            .find(|(probe_method, _)| method == *probe_method)
+        else {
+            return;
+        };
+
+        for handler_id in handler_ids {
+            if let Some(handler) = self.handlers.get_mut(*handler_id) {
+                handler(payload.clone(), cx.clone());
+            }
+        }
+    }
+}
+
+pub struct NotificationSubscription {
+    id: NotificationSubscriptionId,
+    set: Arc<Mutex<NotificationSubscriptionSet>>,
+}
+
+impl Drop for NotificationSubscription {
+    fn drop(&mut self) {
+        let mut set = self.set.lock();
+        set.handlers.remove(self.id);
+        set.methods.retain_mut(|(_, handler_ids)| {
+            handler_ids.retain(|id| *id != self.id);
+            !handler_ids.is_empty()
+        });
+    }
+}

crates/context_server/src/context_server.rs 🔗

@@ -96,22 +96,6 @@ impl ContextServer {
         self.initialize(self.new_client(cx)?).await
     }
 
-    /// Starts the context server, making sure handlers are registered before initialization happens
-    pub async fn start_with_handlers(
-        &self,
-        notification_handlers: Vec<(
-            &'static str,
-            Box<dyn 'static + Send + FnMut(serde_json::Value, AsyncApp)>,
-        )>,
-        cx: &AsyncApp,
-    ) -> Result<()> {
-        let client = self.new_client(cx)?;
-        for (method, handler) in notification_handlers {
-            client.on_notification(method, handler);
-        }
-        self.initialize(client).await
-    }
-
     fn new_client(&self, cx: &AsyncApp) -> Result<Client> {
         Ok(match &self.configuration {
             ContextServerTransport::Stdio(command, working_directory) => Client::stdio(

crates/context_server/src/protocol.rs 🔗

@@ -12,7 +12,7 @@ use futures::channel::oneshot;
 use gpui::AsyncApp;
 use serde_json::Value;
 
-use crate::client::Client;
+use crate::client::{Client, NotificationSubscription};
 use crate::types::{self, Notification, Request};
 
 pub struct ModelContextProtocol {
@@ -119,7 +119,7 @@ impl InitializedContextServerProtocol {
         &self,
         method: &'static str,
         f: Box<dyn 'static + Send + FnMut(Value, AsyncApp)>,
-    ) {
-        self.inner.on_notification(method, f);
+    ) -> NotificationSubscription {
+        self.inner.on_notification(method, f)
     }
 }

crates/context_server/src/transport/stdio_transport.rs 🔗

@@ -8,9 +8,12 @@ use futures::{
     AsyncBufReadExt as _, AsyncRead, AsyncWrite, AsyncWriteExt as _, Stream, StreamExt as _,
 };
 use gpui::AsyncApp;
+use settings::Settings as _;
 use smol::channel;
 use smol::process::Child;
+use terminal::terminal_settings::TerminalSettings;
 use util::TryFutureExt as _;
+use util::shell_builder::ShellBuilder;
 
 use crate::client::ModelContextServerBinary;
 use crate::transport::Transport;
@@ -28,9 +31,12 @@ impl StdioTransport {
         working_directory: &Option<PathBuf>,
         cx: &AsyncApp,
     ) -> Result<Self> {
-        let mut command = util::command::new_smol_command(&binary.executable);
+        let shell = cx.update(|cx| TerminalSettings::get(None, cx).shell.clone())?;
+        let builder = ShellBuilder::new(&shell, cfg!(windows)).non_interactive();
+        let mut command =
+            builder.build_command(Some(binary.executable.display().to_string()), &binary.args);
+
         command
-            .args(&binary.args)
             .envs(binary.env.unwrap_or_default())
             .stdin(std::process::Stdio::piped())
             .stdout(std::process::Stdio::piped())

crates/context_server/src/types.rs 🔗

@@ -330,7 +330,7 @@ pub struct PromptMessage {
     pub content: MessageContent,
 }
 
-#[derive(Debug, Serialize, Deserialize)]
+#[derive(Debug, Serialize, Deserialize, PartialEq, Eq)]
 #[serde(rename_all = "lowercase")]
 pub enum Role {
     User,

crates/copilot/Cargo.toml 🔗

@@ -33,7 +33,7 @@ fs.workspace = true
 futures.workspace = true
 gpui.workspace = true
 http_client.workspace = true
-edit_prediction.workspace = true
+edit_prediction_types.workspace = true
 language.workspace = true
 log.workspace = true
 lsp.workspace = true
@@ -52,6 +52,7 @@ ui.workspace = true
 util.workspace = true
 workspace.workspace = true
 itertools.workspace = true
+url.workspace = true
 
 [target.'cfg(windows)'.dependencies]
 async-std = { version = "1.12.0", features = ["unstable"] }

crates/copilot/src/copilot.rs 🔗

@@ -1,10 +1,11 @@
 pub mod copilot_chat;
-mod copilot_completion_provider;
+mod copilot_edit_prediction_delegate;
 pub mod copilot_responses;
 pub mod request;
 mod sign_in;
 
-use crate::sign_in::initiate_sign_in_within_workspace;
+use crate::request::NextEditSuggestions;
+use crate::sign_in::initiate_sign_out;
 use ::fs::Fs;
 use anyhow::{Context as _, Result, anyhow};
 use collections::{HashMap, HashSet};
@@ -18,7 +19,7 @@ use http_client::HttpClient;
 use language::language_settings::CopilotSettings;
 use language::{
     Anchor, Bias, Buffer, BufferSnapshot, Language, PointUtf16, ToPointUtf16,
-    language_settings::{EditPredictionProvider, all_language_settings, language_settings},
+    language_settings::{EditPredictionProvider, all_language_settings},
     point_from_lsp, point_to_lsp,
 };
 use lsp::{LanguageServer, LanguageServerBinary, LanguageServerId, LanguageServerName};
@@ -28,12 +29,10 @@ use project::DisableAiSettings;
 use request::StatusNotification;
 use semver::Version;
 use serde_json::json;
-use settings::Settings;
-use settings::SettingsStore;
-use sign_in::{reinstall_and_sign_in_within_workspace, sign_out_within_workspace};
-use std::collections::hash_map::Entry;
+use settings::{Settings, SettingsStore};
 use std::{
     any::TypeId,
+    collections::hash_map::Entry,
     env,
     ffi::OsString,
     mem,
@@ -42,12 +41,14 @@ use std::{
     sync::Arc,
 };
 use sum_tree::Dimensions;
-use util::rel_path::RelPath;
 use util::{ResultExt, fs::remove_matching};
 use workspace::Workspace;
 
-pub use crate::copilot_completion_provider::CopilotCompletionProvider;
-pub use crate::sign_in::{CopilotCodeVerification, initiate_sign_in, reinstall_and_sign_in};
+pub use crate::copilot_edit_prediction_delegate::CopilotEditPredictionDelegate;
+pub use crate::sign_in::{
+    ConfigurationMode, ConfigurationView, CopilotCodeVerification, initiate_sign_in,
+    reinstall_and_sign_in,
+};
 
 actions!(
     copilot,
@@ -98,21 +99,14 @@ pub fn init(
     .detach();
 
     cx.observe_new(|workspace: &mut Workspace, _window, _cx| {
-        workspace.register_action(|workspace, _: &SignIn, window, cx| {
-            if let Some(copilot) = Copilot::global(cx) {
-                let is_reinstall = false;
-                initiate_sign_in_within_workspace(workspace, copilot, is_reinstall, window, cx);
-            }
+        workspace.register_action(|_, _: &SignIn, window, cx| {
+            initiate_sign_in(window, cx);
         });
-        workspace.register_action(|workspace, _: &Reinstall, window, cx| {
-            if let Some(copilot) = Copilot::global(cx) {
-                reinstall_and_sign_in_within_workspace(workspace, copilot, window, cx);
-            }
+        workspace.register_action(|_, _: &Reinstall, window, cx| {
+            reinstall_and_sign_in(window, cx);
         });
-        workspace.register_action(|workspace, _: &SignOut, _window, cx| {
-            if let Some(copilot) = Copilot::global(cx) {
-                sign_out_within_workspace(workspace, copilot, cx);
-            }
+        workspace.register_action(|_, _: &SignOut, window, cx| {
+            initiate_sign_out(window, cx);
         });
     })
     .detach();
@@ -322,6 +316,15 @@ struct GlobalCopilot(Entity<Copilot>);
 
 impl Global for GlobalCopilot {}
 
+/// Copilot's NextEditSuggestion response, with coordinates converted to Anchors.
+struct CopilotEditPrediction {
+    buffer: Entity<Buffer>,
+    range: Range<Anchor>,
+    text: String,
+    command: Option<lsp::Command>,
+    snapshot: BufferSnapshot,
+}
+
 impl Copilot {
     pub fn global(cx: &App) -> Option<Entity<Self>> {
         cx.try_global::<GlobalCopilot>()
@@ -375,7 +378,7 @@ impl Copilot {
         }
     }
 
-    fn start_copilot(
+    pub fn start_copilot(
         &mut self,
         check_edit_prediction_provider: bool,
         awaiting_sign_in_after_start: bool,
@@ -563,6 +566,14 @@ impl Copilot {
         let server = start_language_server.await;
         this.update(cx, |this, cx| {
             cx.notify();
+
+            if env::var("ZED_FORCE_COPILOT_ERROR").is_ok() {
+                this.server = CopilotServer::Error(
+                    "Forced error for testing (ZED_FORCE_COPILOT_ERROR)".into(),
+                );
+                return;
+            }
+
             match server {
                 Ok((server, status)) => {
                     this.server = CopilotServer::Running(RunningCopilotServer {
@@ -584,7 +595,17 @@ impl Copilot {
         .ok();
     }
 
-    pub(crate) fn sign_in(&mut self, cx: &mut Context<Self>) -> Task<Result<()>> {
+    pub fn is_authenticated(&self) -> bool {
+        return matches!(
+            self.server,
+            CopilotServer::Running(RunningCopilotServer {
+                sign_in_status: SignInStatus::Authorized,
+                ..
+            })
+        );
+    }
+
+    pub fn sign_in(&mut self, cx: &mut Context<Self>) -> Task<Result<()>> {
         if let CopilotServer::Running(server) = &mut self.server {
             let task = match &server.sign_in_status {
                 SignInStatus::Authorized => Task::ready(Ok(())).shared(),
@@ -807,7 +828,7 @@ impl Copilot {
                         .ok();
                 }
                 language::BufferEvent::FileHandleChanged
-                | language::BufferEvent::LanguageChanged => {
+                | language::BufferEvent::LanguageChanged(_) => {
                     let new_language_id = id_for_language(buffer.read(cx).language());
                     let Ok(new_uri) = uri_for_buffer(&buffer, cx) else {
                         return Ok(());
@@ -862,101 +883,19 @@ impl Copilot {
         }
     }
 
-    pub fn completions<T>(
-        &mut self,
-        buffer: &Entity<Buffer>,
-        position: T,
-        cx: &mut Context<Self>,
-    ) -> Task<Result<Vec<Completion>>>
-    where
-        T: ToPointUtf16,
-    {
-        self.request_completions::<request::GetCompletions, _>(buffer, position, cx)
-    }
-
-    pub fn completions_cycling<T>(
+    pub(crate) fn completions(
         &mut self,
         buffer: &Entity<Buffer>,
-        position: T,
-        cx: &mut Context<Self>,
-    ) -> Task<Result<Vec<Completion>>>
-    where
-        T: ToPointUtf16,
-    {
-        self.request_completions::<request::GetCompletionsCycling, _>(buffer, position, cx)
-    }
-
-    pub fn accept_completion(
-        &mut self,
-        completion: &Completion,
+        position: Anchor,
         cx: &mut Context<Self>,
-    ) -> Task<Result<()>> {
-        let server = match self.server.as_authenticated() {
-            Ok(server) => server,
-            Err(error) => return Task::ready(Err(error)),
-        };
-        let request =
-            server
-                .lsp
-                .request::<request::NotifyAccepted>(request::NotifyAcceptedParams {
-                    uuid: completion.uuid.clone(),
-                });
-        cx.background_spawn(async move {
-            request
-                .await
-                .into_response()
-                .context("copilot: notify accepted")?;
-            Ok(())
-        })
-    }
-
-    pub fn discard_completions(
-        &mut self,
-        completions: &[Completion],
-        cx: &mut Context<Self>,
-    ) -> Task<Result<()>> {
-        let server = match self.server.as_authenticated() {
-            Ok(server) => server,
-            Err(_) => return Task::ready(Ok(())),
-        };
-        let request =
-            server
-                .lsp
-                .request::<request::NotifyRejected>(request::NotifyRejectedParams {
-                    uuids: completions
-                        .iter()
-                        .map(|completion| completion.uuid.clone())
-                        .collect(),
-                });
-        cx.background_spawn(async move {
-            request
-                .await
-                .into_response()
-                .context("copilot: notify rejected")?;
-            Ok(())
-        })
-    }
-
-    fn request_completions<R, T>(
-        &mut self,
-        buffer: &Entity<Buffer>,
-        position: T,
-        cx: &mut Context<Self>,
-    ) -> Task<Result<Vec<Completion>>>
-    where
-        R: 'static
-            + lsp::request::Request<
-                Params = request::GetCompletionsParams,
-                Result = request::GetCompletionsResult,
-            >,
-        T: ToPointUtf16,
-    {
+    ) -> Task<Result<Vec<CopilotEditPrediction>>> {
         self.register_buffer(buffer, cx);
 
         let server = match self.server.as_authenticated() {
             Ok(server) => server,
             Err(error) => return Task::ready(Err(error)),
         };
+        let buffer_entity = buffer.clone();
         let lsp = server.lsp.clone();
         let registered_buffer = server
             .registered_buffers
@@ -966,46 +905,31 @@ impl Copilot {
         let buffer = buffer.read(cx);
         let uri = registered_buffer.uri.clone();
         let position = position.to_point_utf16(buffer);
-        let settings = language_settings(
-            buffer.language_at(position).map(|l| l.name()),
-            buffer.file(),
-            cx,
-        );
-        let tab_size = settings.tab_size;
-        let hard_tabs = settings.hard_tabs;
-        let relative_path = buffer
-            .file()
-            .map_or(RelPath::empty().into(), |file| file.path().clone());
 
         cx.background_spawn(async move {
             let (version, snapshot) = snapshot.await?;
             let result = lsp
-                .request::<R>(request::GetCompletionsParams {
-                    doc: request::GetCompletionsDocument {
-                        uri,
-                        tab_size: tab_size.into(),
-                        indent_size: 1,
-                        insert_spaces: !hard_tabs,
-                        relative_path: relative_path.to_proto(),
-                        position: point_to_lsp(position),
-                        version: version.try_into().unwrap(),
-                    },
+                .request::<NextEditSuggestions>(request::NextEditSuggestionsParams {
+                    text_document: lsp::VersionedTextDocumentIdentifier { uri, version },
+                    position: point_to_lsp(position),
                 })
                 .await
                 .into_response()
                 .context("copilot: get completions")?;
             let completions = result
-                .completions
+                .edits
                 .into_iter()
                 .map(|completion| {
                     let start = snapshot
                         .clip_point_utf16(point_from_lsp(completion.range.start), Bias::Left);
                     let end =
                         snapshot.clip_point_utf16(point_from_lsp(completion.range.end), Bias::Left);
-                    Completion {
-                        uuid: completion.uuid,
+                    CopilotEditPrediction {
+                        buffer: buffer_entity.clone(),
                         range: snapshot.anchor_before(start)..snapshot.anchor_after(end),
                         text: completion.text,
+                        command: completion.command,
+                        snapshot: snapshot.clone(),
                     }
                 })
                 .collect();
@@ -1013,6 +937,35 @@ impl Copilot {
         })
     }
 
+    pub(crate) fn accept_completion(
+        &mut self,
+        completion: &CopilotEditPrediction,
+        cx: &mut Context<Self>,
+    ) -> Task<Result<()>> {
+        let server = match self.server.as_authenticated() {
+            Ok(server) => server,
+            Err(error) => return Task::ready(Err(error)),
+        };
+        if let Some(command) = &completion.command {
+            let request = server
+                .lsp
+                .request::<lsp::ExecuteCommand>(lsp::ExecuteCommandParams {
+                    command: command.command.clone(),
+                    arguments: command.arguments.clone().unwrap_or_default(),
+                    ..Default::default()
+                });
+            cx.background_spawn(async move {
+                request
+                    .await
+                    .into_response()
+                    .context("copilot: notify accepted")?;
+                Ok(())
+            })
+        } else {
+            Task::ready(Ok(()))
+        }
+    }
+
     pub fn status(&self) -> Status {
         match &self.server {
             CopilotServer::Starting { task } => Status::Starting { task: task.clone() },
@@ -1235,7 +1188,10 @@ async fn get_copilot_lsp(fs: Arc<dyn Fs>, node_runtime: NodeRuntime) -> anyhow::
         .await;
     if should_install {
         node_runtime
-            .npm_install_packages(paths::copilot_dir(), &[(PACKAGE_NAME, &latest_version)])
+            .npm_install_packages(
+                paths::copilot_dir(),
+                &[(PACKAGE_NAME, &latest_version.to_string())],
+            )
             .await?;
     }
 
@@ -1246,7 +1202,11 @@ async fn get_copilot_lsp(fs: Arc<dyn Fs>, node_runtime: NodeRuntime) -> anyhow::
 mod tests {
     use super::*;
     use gpui::TestAppContext;
-    use util::{path, paths::PathStyle, rel_path::rel_path};
+    use util::{
+        path,
+        paths::PathStyle,
+        rel_path::{RelPath, rel_path},
+    };
 
     #[gpui::test(iterations = 10)]
     async fn test_buffer_management(cx: &mut TestAppContext) {

crates/copilot/src/copilot_completion_provider.rs → crates/copilot/src/copilot_edit_prediction_delegate.rs 🔗

@@ -1,53 +1,33 @@
-use crate::{Completion, Copilot};
+use crate::{Copilot, CopilotEditPrediction};
 use anyhow::Result;
-use edit_prediction::{Direction, EditPrediction, EditPredictionProvider};
-use gpui::{App, Context, Entity, EntityId, Task};
-use language::{Buffer, OffsetRangeExt, ToOffset, language_settings::AllLanguageSettings};
-use settings::Settings;
-use std::{path::Path, time::Duration};
+use edit_prediction_types::{EditPrediction, EditPredictionDelegate, interpolate_edits};
+use gpui::{App, Context, Entity, Task};
+use language::{Anchor, Buffer, EditPreview, OffsetRangeExt};
+use std::{ops::Range, sync::Arc, time::Duration};
 
 pub const COPILOT_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
 
-pub struct CopilotCompletionProvider {
-    cycled: bool,
-    buffer_id: Option<EntityId>,
-    completions: Vec<Completion>,
-    active_completion_index: usize,
-    file_extension: Option<String>,
+pub struct CopilotEditPredictionDelegate {
+    completion: Option<(CopilotEditPrediction, EditPreview)>,
     pending_refresh: Option<Task<Result<()>>>,
-    pending_cycling_refresh: Option<Task<Result<()>>>,
     copilot: Entity<Copilot>,
 }
 
-impl CopilotCompletionProvider {
+impl CopilotEditPredictionDelegate {
     pub fn new(copilot: Entity<Copilot>) -> Self {
         Self {
-            cycled: false,
-            buffer_id: None,
-            completions: Vec::new(),
-            active_completion_index: 0,
-            file_extension: None,
+            completion: None,
             pending_refresh: None,
-            pending_cycling_refresh: None,
             copilot,
         }
     }
 
-    fn active_completion(&self) -> Option<&Completion> {
-        self.completions.get(self.active_completion_index)
-    }
-
-    fn push_completion(&mut self, new_completion: Completion) {
-        for completion in &self.completions {
-            if completion.text == new_completion.text && completion.range == new_completion.range {
-                return;
-            }
-        }
-        self.completions.push(new_completion);
+    fn active_completion(&self) -> Option<&(CopilotEditPrediction, EditPreview)> {
+        self.completion.as_ref()
     }
 }
 
-impl EditPredictionProvider for CopilotCompletionProvider {
+impl EditPredictionDelegate for CopilotEditPredictionDelegate {
     fn name() -> &'static str {
         "copilot"
     }
@@ -56,7 +36,7 @@ impl EditPredictionProvider for CopilotCompletionProvider {
         "Copilot"
     }
 
-    fn show_completions_in_menu() -> bool {
+    fn show_predictions_in_menu() -> bool {
         true
     }
 
@@ -64,12 +44,8 @@ impl EditPredictionProvider for CopilotCompletionProvider {
         true
     }
 
-    fn supports_jump_to_edit() -> bool {
-        false
-    }
-
     fn is_refreshing(&self, _cx: &App) -> bool {
-        self.pending_refresh.is_some() && self.completions.is_empty()
+        self.pending_refresh.is_some() && self.completion.is_none()
     }
 
     fn is_enabled(
@@ -102,160 +78,96 @@ impl EditPredictionProvider for CopilotCompletionProvider {
                 })?
                 .await?;
 
-            this.update(cx, |this, cx| {
-                if !completions.is_empty() {
-                    this.cycled = false;
+            if let Some(mut completion) = completions.into_iter().next()
+                && let Some(trimmed_completion) = cx
+                    .update(|cx| trim_completion(&completion, cx))
+                    .ok()
+                    .flatten()
+            {
+                let preview = buffer
+                    .update(cx, |this, cx| {
+                        this.preview_edits(Arc::from(std::slice::from_ref(&trimmed_completion)), cx)
+                    })?
+                    .await;
+                this.update(cx, |this, cx| {
                     this.pending_refresh = None;
-                    this.pending_cycling_refresh = None;
-                    this.completions.clear();
-                    this.active_completion_index = 0;
-                    this.buffer_id = Some(buffer.entity_id());
-                    this.file_extension = buffer.read(cx).file().and_then(|file| {
-                        Some(
-                            Path::new(file.file_name(cx))
-                                .extension()?
-                                .to_str()?
-                                .to_string(),
-                        )
-                    });
-
-                    for completion in completions {
-                        this.push_completion(completion);
-                    }
+                    completion.range = trimmed_completion.0;
+                    completion.text = trimmed_completion.1.to_string();
+                    this.completion = Some((completion, preview));
+
                     cx.notify();
-                }
-            })?;
+                })?;
+            }
 
             Ok(())
         }));
     }
 
-    fn cycle(
-        &mut self,
-        buffer: Entity<Buffer>,
-        cursor_position: language::Anchor,
-        direction: Direction,
-        cx: &mut Context<Self>,
-    ) {
-        if self.cycled {
-            match direction {
-                Direction::Prev => {
-                    self.active_completion_index = if self.active_completion_index == 0 {
-                        self.completions.len().saturating_sub(1)
-                    } else {
-                        self.active_completion_index - 1
-                    };
-                }
-                Direction::Next => {
-                    if self.completions.is_empty() {
-                        self.active_completion_index = 0
-                    } else {
-                        self.active_completion_index =
-                            (self.active_completion_index + 1) % self.completions.len();
-                    }
-                }
-            }
-
-            cx.notify();
-        } else {
-            let copilot = self.copilot.clone();
-            self.pending_cycling_refresh = Some(cx.spawn(async move |this, cx| {
-                let completions = copilot
-                    .update(cx, |copilot, cx| {
-                        copilot.completions_cycling(&buffer, cursor_position, cx)
-                    })?
-                    .await?;
-
-                this.update(cx, |this, cx| {
-                    this.cycled = true;
-                    this.file_extension = buffer.read(cx).file().and_then(|file| {
-                        Some(
-                            Path::new(file.file_name(cx))
-                                .extension()?
-                                .to_str()?
-                                .to_string(),
-                        )
-                    });
-                    for completion in completions {
-                        this.push_completion(completion);
-                    }
-                    this.cycle(buffer, cursor_position, direction, cx);
-                })?;
-
-                Ok(())
-            }));
-        }
-    }
-
     fn accept(&mut self, cx: &mut Context<Self>) {
-        if let Some(completion) = self.active_completion() {
+        if let Some((completion, _)) = self.active_completion() {
             self.copilot
                 .update(cx, |copilot, cx| copilot.accept_completion(completion, cx))
                 .detach_and_log_err(cx);
         }
     }
 
-    fn discard(&mut self, cx: &mut Context<Self>) {
-        let settings = AllLanguageSettings::get_global(cx);
-
-        let copilot_enabled = settings.show_edit_predictions(None, cx);
-
-        if !copilot_enabled {
-            return;
-        }
-
-        self.copilot
-            .update(cx, |copilot, cx| {
-                copilot.discard_completions(&self.completions, cx)
-            })
-            .detach_and_log_err(cx);
-    }
+    fn discard(&mut self, _: &mut Context<Self>) {}
 
     fn suggest(
         &mut self,
         buffer: &Entity<Buffer>,
-        cursor_position: language::Anchor,
+        _: language::Anchor,
         cx: &mut Context<Self>,
     ) -> Option<EditPrediction> {
         let buffer_id = buffer.entity_id();
         let buffer = buffer.read(cx);
-        let completion = self.active_completion()?;
-        if Some(buffer_id) != self.buffer_id
+        let (completion, edit_preview) = self.active_completion()?;
+
+        if Some(buffer_id) != Some(completion.buffer.entity_id())
             || !completion.range.start.is_valid(buffer)
             || !completion.range.end.is_valid(buffer)
         {
             return None;
         }
+        let edits = vec![(
+            completion.range.clone(),
+            Arc::from(completion.text.as_ref()),
+        )];
+        let edits = interpolate_edits(&completion.snapshot, &buffer.snapshot(), &edits)
+            .filter(|edits| !edits.is_empty())?;
+
+        Some(EditPrediction::Local {
+            id: None,
+            edits,
+            edit_preview: Some(edit_preview.clone()),
+        })
+    }
+}
 
-        let mut completion_range = completion.range.to_offset(buffer);
-        let prefix_len = common_prefix(
-            buffer.chars_for_range(completion_range.clone()),
-            completion.text.chars(),
-        );
-        completion_range.start += prefix_len;
-        let suffix_len = common_prefix(
-            buffer.reversed_chars_for_range(completion_range.clone()),
-            completion.text[prefix_len..].chars().rev(),
-        );
-        completion_range.end = completion_range.end.saturating_sub(suffix_len);
-
-        if completion_range.is_empty()
-            && completion_range.start == cursor_position.to_offset(buffer)
-        {
-            let completion_text = &completion.text[prefix_len..completion.text.len() - suffix_len];
-            if completion_text.trim().is_empty() {
-                None
-            } else {
-                let position = cursor_position.bias_right(buffer);
-                Some(EditPrediction::Local {
-                    id: None,
-                    edits: vec![(position..position, completion_text.into())],
-                    edit_preview: None,
-                })
-            }
-        } else {
-            None
-        }
+fn trim_completion(
+    completion: &CopilotEditPrediction,
+    cx: &mut App,
+) -> Option<(Range<Anchor>, Arc<str>)> {
+    let buffer = completion.buffer.read(cx);
+    let mut completion_range = completion.range.to_offset(buffer);
+    let prefix_len = common_prefix(
+        buffer.chars_for_range(completion_range.clone()),
+        completion.text.chars(),
+    );
+    completion_range.start += prefix_len;
+    let suffix_len = common_prefix(
+        buffer.reversed_chars_for_range(completion_range.clone()),
+        completion.text[prefix_len..].chars().rev(),
+    );
+    completion_range.end = completion_range.end.saturating_sub(suffix_len);
+    let completion_text = &completion.text[prefix_len..completion.text.len() - suffix_len];
+    if completion_text.trim().is_empty() {
+        None
+    } else {
+        let completion_range =
+            buffer.anchor_after(completion_range.start)..buffer.anchor_after(completion_range.end);
+
+        Some((completion_range, Arc::from(completion_text)))
     }
 }
 
@@ -269,6 +181,7 @@ fn common_prefix<T1: Iterator<Item = char>, T2: Iterator<Item = char>>(a: T1, b:
 #[cfg(test)]
 mod tests {
     use super::*;
+    use edit_prediction_types::EditPredictionGranularity;
     use editor::{
         Editor, ExcerptRange, MultiBuffer, MultiBufferOffset, SelectionEffects,
         test::editor_lsp_test_context::EditorLspTestContext,
@@ -281,6 +194,7 @@ mod tests {
         Point,
         language_settings::{CompletionSettingsContent, LspInsertMode, WordsCompletionMode},
     };
+    use lsp::Uri;
     use project::Project;
     use serde_json::json;
     use settings::{AllLanguageSettingsContent, SettingsStore};
@@ -314,7 +228,7 @@ mod tests {
             cx,
         )
         .await;
-        let copilot_provider = cx.new(|_| CopilotCompletionProvider::new(copilot));
+        let copilot_provider = cx.new(|_| CopilotEditPredictionDelegate::new(copilot));
         cx.update_editor(|editor, window, cx| {
             editor.set_edit_prediction_provider(Some(copilot_provider), window, cx)
         });
@@ -336,12 +250,15 @@ mod tests {
         ));
         handle_copilot_completion_request(
             &copilot_lsp,
-            vec![crate::request::Completion {
+            vec![crate::request::NextEditSuggestion {
                 text: "one.copilot1".into(),
                 range: lsp::Range::new(lsp::Position::new(0, 0), lsp::Position::new(0, 4)),
-                ..Default::default()
+                command: None,
+                text_document: lsp::VersionedTextDocumentIdentifier {
+                    uri: Uri::from_file_path(path!("/root/dir/file.rs")).unwrap(),
+                    version: 0,
+                },
             }],
-            vec![],
         );
         executor.advance_clock(COPILOT_DEBOUNCE_TIMEOUT);
         cx.update_editor(|editor, window, cx| {
@@ -382,12 +299,15 @@ mod tests {
         ));
         handle_copilot_completion_request(
             &copilot_lsp,
-            vec![crate::request::Completion {
+            vec![crate::request::NextEditSuggestion {
                 text: "one.copilot1".into(),
                 range: lsp::Range::new(lsp::Position::new(0, 0), lsp::Position::new(0, 4)),
-                ..Default::default()
+                command: None,
+                text_document: lsp::VersionedTextDocumentIdentifier {
+                    uri: Uri::from_file_path(path!("/root/dir/file.rs")).unwrap(),
+                    version: 0,
+                },
             }],
-            vec![],
         );
         executor.advance_clock(COPILOT_DEBOUNCE_TIMEOUT);
         cx.update_editor(|editor, _, cx| {
@@ -411,12 +331,15 @@ mod tests {
         // After debouncing, new Copilot completions should be requested.
         handle_copilot_completion_request(
             &copilot_lsp,
-            vec![crate::request::Completion {
+            vec![crate::request::NextEditSuggestion {
                 text: "one.copilot2".into(),
                 range: lsp::Range::new(lsp::Position::new(0, 0), lsp::Position::new(0, 5)),
-                ..Default::default()
+                command: None,
+                text_document: lsp::VersionedTextDocumentIdentifier {
+                    uri: Uri::from_file_path(path!("/root/dir/file.rs")).unwrap(),
+                    version: 0,
+                },
             }],
-            vec![],
         );
         executor.advance_clock(COPILOT_DEBOUNCE_TIMEOUT);
         cx.update_editor(|editor, window, cx| {
@@ -478,45 +401,6 @@ mod tests {
             assert_eq!(editor.display_text(cx), "one.cop\ntwo\nthree\n");
             assert_eq!(editor.text(cx), "one.cop\ntwo\nthree\n");
         });
-
-        // Reset the editor to verify how suggestions behave when tabbing on leading indentation.
-        cx.update_editor(|editor, window, cx| {
-            editor.set_text("fn foo() {\n  \n}", window, cx);
-            editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
-                s.select_ranges([Point::new(1, 2)..Point::new(1, 2)])
-            });
-        });
-        handle_copilot_completion_request(
-            &copilot_lsp,
-            vec![crate::request::Completion {
-                text: "    let x = 4;".into(),
-                range: lsp::Range::new(lsp::Position::new(1, 0), lsp::Position::new(1, 2)),
-                ..Default::default()
-            }],
-            vec![],
-        );
-
-        cx.update_editor(|editor, window, cx| {
-            editor.next_edit_prediction(&Default::default(), window, cx)
-        });
-        executor.advance_clock(COPILOT_DEBOUNCE_TIMEOUT);
-        cx.update_editor(|editor, window, cx| {
-            assert!(editor.has_active_edit_prediction());
-            assert_eq!(editor.display_text(cx), "fn foo() {\n    let x = 4;\n}");
-            assert_eq!(editor.text(cx), "fn foo() {\n  \n}");
-
-            // Tabbing inside of leading whitespace inserts indentation without accepting the suggestion.
-            editor.tab(&Default::default(), window, cx);
-            assert!(editor.has_active_edit_prediction());
-            assert_eq!(editor.text(cx), "fn foo() {\n    \n}");
-            assert_eq!(editor.display_text(cx), "fn foo() {\n    let x = 4;\n}");
-
-            // Using AcceptEditPrediction again accepts the suggestion.
-            editor.accept_edit_prediction(&Default::default(), window, cx);
-            assert!(!editor.has_active_edit_prediction());
-            assert_eq!(editor.text(cx), "fn foo() {\n    let x = 4;\n}");
-            assert_eq!(editor.display_text(cx), "fn foo() {\n    let x = 4;\n}");
-        });
     }
 
     #[gpui::test(iterations = 10)]
@@ -546,7 +430,7 @@ mod tests {
             cx,
         )
         .await;
-        let copilot_provider = cx.new(|_| CopilotCompletionProvider::new(copilot));
+        let copilot_provider = cx.new(|_| CopilotEditPredictionDelegate::new(copilot));
         cx.update_editor(|editor, window, cx| {
             editor.set_edit_prediction_provider(Some(copilot_provider), window, cx)
         });
@@ -569,25 +453,30 @@ mod tests {
         ));
         handle_copilot_completion_request(
             &copilot_lsp,
-            vec![crate::request::Completion {
+            vec![crate::request::NextEditSuggestion {
                 text: "one.copilot1".into(),
                 range: lsp::Range::new(lsp::Position::new(0, 0), lsp::Position::new(0, 4)),
-                ..Default::default()
+                command: None,
+                text_document: lsp::VersionedTextDocumentIdentifier {
+                    uri: Uri::from_file_path(path!("/root/dir/file.rs")).unwrap(),
+                    version: 0,
+                },
             }],
-            vec![],
         );
         executor.advance_clock(COPILOT_DEBOUNCE_TIMEOUT);
         cx.update_editor(|editor, window, cx| {
             assert!(editor.has_active_edit_prediction());
 
             // Accepting the first word of the suggestion should only accept the first word and still show the rest.
-            editor.accept_partial_edit_prediction(&Default::default(), window, cx);
+            editor.accept_partial_edit_prediction(EditPredictionGranularity::Word, window, cx);
+
             assert!(editor.has_active_edit_prediction());
             assert_eq!(editor.text(cx), "one.copilot\ntwo\nthree\n");
             assert_eq!(editor.display_text(cx), "one.copilot1\ntwo\nthree\n");
 
             // Accepting next word should accept the non-word and copilot suggestion should be gone
-            editor.accept_partial_edit_prediction(&Default::default(), window, cx);
+            editor.accept_partial_edit_prediction(EditPredictionGranularity::Word, window, cx);
+
             assert!(!editor.has_active_edit_prediction());
             assert_eq!(editor.text(cx), "one.copilot1\ntwo\nthree\n");
             assert_eq!(editor.display_text(cx), "one.copilot1\ntwo\nthree\n");
@@ -611,19 +500,22 @@ mod tests {
         ));
         handle_copilot_completion_request(
             &copilot_lsp,
-            vec![crate::request::Completion {
+            vec![crate::request::NextEditSuggestion {
                 text: "one.123. copilot\n 456".into(),
                 range: lsp::Range::new(lsp::Position::new(0, 0), lsp::Position::new(0, 4)),
-                ..Default::default()
+                command: None,
+                text_document: lsp::VersionedTextDocumentIdentifier {
+                    uri: Uri::from_file_path(path!("/root/dir/file.rs")).unwrap(),
+                    version: 0,
+                },
             }],
-            vec![],
         );
         executor.advance_clock(COPILOT_DEBOUNCE_TIMEOUT);
         cx.update_editor(|editor, window, cx| {
             assert!(editor.has_active_edit_prediction());
 
             // Accepting the first word (non-word) of the suggestion should only accept the first word and still show the rest.
-            editor.accept_partial_edit_prediction(&Default::default(), window, cx);
+            editor.accept_partial_edit_prediction(EditPredictionGranularity::Word, window, cx);
             assert!(editor.has_active_edit_prediction());
             assert_eq!(editor.text(cx), "one.123. \ntwo\nthree\n");
             assert_eq!(
@@ -632,7 +524,7 @@ mod tests {
             );
 
             // Accepting next word should accept the next word and copilot suggestion should still exist
-            editor.accept_partial_edit_prediction(&Default::default(), window, cx);
+            editor.accept_partial_edit_prediction(EditPredictionGranularity::Word, window, cx);
             assert!(editor.has_active_edit_prediction());
             assert_eq!(editor.text(cx), "one.123. copilot\ntwo\nthree\n");
             assert_eq!(
@@ -641,7 +533,7 @@ mod tests {
             );
 
             // Accepting the whitespace should accept the non-word/whitespaces with newline and copilot suggestion should be gone
-            editor.accept_partial_edit_prediction(&Default::default(), window, cx);
+            editor.accept_partial_edit_prediction(EditPredictionGranularity::Word, window, cx);
             assert!(!editor.has_active_edit_prediction());
             assert_eq!(editor.text(cx), "one.123. copilot\n 456\ntwo\nthree\n");
             assert_eq!(
@@ -670,7 +562,7 @@ mod tests {
             cx,
         )
         .await;
-        let copilot_provider = cx.new(|_| CopilotCompletionProvider::new(copilot));
+        let copilot_provider = cx.new(|_| CopilotEditPredictionDelegate::new(copilot));
         cx.update_editor(|editor, window, cx| {
             editor.set_edit_prediction_provider(Some(copilot_provider), window, cx)
         });
@@ -683,15 +575,18 @@ mod tests {
 
         handle_copilot_completion_request(
             &copilot_lsp,
-            vec![crate::request::Completion {
+            vec![crate::request::NextEditSuggestion {
                 text: "two.foo()".into(),
                 range: lsp::Range::new(lsp::Position::new(1, 0), lsp::Position::new(1, 2)),
-                ..Default::default()
+                command: None,
+                text_document: lsp::VersionedTextDocumentIdentifier {
+                    uri: Uri::from_file_path(path!("/root/dir/file.rs")).unwrap(),
+                    version: 0,
+                },
             }],
-            vec![],
         );
         cx.update_editor(|editor, window, cx| {
-            editor.next_edit_prediction(&Default::default(), window, cx)
+            editor.show_edit_prediction(&Default::default(), window, cx)
         });
         executor.advance_clock(COPILOT_DEBOUNCE_TIMEOUT);
         cx.update_editor(|editor, window, cx| {
@@ -700,15 +595,22 @@ mod tests {
             assert_eq!(editor.text(cx), "one\ntw\nthree\n");
 
             editor.backspace(&Default::default(), window, cx);
+        });
+        executor.advance_clock(COPILOT_DEBOUNCE_TIMEOUT);
+        cx.run_until_parked();
+        cx.update_editor(|editor, window, cx| {
             assert!(editor.has_active_edit_prediction());
             assert_eq!(editor.display_text(cx), "one\ntwo.foo()\nthree\n");
             assert_eq!(editor.text(cx), "one\nt\nthree\n");
 
             editor.backspace(&Default::default(), window, cx);
+        });
+        executor.advance_clock(COPILOT_DEBOUNCE_TIMEOUT);
+        cx.run_until_parked();
+        cx.update_editor(|editor, window, cx| {
             assert!(editor.has_active_edit_prediction());
             assert_eq!(editor.display_text(cx), "one\ntwo.foo()\nthree\n");
             assert_eq!(editor.text(cx), "one\n\nthree\n");
-
             // Deleting across the original suggestion range invalidates it.
             editor.backspace(&Default::default(), window, cx);
             assert!(!editor.has_active_edit_prediction());
@@ -750,10 +652,10 @@ mod tests {
         editor
             .update(cx, |editor, window, cx| {
                 use gpui::Focusable;
-                window.focus(&editor.focus_handle(cx));
+                window.focus(&editor.focus_handle(cx), cx);
             })
             .unwrap();
-        let copilot_provider = cx.new(|_| CopilotCompletionProvider::new(copilot));
+        let copilot_provider = cx.new(|_| CopilotEditPredictionDelegate::new(copilot));
         editor
             .update(cx, |editor, window, cx| {
                 editor.set_edit_prediction_provider(Some(copilot_provider), window, cx)
@@ -762,19 +664,22 @@ mod tests {
 
         handle_copilot_completion_request(
             &copilot_lsp,
-            vec![crate::request::Completion {
+            vec![crate::request::NextEditSuggestion {
                 text: "b = 2 + a".into(),
                 range: lsp::Range::new(lsp::Position::new(1, 0), lsp::Position::new(1, 5)),
-                ..Default::default()
+                command: None,
+                text_document: lsp::VersionedTextDocumentIdentifier {
+                    uri: Uri::from_file_path(path!("/root/dir/file.rs")).unwrap(),
+                    version: 0,
+                },
             }],
-            vec![],
         );
         _ = editor.update(cx, |editor, window, cx| {
             // Ensure copilot suggestions are shown for the first excerpt.
             editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
                 s.select_ranges([Point::new(1, 5)..Point::new(1, 5)])
             });
-            editor.next_edit_prediction(&Default::default(), window, cx);
+            editor.show_edit_prediction(&Default::default(), window, cx);
         });
         executor.advance_clock(COPILOT_DEBOUNCE_TIMEOUT);
         _ = editor.update(cx, |editor, _, cx| {
@@ -788,12 +693,15 @@ mod tests {
 
         handle_copilot_completion_request(
             &copilot_lsp,
-            vec![crate::request::Completion {
+            vec![crate::request::NextEditSuggestion {
                 text: "d = 4 + c".into(),
                 range: lsp::Range::new(lsp::Position::new(1, 0), lsp::Position::new(1, 6)),
-                ..Default::default()
+                command: None,
+                text_document: lsp::VersionedTextDocumentIdentifier {
+                    uri: Uri::from_file_path(path!("/root/dir/file.rs")).unwrap(),
+                    version: 0,
+                },
             }],
-            vec![],
         );
         _ = editor.update(cx, |editor, window, cx| {
             // Move to another excerpt, ensuring the suggestion gets cleared.
@@ -848,7 +756,7 @@ mod tests {
             cx,
         )
         .await;
-        let copilot_provider = cx.new(|_| CopilotCompletionProvider::new(copilot));
+        let copilot_provider = cx.new(|_| CopilotEditPredictionDelegate::new(copilot));
         cx.update_editor(|editor, window, cx| {
             editor.set_edit_prediction_provider(Some(copilot_provider), window, cx)
         });
@@ -870,15 +778,18 @@ mod tests {
         ));
         handle_copilot_completion_request(
             &copilot_lsp,
-            vec![crate::request::Completion {
+            vec![crate::request::NextEditSuggestion {
                 text: "two.foo()".into(),
                 range: lsp::Range::new(lsp::Position::new(1, 0), lsp::Position::new(1, 2)),
-                ..Default::default()
+                command: None,
+                text_document: lsp::VersionedTextDocumentIdentifier {
+                    uri: Uri::from_file_path(path!("/root/dir/file.rs")).unwrap(),
+                    version: 0,
+                },
             }],
-            vec![],
         );
         cx.update_editor(|editor, window, cx| {
-            editor.next_edit_prediction(&Default::default(), window, cx)
+            editor.show_edit_prediction(&Default::default(), window, cx)
         });
         executor.advance_clock(COPILOT_DEBOUNCE_TIMEOUT);
         cx.update_editor(|editor, _, cx| {
@@ -900,12 +811,15 @@ mod tests {
         ));
         handle_copilot_completion_request(
             &copilot_lsp,
-            vec![crate::request::Completion {
+            vec![crate::request::NextEditSuggestion {
                 text: "two.foo()".into(),
                 range: lsp::Range::new(lsp::Position::new(1, 0), lsp::Position::new(1, 3)),
-                ..Default::default()
+                command: None,
+                text_document: lsp::VersionedTextDocumentIdentifier {
+                    uri: Uri::from_file_path(path!("/root/dir/file.rs")).unwrap(),
+                    version: 0,
+                },
             }],
-            vec![],
         );
         executor.advance_clock(COPILOT_DEBOUNCE_TIMEOUT);
         cx.update_editor(|editor, _, cx| {
@@ -927,12 +841,15 @@ mod tests {
         ));
         handle_copilot_completion_request(
             &copilot_lsp,
-            vec![crate::request::Completion {
+            vec![crate::request::NextEditSuggestion {
                 text: "two.foo()".into(),
                 range: lsp::Range::new(lsp::Position::new(1, 0), lsp::Position::new(1, 4)),
-                ..Default::default()
+                command: None,
+                text_document: lsp::VersionedTextDocumentIdentifier {
+                    uri: Uri::from_file_path(path!("/root/dir/file.rs")).unwrap(),
+                    version: 0,
+                },
             }],
-            vec![],
         );
         executor.advance_clock(COPILOT_DEBOUNCE_TIMEOUT);
         cx.update_editor(|editor, _, cx| {
@@ -997,10 +914,10 @@ mod tests {
         editor
             .update(cx, |editor, window, cx| {
                 use gpui::Focusable;
-                window.focus(&editor.focus_handle(cx))
+                window.focus(&editor.focus_handle(cx), cx)
             })
             .unwrap();
-        let copilot_provider = cx.new(|_| CopilotCompletionProvider::new(copilot));
+        let copilot_provider = cx.new(|_| CopilotEditPredictionDelegate::new(copilot));
         editor
             .update(cx, |editor, window, cx| {
                 editor.set_edit_prediction_provider(Some(copilot_provider), window, cx)
@@ -1008,16 +925,20 @@ mod tests {
             .unwrap();
 
         let mut copilot_requests = copilot_lsp
-            .set_request_handler::<crate::request::GetCompletions, _, _>(
+            .set_request_handler::<crate::request::NextEditSuggestions, _, _>(
                 move |_params, _cx| async move {
-                    Ok(crate::request::GetCompletionsResult {
-                        completions: vec![crate::request::Completion {
+                    Ok(crate::request::NextEditSuggestionsResult {
+                        edits: vec![crate::request::NextEditSuggestion {
                             text: "next line".into(),
                             range: lsp::Range::new(
                                 lsp::Position::new(1, 0),
                                 lsp::Position::new(1, 0),
                             ),
-                            ..Default::default()
+                            command: None,
+                            text_document: lsp::VersionedTextDocumentIdentifier {
+                                uri: Uri::from_file_path(path!("/root/dir/file.rs")).unwrap(),
+                                version: 0,
+                            },
                         }],
                     })
                 },
@@ -1046,23 +967,14 @@ mod tests {
 
     fn handle_copilot_completion_request(
         lsp: &lsp::FakeLanguageServer,
-        completions: Vec<crate::request::Completion>,
-        completions_cycling: Vec<crate::request::Completion>,
+        completions: Vec<crate::request::NextEditSuggestion>,
     ) {
-        lsp.set_request_handler::<crate::request::GetCompletions, _, _>(move |_params, _cx| {
-            let completions = completions.clone();
-            async move {
-                Ok(crate::request::GetCompletionsResult {
-                    completions: completions.clone(),
-                })
-            }
-        });
-        lsp.set_request_handler::<crate::request::GetCompletionsCycling, _, _>(
+        lsp.set_request_handler::<crate::request::NextEditSuggestions, _, _>(
             move |_params, _cx| {
-                let completions_cycling = completions_cycling.clone();
+                let completions = completions.clone();
                 async move {
-                    Ok(crate::request::GetCompletionsResult {
-                        completions: completions_cycling.clone(),
+                    Ok(crate::request::NextEditSuggestionsResult {
+                        edits: completions.clone(),
                     })
                 }
             },

crates/copilot/src/request.rs 🔗

@@ -1,3 +1,4 @@
+use lsp::VersionedTextDocumentIdentifier;
 use serde::{Deserialize, Serialize};
 
 pub enum CheckStatus {}
@@ -88,72 +89,6 @@ impl lsp::request::Request for SignOut {
     const METHOD: &'static str = "signOut";
 }
 
-pub enum GetCompletions {}
-
-#[derive(Debug, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct GetCompletionsParams {
-    pub doc: GetCompletionsDocument,
-}
-
-#[derive(Debug, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct GetCompletionsDocument {
-    pub tab_size: u32,
-    pub indent_size: u32,
-    pub insert_spaces: bool,
-    pub uri: lsp::Uri,
-    pub relative_path: String,
-    pub position: lsp::Position,
-    pub version: usize,
-}
-
-#[derive(Debug, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct GetCompletionsResult {
-    pub completions: Vec<Completion>,
-}
-
-#[derive(Clone, Debug, Default, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct Completion {
-    pub text: String,
-    pub position: lsp::Position,
-    pub uuid: String,
-    pub range: lsp::Range,
-    pub display_text: String,
-}
-
-impl lsp::request::Request for GetCompletions {
-    type Params = GetCompletionsParams;
-    type Result = GetCompletionsResult;
-    const METHOD: &'static str = "getCompletions";
-}
-
-pub enum GetCompletionsCycling {}
-
-impl lsp::request::Request for GetCompletionsCycling {
-    type Params = GetCompletionsParams;
-    type Result = GetCompletionsResult;
-    const METHOD: &'static str = "getCompletionsCycling";
-}
-
-pub enum LogMessage {}
-
-#[derive(Debug, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct LogMessageParams {
-    pub level: u8,
-    pub message: String,
-    pub metadata_str: String,
-    pub extra: Vec<String>,
-}
-
-impl lsp::notification::Notification for LogMessage {
-    type Params = LogMessageParams;
-    const METHOD: &'static str = "LogMessage";
-}
-
 pub enum StatusNotification {}
 
 #[derive(Debug, Serialize, Deserialize)]
@@ -223,3 +158,36 @@ impl lsp::request::Request for NotifyRejected {
     type Result = String;
     const METHOD: &'static str = "notifyRejected";
 }
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct NextEditSuggestions;
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct NextEditSuggestionsParams {
+    pub(crate) text_document: VersionedTextDocumentIdentifier,
+    pub(crate) position: lsp::Position,
+}
+
+#[derive(Clone, Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct NextEditSuggestion {
+    pub text: String,
+    pub text_document: VersionedTextDocumentIdentifier,
+    pub range: lsp::Range,
+    pub command: Option<lsp::Command>,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct NextEditSuggestionsResult {
+    pub edits: Vec<NextEditSuggestion>,
+}
+
+impl lsp::request::Request for NextEditSuggestions {
+    type Params = NextEditSuggestionsParams;
+    type Result = NextEditSuggestionsResult;
+
+    const METHOD: &'static str = "textDocument/copilotInlineEdit";
+}

crates/copilot/src/sign_in.rs 🔗

@@ -1,166 +1,159 @@
 use crate::{Copilot, Status, request::PromptUserDeviceFlow};
+use anyhow::Context as _;
 use gpui::{
-    Animation, AnimationExt, App, ClipboardItem, Context, DismissEvent, Element, Entity,
-    EventEmitter, FocusHandle, Focusable, InteractiveElement, IntoElement, MouseDownEvent,
-    ParentElement, Render, Styled, Subscription, Transformation, Window, div, percentage, svg,
+    App, ClipboardItem, Context, DismissEvent, Element, Entity, EventEmitter, FocusHandle,
+    Focusable, InteractiveElement, IntoElement, MouseDownEvent, ParentElement, Render, Styled,
+    Subscription, Window, WindowBounds, WindowOptions, div, point,
 };
-use std::time::Duration;
-use ui::{Button, Label, Vector, VectorName, prelude::*};
+use ui::{ButtonLike, CommonAnimationExt, ConfiguredApiCard, Vector, VectorName, prelude::*};
+use url::Url;
 use util::ResultExt as _;
-use workspace::notifications::NotificationId;
-use workspace::{ModalView, Toast, Workspace};
+use workspace::{Toast, Workspace, notifications::NotificationId};
 
 const COPILOT_SIGN_UP_URL: &str = "https://github.com/features/copilot";
+const ERROR_LABEL: &str =
+    "Copilot had issues starting. You can try reinstalling it and signing in again.";
 
 struct CopilotStatusToast;
 
 pub fn initiate_sign_in(window: &mut Window, cx: &mut App) {
+    let is_reinstall = false;
+    initiate_sign_in_impl(is_reinstall, window, cx)
+}
+
+pub fn initiate_sign_out(window: &mut Window, cx: &mut App) {
     let Some(copilot) = Copilot::global(cx) else {
         return;
     };
-    let Some(workspace) = window.root::<Workspace>().flatten() else {
-        return;
-    };
-    workspace.update(cx, |workspace, cx| {
-        let is_reinstall = false;
-        initiate_sign_in_within_workspace(workspace, copilot, is_reinstall, window, cx)
-    });
+
+    copilot_toast(Some("Signing out of Copilot…"), window, cx);
+
+    let sign_out_task = copilot.update(cx, |copilot, cx| copilot.sign_out(cx));
+    window
+        .spawn(cx, async move |cx| match sign_out_task.await {
+            Ok(()) => {
+                cx.update(|window, cx| copilot_toast(Some("Signed out of Copilot"), window, cx))
+            }
+            Err(err) => cx.update(|window, cx| {
+                if let Some(workspace) = window.root::<Workspace>().flatten() {
+                    workspace.update(cx, |workspace, cx| {
+                        workspace.show_error(&err, cx);
+                    })
+                } else {
+                    log::error!("{:?}", err);
+                }
+            }),
+        })
+        .detach();
 }
 
 pub fn reinstall_and_sign_in(window: &mut Window, cx: &mut App) {
     let Some(copilot) = Copilot::global(cx) else {
         return;
     };
+    let _ = copilot.update(cx, |copilot, cx| copilot.reinstall(cx));
+    let is_reinstall = true;
+    initiate_sign_in_impl(is_reinstall, window, cx);
+}
+
+fn open_copilot_code_verification_window(copilot: &Entity<Copilot>, window: &Window, cx: &mut App) {
+    let current_window_center = window.bounds().center();
+    let height = px(450.);
+    let width = px(350.);
+    let window_bounds = WindowBounds::Windowed(gpui::bounds(
+        current_window_center - point(height / 2.0, width / 2.0),
+        gpui::size(height, width),
+    ));
+    cx.open_window(
+        WindowOptions {
+            kind: gpui::WindowKind::PopUp,
+            window_bounds: Some(window_bounds),
+            is_resizable: false,
+            is_movable: true,
+            titlebar: Some(gpui::TitlebarOptions {
+                appears_transparent: true,
+                ..Default::default()
+            }),
+            ..Default::default()
+        },
+        |window, cx| cx.new(|cx| CopilotCodeVerification::new(&copilot, window, cx)),
+    )
+    .context("Failed to open Copilot code verification window")
+    .log_err();
+}
+
+fn copilot_toast(message: Option<&'static str>, window: &Window, cx: &mut App) {
+    const NOTIFICATION_ID: NotificationId = NotificationId::unique::<CopilotStatusToast>();
+
     let Some(workspace) = window.root::<Workspace>().flatten() else {
         return;
     };
-    workspace.update(cx, |workspace, cx| {
-        reinstall_and_sign_in_within_workspace(workspace, copilot, window, cx);
-    });
-}
 
-pub fn reinstall_and_sign_in_within_workspace(
-    workspace: &mut Workspace,
-    copilot: Entity<Copilot>,
-    window: &mut Window,
-    cx: &mut Context<Workspace>,
-) {
-    let _ = copilot.update(cx, |copilot, cx| copilot.reinstall(cx));
-    let is_reinstall = true;
-    initiate_sign_in_within_workspace(workspace, copilot, is_reinstall, window, cx);
+    workspace.update(cx, |workspace, cx| match message {
+        Some(message) => workspace.show_toast(Toast::new(NOTIFICATION_ID, message), cx),
+        None => workspace.dismiss_toast(&NOTIFICATION_ID, cx),
+    });
 }
 
-pub fn initiate_sign_in_within_workspace(
-    workspace: &mut Workspace,
-    copilot: Entity<Copilot>,
-    is_reinstall: bool,
-    window: &mut Window,
-    cx: &mut Context<Workspace>,
-) {
+pub fn initiate_sign_in_impl(is_reinstall: bool, window: &mut Window, cx: &mut App) {
+    let Some(copilot) = Copilot::global(cx) else {
+        return;
+    };
     if matches!(copilot.read(cx).status(), Status::Disabled) {
         copilot.update(cx, |copilot, cx| copilot.start_copilot(false, true, cx));
     }
     match copilot.read(cx).status() {
         Status::Starting { task } => {
-            workspace.show_toast(
-                Toast::new(
-                    NotificationId::unique::<CopilotStatusToast>(),
-                    if is_reinstall {
-                        "Copilot is reinstalling..."
-                    } else {
-                        "Copilot is starting..."
-                    },
-                ),
+            copilot_toast(
+                Some(if is_reinstall {
+                    "Copilot is reinstalling…"
+                } else {
+                    "Copilot is starting…"
+                }),
+                window,
                 cx,
             );
 
-            cx.spawn_in(window, async move |workspace, cx| {
-                task.await;
-                if let Some(copilot) = cx.update(|_window, cx| Copilot::global(cx)).ok().flatten() {
-                    workspace
-                        .update_in(cx, |workspace, window, cx| {
-                            match copilot.read(cx).status() {
-                                Status::Authorized => workspace.show_toast(
-                                    Toast::new(
-                                        NotificationId::unique::<CopilotStatusToast>(),
-                                        "Copilot has started.",
-                                    ),
-                                    cx,
-                                ),
-                                _ => {
-                                    workspace.dismiss_toast(
-                                        &NotificationId::unique::<CopilotStatusToast>(),
-                                        cx,
-                                    );
-                                    copilot
-                                        .update(cx, |copilot, cx| copilot.sign_in(cx))
-                                        .detach_and_log_err(cx);
-                                    workspace.toggle_modal(window, cx, |_, cx| {
-                                        CopilotCodeVerification::new(&copilot, cx)
-                                    });
-                                }
+            window
+                .spawn(cx, async move |cx| {
+                    task.await;
+                    cx.update(|window, cx| {
+                        let Some(copilot) = Copilot::global(cx) else {
+                            return;
+                        };
+                        match copilot.read(cx).status() {
+                            Status::Authorized => {
+                                copilot_toast(Some("Copilot has started."), window, cx)
                             }
-                        })
-                        .log_err();
-                }
-            })
-            .detach();
+                            _ => {
+                                copilot_toast(None, window, cx);
+                                copilot
+                                    .update(cx, |copilot, cx| copilot.sign_in(cx))
+                                    .detach_and_log_err(cx);
+                                open_copilot_code_verification_window(&copilot, window, cx);
+                            }
+                        }
+                    })
+                    .log_err();
+                })
+                .detach();
         }
         _ => {
             copilot
                 .update(cx, |copilot, cx| copilot.sign_in(cx))
                 .detach();
-            workspace.toggle_modal(window, cx, |_, cx| {
-                CopilotCodeVerification::new(&copilot, cx)
-            });
+            open_copilot_code_verification_window(&copilot, window, cx);
         }
     }
 }
 
-pub fn sign_out_within_workspace(
-    workspace: &mut Workspace,
-    copilot: Entity<Copilot>,
-    cx: &mut Context<Workspace>,
-) {
-    workspace.show_toast(
-        Toast::new(
-            NotificationId::unique::<CopilotStatusToast>(),
-            "Signing out of Copilot...",
-        ),
-        cx,
-    );
-    let sign_out_task = copilot.update(cx, |copilot, cx| copilot.sign_out(cx));
-    cx.spawn(async move |workspace, cx| match sign_out_task.await {
-        Ok(()) => {
-            workspace
-                .update(cx, |workspace, cx| {
-                    workspace.show_toast(
-                        Toast::new(
-                            NotificationId::unique::<CopilotStatusToast>(),
-                            "Signed out of Copilot.",
-                        ),
-                        cx,
-                    )
-                })
-                .ok();
-        }
-        Err(err) => {
-            workspace
-                .update(cx, |workspace, cx| {
-                    workspace.show_error(&err, cx);
-                })
-                .ok();
-        }
-    })
-    .detach();
-}
-
 pub struct CopilotCodeVerification {
     status: Status,
     connect_clicked: bool,
     focus_handle: FocusHandle,
     copilot: Entity<Copilot>,
     _subscription: Subscription,
+    sign_up_url: Option<String>,
 }
 
 impl Focusable for CopilotCodeVerification {
@@ -170,29 +163,44 @@ impl Focusable for CopilotCodeVerification {
 }
 
 impl EventEmitter<DismissEvent> for CopilotCodeVerification {}
-impl ModalView for CopilotCodeVerification {
-    fn on_before_dismiss(
-        &mut self,
-        _: &mut Window,
-        cx: &mut Context<Self>,
-    ) -> workspace::DismissDecision {
-        self.copilot.update(cx, |copilot, cx| {
-            if matches!(copilot.status(), Status::SigningIn { .. }) {
-                copilot.sign_out(cx).detach_and_log_err(cx);
+
+impl CopilotCodeVerification {
+    pub fn new(copilot: &Entity<Copilot>, window: &mut Window, cx: &mut Context<Self>) -> Self {
+        window.on_window_should_close(cx, |window, cx| {
+            if let Some(this) = window.root::<CopilotCodeVerification>().flatten() {
+                this.update(cx, |this, cx| {
+                    this.before_dismiss(cx);
+                });
             }
+            true
         });
-        workspace::DismissDecision::Dismiss(true)
-    }
-}
+        cx.subscribe_in(
+            &cx.entity(),
+            window,
+            |this, _, _: &DismissEvent, window, cx| {
+                window.remove_window();
+                this.before_dismiss(cx);
+            },
+        )
+        .detach();
 
-impl CopilotCodeVerification {
-    pub fn new(copilot: &Entity<Copilot>, cx: &mut Context<Self>) -> Self {
         let status = copilot.read(cx).status();
+        // Determine sign-up URL based on verification_uri domain if available
+        let sign_up_url = if let Status::SigningIn {
+            prompt: Some(ref prompt),
+        } = status
+        {
+            // Extract domain from verification_uri to construct sign-up URL
+            Self::get_sign_up_url_from_verification(&prompt.verification_uri)
+        } else {
+            None
+        };
         Self {
             status,
             connect_clicked: false,
             focus_handle: cx.focus_handle(),
             copilot: copilot.clone(),
+            sign_up_url,
             _subscription: cx.observe(copilot, |this, copilot, cx| {
                 let status = copilot.read(cx).status();
                 match status {
@@ -206,54 +214,74 @@ impl CopilotCodeVerification {
     }
 
     pub fn set_status(&mut self, status: Status, cx: &mut Context<Self>) {
+        // Update sign-up URL if we have a new verification URI
+        if let Status::SigningIn {
+            prompt: Some(ref prompt),
+        } = status
+        {
+            self.sign_up_url = Self::get_sign_up_url_from_verification(&prompt.verification_uri);
+        }
         self.status = status;
         cx.notify();
     }
 
+    fn get_sign_up_url_from_verification(verification_uri: &str) -> Option<String> {
+        // Extract domain from verification URI using url crate
+        if let Ok(url) = Url::parse(verification_uri)
+            && let Some(host) = url.host_str()
+            && !host.contains("github.com")
+        {
+            // For GHE, construct URL from domain
+            Some(format!("https://{}/features/copilot", host))
+        } else {
+            None
+        }
+    }
+
     fn render_device_code(data: &PromptUserDeviceFlow, cx: &mut Context<Self>) -> impl IntoElement {
         let copied = cx
             .read_from_clipboard()
             .map(|item| item.text().as_ref() == Some(&data.user_code))
             .unwrap_or(false);
-        h_flex()
-            .w_full()
-            .p_1()
-            .border_1()
-            .border_muted(cx)
-            .rounded_sm()
-            .cursor_pointer()
-            .justify_between()
-            .on_mouse_down(gpui::MouseButton::Left, {
+
+        ButtonLike::new("copy-button")
+            .full_width()
+            .style(ButtonStyle::Tinted(ui::TintColor::Accent))
+            .size(ButtonSize::Medium)
+            .child(
+                h_flex()
+                    .w_full()
+                    .p_1()
+                    .justify_between()
+                    .child(Label::new(data.user_code.clone()))
+                    .child(Label::new(if copied { "Copied!" } else { "Copy" })),
+            )
+            .on_click({
                 let user_code = data.user_code.clone();
                 move |_, window, cx| {
                     cx.write_to_clipboard(ClipboardItem::new_string(user_code.clone()));
                     window.refresh();
                 }
             })
-            .child(div().flex_1().child(Label::new(data.user_code.clone())))
-            .child(div().flex_none().px_1().child(Label::new(if copied {
-                "Copied!"
-            } else {
-                "Copy"
-            })))
     }
 
     fn render_prompting_modal(
         connect_clicked: bool,
         data: &PromptUserDeviceFlow,
-
         cx: &mut Context<Self>,
     ) -> impl Element {
         let connect_button_label = if connect_clicked {
-            "Waiting for connection..."
+            "Waiting for connection…"
         } else {
             "Connect to GitHub"
         };
+
         v_flex()
             .flex_1()
-            .gap_2()
+            .gap_2p5()
             .items_center()
-            .child(Headline::new("Use GitHub Copilot in Zed.").size(HeadlineSize::Large))
+            .text_center()
+            .child(Headline::new("Use GitHub Copilot in Zed").size(HeadlineSize::Large))
             .child(
                 Label::new("Using Copilot requires an active subscription on GitHub.")
                     .color(Color::Muted),
@@ -261,110 +289,154 @@ impl CopilotCodeVerification {
             .child(Self::render_device_code(data, cx))
             .child(
                 Label::new("Paste this code into GitHub after clicking the button below.")
-                    .size(ui::LabelSize::Small),
-            )
-            .child(
-                Button::new("connect-button", connect_button_label)
-                    .on_click({
-                        let verification_uri = data.verification_uri.clone();
-                        cx.listener(move |this, _, _window, cx| {
-                            cx.open_url(&verification_uri);
-                            this.connect_clicked = true;
-                        })
-                    })
-                    .full_width()
-                    .style(ButtonStyle::Filled),
+                    .color(Color::Muted),
             )
             .child(
-                Button::new("copilot-enable-cancel-button", "Cancel")
-                    .full_width()
-                    .on_click(cx.listener(|_, _, _, cx| {
-                        cx.emit(DismissEvent);
-                    })),
+                v_flex()
+                    .w_full()
+                    .gap_1()
+                    .child(
+                        Button::new("connect-button", connect_button_label)
+                            .full_width()
+                            .style(ButtonStyle::Outlined)
+                            .size(ButtonSize::Medium)
+                            .on_click({
+                                let verification_uri = data.verification_uri.clone();
+                                cx.listener(move |this, _, _window, cx| {
+                                    cx.open_url(&verification_uri);
+                                    this.connect_clicked = true;
+                                })
+                            }),
+                    )
+                    .child(
+                        Button::new("copilot-enable-cancel-button", "Cancel")
+                            .full_width()
+                            .size(ButtonSize::Medium)
+                            .on_click(cx.listener(|_, _, _, cx| {
+                                cx.emit(DismissEvent);
+                            })),
+                    ),
             )
     }
 
     fn render_enabled_modal(cx: &mut Context<Self>) -> impl Element {
         v_flex()
             .gap_2()
+            .text_center()
+            .justify_center()
             .child(Headline::new("Copilot Enabled!").size(HeadlineSize::Large))
-            .child(Label::new(
-                "You can update your settings or sign out from the Copilot menu in the status bar.",
-            ))
+            .child(Label::new("You're all set to use GitHub Copilot.").color(Color::Muted))
             .child(
                 Button::new("copilot-enabled-done-button", "Done")
                     .full_width()
+                    .style(ButtonStyle::Outlined)
+                    .size(ButtonSize::Medium)
                     .on_click(cx.listener(|_, _, _, cx| cx.emit(DismissEvent))),
             )
     }
 
-    fn render_unauthorized_modal(cx: &mut Context<Self>) -> impl Element {
-        v_flex()
-            .child(Headline::new("You must have an active GitHub Copilot subscription.").size(HeadlineSize::Large))
+    fn render_unauthorized_modal(&self, cx: &mut Context<Self>) -> impl Element {
+        let sign_up_url = self
+            .sign_up_url
+            .as_deref()
+            .unwrap_or(COPILOT_SIGN_UP_URL)
+            .to_owned();
+        let description = "Enable Copilot by connecting your existing license once you have subscribed or renewed your subscription.";
 
-            .child(Label::new(
-                "You can enable Copilot by connecting your existing license once you have subscribed or renewed your subscription.",
-            ).color(Color::Warning))
+        v_flex()
+            .gap_2()
+            .text_center()
+            .justify_center()
+            .child(
+                Headline::new("You must have an active GitHub Copilot subscription.")
+                    .size(HeadlineSize::Large),
+            )
+            .child(Label::new(description).color(Color::Warning))
             .child(
                 Button::new("copilot-subscribe-button", "Subscribe on GitHub")
                     .full_width()
-                    .on_click(|_, _, cx| cx.open_url(COPILOT_SIGN_UP_URL)),
+                    .style(ButtonStyle::Outlined)
+                    .size(ButtonSize::Medium)
+                    .on_click(move |_, _, cx| cx.open_url(&sign_up_url)),
             )
             .child(
                 Button::new("copilot-subscribe-cancel-button", "Cancel")
                     .full_width()
+                    .size(ButtonSize::Medium)
                     .on_click(cx.listener(|_, _, _, cx| cx.emit(DismissEvent))),
             )
     }
 
-    fn render_loading(window: &mut Window, _: &mut Context<Self>) -> impl Element {
-        let loading_icon = svg()
-            .size_8()
-            .path(IconName::ArrowCircle.path())
-            .text_color(window.text_style().color)
-            .with_animation(
-                "icon_circle_arrow",
-                Animation::new(Duration::from_secs(2)).repeat(),
-                |svg, delta| svg.with_transformation(Transformation::rotate(percentage(delta))),
-            );
+    fn render_error_modal(_cx: &mut Context<Self>) -> impl Element {
+        v_flex()
+            .gap_2()
+            .text_center()
+            .justify_center()
+            .child(Headline::new("An Error Happened").size(HeadlineSize::Large))
+            .child(Label::new(ERROR_LABEL).color(Color::Muted))
+            .child(
+                Button::new("copilot-subscribe-button", "Reinstall Copilot and Sign In")
+                    .full_width()
+                    .style(ButtonStyle::Outlined)
+                    .size(ButtonSize::Medium)
+                    .icon(IconName::Download)
+                    .icon_color(Color::Muted)
+                    .icon_position(IconPosition::Start)
+                    .icon_size(IconSize::Small)
+                    .on_click(|_, window, cx| reinstall_and_sign_in(window, cx)),
+            )
+    }
 
-        h_flex().justify_center().child(loading_icon)
+    fn before_dismiss(
+        &mut self,
+        cx: &mut Context<'_, CopilotCodeVerification>,
+    ) -> workspace::DismissDecision {
+        self.copilot.update(cx, |copilot, cx| {
+            if matches!(copilot.status(), Status::SigningIn { .. }) {
+                copilot.sign_out(cx).detach_and_log_err(cx);
+            }
+        });
+        workspace::DismissDecision::Dismiss(true)
     }
 }
 
 impl Render for CopilotCodeVerification {
-    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
+    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
         let prompt = match &self.status {
-            Status::SigningIn { prompt: None } => {
-                Self::render_loading(window, cx).into_any_element()
-            }
+            Status::SigningIn { prompt: None } => Icon::new(IconName::ArrowCircle)
+                .color(Color::Muted)
+                .with_rotate_animation(2)
+                .into_any_element(),
             Status::SigningIn {
                 prompt: Some(prompt),
             } => Self::render_prompting_modal(self.connect_clicked, prompt, cx).into_any_element(),
             Status::Unauthorized => {
                 self.connect_clicked = false;
-                Self::render_unauthorized_modal(cx).into_any_element()
+                self.render_unauthorized_modal(cx).into_any_element()
             }
             Status::Authorized => {
                 self.connect_clicked = false;
                 Self::render_enabled_modal(cx).into_any_element()
             }
+            Status::Error(..) => Self::render_error_modal(cx).into_any_element(),
             _ => div().into_any_element(),
         };
 
         v_flex()
-            .id("copilot code verification")
+            .id("copilot_code_verification")
             .track_focus(&self.focus_handle(cx))
-            .elevation_3(cx)
-            .w_96()
-            .items_center()
-            .p_4()
+            .size_full()
+            .px_4()
+            .py_8()
             .gap_2()
+            .items_center()
+            .justify_center()
+            .elevation_3(cx)
             .on_action(cx.listener(|_, _: &menu::Cancel, _, cx| {
                 cx.emit(DismissEvent);
             }))
-            .on_any_mouse_down(cx.listener(|this, _: &MouseDownEvent, window, _| {
-                window.focus(&this.focus_handle);
+            .on_any_mouse_down(cx.listener(|this, _: &MouseDownEvent, window, cx| {
+                window.focus(&this.focus_handle, cx);
             }))
             .child(
                 Vector::new(VectorName::ZedXCopilot, rems(8.), rems(4.))
@@ -373,3 +445,243 @@ impl Render for CopilotCodeVerification {
             .child(prompt)
     }
 }
+
+pub struct ConfigurationView {
+    copilot_status: Option<Status>,
+    is_authenticated: fn(cx: &App) -> bool,
+    edit_prediction: bool,
+    _subscription: Option<Subscription>,
+}
+
+pub enum ConfigurationMode {
+    Chat,
+    EditPrediction,
+}
+
+impl ConfigurationView {
+    pub fn new(
+        is_authenticated: fn(cx: &App) -> bool,
+        mode: ConfigurationMode,
+        cx: &mut Context<Self>,
+    ) -> Self {
+        let copilot = Copilot::global(cx);
+
+        Self {
+            copilot_status: copilot.as_ref().map(|copilot| copilot.read(cx).status()),
+            is_authenticated,
+            edit_prediction: matches!(mode, ConfigurationMode::EditPrediction),
+            _subscription: copilot.as_ref().map(|copilot| {
+                cx.observe(copilot, |this, model, cx| {
+                    this.copilot_status = Some(model.read(cx).status());
+                    cx.notify();
+                })
+            }),
+        }
+    }
+}
+
+impl ConfigurationView {
+    fn is_starting(&self) -> bool {
+        matches!(&self.copilot_status, Some(Status::Starting { .. }))
+    }
+
+    fn is_signing_in(&self) -> bool {
+        matches!(
+            &self.copilot_status,
+            Some(Status::SigningIn { .. })
+                | Some(Status::SignedOut {
+                    awaiting_signing_in: true
+                })
+        )
+    }
+
+    fn is_error(&self) -> bool {
+        matches!(&self.copilot_status, Some(Status::Error(_)))
+    }
+
+    fn has_no_status(&self) -> bool {
+        self.copilot_status.is_none()
+    }
+
+    fn loading_message(&self) -> Option<SharedString> {
+        if self.is_starting() {
+            Some("Starting Copilot…".into())
+        } else if self.is_signing_in() {
+            Some("Signing into Copilot…".into())
+        } else {
+            None
+        }
+    }
+
+    fn render_loading_button(
+        &self,
+        label: impl Into<SharedString>,
+        edit_prediction: bool,
+    ) -> impl IntoElement {
+        ButtonLike::new("loading_button")
+            .disabled(true)
+            .style(ButtonStyle::Outlined)
+            .when(edit_prediction, |this| this.size(ButtonSize::Medium))
+            .child(
+                h_flex()
+                    .w_full()
+                    .gap_1()
+                    .justify_center()
+                    .child(
+                        Icon::new(IconName::ArrowCircle)
+                            .size(IconSize::Small)
+                            .color(Color::Muted)
+                            .with_rotate_animation(4),
+                    )
+                    .child(Label::new(label)),
+            )
+    }
+
+    fn render_sign_in_button(&self, edit_prediction: bool) -> impl IntoElement {
+        let label = if edit_prediction {
+            "Sign in to GitHub"
+        } else {
+            "Sign in to use GitHub Copilot"
+        };
+
+        Button::new("sign_in", label)
+            .map(|this| {
+                if edit_prediction {
+                    this.size(ButtonSize::Medium)
+                } else {
+                    this.full_width()
+                }
+            })
+            .style(ButtonStyle::Outlined)
+            .icon(IconName::Github)
+            .icon_color(Color::Muted)
+            .icon_position(IconPosition::Start)
+            .icon_size(IconSize::Small)
+            .on_click(|_, window, cx| initiate_sign_in(window, cx))
+    }
+
+    fn render_reinstall_button(&self, edit_prediction: bool) -> impl IntoElement {
+        let label = if edit_prediction {
+            "Reinstall and Sign in"
+        } else {
+            "Reinstall Copilot and Sign in"
+        };
+
+        Button::new("reinstall_and_sign_in", label)
+            .map(|this| {
+                if edit_prediction {
+                    this.size(ButtonSize::Medium)
+                } else {
+                    this.full_width()
+                }
+            })
+            .style(ButtonStyle::Outlined)
+            .icon(IconName::Download)
+            .icon_color(Color::Muted)
+            .icon_position(IconPosition::Start)
+            .icon_size(IconSize::Small)
+            .on_click(|_, window, cx| reinstall_and_sign_in(window, cx))
+    }
+
+    fn render_for_edit_prediction(&self) -> impl IntoElement {
+        let container = |description: SharedString, action: AnyElement| {
+            h_flex()
+                .pt_2p5()
+                .w_full()
+                .justify_between()
+                .child(
+                    v_flex()
+                        .w_full()
+                        .max_w_1_2()
+                        .child(Label::new("Authenticate To Use"))
+                        .child(
+                            Label::new(description)
+                                .color(Color::Muted)
+                                .size(LabelSize::Small),
+                        ),
+                )
+                .child(action)
+        };
+
+        let start_label = "To use Copilot for edit predictions, you need to be logged in to GitHub. Note that your GitHub account must have an active Copilot subscription.".into();
+        let no_status_label = "Copilot requires an active GitHub Copilot subscription. Please ensure Copilot is configured and try again, or use a different edit predictions provider.".into();
+
+        if let Some(msg) = self.loading_message() {
+            container(
+                start_label,
+                self.render_loading_button(msg, true).into_any_element(),
+            )
+            .into_any_element()
+        } else if self.is_error() {
+            container(
+                ERROR_LABEL.into(),
+                self.render_reinstall_button(true).into_any_element(),
+            )
+            .into_any_element()
+        } else if self.has_no_status() {
+            container(
+                no_status_label,
+                self.render_sign_in_button(true).into_any_element(),
+            )
+            .into_any_element()
+        } else {
+            container(
+                start_label,
+                self.render_sign_in_button(true).into_any_element(),
+            )
+            .into_any_element()
+        }
+    }
+
+    fn render_for_chat(&self) -> impl IntoElement {
+        let start_label = "To use Zed's agent with GitHub Copilot, you need to be logged in to GitHub. Note that your GitHub account must have an active Copilot Chat subscription.";
+        let no_status_label = "Copilot Chat requires an active GitHub Copilot subscription. Please ensure Copilot is configured and try again, or use a different LLM provider.";
+
+        if let Some(msg) = self.loading_message() {
+            v_flex()
+                .gap_2()
+                .child(Label::new(start_label))
+                .child(self.render_loading_button(msg, false))
+                .into_any_element()
+        } else if self.is_error() {
+            v_flex()
+                .gap_2()
+                .child(Label::new(ERROR_LABEL))
+                .child(self.render_reinstall_button(false))
+                .into_any_element()
+        } else if self.has_no_status() {
+            v_flex()
+                .gap_2()
+                .child(Label::new(no_status_label))
+                .child(self.render_sign_in_button(false))
+                .into_any_element()
+        } else {
+            v_flex()
+                .gap_2()
+                .child(Label::new(start_label))
+                .child(self.render_sign_in_button(false))
+                .into_any_element()
+        }
+    }
+}
+
+impl Render for ConfigurationView {
+    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
+        let is_authenticated = self.is_authenticated;
+
+        if is_authenticated(cx) {
+            return ConfiguredApiCard::new("Authorized")
+                .button_label("Sign Out")
+                .on_click(|_, window, cx| {
+                    initiate_sign_out(window, cx);
+                })
+                .into_any_element();
+        }
+
+        if self.edit_prediction {
+            self.render_for_edit_prediction().into_any_element()
+        } else {
+            self.render_for_chat().into_any_element()
+        }
+    }
+}

crates/crashes/Cargo.toml 🔗

@@ -23,6 +23,9 @@ zstd.workspace = true
 [target.'cfg(target_os = "macos")'.dependencies]
 mach2.workspace = true
 
+[target.'cfg(target_os = "windows")'.dependencies]
+windows.workspace = true
+
 [lints]
 workspace = true
 

crates/crashes/src/crashes.rs 🔗

@@ -3,6 +3,8 @@ use log::info;
 use minidumper::{Client, LoopAction, MinidumpBinary};
 use release_channel::{RELEASE_CHANNEL, ReleaseChannel};
 use serde::{Deserialize, Serialize};
+
+#[cfg(not(target_os = "windows"))]
 use smol::process::Command;
 
 #[cfg(target_os = "macos")]
@@ -70,11 +72,16 @@ pub async fn init(crash_init: InitCrashHandler) {
     // used by the crash handler isn't destroyed correctly which causes it to stay on the file
     // system and block further attempts to initialize crash handlers with that socket path.
     let socket_name = paths::temp_dir().join(format!("zed-crash-handler-{zed_pid}"));
+    #[cfg(not(target_os = "windows"))]
     let _crash_handler = Command::new(exe)
         .arg("--crash-handler")
         .arg(&socket_name)
         .spawn()
         .expect("unable to spawn server process");
+
+    #[cfg(target_os = "windows")]
+    spawn_crash_handler_windows(&exe, &socket_name);
+
     #[cfg(target_os = "linux")]
     let server_pid = _crash_handler.id();
     info!("spawning crash handler process");
@@ -342,6 +349,57 @@ pub fn panic_hook(info: &PanicHookInfo) {
     }
 }
 
+#[cfg(target_os = "windows")]
+fn spawn_crash_handler_windows(exe: &Path, socket_name: &Path) {
+    use std::ffi::OsStr;
+    use std::iter::once;
+    use std::os::windows::ffi::OsStrExt;
+    use windows::Win32::System::Threading::{
+        CreateProcessW, PROCESS_CREATION_FLAGS, PROCESS_INFORMATION, STARTF_FORCEOFFFEEDBACK,
+        STARTUPINFOW,
+    };
+    use windows::core::PWSTR;
+
+    let mut command_line: Vec<u16> = OsStr::new(&format!(
+        "\"{}\" --crash-handler \"{}\"",
+        exe.display(),
+        socket_name.display()
+    ))
+    .encode_wide()
+    .chain(once(0))
+    .collect();
+
+    let mut startup_info = STARTUPINFOW::default();
+    startup_info.cb = std::mem::size_of::<STARTUPINFOW>() as u32;
+
+    // By default, Windows enables a "busy" cursor when a GUI application is launched.
+    // This cursor is disabled once the application starts processing window messages.
+    // Since the crash handler process doesn't process messages, this "busy" cursor stays enabled for a long time.
+    // Disable the cursor feedback to prevent this from happening.
+    startup_info.dwFlags = STARTF_FORCEOFFFEEDBACK;
+
+    let mut process_info = PROCESS_INFORMATION::default();
+
+    unsafe {
+        CreateProcessW(
+            None,
+            Some(PWSTR(command_line.as_mut_ptr())),
+            None,
+            None,
+            false,
+            PROCESS_CREATION_FLAGS(0),
+            None,
+            None,
+            &startup_info,
+            &mut process_info,
+        )
+        .expect("unable to spawn server process");
+
+        windows::Win32::Foundation::CloseHandle(process_info.hProcess).ok();
+        windows::Win32::Foundation::CloseHandle(process_info.hThread).ok();
+    }
+}
+
 pub fn crash_server(socket: &Path) {
     let Ok(mut server) = minidumper::Server::with_name(socket) else {
         log::info!("Couldn't create socket, there may already be a running crash server");

crates/dap_adapters/src/python.rs 🔗

@@ -870,7 +870,7 @@ impl DebugAdapter for PythonDebugAdapter {
                 .active_toolchain(
                     delegate.worktree_id(),
                     base_path.into_arc(),
-                    language::LanguageName::new(Self::LANGUAGE_NAME),
+                    language::LanguageName::new_static(Self::LANGUAGE_NAME),
                     cx,
                 )
                 .await

crates/debugger_tools/src/dap_log.rs 🔗

@@ -1017,11 +1017,13 @@ impl SearchableItem for DapLogView {
     fn update_matches(
         &mut self,
         matches: &[Self::Match],
+        active_match_index: Option<usize>,
         window: &mut Window,
         cx: &mut Context<Self>,
     ) {
-        self.editor
-            .update(cx, |e, cx| e.update_matches(matches, window, cx))
+        self.editor.update(cx, |e, cx| {
+            e.update_matches(matches, active_match_index, window, cx)
+        })
     }
 
     fn query_suggestion(&mut self, window: &mut Window, cx: &mut Context<Self>) -> String {

crates/debugger_ui/Cargo.toml 🔗

@@ -37,6 +37,7 @@ dap_adapters = { workspace = true, optional = true }
 db.workspace = true
 debugger_tools.workspace = true
 editor.workspace = true
+feature_flags.workspace = true
 file_icons.workspace = true
 futures.workspace = true
 fuzzy.workspace = true
@@ -82,6 +83,7 @@ dap_adapters = { workspace = true, features = ["test-support"] }
 debugger_tools = { workspace = true, features = ["test-support"] }
 editor = { workspace = true, features = ["test-support"] }
 gpui = { workspace = true, features = ["test-support"] }
+language = { workspace = true, features = ["test-support"] }
 project = { workspace = true, features = ["test-support"] }
 tree-sitter-go.workspace = true
 unindent.workspace = true

crates/debugger_ui/src/attach_modal.rs 🔗

@@ -317,7 +317,7 @@ impl PickerDelegate for AttachModalDelegate {
         let candidate = self.candidates.get(hit.candidate_id)?;
 
         Some(
-            ListItem::new(SharedString::from(format!("process-entry-{ix}")))
+            ListItem::new(format!("process-entry-{ix}"))
                 .inset(true)
                 .spacing(ListItemSpacing::Sparse)
                 .toggle_state(selected)
@@ -327,7 +327,7 @@ impl PickerDelegate for AttachModalDelegate {
                         .child(Label::new(format!("{} {}", candidate.name, candidate.pid)))
                         .child(
                             div()
-                                .id(SharedString::from(format!("process-entry-{ix}-command")))
+                                .id(format!("process-entry-{ix}-command"))
                                 .tooltip(Tooltip::text(
                                     candidate
                                         .command

crates/debugger_ui/src/debugger_panel.rs 🔗

@@ -15,10 +15,11 @@ use dap::adapters::DebugAdapterName;
 use dap::{DapRegistry, StartDebuggingRequestArguments};
 use dap::{client::SessionId, debugger_settings::DebuggerSettings};
 use editor::{Editor, MultiBufferOffset, ToPoint};
+use feature_flags::{FeatureFlag, FeatureFlagAppExt as _};
 use gpui::{
-    Action, App, AsyncWindowContext, ClipboardItem, Context, DismissEvent, Entity, EntityId,
-    EventEmitter, FocusHandle, Focusable, MouseButton, MouseDownEvent, Point, Subscription, Task,
-    WeakEntity, anchored, deferred,
+    Action, App, AsyncWindowContext, ClipboardItem, Context, Corner, DismissEvent, Entity,
+    EntityId, EventEmitter, FocusHandle, Focusable, MouseButton, MouseDownEvent, Point,
+    Subscription, Task, WeakEntity, anchored, deferred,
 };
 
 use itertools::Itertools as _;
@@ -31,7 +32,9 @@ use settings::Settings;
 use std::sync::{Arc, LazyLock};
 use task::{DebugScenario, TaskContext};
 use tree_sitter::{Query, StreamingIterator as _};
-use ui::{ContextMenu, Divider, PopoverMenuHandle, Tab, Tooltip, prelude::*};
+use ui::{
+    ContextMenu, Divider, PopoverMenu, PopoverMenuHandle, SplitButton, Tab, Tooltip, prelude::*,
+};
 use util::rel_path::RelPath;
 use util::{ResultExt, debug_panic, maybe};
 use workspace::SplitDirection;
@@ -42,6 +45,12 @@ use workspace::{
 };
 use zed_actions::ToggleFocus;
 
+pub struct DebuggerHistoryFeatureFlag;
+
+impl FeatureFlag for DebuggerHistoryFeatureFlag {
+    const NAME: &'static str = "debugger-history";
+}
+
 const DEBUG_PANEL_KEY: &str = "DebugPanel";
 
 pub struct DebugPanel {
@@ -284,7 +293,7 @@ impl DebugPanel {
             }
         });
 
-        session.update(cx, |session, _| match &mut session.mode {
+        session.update(cx, |session, _| match &mut session.state {
             SessionState::Booting(state_task) => {
                 *state_task = Some(boot_task);
             }
@@ -568,7 +577,7 @@ impl DebugPanel {
                 menu
             });
 
-            window.focus(&context_menu.focus_handle(cx));
+            window.focus(&context_menu.focus_handle(cx), cx);
             let subscription = cx.subscribe(&context_menu, |this, _, _: &DismissEvent, cx| {
                 this.context_menu.take();
                 cx.notify();
@@ -662,6 +671,12 @@ impl DebugPanel {
             )
         };
 
+        let thread_status = active_session
+            .as_ref()
+            .map(|session| session.read(cx).running_state())
+            .and_then(|state| state.read(cx).thread_status(cx))
+            .unwrap_or(project::debugger::session::ThreadStatus::Exited);
+
         Some(
             div.w_full()
                 .py_1()
@@ -679,10 +694,6 @@ impl DebugPanel {
                                     .as_ref()
                                     .map(|session| session.read(cx).running_state()),
                                 |this, running_state| {
-                                    let thread_status =
-                                        running_state.read(cx).thread_status(cx).unwrap_or(
-                                            project::debugger::session::ThreadStatus::Exited,
-                                        );
                                     let capabilities = running_state.read(cx).capabilities(cx);
                                     let supports_detach =
                                         running_state.read(cx).session().read(cx).is_attached();
@@ -740,7 +751,7 @@ impl DebugPanel {
                                         }
                                     })
                                     .child(
-                                        IconButton::new("debug-step-over", IconName::ArrowRight)
+                                        IconButton::new("step-over", IconName::DebugStepOver)
                                             .icon_size(IconSize::Small)
                                             .on_click(window.listener_for(
                                                 running_state,
@@ -762,32 +773,29 @@ impl DebugPanel {
                                             }),
                                     )
                                     .child(
-                                        IconButton::new(
-                                            "debug-step-into",
-                                            IconName::ArrowDownRight,
-                                        )
-                                        .icon_size(IconSize::Small)
-                                        .on_click(window.listener_for(
-                                            running_state,
-                                            |this, _, _window, cx| {
-                                                this.step_in(cx);
-                                            },
-                                        ))
-                                        .disabled(thread_status != ThreadStatus::Stopped)
-                                        .tooltip({
-                                            let focus_handle = focus_handle.clone();
-                                            move |_window, cx| {
-                                                Tooltip::for_action_in(
-                                                    "Step In",
-                                                    &StepInto,
-                                                    &focus_handle,
-                                                    cx,
-                                                )
-                                            }
-                                        }),
+                                        IconButton::new("step-into", IconName::DebugStepInto)
+                                            .icon_size(IconSize::Small)
+                                            .on_click(window.listener_for(
+                                                running_state,
+                                                |this, _, _window, cx| {
+                                                    this.step_in(cx);
+                                                },
+                                            ))
+                                            .disabled(thread_status != ThreadStatus::Stopped)
+                                            .tooltip({
+                                                let focus_handle = focus_handle.clone();
+                                                move |_window, cx| {
+                                                    Tooltip::for_action_in(
+                                                        "Step In",
+                                                        &StepInto,
+                                                        &focus_handle,
+                                                        cx,
+                                                    )
+                                                }
+                                            }),
                                     )
                                     .child(
-                                        IconButton::new("debug-step-out", IconName::ArrowUpRight)
+                                        IconButton::new("step-out", IconName::DebugStepOut)
                                             .icon_size(IconSize::Small)
                                             .on_click(window.listener_for(
                                                 running_state,
@@ -874,36 +882,53 @@ impl DebugPanel {
                                                 }
                                             }),
                                     )
+                                    .when(supports_detach, |div| {
+                                        div.child(
+                                            IconButton::new(
+                                                "debug-disconnect",
+                                                IconName::DebugDetach,
+                                            )
+                                            .disabled(
+                                                thread_status != ThreadStatus::Stopped
+                                                    && thread_status != ThreadStatus::Running,
+                                            )
+                                            .icon_size(IconSize::Small)
+                                            .on_click(window.listener_for(
+                                                running_state,
+                                                |this, _, _, cx| {
+                                                    this.detach_client(cx);
+                                                },
+                                            ))
+                                            .tooltip({
+                                                let focus_handle = focus_handle.clone();
+                                                move |_window, cx| {
+                                                    Tooltip::for_action_in(
+                                                        "Detach",
+                                                        &Detach,
+                                                        &focus_handle,
+                                                        cx,
+                                                    )
+                                                }
+                                            }),
+                                        )
+                                    })
                                     .when(
-                                        supports_detach,
-                                        |div| {
-                                            div.child(
-                                                IconButton::new(
-                                                    "debug-disconnect",
-                                                    IconName::DebugDetach,
-                                                )
-                                                .disabled(
-                                                    thread_status != ThreadStatus::Stopped
-                                                        && thread_status != ThreadStatus::Running,
+                                        cx.has_flag::<DebuggerHistoryFeatureFlag>(),
+                                        |this| {
+                                            this.child(Divider::vertical()).child(
+                                                SplitButton::new(
+                                                    self.render_history_button(
+                                                        &running_state,
+                                                        thread_status,
+                                                        window,
+                                                    ),
+                                                    self.render_history_toggle_button(
+                                                        thread_status,
+                                                        &running_state,
+                                                    )
+                                                    .into_any_element(),
                                                 )
-                                                .icon_size(IconSize::Small)
-                                                .on_click(window.listener_for(
-                                                    running_state,
-                                                    |this, _, _, cx| {
-                                                        this.detach_client(cx);
-                                                    },
-                                                ))
-                                                .tooltip({
-                                                    let focus_handle = focus_handle.clone();
-                                                    move |_window, cx| {
-                                                        Tooltip::for_action_in(
-                                                            "Detach",
-                                                            &Detach,
-                                                            &focus_handle,
-                                                            cx,
-                                                        )
-                                                    }
-                                                }),
+                                                .style(ui::SplitButtonStyle::Outlined),
                                             )
                                         },
                                     )
@@ -1027,7 +1052,7 @@ impl DebugPanel {
         cx: &mut Context<Self>,
     ) {
         debug_assert!(self.sessions_with_children.contains_key(&session_item));
-        session_item.focus_handle(cx).focus(window);
+        session_item.focus_handle(cx).focus(window, cx);
         session_item.update(cx, |this, cx| {
             this.running_state().update(cx, |this, cx| {
                 this.go_to_selected_stack_frame(window, cx);
@@ -1320,6 +1345,97 @@ impl DebugPanel {
             });
         }
     }
+
+    fn render_history_button(
+        &self,
+        running_state: &Entity<RunningState>,
+        thread_status: ThreadStatus,
+        window: &mut Window,
+    ) -> IconButton {
+        IconButton::new("debug-back-in-history", IconName::HistoryRerun)
+            .icon_size(IconSize::Small)
+            .on_click(window.listener_for(running_state, |this, _, _window, cx| {
+                this.session().update(cx, |session, cx| {
+                    let ix = session
+                        .active_snapshot_index()
+                        .unwrap_or_else(|| session.historic_snapshots().len());
+
+                    session.select_historic_snapshot(Some(ix.saturating_sub(1)), cx);
+                })
+            }))
+            .disabled(
+                thread_status == ThreadStatus::Running || thread_status == ThreadStatus::Stepping,
+            )
+    }
+
+    fn render_history_toggle_button(
+        &self,
+        thread_status: ThreadStatus,
+        running_state: &Entity<RunningState>,
+    ) -> impl IntoElement {
+        PopoverMenu::new("debug-back-in-history-menu")
+            .trigger(
+                ui::ButtonLike::new_rounded_right("debug-back-in-history-menu-trigger")
+                    .layer(ui::ElevationIndex::ModalSurface)
+                    .size(ui::ButtonSize::None)
+                    .child(
+                        div()
+                            .px_1()
+                            .child(Icon::new(IconName::ChevronDown).size(IconSize::XSmall)),
+                    )
+                    .disabled(
+                        thread_status == ThreadStatus::Running
+                            || thread_status == ThreadStatus::Stepping,
+                    ),
+            )
+            .menu({
+                let running_state = running_state.clone();
+                move |window, cx| {
+                    let handler =
+                        |ix: Option<usize>, running_state: Entity<RunningState>, cx: &mut App| {
+                            running_state.update(cx, |state, cx| {
+                                state.session().update(cx, |session, cx| {
+                                    session.select_historic_snapshot(ix, cx);
+                                })
+                            })
+                        };
+
+                    let running_state = running_state.clone();
+                    Some(ContextMenu::build(
+                        window,
+                        cx,
+                        move |mut context_menu, _window, cx| {
+                            let history = running_state
+                                .read(cx)
+                                .session()
+                                .read(cx)
+                                .historic_snapshots();
+
+                            context_menu = context_menu.entry("Current State", None, {
+                                let running_state = running_state.clone();
+                                move |_window, cx| {
+                                    handler(None, running_state.clone(), cx);
+                                }
+                            });
+                            context_menu = context_menu.separator();
+
+                            for (ix, _) in history.iter().enumerate().rev() {
+                                context_menu =
+                                    context_menu.entry(format!("history-{}", ix + 1), None, {
+                                        let running_state = running_state.clone();
+                                        move |_window, cx| {
+                                            handler(Some(ix), running_state.clone(), cx);
+                                        }
+                                    });
+                            }
+
+                            context_menu
+                        },
+                    ))
+                }
+            })
+            .anchor(Corner::TopRight)
+    }
 }
 
 async fn register_session_inner(
@@ -1441,7 +1557,7 @@ impl Panel for DebugPanel {
             self.sessions_with_children.keys().for_each(|session_item| {
                 session_item.update(cx, |item, cx| {
                     item.running_state()
-                        .update(cx, |state, _| state.invert_axies())
+                        .update(cx, |state, cx| state.invert_axies(cx))
                 })
             });
         }
@@ -1463,8 +1579,10 @@ impl Panel for DebugPanel {
         Some(proto::PanelId::DebugPanel)
     }
 
-    fn icon(&self, _window: &Window, _cx: &App) -> Option<IconName> {
-        Some(IconName::Debug)
+    fn icon(&self, _window: &Window, cx: &App) -> Option<IconName> {
+        DebuggerSettings::get_global(cx)
+            .button
+            .then_some(IconName::Debug)
     }
 
     fn icon_tooltip(&self, _window: &Window, cx: &App) -> Option<&'static str> {

crates/debugger_ui/src/debugger_ui.rs 🔗

@@ -387,7 +387,7 @@ pub fn init(cx: &mut App) {
                     window.on_action(
                         TypeId::of::<editor::actions::EvaluateSelectedText>(),
                         move |_, _, window, cx| {
-                            maybe!({
+                            let status = maybe!({
                                 let text = editor
                                     .update(cx, |editor, cx| {
                                         let range = editor
@@ -411,7 +411,13 @@ pub fn init(cx: &mut App) {
 
                                         state.session().update(cx, |session, cx| {
                                             session
-                                                .evaluate(text, None, stack_id, None, cx)
+                                                .evaluate(
+                                                    text,
+                                                    Some(dap::EvaluateArgumentsContext::Repl),
+                                                    stack_id,
+                                                    None,
+                                                    cx,
+                                                )
                                                 .detach();
                                         });
                                     });
@@ -419,6 +425,9 @@ pub fn init(cx: &mut App) {
 
                                 Some(())
                             });
+                            if status.is_some() {
+                                cx.stop_propagation();
+                            }
                         },
                     );
                 })

crates/debugger_ui/src/new_process_modal.rs 🔗

@@ -574,7 +574,7 @@ impl Render for NewProcessModal {
                     NewProcessMode::Launch => NewProcessMode::Task,
                 };
 
-                this.mode_focus_handle(cx).focus(window);
+                this.mode_focus_handle(cx).focus(window, cx);
             }))
             .on_action(
                 cx.listener(|this, _: &pane::ActivatePreviousItem, window, cx| {
@@ -585,7 +585,7 @@ impl Render for NewProcessModal {
                         NewProcessMode::Launch => NewProcessMode::Attach,
                     };
 
-                    this.mode_focus_handle(cx).focus(window);
+                    this.mode_focus_handle(cx).focus(window, cx);
                 }),
             )
             .child(
@@ -602,7 +602,7 @@ impl Render for NewProcessModal {
                                     NewProcessMode::Task.to_string(),
                                     cx.listener(|this, _, window, cx| {
                                         this.mode = NewProcessMode::Task;
-                                        this.mode_focus_handle(cx).focus(window);
+                                        this.mode_focus_handle(cx).focus(window, cx);
                                         cx.notify();
                                     }),
                                 )
@@ -611,7 +611,7 @@ impl Render for NewProcessModal {
                                     NewProcessMode::Debug.to_string(),
                                     cx.listener(|this, _, window, cx| {
                                         this.mode = NewProcessMode::Debug;
-                                        this.mode_focus_handle(cx).focus(window);
+                                        this.mode_focus_handle(cx).focus(window, cx);
                                         cx.notify();
                                     }),
                                 )
@@ -629,7 +629,7 @@ impl Render for NewProcessModal {
                                                 cx,
                                             );
                                         }
-                                        this.mode_focus_handle(cx).focus(window);
+                                        this.mode_focus_handle(cx).focus(window, cx);
                                         cx.notify();
                                     }),
                                 )
@@ -638,7 +638,7 @@ impl Render for NewProcessModal {
                                     NewProcessMode::Launch.to_string(),
                                     cx.listener(|this, _, window, cx| {
                                         this.mode = NewProcessMode::Launch;
-                                        this.mode_focus_handle(cx).focus(window);
+                                        this.mode_focus_handle(cx).focus(window, cx);
                                         cx.notify();
                                     }),
                                 )
@@ -840,17 +840,17 @@ impl ConfigureMode {
         }
     }
 
-    fn on_tab(&mut self, _: &menu::SelectNext, window: &mut Window, _: &mut Context<Self>) {
-        window.focus_next();
+    fn on_tab(&mut self, _: &menu::SelectNext, window: &mut Window, cx: &mut Context<Self>) {
+        window.focus_next(cx);
     }
 
     fn on_tab_prev(
         &mut self,
         _: &menu::SelectPrevious,
         window: &mut Window,
-        _: &mut Context<Self>,
+        cx: &mut Context<Self>,
     ) {
-        window.focus_prev();
+        window.focus_prev(cx);
     }
 
     fn render(
@@ -881,7 +881,6 @@ impl ConfigureMode {
                     .label("Stop on Entry")
                     .label_position(SwitchLabelPosition::Start)
                     .label_size(LabelSize::Default)
-                    .color(ui::SwitchColor::Accent)
                     .on_click({
                         let this = cx.weak_entity();
                         move |state, _, cx| {
@@ -924,7 +923,7 @@ impl AttachMode {
                 window,
                 cx,
             );
-            window.focus(&modal.focus_handle(cx));
+            window.focus(&modal.focus_handle(cx), cx);
 
             modal
         });
@@ -1023,7 +1022,7 @@ impl DebugDelegate {
             Some(TaskSourceKind::Lsp { language_name, .. }) => {
                 Some(format!("LSP: {language_name}"))
             }
-            Some(TaskSourceKind::Language { name }) => Some(format!("Lang: {name}")),
+            Some(TaskSourceKind::Language { name }) => Some(format!("Language: {name}")),
             _ => context.clone().and_then(|ctx| {
                 ctx.task_context
                     .task_variables
@@ -1520,7 +1519,7 @@ impl PickerDelegate for DebugDelegate {
         });
 
         Some(
-            ListItem::new(SharedString::from(format!("debug-scenario-selection-{ix}")))
+            ListItem::new(format!("debug-scenario-selection-{ix}"))
                 .inset(true)
                 .start_slot::<IconWithIndicator>(icon)
                 .spacing(ListItemSpacing::Sparse)

crates/debugger_ui/src/onboarding_modal.rs 🔗

@@ -83,8 +83,8 @@ impl Render for DebuggerOnboardingModal {
                 debugger_onboarding_event!("Canceled", trigger = "Action");
                 cx.emit(DismissEvent);
             }))
-            .on_any_mouse_down(cx.listener(|this, _: &MouseDownEvent, window, _cx| {
-                this.focus_handle.focus(window);
+            .on_any_mouse_down(cx.listener(|this, _: &MouseDownEvent, window, cx| {
+                this.focus_handle.focus(window, cx);
             }))
             .child(
                 div()

crates/debugger_ui/src/session/running.rs 🔗

@@ -286,10 +286,10 @@ impl Item for SubView {
 impl Render for SubView {
     fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
         v_flex()
-            .id(SharedString::from(format!(
+            .id(format!(
                 "subview-container-{}",
                 self.kind.to_shared_string()
-            )))
+            ))
             .on_hover(cx.listener(|this, hovered, _, cx| {
                 this.hovered = *hovered;
                 cx.notify();
@@ -348,7 +348,7 @@ pub(crate) fn new_debugger_pane(
                         debug_assert!(_previous_subscription.is_none());
                         running
                             .panes
-                            .split(&this_pane, &new_pane, split_direction)?;
+                            .split(&this_pane, &new_pane, split_direction, cx)?;
                         anyhow::Ok(new_pane)
                     })
                 })
@@ -484,10 +484,7 @@ pub(crate) fn new_debugger_pane(
                                 let deemphasized = !pane.has_focus(window, cx);
                                 let item_ = item.boxed_clone();
                                 div()
-                                    .id(SharedString::from(format!(
-                                        "debugger_tab_{}",
-                                        item.item_id().as_u64()
-                                    )))
+                                    .id(format!("debugger_tab_{}", item.item_id().as_u64()))
                                     .p_1()
                                     .rounded_md()
                                     .cursor_pointer()
@@ -607,7 +604,7 @@ impl DebugTerminal {
         let focus_handle = cx.focus_handle();
         let focus_subscription = cx.on_focus(&focus_handle, window, |this, window, cx| {
             if let Some(terminal) = this.terminal.as_ref() {
-                terminal.focus_handle(cx).focus(window);
+                terminal.focus_handle(cx).focus(window, cx);
             }
         });
 
@@ -1465,7 +1462,7 @@ impl RunningState {
         this.serialize_layout(window, cx);
         match event {
             Event::Remove { .. } => {
-                let _did_find_pane = this.panes.remove(source_pane).is_ok();
+                let _did_find_pane = this.panes.remove(source_pane, cx).is_ok();
                 debug_assert!(_did_find_pane);
                 cx.notify();
             }
@@ -1743,7 +1740,7 @@ impl RunningState {
 
         let is_building = self.session.update(cx, |session, cx| {
             session.shutdown(cx).detach();
-            matches!(session.mode, session::SessionState::Booting(_))
+            matches!(session.state, session::SessionState::Booting(_))
         });
 
         if is_building {
@@ -1892,9 +1889,9 @@ impl RunningState {
         Member::Axis(group_root)
     }
 
-    pub(crate) fn invert_axies(&mut self) {
+    pub(crate) fn invert_axies(&mut self, cx: &mut App) {
         self.dock_axis = self.dock_axis.invert();
-        self.panes.invert_axies();
+        self.panes.invert_axies(cx);
     }
 }
 

crates/debugger_ui/src/session/running/breakpoint_list.rs 🔗

@@ -310,7 +310,7 @@ impl BreakpointList {
 
     fn dismiss(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
         if self.input.focus_handle(cx).contains_focused(window, cx) {
-            self.focus_handle.focus(window);
+            self.focus_handle.focus(window, cx);
         } else if self.strip_mode.is_some() {
             self.strip_mode.take();
             cx.notify();
@@ -364,9 +364,9 @@ impl BreakpointList {
                         }
                     }
                 }
-                self.focus_handle.focus(window);
+                self.focus_handle.focus(window, cx);
             } else {
-                handle.focus(window);
+                handle.focus(window, cx);
             }
 
             return;
@@ -627,7 +627,7 @@ impl BreakpointList {
                 .on_click({
                     let focus_handle = focus_handle.clone();
                     move |_, window, cx| {
-                        focus_handle.focus(window);
+                        focus_handle.focus(window, cx);
                         window.dispatch_action(ToggleEnableBreakpoint.boxed_clone(), cx)
                     }
                 }),
@@ -654,7 +654,7 @@ impl BreakpointList {
                     )
                     .on_click({
                         move |_, window, cx| {
-                            focus_handle.focus(window);
+                            focus_handle.focus(window, cx);
                             window.dispatch_action(UnsetBreakpoint.boxed_clone(), cx)
                         }
                     }),

crates/debugger_ui/src/session/running/console.rs 🔗

@@ -105,7 +105,7 @@ impl Console {
             cx.subscribe(&stack_frame_list, Self::handle_stack_frame_list_events),
             cx.on_focus(&focus_handle, window, |console, window, cx| {
                 if console.is_running(cx) {
-                    console.query_bar.focus_handle(cx).focus(window);
+                    console.query_bar.focus_handle(cx).focus(window, cx);
                 }
             }),
         ];
@@ -252,10 +252,11 @@ impl Console {
                         let start_offset = range.start;
                         let range = buffer.anchor_after(MultiBufferOffset(range.start))
                             ..buffer.anchor_before(MultiBufferOffset(range.end));
+                        let color_fn = color_fetcher(color);
                         console.highlight_background_key::<ConsoleAnsiHighlight>(
                             start_offset,
                             &[range],
-                            color_fetcher(color),
+                            move |_, theme| color_fn(theme),
                             cx,
                         );
                     }
@@ -559,7 +560,6 @@ impl CompletionProvider for ConsoleQueryBarCompletionProvider {
         position: language::Anchor,
         text: &str,
         trigger_in_words: bool,
-        menu_is_open: bool,
         cx: &mut Context<Editor>,
     ) -> bool {
         let mut chars = text.chars();
@@ -570,9 +570,6 @@ impl CompletionProvider for ConsoleQueryBarCompletionProvider {
         };
 
         let snapshot = buffer.read(cx).snapshot();
-        if !menu_is_open && !snapshot.settings_at(position, cx).show_completions_on_input {
-            return false;
-        }
 
         let classifier = snapshot
             .char_classifier_at(position)

crates/debugger_ui/src/session/running/loaded_source_list.rs 🔗

@@ -17,7 +17,9 @@ impl LoadedSourceList {
         let list = ListState::new(0, gpui::ListAlignment::Top, px(1000.));
 
         let _subscription = cx.subscribe(&session, |this, _, event, cx| match event {
-            SessionEvent::Stopped(_) | SessionEvent::LoadedSources => {
+            SessionEvent::Stopped(_)
+            | SessionEvent::HistoricSnapshotSelected
+            | SessionEvent::LoadedSources => {
                 this.invalidate = true;
                 cx.notify();
             }

crates/debugger_ui/src/session/running/memory_view.rs 🔗

@@ -403,7 +403,7 @@ impl MemoryView {
                 this.set_placeholder_text("Write to Selected Memory Range", window, cx);
             });
             self.is_writing_memory = true;
-            self.query_editor.focus_handle(cx).focus(window);
+            self.query_editor.focus_handle(cx).focus(window, cx);
         } else {
             self.query_editor.update(cx, |this, cx| {
                 this.clear(window, cx);

crates/debugger_ui/src/session/running/module_list.rs 🔗

@@ -32,7 +32,9 @@ impl ModuleList {
         let focus_handle = cx.focus_handle();
 
         let _subscription = cx.subscribe(&session, |this, _, event, cx| match event {
-            SessionEvent::Stopped(_) | SessionEvent::Modules => {
+            SessionEvent::Stopped(_)
+            | SessionEvent::HistoricSnapshotSelected
+            | SessionEvent::Modules => {
                 if this._rebuild_task.is_some() {
                     this.schedule_rebuild(cx);
                 }

crates/debugger_ui/src/session/running/stack_frame_list.rs 🔗

@@ -4,6 +4,7 @@ use std::time::Duration;
 
 use anyhow::{Context as _, Result, anyhow};
 use dap::StackFrameId;
+use dap::adapters::DebugAdapterName;
 use db::kvp::KEY_VALUE_STORE;
 use gpui::{
     Action, AnyElement, Entity, EventEmitter, FocusHandle, Focusable, FontWeight, ListState,
@@ -20,7 +21,7 @@ use project::debugger::breakpoint_store::ActiveStackFrame;
 use project::debugger::session::{Session, SessionEvent, StackFrame, ThreadStatus};
 use project::{ProjectItem, ProjectPath};
 use ui::{Tooltip, WithScrollbar, prelude::*};
-use workspace::{ItemHandle, Workspace};
+use workspace::{ItemHandle, Workspace, WorkspaceId};
 
 use super::RunningState;
 
@@ -58,6 +59,14 @@ impl From<StackFrameFilter> for String {
     }
 }
 
+pub(crate) fn stack_frame_filter_key(
+    adapter_name: &DebugAdapterName,
+    workspace_id: WorkspaceId,
+) -> String {
+    let database_id: i64 = workspace_id.into();
+    format!("stack-frame-list-filter-{}-{}", adapter_name.0, database_id)
+}
+
 pub struct StackFrameList {
     focus_handle: FocusHandle,
     _subscription: Subscription,
@@ -97,7 +106,9 @@ impl StackFrameList {
                 SessionEvent::Threads => {
                     this.schedule_refresh(false, window, cx);
                 }
-                SessionEvent::Stopped(..) | SessionEvent::StackTrace => {
+                SessionEvent::Stopped(..)
+                | SessionEvent::StackTrace
+                | SessionEvent::HistoricSnapshotSelected => {
                     this.schedule_refresh(true, window, cx);
                 }
                 _ => {}
@@ -105,14 +116,18 @@ impl StackFrameList {
 
         let list_state = ListState::new(0, gpui::ListAlignment::Top, px(1000.));
 
-        let list_filter = KEY_VALUE_STORE
-            .read_kvp(&format!(
-                "stack-frame-list-filter-{}",
-                session.read(cx).adapter().0
-            ))
+        let list_filter = workspace
+            .read_with(cx, |workspace, _| workspace.database_id())
             .ok()
             .flatten()
-            .map(StackFrameFilter::from_str_or_default)
+            .and_then(|database_id| {
+                let key = stack_frame_filter_key(&session.read(cx).adapter(), database_id);
+                KEY_VALUE_STORE
+                    .read_kvp(&key)
+                    .ok()
+                    .flatten()
+                    .map(StackFrameFilter::from_str_or_default)
+            })
             .unwrap_or(StackFrameFilter::All);
 
         let mut this = Self {
@@ -225,7 +240,6 @@ impl StackFrameList {
             }
             this.update_in(cx, |this, window, cx| {
                 this.build_entries(select_first, window, cx);
-                cx.notify();
             })
             .ok();
         })
@@ -806,15 +820,8 @@ impl StackFrameList {
             .ok()
             .flatten()
         {
-            let database_id: i64 = database_id.into();
-            let save_task = KEY_VALUE_STORE.write_kvp(
-                format!(
-                    "stack-frame-list-filter-{}-{}",
-                    self.session.read(cx).adapter().0,
-                    database_id,
-                ),
-                self.list_filter.into(),
-            );
+            let key = stack_frame_filter_key(&self.session.read(cx).adapter(), database_id);
+            let save_task = KEY_VALUE_STORE.write_kvp(key, self.list_filter.into());
             cx.background_spawn(save_task).detach();
         }
 

crates/debugger_ui/src/session/running/variable_list.rs 🔗

@@ -217,6 +217,12 @@ impl VariableList {
         let _subscriptions = vec![
             cx.subscribe(&stack_frame_list, Self::handle_stack_frame_list_events),
             cx.subscribe(&session, |this, _, event, cx| match event {
+                SessionEvent::HistoricSnapshotSelected => {
+                    this.selection.take();
+                    this.edited_path.take();
+                    this.selected_stack_frame_id.take();
+                    this.build_entries(cx);
+                }
                 SessionEvent::Stopped(_) => {
                     this.selection.take();
                     this.edited_path.take();
@@ -225,7 +231,6 @@ impl VariableList {
                 SessionEvent::Variables | SessionEvent::Watchers => {
                     this.build_entries(cx);
                 }
-
                 _ => {}
             }),
             cx.on_focus_out(&focus_handle, window, |this, _, _, cx| {
@@ -524,7 +529,7 @@ impl VariableList {
 
     fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
         self.edited_path.take();
-        self.focus_handle.focus(window);
+        self.focus_handle.focus(window, cx);
         cx.notify();
     }
 
@@ -1062,7 +1067,7 @@ impl VariableList {
             editor.select_all(&editor::actions::SelectAll, window, cx);
             editor
         });
-        editor.focus_handle(cx).focus(window);
+        editor.focus_handle(cx).focus(window, cx);
         editor
     }
 

crates/debugger_ui/src/tests/inline_values.rs 🔗

@@ -4,7 +4,7 @@ use dap::{Scope, StackFrame, Variable, requests::Variables};
 use editor::{Editor, EditorMode, MultiBuffer};
 use gpui::{BackgroundExecutor, TestAppContext, VisualTestContext};
 use language::{
-    Language, LanguageConfig, LanguageMatcher, tree_sitter_python, tree_sitter_rust,
+    Language, LanguageConfig, LanguageMatcher, rust_lang, tree_sitter_python,
     tree_sitter_typescript,
 };
 use project::{FakeFs, Project};
@@ -224,7 +224,7 @@ fn main() {
         .unwrap();
 
     buffer.update(cx, |buffer, cx| {
-        buffer.set_language(Some(Arc::new(rust_lang())), cx);
+        buffer.set_language(Some(rust_lang()), cx);
     });
 
     let (editor, cx) = cx.add_window_view(|window, cx| {
@@ -1521,23 +1521,6 @@ fn main() {
     });
 }
 
-fn rust_lang() -> Language {
-    let debug_variables_query = include_str!("../../../languages/src/rust/debugger.scm");
-    Language::new(
-        LanguageConfig {
-            name: "Rust".into(),
-            matcher: LanguageMatcher {
-                path_suffixes: vec!["rs".to_string()],
-                ..Default::default()
-            },
-            ..Default::default()
-        },
-        Some(tree_sitter_rust::LANGUAGE.into()),
-    )
-    .with_debug_variables_query(debug_variables_query)
-    .unwrap()
-}
-
 #[gpui::test]
 async fn test_python_inline_values(executor: BackgroundExecutor, cx: &mut TestAppContext) {
     init_test(cx);
@@ -1859,21 +1842,23 @@ fn python_lang() -> Language {
     .unwrap()
 }
 
-fn go_lang() -> Language {
+fn go_lang() -> Arc<Language> {
     let debug_variables_query = include_str!("../../../languages/src/go/debugger.scm");
-    Language::new(
-        LanguageConfig {
-            name: "Go".into(),
-            matcher: LanguageMatcher {
-                path_suffixes: vec!["go".to_string()],
+    Arc::new(
+        Language::new(
+            LanguageConfig {
+                name: "Go".into(),
+                matcher: LanguageMatcher {
+                    path_suffixes: vec!["go".to_string()],
+                    ..Default::default()
+                },
                 ..Default::default()
             },
-            ..Default::default()
-        },
-        Some(tree_sitter_go::LANGUAGE.into()),
+            Some(tree_sitter_go::LANGUAGE.into()),
+        )
+        .with_debug_variables_query(debug_variables_query)
+        .unwrap(),
     )
-    .with_debug_variables_query(debug_variables_query)
-    .unwrap()
 }
 
 /// Test utility function for inline values testing
@@ -1891,7 +1876,7 @@ async fn test_inline_values_util(
     before: &str,
     after: &str,
     active_debug_line: Option<usize>,
-    language: Language,
+    language: Arc<Language>,
     executor: BackgroundExecutor,
     cx: &mut TestAppContext,
 ) {
@@ -2091,7 +2076,7 @@ async fn test_inline_values_util(
         .unwrap();
 
     buffer.update(cx, |buffer, cx| {
-        buffer.set_language(Some(Arc::new(language)), cx);
+        buffer.set_language(Some(language), cx);
     });
 
     let (editor, cx) = cx.add_window_view(|window, cx| {
@@ -2276,55 +2261,61 @@ fn main() {
     .await;
 }
 
-fn javascript_lang() -> Language {
+fn javascript_lang() -> Arc<Language> {
     let debug_variables_query = include_str!("../../../languages/src/javascript/debugger.scm");
-    Language::new(
-        LanguageConfig {
-            name: "JavaScript".into(),
-            matcher: LanguageMatcher {
-                path_suffixes: vec!["js".to_string()],
+    Arc::new(
+        Language::new(
+            LanguageConfig {
+                name: "JavaScript".into(),
+                matcher: LanguageMatcher {
+                    path_suffixes: vec!["js".to_string()],
+                    ..Default::default()
+                },
                 ..Default::default()
             },
-            ..Default::default()
-        },
-        Some(tree_sitter_typescript::LANGUAGE_TYPESCRIPT.into()),
+            Some(tree_sitter_typescript::LANGUAGE_TYPESCRIPT.into()),
+        )
+        .with_debug_variables_query(debug_variables_query)
+        .unwrap(),
     )
-    .with_debug_variables_query(debug_variables_query)
-    .unwrap()
 }
 
-fn typescript_lang() -> Language {
+fn typescript_lang() -> Arc<Language> {
     let debug_variables_query = include_str!("../../../languages/src/typescript/debugger.scm");
-    Language::new(
-        LanguageConfig {
-            name: "TypeScript".into(),
-            matcher: LanguageMatcher {
-                path_suffixes: vec!["ts".to_string()],
+    Arc::new(
+        Language::new(
+            LanguageConfig {
+                name: "TypeScript".into(),
+                matcher: LanguageMatcher {
+                    path_suffixes: vec!["ts".to_string()],
+                    ..Default::default()
+                },
                 ..Default::default()
             },
-            ..Default::default()
-        },
-        Some(tree_sitter_typescript::LANGUAGE_TYPESCRIPT.into()),
+            Some(tree_sitter_typescript::LANGUAGE_TYPESCRIPT.into()),
+        )
+        .with_debug_variables_query(debug_variables_query)
+        .unwrap(),
     )
-    .with_debug_variables_query(debug_variables_query)
-    .unwrap()
 }
 
-fn tsx_lang() -> Language {
+fn tsx_lang() -> Arc<Language> {
     let debug_variables_query = include_str!("../../../languages/src/tsx/debugger.scm");
-    Language::new(
-        LanguageConfig {
-            name: "TSX".into(),
-            matcher: LanguageMatcher {
-                path_suffixes: vec!["tsx".to_string()],
+    Arc::new(
+        Language::new(
+            LanguageConfig {
+                name: "TSX".into(),
+                matcher: LanguageMatcher {
+                    path_suffixes: vec!["tsx".to_string()],
+                    ..Default::default()
+                },
                 ..Default::default()
             },
-            ..Default::default()
-        },
-        Some(tree_sitter_typescript::LANGUAGE_TSX.into()),
+            Some(tree_sitter_typescript::LANGUAGE_TSX.into()),
+        )
+        .with_debug_variables_query(debug_variables_query)
+        .unwrap(),
     )
-    .with_debug_variables_query(debug_variables_query)
-    .unwrap()
 }
 
 #[gpui::test]

crates/debugger_ui/src/tests/stack_frame_list.rs 🔗

@@ -1,12 +1,15 @@
 use crate::{
     debugger_panel::DebugPanel,
-    session::running::stack_frame_list::{StackFrameEntry, StackFrameFilter},
+    session::running::stack_frame_list::{
+        StackFrameEntry, StackFrameFilter, stack_frame_filter_key,
+    },
     tests::{active_debug_session_panel, init_test, init_test_workspace, start_debug_session},
 };
 use dap::{
     StackFrame,
     requests::{Scopes, StackTrace, Threads},
 };
+use db::kvp::KEY_VALUE_STORE;
 use editor::{Editor, ToPoint as _};
 use gpui::{BackgroundExecutor, TestAppContext, VisualTestContext};
 use project::{FakeFs, Project};
@@ -1085,3 +1088,180 @@ async fn test_stack_frame_filter(executor: BackgroundExecutor, cx: &mut TestAppC
         );
     });
 }
+
+#[gpui::test]
+async fn test_stack_frame_filter_persistence(
+    executor: BackgroundExecutor,
+    cx: &mut TestAppContext,
+) {
+    init_test(cx);
+
+    let fs = FakeFs::new(executor.clone());
+
+    fs.insert_tree(
+        path!("/project"),
+        json!({
+           "src": {
+               "test.js": "function main() { console.log('hello'); }",
+           }
+        }),
+    )
+    .await;
+
+    let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
+    let workspace = init_test_workspace(&project, cx).await;
+    let cx = &mut VisualTestContext::from_window(*workspace, cx);
+    workspace
+        .update(cx, |workspace, _, _| {
+            workspace.set_random_database_id();
+        })
+        .unwrap();
+
+    let threads_response = dap::ThreadsResponse {
+        threads: vec![dap::Thread {
+            id: 1,
+            name: "Thread 1".into(),
+        }],
+    };
+
+    let stack_trace_response = dap::StackTraceResponse {
+        stack_frames: vec![StackFrame {
+            id: 1,
+            name: "main".into(),
+            source: Some(dap::Source {
+                name: Some("test.js".into()),
+                path: Some(path!("/project/src/test.js").into()),
+                source_reference: None,
+                presentation_hint: None,
+                origin: None,
+                sources: None,
+                adapter_data: None,
+                checksums: None,
+            }),
+            line: 1,
+            column: 1,
+            end_line: None,
+            end_column: None,
+            can_restart: None,
+            instruction_pointer_reference: None,
+            module_id: None,
+            presentation_hint: None,
+        }],
+        total_frames: None,
+    };
+
+    let stopped_event = dap::StoppedEvent {
+        reason: dap::StoppedEventReason::Pause,
+        description: None,
+        thread_id: Some(1),
+        preserve_focus_hint: None,
+        text: None,
+        all_threads_stopped: None,
+        hit_breakpoint_ids: None,
+    };
+
+    let session = start_debug_session(&workspace, cx, |_| {}).unwrap();
+    let client = session.update(cx, |session, _| session.adapter_client().unwrap());
+    let adapter_name = session.update(cx, |session, _| session.adapter());
+
+    client.on_request::<Threads, _>({
+        let threads_response = threads_response.clone();
+        move |_, _| Ok(threads_response.clone())
+    });
+
+    client.on_request::<Scopes, _>(move |_, _| Ok(dap::ScopesResponse { scopes: vec![] }));
+
+    client.on_request::<StackTrace, _>({
+        let stack_trace_response = stack_trace_response.clone();
+        move |_, _| Ok(stack_trace_response.clone())
+    });
+
+    client
+        .fake_event(dap::messages::Events::Stopped(stopped_event.clone()))
+        .await;
+
+    cx.run_until_parked();
+
+    let stack_frame_list =
+        active_debug_session_panel(workspace, cx).update(cx, |debug_panel_item, cx| {
+            debug_panel_item
+                .running_state()
+                .update(cx, |state, _| state.stack_frame_list().clone())
+        });
+
+    stack_frame_list.update(cx, |stack_frame_list, _cx| {
+        assert_eq!(
+            stack_frame_list.list_filter(),
+            StackFrameFilter::All,
+            "Initial filter should be All"
+        );
+    });
+
+    stack_frame_list.update(cx, |stack_frame_list, cx| {
+        stack_frame_list
+            .toggle_frame_filter(Some(project::debugger::session::ThreadStatus::Stopped), cx);
+        assert_eq!(
+            stack_frame_list.list_filter(),
+            StackFrameFilter::OnlyUserFrames,
+            "Filter should be OnlyUserFrames after toggle"
+        );
+    });
+
+    cx.run_until_parked();
+
+    let workspace_id = workspace
+        .update(cx, |workspace, _window, _cx| workspace.database_id())
+        .ok()
+        .flatten()
+        .expect("workspace id has to be some for this test to work properly");
+
+    let key = stack_frame_filter_key(&adapter_name, workspace_id);
+    let stored_value = KEY_VALUE_STORE.read_kvp(&key).unwrap();
+    assert_eq!(
+        stored_value,
+        Some(StackFrameFilter::OnlyUserFrames.into()),
+        "Filter should be persisted in KVP store with key: {}",
+        key
+    );
+
+    client
+        .fake_event(dap::messages::Events::Terminated(None))
+        .await;
+    cx.run_until_parked();
+
+    let session2 = start_debug_session(&workspace, cx, |_| {}).unwrap();
+    let client2 = session2.update(cx, |session, _| session.adapter_client().unwrap());
+
+    client2.on_request::<Threads, _>({
+        let threads_response = threads_response.clone();
+        move |_, _| Ok(threads_response.clone())
+    });
+
+    client2.on_request::<Scopes, _>(move |_, _| Ok(dap::ScopesResponse { scopes: vec![] }));
+
+    client2.on_request::<StackTrace, _>({
+        let stack_trace_response = stack_trace_response.clone();
+        move |_, _| Ok(stack_trace_response.clone())
+    });
+
+    client2
+        .fake_event(dap::messages::Events::Stopped(stopped_event.clone()))
+        .await;
+
+    cx.run_until_parked();
+
+    let stack_frame_list2 =
+        active_debug_session_panel(workspace, cx).update(cx, |debug_panel_item, cx| {
+            debug_panel_item
+                .running_state()
+                .update(cx, |state, _| state.stack_frame_list().clone())
+        });
+
+    stack_frame_list2.update(cx, |stack_frame_list, _cx| {
+        assert_eq!(
+            stack_frame_list.list_filter(),
+            StackFrameFilter::OnlyUserFrames,
+            "Filter should be restored from KVP store in new session"
+        );
+    });
+}

crates/deepseek/src/deepseek.rs 🔗

@@ -103,8 +103,9 @@ impl Model {
 
     pub fn max_output_tokens(&self) -> Option<u64> {
         match self {
-            Self::Chat => Some(8_192),
-            Self::Reasoner => Some(64_000),
+            // Their API treats this max against the context window, which means we hit the limit a lot
+            // Using the default value of None in the API instead
+            Self::Chat | Self::Reasoner => None,
             Self::Custom {
                 max_output_tokens, ..
             } => *max_output_tokens,
@@ -155,6 +156,8 @@ pub enum RequestMessage {
         content: Option<String>,
         #[serde(default, skip_serializing_if = "Vec::is_empty")]
         tool_calls: Vec<ToolCall>,
+        #[serde(default, skip_serializing_if = "Option::is_none")]
+        reasoning_content: Option<String>,
     },
     User {
         content: String,

crates/diagnostics/src/buffer_diagnostics.rs 🔗

@@ -6,7 +6,7 @@ use crate::{
 use anyhow::Result;
 use collections::HashMap;
 use editor::{
-    Editor, EditorEvent, ExcerptRange, MultiBuffer, PathKey,
+    Editor, EditorEvent, EditorSettings, ExcerptRange, MultiBuffer, PathKey,
     display_map::{BlockPlacement, BlockProperties, BlockStyle, CustomBlockId},
     multibuffer_context_lines,
 };
@@ -175,7 +175,7 @@ impl BufferDiagnosticsEditor {
                     // `BufferDiagnosticsEditor` instance.
                     EditorEvent::Focused => {
                         if buffer_diagnostics_editor.multibuffer.read(cx).is_empty() {
-                            window.focus(&buffer_diagnostics_editor.focus_handle);
+                            window.focus(&buffer_diagnostics_editor.focus_handle, cx);
                         }
                     }
                     EditorEvent::Blurred => {
@@ -517,7 +517,7 @@ impl BufferDiagnosticsEditor {
                                 .editor
                                 .read(cx)
                                 .focus_handle(cx)
-                                .focus(window);
+                                .focus(window, cx);
                         }
                     }
                 }
@@ -617,7 +617,7 @@ impl BufferDiagnosticsEditor {
         // not empty, focus on the editor instead, which will allow the user to
         // start interacting and editing the buffer's contents.
         if self.focus_handle.is_focused(window) && !self.multibuffer.read(cx).is_empty() {
-            self.editor.focus_handle(cx).focus(window)
+            self.editor.focus_handle(cx).focus(window, cx)
         }
     }
 
@@ -701,8 +701,12 @@ impl Item for BufferDiagnosticsEditor {
         });
     }
 
-    fn breadcrumb_location(&self, _: &App) -> ToolbarItemLocation {
-        ToolbarItemLocation::PrimaryLeft
+    fn breadcrumb_location(&self, cx: &App) -> ToolbarItemLocation {
+        if EditorSettings::get_global(cx).toolbar.breadcrumbs {
+            ToolbarItemLocation::PrimaryLeft
+        } else {
+            ToolbarItemLocation::Hidden
+        }
     }
 
     fn breadcrumbs(&self, theme: &theme::Theme, cx: &App) -> Option<Vec<BreadcrumbText>> {

crates/diagnostics/src/diagnostic_renderer.rs 🔗

@@ -315,6 +315,6 @@ impl DiagnosticBlock {
         editor.change_selections(Default::default(), window, cx, |s| {
             s.select_ranges([range.start..range.start]);
         });
-        window.focus(&editor.focus_handle(cx));
+        window.focus(&editor.focus_handle(cx), cx);
     }
 }

crates/diagnostics/src/diagnostics.rs 🔗

@@ -12,7 +12,7 @@ use buffer_diagnostics::BufferDiagnosticsEditor;
 use collections::{BTreeSet, HashMap, HashSet};
 use diagnostic_renderer::DiagnosticBlock;
 use editor::{
-    Editor, EditorEvent, ExcerptRange, MultiBuffer, PathKey,
+    Editor, EditorEvent, EditorSettings, ExcerptRange, MultiBuffer, PathKey,
     display_map::{BlockPlacement, BlockProperties, BlockStyle, CustomBlockId},
     multibuffer_context_lines,
 };
@@ -243,7 +243,7 @@ impl ProjectDiagnosticsEditor {
                 match event {
                     EditorEvent::Focused => {
                         if this.multibuffer.read(cx).is_empty() {
-                            window.focus(&this.focus_handle);
+                            window.focus(&this.focus_handle, cx);
                         }
                     }
                     EditorEvent::Blurred => this.close_diagnosticless_buffers(cx, false),
@@ -434,7 +434,7 @@ impl ProjectDiagnosticsEditor {
 
     fn focus_in(&mut self, window: &mut Window, cx: &mut Context<Self>) {
         if self.focus_handle.is_focused(window) && !self.multibuffer.read(cx).is_empty() {
-            self.editor.focus_handle(cx).focus(window)
+            self.editor.focus_handle(cx).focus(window, cx)
         }
     }
 
@@ -650,7 +650,7 @@ impl ProjectDiagnosticsEditor {
                         })
                     });
                     if this.focus_handle.is_focused(window) {
-                        this.editor.read(cx).focus_handle(cx).focus(window);
+                        this.editor.read(cx).focus_handle(cx).focus(window, cx);
                     }
                 }
 
@@ -894,8 +894,12 @@ impl Item for ProjectDiagnosticsEditor {
         Some(Box::new(self.editor.clone()))
     }
 
-    fn breadcrumb_location(&self, _: &App) -> ToolbarItemLocation {
-        ToolbarItemLocation::PrimaryLeft
+    fn breadcrumb_location(&self, cx: &App) -> ToolbarItemLocation {
+        if EditorSettings::get_global(cx).toolbar.breadcrumbs {
+            ToolbarItemLocation::PrimaryLeft
+        } else {
+            ToolbarItemLocation::Hidden
+        }
     }
 
     fn breadcrumbs(&self, theme: &theme::Theme, cx: &App) -> Option<Vec<BreadcrumbText>> {
@@ -1045,54 +1049,47 @@ async fn heuristic_syntactic_expand(
         let node_range = node_start..node_end;
         let row_count = node_end.row - node_start.row + 1;
         let mut ancestor_range = None;
-        let reached_outline_node = cx.background_executor().scoped({
-            let node_range = node_range.clone();
-            let outline_range = outline_range.clone();
-            let ancestor_range = &mut ancestor_range;
-            |scope| {
-                scope.spawn(async move {
-                    // Stop if we've exceeded the row count or reached an outline node. Then, find the interval
-                    // of node children which contains the query range. For example, this allows just returning
-                    // the header of a declaration rather than the entire declaration.
-                    if row_count > max_row_count || outline_range == Some(node_range.clone()) {
-                        let mut cursor = node.walk();
-                        let mut included_child_start = None;
-                        let mut included_child_end = None;
-                        let mut previous_end = node_start;
-                        if cursor.goto_first_child() {
-                            loop {
-                                let child_node = cursor.node();
-                                let child_range =
-                                    previous_end..Point::from_ts_point(child_node.end_position());
-                                if included_child_start.is_none()
-                                    && child_range.contains(&input_range.start)
-                                {
-                                    included_child_start = Some(child_range.start);
-                                }
-                                if child_range.contains(&input_range.end) {
-                                    included_child_end = Some(child_range.end);
-                                }
-                                previous_end = child_range.end;
-                                if !cursor.goto_next_sibling() {
-                                    break;
-                                }
+        cx.background_executor()
+            .await_on_background(async {
+                // Stop if we've exceeded the row count or reached an outline node. Then, find the interval
+                // of node children which contains the query range. For example, this allows just returning
+                // the header of a declaration rather than the entire declaration.
+                if row_count > max_row_count || outline_range == Some(node_range.clone()) {
+                    let mut cursor = node.walk();
+                    let mut included_child_start = None;
+                    let mut included_child_end = None;
+                    let mut previous_end = node_start;
+                    if cursor.goto_first_child() {
+                        loop {
+                            let child_node = cursor.node();
+                            let child_range =
+                                previous_end..Point::from_ts_point(child_node.end_position());
+                            if included_child_start.is_none()
+                                && child_range.contains(&input_range.start)
+                            {
+                                included_child_start = Some(child_range.start);
                             }
-                        }
-                        let end = included_child_end.unwrap_or(node_range.end);
-                        if let Some(start) = included_child_start {
-                            let row_count = end.row - start.row;
-                            if row_count < max_row_count {
-                                *ancestor_range =
-                                    Some(Some(RangeInclusive::new(start.row, end.row)));
-                                return;
+                            if child_range.contains(&input_range.end) {
+                                included_child_end = Some(child_range.end);
+                            }
+                            previous_end = child_range.end;
+                            if !cursor.goto_next_sibling() {
+                                break;
                             }
                         }
-                        *ancestor_range = Some(None);
                     }
-                })
-            }
-        });
-        reached_outline_node.await;
+                    let end = included_child_end.unwrap_or(node_range.end);
+                    if let Some(start) = included_child_start {
+                        let row_count = end.row - start.row;
+                        if row_count < max_row_count {
+                            ancestor_range = Some(Some(RangeInclusive::new(start.row, end.row)));
+                            return;
+                        }
+                    }
+                    ancestor_range = Some(None);
+                }
+            })
+            .await;
         if let Some(node) = ancestor_range {
             return node;
         }

crates/docs_preprocessor/Cargo.toml 🔗

@@ -7,8 +7,6 @@ license = "GPL-3.0-or-later"
 
 [dependencies]
 anyhow.workspace = true
-command_palette.workspace = true
-gpui.workspace = true
 # We are specifically pinning this version of mdbook, as later versions introduce issues with double-nested subdirectories.
 # Ask @maxdeviant about this before bumping.
 mdbook = "= 0.4.40"
@@ -17,7 +15,6 @@ serde.workspace = true
 serde_json.workspace = true
 settings.workspace = true
 util.workspace = true
-zed.workspace = true
 zlog.workspace = true
 task.workspace = true
 theme.workspace = true
@@ -27,4 +24,4 @@ workspace = true
 
 [[bin]]
 name = "docs_preprocessor"
-path = "src/main.rs"
+path = "src/main.rs"

crates/docs_preprocessor/src/main.rs 🔗

@@ -22,16 +22,13 @@ static KEYMAP_WINDOWS: LazyLock<KeymapFile> = LazyLock::new(|| {
     load_keymap("keymaps/default-windows.json").expect("Failed to load Windows keymap")
 });
 
-static ALL_ACTIONS: LazyLock<Vec<ActionDef>> = LazyLock::new(dump_all_gpui_actions);
+static ALL_ACTIONS: LazyLock<Vec<ActionDef>> = LazyLock::new(load_all_actions);
 
 const FRONT_MATTER_COMMENT: &str = "<!-- ZED_META {} -->";
 
 fn main() -> Result<()> {
     zlog::init();
     zlog::init_output_stderr();
-    // call a zed:: function so everything in `zed` crate is linked and
-    // all actions in the actual app are registered
-    zed::stdout_is_a_pty();
     let args = std::env::args().skip(1).collect::<Vec<_>>();
 
     match args.get(0).map(String::as_str) {
@@ -72,8 +69,8 @@ enum PreprocessorError {
 impl PreprocessorError {
     fn new_for_not_found_action(action_name: String) -> Self {
         for action in &*ALL_ACTIONS {
-            for alias in action.deprecated_aliases {
-                if alias == &action_name {
+            for alias in &action.deprecated_aliases {
+                if alias == action_name.as_str() {
                     return PreprocessorError::DeprecatedActionUsed {
                         used: action_name,
                         should_be: action.name.to_string(),
@@ -214,7 +211,7 @@ fn template_and_validate_keybindings(book: &mut Book, errors: &mut HashSet<Prepr
         chapter.content = regex
             .replace_all(&chapter.content, |caps: &regex::Captures| {
                 let action = caps[1].trim();
-                if find_action_by_name(action).is_none() {
+                if is_missing_action(action) {
                     errors.insert(PreprocessorError::new_for_not_found_action(
                         action.to_string(),
                     ));
@@ -244,10 +241,12 @@ fn template_and_validate_actions(book: &mut Book, errors: &mut HashSet<Preproces
             .replace_all(&chapter.content, |caps: &regex::Captures| {
                 let name = caps[1].trim();
                 let Some(action) = find_action_by_name(name) else {
-                    errors.insert(PreprocessorError::new_for_not_found_action(
-                        name.to_string(),
-                    ));
-                    return String::new();
+                    if actions_available() {
+                        errors.insert(PreprocessorError::new_for_not_found_action(
+                            name.to_string(),
+                        ));
+                    }
+                    return format!("<code class=\"hljs\">{}</code>", name);
                 };
                 format!("<code class=\"hljs\">{}</code>", &action.human_name)
             })
@@ -257,11 +256,19 @@ fn template_and_validate_actions(book: &mut Book, errors: &mut HashSet<Preproces
 
 fn find_action_by_name(name: &str) -> Option<&ActionDef> {
     ALL_ACTIONS
-        .binary_search_by(|action| action.name.cmp(name))
+        .binary_search_by(|action| action.name.as_str().cmp(name))
         .ok()
         .map(|index| &ALL_ACTIONS[index])
 }
 
+fn actions_available() -> bool {
+    !ALL_ACTIONS.is_empty()
+}
+
+fn is_missing_action(name: &str) -> bool {
+    actions_available() && find_action_by_name(name).is_none()
+}
+
 fn find_binding(os: &str, action: &str) -> Option<String> {
     let keymap = match os {
         "macos" => &KEYMAP_MACOS,
@@ -384,18 +391,13 @@ fn template_and_validate_json_snippets(book: &mut Book, errors: &mut HashSet<Pre
                 let keymap = settings::KeymapFile::parse(&snippet_json_fixed)
                     .context("Failed to parse keymap JSON")?;
                 for section in keymap.sections() {
-                    for (keystrokes, action) in section.bindings() {
-                        keystrokes
-                            .split_whitespace()
-                            .map(|source| gpui::Keystroke::parse(source))
-                            .collect::<std::result::Result<Vec<_>, _>>()
-                            .context("Failed to parse keystroke")?;
+                    for (_keystrokes, action) in section.bindings() {
                         if let Some((action_name, _)) = settings::KeymapFile::parse_action(action)
                             .map_err(|err| anyhow::format_err!(err))
                             .context("Failed to parse action")?
                         {
                             anyhow::ensure!(
-                                find_action_by_name(action_name).is_some(),
+                                !is_missing_action(action_name),
                                 "Action not found: {}",
                                 action_name
                             );
@@ -491,27 +493,35 @@ where
     });
 }
 
-#[derive(Debug, serde::Serialize)]
+#[derive(Debug, serde::Serialize, serde::Deserialize)]
 struct ActionDef {
-    name: &'static str,
+    name: String,
     human_name: String,
-    deprecated_aliases: &'static [&'static str],
-    docs: Option<&'static str>,
+    deprecated_aliases: Vec<String>,
+    #[serde(rename = "documentation")]
+    docs: Option<String>,
 }
 
-fn dump_all_gpui_actions() -> Vec<ActionDef> {
-    let mut actions = gpui::generate_list_of_all_registered_actions()
-        .map(|action| ActionDef {
-            name: action.name,
-            human_name: command_palette::humanize_action_name(action.name),
-            deprecated_aliases: action.deprecated_aliases,
-            docs: action.documentation,
-        })
-        .collect::<Vec<ActionDef>>();
-
-    actions.sort_by_key(|a| a.name);
-
-    actions
+fn load_all_actions() -> Vec<ActionDef> {
+    let asset_path = concat!(env!("CARGO_MANIFEST_DIR"), "/actions.json");
+    match std::fs::read_to_string(asset_path) {
+        Ok(content) => {
+            let mut actions: Vec<ActionDef> =
+                serde_json::from_str(&content).expect("Failed to parse actions.json");
+            actions.sort_by(|a, b| a.name.cmp(&b.name));
+            actions
+        }
+        Err(err) => {
+            if std::env::var("CI").is_ok() {
+                panic!("actions.json not found at {}: {}", asset_path, err);
+            }
+            eprintln!(
+                "Warning: actions.json not found, action validation will be skipped: {}",
+                err
+            );
+            Vec::new()
+        }
+    }
 }
 
 fn handle_postprocessing() -> Result<()> {
@@ -647,7 +657,7 @@ fn generate_big_table_of_actions() -> String {
     let mut output = String::new();
 
     let mut actions_sorted = actions.iter().collect::<Vec<_>>();
-    actions_sorted.sort_by_key(|a| a.name);
+    actions_sorted.sort_by_key(|a| a.name.as_str());
 
     // Start the definition list with custom styling for better spacing
     output.push_str("<dl style=\"line-height: 1.8;\">\n");
@@ -664,7 +674,7 @@ fn generate_big_table_of_actions() -> String {
         output.push_str("<dd style=\"margin-left: 2em; margin-bottom: 1em;\">\n");
 
         // Add the description, escaping HTML if needed
-        if let Some(description) = action.docs {
+        if let Some(description) = action.docs.as_ref() {
             output.push_str(
                 &description
                     .replace("&", "&amp;")
@@ -674,7 +684,7 @@ fn generate_big_table_of_actions() -> String {
             output.push_str("<br>\n");
         }
         output.push_str("Keymap Name: <code>");
-        output.push_str(action.name);
+        output.push_str(&action.name);
         output.push_str("</code><br>\n");
         if !action.deprecated_aliases.is_empty() {
             output.push_str("Deprecated Alias(es): ");

crates/edit_prediction/Cargo.toml 🔗

@@ -11,7 +11,70 @@ workspace = true
 [lib]
 path = "src/edit_prediction.rs"
 
+[features]
+cli-support = []
+
 [dependencies]
+ai_onboarding.workspace = true
+anyhow.workspace = true
+arrayvec.workspace = true
+brotli.workspace = true
+buffer_diff.workspace = true
 client.workspace = true
+cloud_llm_client.workspace = true
+collections.workspace = true
+copilot.workspace = true
+db.workspace = true
+edit_prediction_types.workspace = true
+edit_prediction_context.workspace = true
+feature_flags.workspace = true
+fs.workspace = true
+futures.workspace = true
 gpui.workspace = true
+indoc.workspace = true
+itertools.workspace = true
 language.workspace = true
+language_model.workspace = true
+log.workspace = true
+lsp.workspace = true
+menu.workspace = true
+open_ai.workspace = true
+postage.workspace = true
+pretty_assertions.workspace = true
+project.workspace = true
+pulldown-cmark.workspace = true
+rand.workspace = true
+regex.workspace = true
+release_channel.workspace = true
+semver.workspace = true
+serde.workspace = true
+serde_json.workspace = true
+settings.workspace = true
+strum.workspace = true
+telemetry.workspace = true
+telemetry_events.workspace = true
+text.workspace = true
+thiserror.workspace = true
+time.workspace = true
+ui.workspace = true
+util.workspace = true
+uuid.workspace = true
+workspace.workspace = true
+worktree.workspace = true
+zed_actions.workspace = true
+zeta_prompt.workspace = true
+
+[dev-dependencies]
+clock = { workspace = true, features = ["test-support"] }
+cloud_api_types.workspace = true
+cloud_llm_client = { workspace = true, features = ["test-support"] }
+ctor.workspace = true
+gpui = { workspace = true, features = ["test-support"] }
+indoc.workspace = true
+language = { workspace = true, features = ["test-support"] }
+language_model = { workspace = true, features = ["test-support"] }
+lsp.workspace = true
+parking_lot.workspace = true
+project = { workspace = true, features = ["test-support"] }
+settings = { workspace = true, features = ["test-support"] }
+zlog.workspace = true

crates/edit_prediction/src/capture_example.rs 🔗

@@ -0,0 +1,375 @@
+use crate::{
+    EditPredictionStore, StoredEvent,
+    cursor_excerpt::editable_and_context_ranges_for_cursor_position, example_spec::ExampleSpec,
+};
+use anyhow::Result;
+use buffer_diff::BufferDiffSnapshot;
+use collections::HashMap;
+use gpui::{App, Entity, Task};
+use language::{Buffer, ToPoint as _};
+use project::Project;
+use std::{collections::hash_map, fmt::Write as _, path::Path, sync::Arc};
+use text::{BufferSnapshot as TextBufferSnapshot, ToOffset as _};
+
+pub fn capture_example(
+    project: Entity<Project>,
+    buffer: Entity<Buffer>,
+    cursor_anchor: language::Anchor,
+    last_event_is_expected_patch: bool,
+    cx: &mut App,
+) -> Option<Task<Result<ExampleSpec>>> {
+    let ep_store = EditPredictionStore::try_global(cx)?;
+    let snapshot = buffer.read(cx).snapshot();
+    let file = snapshot.file()?;
+    let worktree_id = file.worktree_id(cx);
+    let repository = project.read(cx).active_repository(cx)?;
+    let repository_snapshot = repository.read(cx).snapshot();
+    let worktree = project.read(cx).worktree_for_id(worktree_id, cx)?;
+    let cursor_path = worktree.read(cx).root_name().join(file.path());
+    if worktree.read(cx).abs_path() != repository_snapshot.work_directory_abs_path {
+        return None;
+    }
+
+    let repository_url = repository_snapshot
+        .remote_origin_url
+        .clone()
+        .or_else(|| repository_snapshot.remote_upstream_url.clone())?;
+    let revision = repository_snapshot.head_commit.as_ref()?.sha.to_string();
+
+    let mut events = ep_store.update(cx, |store, cx| {
+        store.edit_history_for_project_with_pause_split_last_event(&project, cx)
+    });
+
+    let git_store = project.read(cx).git_store().clone();
+
+    Some(cx.spawn(async move |mut cx| {
+        let snapshots_by_path = collect_snapshots(&project, &git_store, &events, &mut cx).await?;
+        let cursor_excerpt = cx
+            .background_executor()
+            .spawn(async move { compute_cursor_excerpt(&snapshot, cursor_anchor) })
+            .await;
+        let uncommitted_diff = cx
+            .background_executor()
+            .spawn(async move { compute_uncommitted_diff(snapshots_by_path) })
+            .await;
+
+        let mut edit_history = String::new();
+        let mut expected_patch = String::new();
+        if last_event_is_expected_patch {
+            if let Some(stored_event) = events.pop() {
+                zeta_prompt::write_event(&mut expected_patch, &stored_event.event);
+            }
+        }
+
+        for stored_event in &events {
+            zeta_prompt::write_event(&mut edit_history, &stored_event.event);
+            if !edit_history.ends_with('\n') {
+                edit_history.push('\n');
+            }
+        }
+
+        let name = generate_timestamp_name();
+
+        Ok(ExampleSpec {
+            name,
+            repository_url,
+            revision,
+            uncommitted_diff,
+            cursor_path: cursor_path.as_std_path().into(),
+            cursor_position: cursor_excerpt,
+            edit_history,
+            expected_patch,
+        })
+    }))
+}
+
+fn compute_cursor_excerpt(
+    snapshot: &language::BufferSnapshot,
+    cursor_anchor: language::Anchor,
+) -> String {
+    let cursor_point = cursor_anchor.to_point(snapshot);
+    let (_editable_range, context_range) =
+        editable_and_context_ranges_for_cursor_position(cursor_point, snapshot, 100, 50);
+
+    let context_start_offset = context_range.start.to_offset(snapshot);
+    let cursor_offset = cursor_anchor.to_offset(snapshot);
+    let cursor_offset_in_excerpt = cursor_offset.saturating_sub(context_start_offset);
+    let mut excerpt = snapshot.text_for_range(context_range).collect::<String>();
+    if cursor_offset_in_excerpt <= excerpt.len() {
+        excerpt.insert_str(cursor_offset_in_excerpt, zeta_prompt::CURSOR_MARKER);
+    }
+    excerpt
+}
+
+async fn collect_snapshots(
+    project: &Entity<Project>,
+    git_store: &Entity<project::git_store::GitStore>,
+    events: &[StoredEvent],
+    cx: &mut gpui::AsyncApp,
+) -> Result<HashMap<Arc<Path>, (TextBufferSnapshot, BufferDiffSnapshot)>> {
+    let mut snapshots_by_path = HashMap::default();
+    for stored_event in events {
+        let zeta_prompt::Event::BufferChange { path, .. } = stored_event.event.as_ref();
+        if let Some((project_path, full_path)) = project.read_with(cx, |project, cx| {
+            let project_path = project.find_project_path(path, cx)?;
+            let full_path = project
+                .worktree_for_id(project_path.worktree_id, cx)?
+                .read(cx)
+                .root_name()
+                .join(&project_path.path)
+                .as_std_path()
+                .into();
+            Some((project_path, full_path))
+        })? {
+            if let hash_map::Entry::Vacant(entry) = snapshots_by_path.entry(full_path) {
+                let buffer = project
+                    .update(cx, |project, cx| {
+                        project.open_buffer(project_path.clone(), cx)
+                    })?
+                    .await?;
+                let diff = git_store
+                    .update(cx, |git_store, cx| {
+                        git_store.open_uncommitted_diff(buffer.clone(), cx)
+                    })?
+                    .await?;
+                let diff_snapshot = diff.update(cx, |diff, cx| diff.snapshot(cx))?;
+                entry.insert((stored_event.old_snapshot.clone(), diff_snapshot));
+            }
+        }
+    }
+    Ok(snapshots_by_path)
+}
+
+fn compute_uncommitted_diff(
+    snapshots_by_path: HashMap<Arc<Path>, (TextBufferSnapshot, BufferDiffSnapshot)>,
+) -> String {
+    let mut uncommitted_diff = String::new();
+    for (full_path, (before_text, diff_snapshot)) in snapshots_by_path {
+        if let Some(head_text) = &diff_snapshot.base_text_string() {
+            let file_diff = language::unified_diff(head_text, &before_text.text());
+            if !file_diff.is_empty() {
+                let path_str = full_path.to_string_lossy();
+                writeln!(uncommitted_diff, "--- a/{path_str}").ok();
+                writeln!(uncommitted_diff, "+++ b/{path_str}").ok();
+                uncommitted_diff.push_str(&file_diff);
+                if !uncommitted_diff.ends_with('\n') {
+                    uncommitted_diff.push('\n');
+                }
+            }
+        }
+    }
+    uncommitted_diff
+}
+
+fn generate_timestamp_name() -> String {
+    let format = time::format_description::parse("[year]-[month]-[day] [hour]:[minute]:[second]");
+    match format {
+        Ok(format) => {
+            let now = time::OffsetDateTime::now_local()
+                .unwrap_or_else(|_| time::OffsetDateTime::now_utc());
+            now.format(&format)
+                .unwrap_or_else(|_| "unknown-time".to_string())
+        }
+        Err(_) => "unknown-time".to_string(),
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use client::{Client, UserStore};
+    use clock::FakeSystemClock;
+    use gpui::{AppContext as _, TestAppContext, http_client::FakeHttpClient};
+    use indoc::indoc;
+    use language::{Anchor, Point};
+    use project::{FakeFs, Project};
+    use serde_json::json;
+    use settings::SettingsStore;
+    use std::path::Path;
+
+    #[gpui::test]
+    async fn test_capture_example(cx: &mut TestAppContext) {
+        init_test(cx);
+        let fs = FakeFs::new(cx.executor());
+
+        let committed_contents = indoc! {"
+            fn main() {
+                one();
+                two();
+                three();
+                four();
+                five();
+                six();
+                seven();
+                eight();
+                nine();
+            }
+        "};
+
+        let disk_contents = indoc! {"
+            fn main() {
+                // comment 1
+                one();
+                two();
+                three();
+                four();
+                five();
+                six();
+                seven();
+                eight();
+                // comment 2
+                nine();
+            }
+        "};
+
+        fs.insert_tree(
+            "/project",
+            json!({
+                ".git": {},
+                "src": {
+                    "main.rs": disk_contents,
+                }
+            }),
+        )
+        .await;
+
+        fs.set_head_for_repo(
+            Path::new("/project/.git"),
+            &[("src/main.rs", committed_contents.to_string())],
+            "abc123def456",
+        );
+        fs.set_remote_for_repo(
+            Path::new("/project/.git"),
+            "origin",
+            "https://github.com/test/repo.git",
+        );
+
+        let project = Project::test(fs.clone(), ["/project".as_ref()], cx).await;
+
+        let buffer = project
+            .update(cx, |project, cx| {
+                project.open_local_buffer("/project/src/main.rs", cx)
+            })
+            .await
+            .unwrap();
+
+        let ep_store = cx.read(|cx| EditPredictionStore::try_global(cx).unwrap());
+        ep_store.update(cx, |ep_store, cx| {
+            ep_store.register_buffer(&buffer, &project, cx)
+        });
+        cx.run_until_parked();
+
+        buffer.update(cx, |buffer, cx| {
+            let point = Point::new(6, 0);
+            buffer.edit([(point..point, "    // comment 3\n")], None, cx);
+            let point = Point::new(4, 0);
+            buffer.edit([(point..point, "    // comment 4\n")], None, cx);
+
+            pretty_assertions::assert_eq!(
+                buffer.text(),
+                indoc! {"
+                    fn main() {
+                        // comment 1
+                        one();
+                        two();
+                        // comment 4
+                        three();
+                        four();
+                        // comment 3
+                        five();
+                        six();
+                        seven();
+                        eight();
+                        // comment 2
+                        nine();
+                    }
+                "}
+            );
+        });
+        cx.run_until_parked();
+
+        let mut example = cx
+            .update(|cx| {
+                capture_example(project.clone(), buffer.clone(), Anchor::MIN, false, cx).unwrap()
+            })
+            .await
+            .unwrap();
+        example.name = "test".to_string();
+
+        pretty_assertions::assert_eq!(
+            example,
+            ExampleSpec {
+                name: "test".to_string(),
+                repository_url: "https://github.com/test/repo.git".to_string(),
+                revision: "abc123def456".to_string(),
+                uncommitted_diff: indoc! {"
+                    --- a/project/src/main.rs
+                    +++ b/project/src/main.rs
+                    @@ -1,4 +1,5 @@
+                     fn main() {
+                    +    // comment 1
+                         one();
+                         two();
+                         three();
+                    @@ -7,5 +8,6 @@
+                         six();
+                         seven();
+                         eight();
+                    +    // comment 2
+                         nine();
+                     }
+                "}
+                .to_string(),
+                cursor_path: Path::new("project/src/main.rs").into(),
+                cursor_position: indoc! {"
+                    <|user_cursor|>fn main() {
+                        // comment 1
+                        one();
+                        two();
+                        // comment 4
+                        three();
+                        four();
+                        // comment 3
+                        five();
+                        six();
+                        seven();
+                        eight();
+                        // comment 2
+                        nine();
+                    }
+                "}
+                .to_string(),
+                edit_history: indoc! {"
+                    --- a/project/src/main.rs
+                    +++ b/project/src/main.rs
+                    @@ -2,8 +2,10 @@
+                         // comment 1
+                         one();
+                         two();
+                    +    // comment 4
+                         three();
+                         four();
+                    +    // comment 3
+                         five();
+                         six();
+                         seven();
+                "}
+                .to_string(),
+                expected_patch: "".to_string(),
+            }
+        );
+    }
+
+    fn init_test(cx: &mut TestAppContext) {
+        cx.update(|cx| {
+            let settings_store = SettingsStore::test(cx);
+            cx.set_global(settings_store);
+            zlog::init_test();
+            let http_client = FakeHttpClient::with_404_response();
+            let client = Client::new(Arc::new(FakeSystemClock::new()), http_client, cx);
+            language_model::init(client.clone(), cx);
+            let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
+            EditPredictionStore::global(&client, &user_store, cx);
+        })
+    }
+}

crates/edit_prediction/src/cursor_excerpt.rs 🔗

@@ -0,0 +1,78 @@
+use language::{BufferSnapshot, Point};
+use std::ops::Range;
+
+pub fn editable_and_context_ranges_for_cursor_position(
+    position: Point,
+    snapshot: &BufferSnapshot,
+    editable_region_token_limit: usize,
+    context_token_limit: usize,
+) -> (Range<Point>, Range<Point>) {
+    let mut scope_range = position..position;
+    let mut remaining_edit_tokens = editable_region_token_limit;
+
+    while let Some(parent) = snapshot.syntax_ancestor(scope_range.clone()) {
+        let parent_tokens = guess_token_count(parent.byte_range().len());
+        let parent_point_range = Point::new(
+            parent.start_position().row as u32,
+            parent.start_position().column as u32,
+        )
+            ..Point::new(
+                parent.end_position().row as u32,
+                parent.end_position().column as u32,
+            );
+        if parent_point_range == scope_range {
+            break;
+        } else if parent_tokens <= editable_region_token_limit {
+            scope_range = parent_point_range;
+            remaining_edit_tokens = editable_region_token_limit - parent_tokens;
+        } else {
+            break;
+        }
+    }
+
+    let editable_range = expand_range(snapshot, scope_range, remaining_edit_tokens);
+    let context_range = expand_range(snapshot, editable_range.clone(), context_token_limit);
+    (editable_range, context_range)
+}
+
+fn expand_range(
+    snapshot: &BufferSnapshot,
+    range: Range<Point>,
+    mut remaining_tokens: usize,
+) -> Range<Point> {
+    let mut expanded_range = range;
+    expanded_range.start.column = 0;
+    expanded_range.end.column = snapshot.line_len(expanded_range.end.row);
+    loop {
+        let mut expanded = false;
+
+        if remaining_tokens > 0 && expanded_range.start.row > 0 {
+            expanded_range.start.row -= 1;
+            let line_tokens =
+                guess_token_count(snapshot.line_len(expanded_range.start.row) as usize);
+            remaining_tokens = remaining_tokens.saturating_sub(line_tokens);
+            expanded = true;
+        }
+
+        if remaining_tokens > 0 && expanded_range.end.row < snapshot.max_point().row {
+            expanded_range.end.row += 1;
+            expanded_range.end.column = snapshot.line_len(expanded_range.end.row);
+            let line_tokens = guess_token_count(expanded_range.end.column as usize);
+            remaining_tokens = remaining_tokens.saturating_sub(line_tokens);
+            expanded = true;
+        }
+
+        if !expanded {
+            break;
+        }
+    }
+    expanded_range
+}
+
+/// Typical number of string bytes per token for the purposes of limiting model input. This is
+/// intentionally low to err on the side of underestimating limits.
+pub(crate) const BYTES_PER_TOKEN_GUESS: usize = 3;
+
+pub fn guess_token_count(bytes: usize) -> usize {
+    bytes / BYTES_PER_TOKEN_GUESS
+}

crates/edit_prediction/src/edit_prediction.rs 🔗

@@ -1,298 +1,2192 @@
-use std::{ops::Range, sync::Arc};
+use anyhow::Result;
+use arrayvec::ArrayVec;
+use client::{Client, EditPredictionUsage, UserStore};
+use cloud_llm_client::predict_edits_v3::{self, PromptFormat};
+use cloud_llm_client::{
+    AcceptEditPredictionBody, EXPIRED_LLM_TOKEN_HEADER_NAME, EditPredictionRejectReason,
+    EditPredictionRejection, MAX_EDIT_PREDICTION_REJECTIONS_PER_REQUEST,
+    MINIMUM_REQUIRED_VERSION_HEADER_NAME, PredictEditsRequestTrigger, RejectEditPredictionsBodyRef,
+    ZED_VERSION_HEADER_NAME,
+};
+use collections::{HashMap, HashSet};
+use db::kvp::{Dismissable, KEY_VALUE_STORE};
+use edit_prediction_context::EditPredictionExcerptOptions;
+use edit_prediction_context::{RelatedExcerptStore, RelatedExcerptStoreEvent, RelatedFile};
+use feature_flags::{FeatureFlag, FeatureFlagAppExt as _};
+use futures::{
+    AsyncReadExt as _, FutureExt as _, StreamExt as _,
+    channel::mpsc::{self, UnboundedReceiver},
+    select_biased,
+};
+use gpui::BackgroundExecutor;
+use gpui::http_client::Url;
+use gpui::{
+    App, AsyncApp, Entity, EntityId, Global, SharedString, Subscription, Task, WeakEntity, actions,
+    http_client::{self, AsyncBody, Method},
+    prelude::*,
+};
+use language::language_settings::all_language_settings;
+use language::{Anchor, Buffer, File, Point, TextBufferSnapshot, ToPoint};
+use language::{BufferSnapshot, OffsetRangeExt};
+use language_model::{LlmApiToken, RefreshLlmTokenListener};
+use project::{Project, ProjectPath, WorktreeId};
+use release_channel::AppVersion;
+use semver::Version;
+use serde::de::DeserializeOwned;
+use settings::{EditPredictionProvider, SettingsStore, update_settings_file};
+use std::collections::{VecDeque, hash_map};
+use text::Edit;
+use workspace::Workspace;
 
-use client::EditPredictionUsage;
-use gpui::{App, Context, Entity, SharedString};
-use language::{Anchor, Buffer, BufferSnapshot, OffsetRangeExt};
+use std::ops::Range;
+use std::path::Path;
+use std::rc::Rc;
+use std::str::FromStr as _;
+use std::sync::{Arc, LazyLock};
+use std::time::{Duration, Instant};
+use std::{env, mem};
+use thiserror::Error;
+use util::{RangeExt as _, ResultExt as _};
+use workspace::notifications::{ErrorMessagePrompt, NotificationId, show_app_notification};
 
-// TODO: Find a better home for `Direction`.
-//
-// This should live in an ancestor crate of `editor` and `edit_prediction`,
-// but at time of writing there isn't an obvious spot.
-#[derive(Copy, Clone, PartialEq, Eq)]
-pub enum Direction {
-    Prev,
-    Next,
+pub mod cursor_excerpt;
+pub mod example_spec;
+mod license_detection;
+pub mod mercury;
+mod onboarding_modal;
+pub mod open_ai_response;
+mod prediction;
+pub mod sweep_ai;
+
+pub mod udiff;
+
+mod capture_example;
+mod zed_edit_prediction_delegate;
+pub mod zeta1;
+pub mod zeta2;
+
+#[cfg(test)]
+mod edit_prediction_tests;
+
+use crate::license_detection::LicenseDetectionWatcher;
+use crate::mercury::Mercury;
+use crate::onboarding_modal::ZedPredictModal;
+pub use crate::prediction::EditPrediction;
+pub use crate::prediction::EditPredictionId;
+use crate::prediction::EditPredictionResult;
+pub use crate::sweep_ai::SweepAi;
+pub use capture_example::capture_example;
+pub use language_model::ApiKeyState;
+pub use telemetry_events::EditPredictionRating;
+pub use zed_edit_prediction_delegate::ZedEditPredictionDelegate;
+
+actions!(
+    edit_prediction,
+    [
+        /// Resets the edit prediction onboarding state.
+        ResetOnboarding,
+        /// Clears the edit prediction history.
+        ClearHistory,
+    ]
+);
+
+/// Maximum number of events to track.
+const EVENT_COUNT_MAX: usize = 6;
+const CHANGE_GROUPING_LINE_SPAN: u32 = 8;
+const LAST_CHANGE_GROUPING_TIME: Duration = Duration::from_secs(1);
+const ZED_PREDICT_DATA_COLLECTION_CHOICE: &str = "zed_predict_data_collection_choice";
+const REJECT_REQUEST_DEBOUNCE: Duration = Duration::from_secs(15);
+
+pub struct SweepFeatureFlag;
+
+impl FeatureFlag for SweepFeatureFlag {
+    const NAME: &str = "sweep-ai";
 }
 
-#[derive(Clone)]
-pub enum EditPrediction {
-    /// Edits within the buffer that requested the prediction
-    Local {
-        id: Option<SharedString>,
-        edits: Vec<(Range<language::Anchor>, Arc<str>)>,
-        edit_preview: Option<language::EditPreview>,
-    },
-    /// Jump to a different file from the one that requested the prediction
-    Jump {
-        id: Option<SharedString>,
-        snapshot: language::BufferSnapshot,
-        target: language::Anchor,
+pub struct MercuryFeatureFlag;
+
+impl FeatureFlag for MercuryFeatureFlag {
+    const NAME: &str = "mercury";
+}
+
+pub const DEFAULT_OPTIONS: ZetaOptions = ZetaOptions {
+    context: EditPredictionExcerptOptions {
+        max_bytes: 512,
+        min_bytes: 128,
+        target_before_cursor_over_total_bytes: 0.5,
     },
+    prompt_format: PromptFormat::DEFAULT,
+};
+
+static USE_OLLAMA: LazyLock<bool> =
+    LazyLock::new(|| env::var("ZED_ZETA2_OLLAMA").is_ok_and(|var| !var.is_empty()));
+
+static EDIT_PREDICTIONS_MODEL_ID: LazyLock<String> = LazyLock::new(|| {
+    match env::var("ZED_ZETA2_MODEL").as_deref() {
+        Ok("zeta2-exp") => "4w5n28vw", // Fine-tuned model @ Baseten
+        Ok(model) => model,
+        Err(_) if *USE_OLLAMA => "qwen3-coder:30b",
+        Err(_) => "yqvev8r3", // Vanilla qwen3-coder @ Baseten
+    }
+    .to_string()
+});
+
+pub struct Zeta2FeatureFlag;
+
+impl FeatureFlag for Zeta2FeatureFlag {
+    const NAME: &'static str = "zeta2";
+
+    fn enabled_for_staff() -> bool {
+        true
+    }
+}
+
+#[derive(Clone)]
+struct EditPredictionStoreGlobal(Entity<EditPredictionStore>);
+
+impl Global for EditPredictionStoreGlobal {}
+
+pub struct EditPredictionStore {
+    client: Arc<Client>,
+    user_store: Entity<UserStore>,
+    llm_token: LlmApiToken,
+    _llm_token_subscription: Subscription,
+    projects: HashMap<EntityId, ProjectState>,
+    use_context: bool,
+    options: ZetaOptions,
+    update_required: bool,
+    #[cfg(feature = "cli-support")]
+    eval_cache: Option<Arc<dyn EvalCache>>,
+    edit_prediction_model: EditPredictionModel,
+    pub sweep_ai: SweepAi,
+    pub mercury: Mercury,
+    data_collection_choice: DataCollectionChoice,
+    reject_predictions_tx: mpsc::UnboundedSender<EditPredictionRejection>,
+    shown_predictions: VecDeque<EditPrediction>,
+    rated_predictions: HashSet<EditPredictionId>,
+    custom_predict_edits_url: Option<Arc<Url>>,
+}
+
+#[derive(Copy, Clone, Default, PartialEq, Eq)]
+pub enum EditPredictionModel {
+    #[default]
+    Zeta1,
+    Zeta2,
+    Sweep,
+    Mercury,
+}
+
+pub struct EditPredictionModelInput {
+    project: Entity<Project>,
+    buffer: Entity<Buffer>,
+    snapshot: BufferSnapshot,
+    position: Anchor,
+    events: Vec<Arc<zeta_prompt::Event>>,
+    related_files: Arc<[RelatedFile]>,
+    recent_paths: VecDeque<ProjectPath>,
+    trigger: PredictEditsRequestTrigger,
+    diagnostic_search_range: Range<Point>,
+    debug_tx: Option<mpsc::UnboundedSender<DebugEvent>>,
+}
+
+#[derive(Debug, Clone, PartialEq)]
+pub struct ZetaOptions {
+    pub context: EditPredictionExcerptOptions,
+    pub prompt_format: predict_edits_v3::PromptFormat,
 }
 
-pub enum DataCollectionState {
-    /// The provider doesn't support data collection.
-    Unsupported,
-    /// Data collection is enabled.
-    Enabled { is_project_open_source: bool },
-    /// Data collection is disabled or unanswered.
-    Disabled { is_project_open_source: bool },
+#[derive(Debug)]
+pub enum DebugEvent {
+    ContextRetrievalStarted(ContextRetrievalStartedDebugEvent),
+    ContextRetrievalFinished(ContextRetrievalFinishedDebugEvent),
+    EditPredictionStarted(EditPredictionStartedDebugEvent),
+    EditPredictionFinished(EditPredictionFinishedDebugEvent),
 }
 
-impl DataCollectionState {
-    pub fn is_supported(&self) -> bool {
-        !matches!(self, DataCollectionState::Unsupported)
+#[derive(Debug)]
+pub struct ContextRetrievalStartedDebugEvent {
+    pub project_entity_id: EntityId,
+    pub timestamp: Instant,
+    pub search_prompt: String,
+}
+
+#[derive(Debug)]
+pub struct ContextRetrievalFinishedDebugEvent {
+    pub project_entity_id: EntityId,
+    pub timestamp: Instant,
+    pub metadata: Vec<(&'static str, SharedString)>,
+}
+
+#[derive(Debug)]
+pub struct EditPredictionStartedDebugEvent {
+    pub buffer: WeakEntity<Buffer>,
+    pub position: Anchor,
+    pub prompt: Option<String>,
+}
+
+#[derive(Debug)]
+pub struct EditPredictionFinishedDebugEvent {
+    pub buffer: WeakEntity<Buffer>,
+    pub position: Anchor,
+    pub model_output: Option<String>,
+}
+
+pub type RequestDebugInfo = predict_edits_v3::DebugInfo;
+
+/// An event with associated metadata for reconstructing buffer state.
+#[derive(Clone)]
+pub struct StoredEvent {
+    pub event: Arc<zeta_prompt::Event>,
+    pub old_snapshot: TextBufferSnapshot,
+}
+
+struct ProjectState {
+    events: VecDeque<StoredEvent>,
+    last_event: Option<LastEvent>,
+    recent_paths: VecDeque<ProjectPath>,
+    registered_buffers: HashMap<gpui::EntityId, RegisteredBuffer>,
+    current_prediction: Option<CurrentEditPrediction>,
+    next_pending_prediction_id: usize,
+    pending_predictions: ArrayVec<PendingPrediction, 2>,
+    debug_tx: Option<mpsc::UnboundedSender<DebugEvent>>,
+    last_prediction_refresh: Option<(EntityId, Instant)>,
+    cancelled_predictions: HashSet<usize>,
+    context: Entity<RelatedExcerptStore>,
+    license_detection_watchers: HashMap<WorktreeId, Rc<LicenseDetectionWatcher>>,
+    _subscription: gpui::Subscription,
+}
+
+impl ProjectState {
+    pub fn events(&self, cx: &App) -> Vec<StoredEvent> {
+        self.events
+            .iter()
+            .cloned()
+            .chain(
+                self.last_event
+                    .as_ref()
+                    .and_then(|event| event.finalize(&self.license_detection_watchers, cx)),
+            )
+            .collect()
     }
 
-    pub fn is_enabled(&self) -> bool {
-        matches!(self, DataCollectionState::Enabled { .. })
+    pub fn events_split_by_pause(&self, cx: &App) -> Vec<StoredEvent> {
+        self.events
+            .iter()
+            .cloned()
+            .chain(self.last_event.as_ref().iter().flat_map(|event| {
+                let (one, two) = event.split_by_pause();
+                let one = one.finalize(&self.license_detection_watchers, cx);
+                let two = two.and_then(|two| two.finalize(&self.license_detection_watchers, cx));
+                one.into_iter().chain(two)
+            }))
+            .collect()
     }
 
-    pub fn is_project_open_source(&self) -> bool {
+    fn cancel_pending_prediction(
+        &mut self,
+        pending_prediction: PendingPrediction,
+        cx: &mut Context<EditPredictionStore>,
+    ) {
+        self.cancelled_predictions.insert(pending_prediction.id);
+
+        cx.spawn(async move |this, cx| {
+            let Some(prediction_id) = pending_prediction.task.await else {
+                return;
+            };
+
+            this.update(cx, |this, _cx| {
+                this.reject_prediction(prediction_id, EditPredictionRejectReason::Canceled, false);
+            })
+            .ok();
+        })
+        .detach()
+    }
+
+    fn active_buffer(
+        &self,
+        project: &Entity<Project>,
+        cx: &App,
+    ) -> Option<(Entity<Buffer>, Option<Anchor>)> {
+        let project = project.read(cx);
+        let active_path = project.path_for_entry(project.active_entry()?, cx)?;
+        let active_buffer = project.buffer_store().read(cx).get_by_path(&active_path)?;
+        let registered_buffer = self.registered_buffers.get(&active_buffer.entity_id())?;
+        Some((active_buffer, registered_buffer.last_position))
+    }
+}
+
+#[derive(Debug, Clone)]
+struct CurrentEditPrediction {
+    pub requested_by: PredictionRequestedBy,
+    pub prediction: EditPrediction,
+    pub was_shown: bool,
+}
+
+impl CurrentEditPrediction {
+    fn should_replace_prediction(&self, old_prediction: &Self, cx: &App) -> bool {
+        let Some(new_edits) = self
+            .prediction
+            .interpolate(&self.prediction.buffer.read(cx))
+        else {
+            return false;
+        };
+
+        if self.prediction.buffer != old_prediction.prediction.buffer {
+            return true;
+        }
+
+        let Some(old_edits) = old_prediction
+            .prediction
+            .interpolate(&old_prediction.prediction.buffer.read(cx))
+        else {
+            return true;
+        };
+
+        let requested_by_buffer_id = self.requested_by.buffer_id();
+
+        // This reduces the occurrence of UI thrash from replacing edits
+        //
+        // TODO: This is fairly arbitrary - should have a more general heuristic that handles multiple edits.
+        if requested_by_buffer_id == Some(self.prediction.buffer.entity_id())
+            && requested_by_buffer_id == Some(old_prediction.prediction.buffer.entity_id())
+            && old_edits.len() == 1
+            && new_edits.len() == 1
+        {
+            let (old_range, old_text) = &old_edits[0];
+            let (new_range, new_text) = &new_edits[0];
+            new_range == old_range && new_text.starts_with(old_text.as_ref())
+        } else {
+            true
+        }
+    }
+}
+
+#[derive(Debug, Clone)]
+enum PredictionRequestedBy {
+    DiagnosticsUpdate,
+    Buffer(EntityId),
+}
+
+impl PredictionRequestedBy {
+    pub fn buffer_id(&self) -> Option<EntityId> {
         match self {
-            Self::Enabled {
-                is_project_open_source,
-            }
-            | Self::Disabled {
-                is_project_open_source,
-            } => *is_project_open_source,
-            _ => false,
+            PredictionRequestedBy::DiagnosticsUpdate => None,
+            PredictionRequestedBy::Buffer(buffer_id) => Some(*buffer_id),
         }
     }
 }
 
-pub trait EditPredictionProvider: 'static + Sized {
-    fn name() -> &'static str;
-    fn display_name() -> &'static str;
-    fn show_completions_in_menu() -> bool;
-    fn show_tab_accept_marker() -> bool {
-        false
+#[derive(Debug)]
+struct PendingPrediction {
+    id: usize,
+    task: Task<Option<EditPredictionId>>,
+}
+
+/// A prediction from the perspective of a buffer.
+#[derive(Debug)]
+enum BufferEditPrediction<'a> {
+    Local { prediction: &'a EditPrediction },
+    Jump { prediction: &'a EditPrediction },
+}
+
+#[cfg(test)]
+impl std::ops::Deref for BufferEditPrediction<'_> {
+    type Target = EditPrediction;
+
+    fn deref(&self) -> &Self::Target {
+        match self {
+            BufferEditPrediction::Local { prediction } => prediction,
+            BufferEditPrediction::Jump { prediction } => prediction,
+        }
     }
-    fn supports_jump_to_edit() -> bool {
-        true
+}
+
+struct RegisteredBuffer {
+    file: Option<Arc<dyn File>>,
+    snapshot: TextBufferSnapshot,
+    last_position: Option<Anchor>,
+    _subscriptions: [gpui::Subscription; 2],
+}
+
+#[derive(Clone)]
+struct LastEvent {
+    old_snapshot: TextBufferSnapshot,
+    new_snapshot: TextBufferSnapshot,
+    old_file: Option<Arc<dyn File>>,
+    new_file: Option<Arc<dyn File>>,
+    end_edit_anchor: Option<Anchor>,
+    snapshot_after_last_editing_pause: Option<TextBufferSnapshot>,
+    last_edit_time: Option<Instant>,
+}
+
+impl LastEvent {
+    pub fn finalize(
+        &self,
+        license_detection_watchers: &HashMap<WorktreeId, Rc<LicenseDetectionWatcher>>,
+        cx: &App,
+    ) -> Option<StoredEvent> {
+        let path = buffer_path_with_id_fallback(self.new_file.as_ref(), &self.new_snapshot, cx);
+        let old_path = buffer_path_with_id_fallback(self.old_file.as_ref(), &self.old_snapshot, cx);
+
+        let in_open_source_repo =
+            [self.new_file.as_ref(), self.old_file.as_ref()]
+                .iter()
+                .all(|file| {
+                    file.is_some_and(|file| {
+                        license_detection_watchers
+                            .get(&file.worktree_id(cx))
+                            .is_some_and(|watcher| watcher.is_project_open_source())
+                    })
+                });
+
+        let diff = compute_diff_between_snapshots(&self.old_snapshot, &self.new_snapshot)?;
+
+        if path == old_path && diff.is_empty() {
+            None
+        } else {
+            Some(StoredEvent {
+                event: Arc::new(zeta_prompt::Event::BufferChange {
+                    old_path,
+                    path,
+                    diff,
+                    in_open_source_repo,
+                    // TODO: Actually detect if this edit was predicted or not
+                    predicted: false,
+                }),
+                old_snapshot: self.old_snapshot.clone(),
+            })
+        }
+    }
+
+    pub fn split_by_pause(&self) -> (LastEvent, Option<LastEvent>) {
+        let Some(boundary_snapshot) = self.snapshot_after_last_editing_pause.as_ref() else {
+            return (self.clone(), None);
+        };
+
+        let before = LastEvent {
+            old_snapshot: self.old_snapshot.clone(),
+            new_snapshot: boundary_snapshot.clone(),
+            old_file: self.old_file.clone(),
+            new_file: self.new_file.clone(),
+            end_edit_anchor: self.end_edit_anchor,
+            snapshot_after_last_editing_pause: None,
+            last_edit_time: self.last_edit_time,
+        };
+
+        let after = LastEvent {
+            old_snapshot: boundary_snapshot.clone(),
+            new_snapshot: self.new_snapshot.clone(),
+            old_file: self.old_file.clone(),
+            new_file: self.new_file.clone(),
+            end_edit_anchor: self.end_edit_anchor,
+            snapshot_after_last_editing_pause: None,
+            last_edit_time: self.last_edit_time,
+        };
+
+        (before, Some(after))
     }
+}
+
+pub(crate) fn compute_diff_between_snapshots(
+    old_snapshot: &TextBufferSnapshot,
+    new_snapshot: &TextBufferSnapshot,
+) -> Option<String> {
+    let edits: Vec<Edit<usize>> = new_snapshot
+        .edits_since::<usize>(&old_snapshot.version)
+        .collect();
+
+    let (first_edit, last_edit) = edits.first().zip(edits.last())?;
+
+    let old_start_point = old_snapshot.offset_to_point(first_edit.old.start);
+    let old_end_point = old_snapshot.offset_to_point(last_edit.old.end);
+    let new_start_point = new_snapshot.offset_to_point(first_edit.new.start);
+    let new_end_point = new_snapshot.offset_to_point(last_edit.new.end);
+
+    const CONTEXT_LINES: u32 = 3;
+
+    let old_context_start_row = old_start_point.row.saturating_sub(CONTEXT_LINES);
+    let new_context_start_row = new_start_point.row.saturating_sub(CONTEXT_LINES);
+    let old_context_end_row =
+        (old_end_point.row + 1 + CONTEXT_LINES).min(old_snapshot.max_point().row);
+    let new_context_end_row =
+        (new_end_point.row + 1 + CONTEXT_LINES).min(new_snapshot.max_point().row);
+
+    let old_start_line_offset = old_snapshot.point_to_offset(Point::new(old_context_start_row, 0));
+    let new_start_line_offset = new_snapshot.point_to_offset(Point::new(new_context_start_row, 0));
+    let old_end_line_offset = old_snapshot
+        .point_to_offset(Point::new(old_context_end_row + 1, 0).min(old_snapshot.max_point()));
+    let new_end_line_offset = new_snapshot
+        .point_to_offset(Point::new(new_context_end_row + 1, 0).min(new_snapshot.max_point()));
+    let old_edit_range = old_start_line_offset..old_end_line_offset;
+    let new_edit_range = new_start_line_offset..new_end_line_offset;
+
+    let old_region_text: String = old_snapshot.text_for_range(old_edit_range).collect();
+    let new_region_text: String = new_snapshot.text_for_range(new_edit_range).collect();
+
+    let diff = language::unified_diff_with_offsets(
+        &old_region_text,
+        &new_region_text,
+        old_context_start_row,
+        new_context_start_row,
+    );
+
+    Some(diff)
+}
 
-    fn data_collection_state(&self, _cx: &App) -> DataCollectionState {
-        DataCollectionState::Unsupported
+fn buffer_path_with_id_fallback(
+    file: Option<&Arc<dyn File>>,
+    snapshot: &TextBufferSnapshot,
+    cx: &App,
+) -> Arc<Path> {
+    if let Some(file) = file {
+        file.full_path(cx).into()
+    } else {
+        Path::new(&format!("untitled-{}", snapshot.remote_id())).into()
+    }
+}
+
+impl EditPredictionStore {
+    pub fn try_global(cx: &App) -> Option<Entity<Self>> {
+        cx.try_global::<EditPredictionStoreGlobal>()
+            .map(|global| global.0.clone())
     }
 
-    fn usage(&self, _cx: &App) -> Option<EditPredictionUsage> {
-        None
+    pub fn global(
+        client: &Arc<Client>,
+        user_store: &Entity<UserStore>,
+        cx: &mut App,
+    ) -> Entity<Self> {
+        cx.try_global::<EditPredictionStoreGlobal>()
+            .map(|global| global.0.clone())
+            .unwrap_or_else(|| {
+                let ep_store = cx.new(|cx| Self::new(client.clone(), user_store.clone(), cx));
+                cx.set_global(EditPredictionStoreGlobal(ep_store.clone()));
+                ep_store
+            })
     }
 
-    fn toggle_data_collection(&mut self, _cx: &mut App) {}
-    fn is_enabled(
+    pub fn new(client: Arc<Client>, user_store: Entity<UserStore>, cx: &mut Context<Self>) -> Self {
+        let refresh_llm_token_listener = RefreshLlmTokenListener::global(cx);
+        let data_collection_choice = Self::load_data_collection_choice();
+
+        let llm_token = LlmApiToken::default();
+
+        let (reject_tx, reject_rx) = mpsc::unbounded();
+        cx.background_spawn({
+            let client = client.clone();
+            let llm_token = llm_token.clone();
+            let app_version = AppVersion::global(cx);
+            let background_executor = cx.background_executor().clone();
+            async move {
+                Self::handle_rejected_predictions(
+                    reject_rx,
+                    client,
+                    llm_token,
+                    app_version,
+                    background_executor,
+                )
+                .await
+            }
+        })
+        .detach();
+
+        let mut this = Self {
+            projects: HashMap::default(),
+            client,
+            user_store,
+            options: DEFAULT_OPTIONS,
+            use_context: false,
+            llm_token,
+            _llm_token_subscription: cx.subscribe(
+                &refresh_llm_token_listener,
+                |this, _listener, _event, cx| {
+                    let client = this.client.clone();
+                    let llm_token = this.llm_token.clone();
+                    cx.spawn(async move |_this, _cx| {
+                        llm_token.refresh(&client).await?;
+                        anyhow::Ok(())
+                    })
+                    .detach_and_log_err(cx);
+                },
+            ),
+            update_required: false,
+            #[cfg(feature = "cli-support")]
+            eval_cache: None,
+            edit_prediction_model: EditPredictionModel::Zeta2,
+            sweep_ai: SweepAi::new(cx),
+            mercury: Mercury::new(cx),
+            data_collection_choice,
+            reject_predictions_tx: reject_tx,
+            rated_predictions: Default::default(),
+            shown_predictions: Default::default(),
+            custom_predict_edits_url: match env::var("ZED_PREDICT_EDITS_URL") {
+                Ok(custom_url) => Url::parse(&custom_url).log_err().map(Into::into),
+                Err(_) => {
+                    if *USE_OLLAMA {
+                        Some(
+                            Url::parse("http://localhost:11434/v1/chat/completions")
+                                .unwrap()
+                                .into(),
+                        )
+                    } else {
+                        None
+                    }
+                }
+            },
+        };
+
+        this.configure_context_retrieval(cx);
+        let weak_this = cx.weak_entity();
+        cx.on_flags_ready(move |_, cx| {
+            weak_this
+                .update(cx, |this, cx| this.configure_context_retrieval(cx))
+                .ok();
+        })
+        .detach();
+        cx.observe_global::<SettingsStore>(|this, cx| {
+            this.configure_context_retrieval(cx);
+        })
+        .detach();
+
+        this
+    }
+
+    #[cfg(test)]
+    pub fn set_custom_predict_edits_url(&mut self, url: Url) {
+        self.custom_predict_edits_url = Some(url.into());
+    }
+
+    pub fn set_edit_prediction_model(&mut self, model: EditPredictionModel) {
+        self.edit_prediction_model = model;
+    }
+
+    pub fn has_sweep_api_token(&self, cx: &App) -> bool {
+        self.sweep_ai.api_token.read(cx).has_key()
+    }
+
+    pub fn has_mercury_api_token(&self, cx: &App) -> bool {
+        self.mercury.api_token.read(cx).has_key()
+    }
+
+    #[cfg(feature = "cli-support")]
+    pub fn with_eval_cache(&mut self, cache: Arc<dyn EvalCache>) {
+        self.eval_cache = Some(cache);
+    }
+
+    pub fn options(&self) -> &ZetaOptions {
+        &self.options
+    }
+
+    pub fn set_options(&mut self, options: ZetaOptions) {
+        self.options = options;
+    }
+
+    pub fn set_use_context(&mut self, use_context: bool) {
+        self.use_context = use_context;
+    }
+
+    pub fn clear_history(&mut self) {
+        for project_state in self.projects.values_mut() {
+            project_state.events.clear();
+        }
+    }
+
+    pub fn clear_history_for_project(&mut self, project: &Entity<Project>) {
+        if let Some(project_state) = self.projects.get_mut(&project.entity_id()) {
+            project_state.events.clear();
+        }
+    }
+
+    pub fn edit_history_for_project(
         &self,
-        buffer: &Entity<Buffer>,
-        cursor_position: language::Anchor,
+        project: &Entity<Project>,
         cx: &App,
-    ) -> bool;
-    fn is_refreshing(&self, cx: &App) -> bool;
-    fn refresh(
+    ) -> Vec<StoredEvent> {
+        self.projects
+            .get(&project.entity_id())
+            .map(|project_state| project_state.events(cx))
+            .unwrap_or_default()
+    }
+
+    pub fn edit_history_for_project_with_pause_split_last_event(
+        &self,
+        project: &Entity<Project>,
+        cx: &App,
+    ) -> Vec<StoredEvent> {
+        self.projects
+            .get(&project.entity_id())
+            .map(|project_state| project_state.events_split_by_pause(cx))
+            .unwrap_or_default()
+    }
+
+    pub fn context_for_project<'a>(
+        &'a self,
+        project: &Entity<Project>,
+        cx: &'a App,
+    ) -> Arc<[RelatedFile]> {
+        self.projects
+            .get(&project.entity_id())
+            .map(|project| project.context.read(cx).related_files())
+            .unwrap_or_else(|| vec![].into())
+    }
+
+    pub fn context_for_project_with_buffers<'a>(
+        &'a self,
+        project: &Entity<Project>,
+        cx: &'a App,
+    ) -> Option<impl 'a + Iterator<Item = (RelatedFile, Entity<Buffer>)>> {
+        self.projects
+            .get(&project.entity_id())
+            .map(|project| project.context.read(cx).related_files_with_buffers())
+    }
+
+    pub fn usage(&self, cx: &App) -> Option<EditPredictionUsage> {
+        if self.edit_prediction_model == EditPredictionModel::Zeta2 {
+            self.user_store.read(cx).edit_prediction_usage()
+        } else {
+            None
+        }
+    }
+
+    pub fn register_project(&mut self, project: &Entity<Project>, cx: &mut Context<Self>) {
+        self.get_or_init_project(project, cx);
+    }
+
+    pub fn register_buffer(
         &mut self,
-        buffer: Entity<Buffer>,
-        cursor_position: language::Anchor,
-        debounce: bool,
+        buffer: &Entity<Buffer>,
+        project: &Entity<Project>,
         cx: &mut Context<Self>,
-    );
-    fn cycle(
+    ) {
+        let project_state = self.get_or_init_project(project, cx);
+        Self::register_buffer_impl(project_state, buffer, project, cx);
+    }
+
+    fn get_or_init_project(
         &mut self,
-        buffer: Entity<Buffer>,
-        cursor_position: language::Anchor,
-        direction: Direction,
+        project: &Entity<Project>,
         cx: &mut Context<Self>,
-    );
-    fn accept(&mut self, cx: &mut Context<Self>);
-    fn discard(&mut self, cx: &mut Context<Self>);
-    fn did_show(&mut self, _cx: &mut Context<Self>) {}
-    fn suggest(
+    ) -> &mut ProjectState {
+        let entity_id = project.entity_id();
+        self.projects
+            .entry(entity_id)
+            .or_insert_with(|| ProjectState {
+                context: {
+                    let related_excerpt_store = cx.new(|cx| RelatedExcerptStore::new(project, cx));
+                    cx.subscribe(&related_excerpt_store, move |this, _, event, _| {
+                        this.handle_excerpt_store_event(entity_id, event);
+                    })
+                    .detach();
+                    related_excerpt_store
+                },
+                events: VecDeque::new(),
+                last_event: None,
+                recent_paths: VecDeque::new(),
+                debug_tx: None,
+                registered_buffers: HashMap::default(),
+                current_prediction: None,
+                cancelled_predictions: HashSet::default(),
+                pending_predictions: ArrayVec::new(),
+                next_pending_prediction_id: 0,
+                last_prediction_refresh: None,
+                license_detection_watchers: HashMap::default(),
+                _subscription: cx.subscribe(&project, Self::handle_project_event),
+            })
+    }
+
+    pub fn remove_project(&mut self, project: &Entity<Project>) {
+        self.projects.remove(&project.entity_id());
+    }
+
+    fn handle_excerpt_store_event(
+        &mut self,
+        project_entity_id: EntityId,
+        event: &RelatedExcerptStoreEvent,
+    ) {
+        if let Some(project_state) = self.projects.get(&project_entity_id) {
+            if let Some(debug_tx) = project_state.debug_tx.clone() {
+                match event {
+                    RelatedExcerptStoreEvent::StartedRefresh => {
+                        debug_tx
+                            .unbounded_send(DebugEvent::ContextRetrievalStarted(
+                                ContextRetrievalStartedDebugEvent {
+                                    project_entity_id: project_entity_id,
+                                    timestamp: Instant::now(),
+                                    search_prompt: String::new(),
+                                },
+                            ))
+                            .ok();
+                    }
+                    RelatedExcerptStoreEvent::FinishedRefresh {
+                        cache_hit_count,
+                        cache_miss_count,
+                        mean_definition_latency,
+                        max_definition_latency,
+                    } => {
+                        debug_tx
+                            .unbounded_send(DebugEvent::ContextRetrievalFinished(
+                                ContextRetrievalFinishedDebugEvent {
+                                    project_entity_id: project_entity_id,
+                                    timestamp: Instant::now(),
+                                    metadata: vec![
+                                        (
+                                            "Cache Hits",
+                                            format!(
+                                                "{}/{}",
+                                                cache_hit_count,
+                                                cache_hit_count + cache_miss_count
+                                            )
+                                            .into(),
+                                        ),
+                                        (
+                                            "Max LSP Time",
+                                            format!("{} ms", max_definition_latency.as_millis())
+                                                .into(),
+                                        ),
+                                        (
+                                            "Mean LSP Time",
+                                            format!("{} ms", mean_definition_latency.as_millis())
+                                                .into(),
+                                        ),
+                                    ],
+                                },
+                            ))
+                            .ok();
+                    }
+                }
+            }
+        }
+    }
+
+    pub fn debug_info(
+        &mut self,
+        project: &Entity<Project>,
+        cx: &mut Context<Self>,
+    ) -> mpsc::UnboundedReceiver<DebugEvent> {
+        let project_state = self.get_or_init_project(project, cx);
+        let (debug_watch_tx, debug_watch_rx) = mpsc::unbounded();
+        project_state.debug_tx = Some(debug_watch_tx);
+        debug_watch_rx
+    }
+
+    fn handle_project_event(
         &mut self,
+        project: Entity<Project>,
+        event: &project::Event,
+        cx: &mut Context<Self>,
+    ) {
+        // TODO [zeta2] init with recent paths
+        match event {
+            project::Event::ActiveEntryChanged(Some(active_entry_id)) => {
+                let Some(project_state) = self.projects.get_mut(&project.entity_id()) else {
+                    return;
+                };
+                let path = project.read(cx).path_for_entry(*active_entry_id, cx);
+                if let Some(path) = path {
+                    if let Some(ix) = project_state
+                        .recent_paths
+                        .iter()
+                        .position(|probe| probe == &path)
+                    {
+                        project_state.recent_paths.remove(ix);
+                    }
+                    project_state.recent_paths.push_front(path);
+                }
+            }
+            project::Event::DiagnosticsUpdated { .. } => {
+                if cx.has_flag::<Zeta2FeatureFlag>() {
+                    self.refresh_prediction_from_diagnostics(project, cx);
+                }
+            }
+            _ => (),
+        }
+    }
+
+    fn register_buffer_impl<'a>(
+        project_state: &'a mut ProjectState,
         buffer: &Entity<Buffer>,
-        cursor_position: language::Anchor,
+        project: &Entity<Project>,
         cx: &mut Context<Self>,
-    ) -> Option<EditPrediction>;
-}
+    ) -> &'a mut RegisteredBuffer {
+        let buffer_id = buffer.entity_id();
 
-pub trait EditPredictionProviderHandle {
-    fn name(&self) -> &'static str;
-    fn display_name(&self) -> &'static str;
-    fn is_enabled(
-        &self,
+        if let Some(file) = buffer.read(cx).file() {
+            let worktree_id = file.worktree_id(cx);
+            if let Some(worktree) = project.read(cx).worktree_for_id(worktree_id, cx) {
+                project_state
+                    .license_detection_watchers
+                    .entry(worktree_id)
+                    .or_insert_with(|| {
+                        let project_entity_id = project.entity_id();
+                        cx.observe_release(&worktree, move |this, _worktree, _cx| {
+                            let Some(project_state) = this.projects.get_mut(&project_entity_id)
+                            else {
+                                return;
+                            };
+                            project_state
+                                .license_detection_watchers
+                                .remove(&worktree_id);
+                        })
+                        .detach();
+                        Rc::new(LicenseDetectionWatcher::new(&worktree, cx))
+                    });
+            }
+        }
+
+        match project_state.registered_buffers.entry(buffer_id) {
+            hash_map::Entry::Occupied(entry) => entry.into_mut(),
+            hash_map::Entry::Vacant(entry) => {
+                let buf = buffer.read(cx);
+                let snapshot = buf.text_snapshot();
+                let file = buf.file().cloned();
+                let project_entity_id = project.entity_id();
+                entry.insert(RegisteredBuffer {
+                    snapshot,
+                    file,
+                    last_position: None,
+                    _subscriptions: [
+                        cx.subscribe(buffer, {
+                            let project = project.downgrade();
+                            move |this, buffer, event, cx| {
+                                if let language::BufferEvent::Edited = event
+                                    && let Some(project) = project.upgrade()
+                                {
+                                    this.report_changes_for_buffer(&buffer, &project, cx);
+                                }
+                            }
+                        }),
+                        cx.observe_release(buffer, move |this, _buffer, _cx| {
+                            let Some(project_state) = this.projects.get_mut(&project_entity_id)
+                            else {
+                                return;
+                            };
+                            project_state.registered_buffers.remove(&buffer_id);
+                        }),
+                    ],
+                })
+            }
+        }
+    }
+
+    fn report_changes_for_buffer(
+        &mut self,
         buffer: &Entity<Buffer>,
-        cursor_position: language::Anchor,
-        cx: &App,
-    ) -> bool;
-    fn show_completions_in_menu(&self) -> bool;
-    fn show_tab_accept_marker(&self) -> bool;
-    fn supports_jump_to_edit(&self) -> bool;
-    fn data_collection_state(&self, cx: &App) -> DataCollectionState;
-    fn usage(&self, cx: &App) -> Option<EditPredictionUsage>;
-    fn toggle_data_collection(&self, cx: &mut App);
-    fn is_refreshing(&self, cx: &App) -> bool;
-    fn refresh(
-        &self,
-        buffer: Entity<Buffer>,
-        cursor_position: language::Anchor,
-        debounce: bool,
-        cx: &mut App,
-    );
-    fn cycle(
-        &self,
-        buffer: Entity<Buffer>,
-        cursor_position: language::Anchor,
-        direction: Direction,
-        cx: &mut App,
-    );
-    fn did_show(&self, cx: &mut App);
-    fn accept(&self, cx: &mut App);
-    fn discard(&self, cx: &mut App);
-    fn suggest(
-        &self,
+        project: &Entity<Project>,
+        cx: &mut Context<Self>,
+    ) {
+        let project_state = self.get_or_init_project(project, cx);
+        let registered_buffer = Self::register_buffer_impl(project_state, buffer, project, cx);
+
+        let buf = buffer.read(cx);
+        let new_file = buf.file().cloned();
+        let new_snapshot = buf.text_snapshot();
+        if new_snapshot.version == registered_buffer.snapshot.version {
+            return;
+        }
+
+        let old_file = mem::replace(&mut registered_buffer.file, new_file.clone());
+        let old_snapshot = mem::replace(&mut registered_buffer.snapshot, new_snapshot.clone());
+        let end_edit_anchor = new_snapshot
+            .anchored_edits_since::<Point>(&old_snapshot.version)
+            .last()
+            .map(|(_, range)| range.end);
+        let events = &mut project_state.events;
+
+        let now = cx.background_executor().now();
+        if let Some(last_event) = project_state.last_event.as_mut() {
+            let is_next_snapshot_of_same_buffer = old_snapshot.remote_id()
+                == last_event.new_snapshot.remote_id()
+                && old_snapshot.version == last_event.new_snapshot.version;
+
+            let should_coalesce = is_next_snapshot_of_same_buffer
+                && end_edit_anchor
+                    .as_ref()
+                    .zip(last_event.end_edit_anchor.as_ref())
+                    .is_some_and(|(a, b)| {
+                        let a = a.to_point(&new_snapshot);
+                        let b = b.to_point(&new_snapshot);
+                        a.row.abs_diff(b.row) <= CHANGE_GROUPING_LINE_SPAN
+                    });
+
+            if should_coalesce {
+                let pause_elapsed = last_event
+                    .last_edit_time
+                    .map(|t| now.duration_since(t) >= LAST_CHANGE_GROUPING_TIME)
+                    .unwrap_or(false);
+                if pause_elapsed {
+                    last_event.snapshot_after_last_editing_pause =
+                        Some(last_event.new_snapshot.clone());
+                }
+
+                last_event.end_edit_anchor = end_edit_anchor;
+                last_event.new_snapshot = new_snapshot;
+                last_event.last_edit_time = Some(now);
+                return;
+            }
+        }
+
+        if events.len() + 1 >= EVENT_COUNT_MAX {
+            events.pop_front();
+        }
+
+        if let Some(event) = project_state.last_event.take() {
+            events.extend(event.finalize(&project_state.license_detection_watchers, cx));
+        }
+
+        project_state.last_event = Some(LastEvent {
+            old_file,
+            new_file,
+            old_snapshot,
+            new_snapshot,
+            end_edit_anchor,
+            snapshot_after_last_editing_pause: None,
+            last_edit_time: Some(now),
+        });
+    }
+
+    fn prediction_at(
+        &mut self,
         buffer: &Entity<Buffer>,
-        cursor_position: language::Anchor,
-        cx: &mut App,
-    ) -> Option<EditPrediction>;
-}
+        position: Option<language::Anchor>,
+        project: &Entity<Project>,
+        cx: &App,
+    ) -> Option<BufferEditPrediction<'_>> {
+        let project_state = self.projects.get_mut(&project.entity_id())?;
+        if let Some(position) = position
+            && let Some(buffer) = project_state
+                .registered_buffers
+                .get_mut(&buffer.entity_id())
+        {
+            buffer.last_position = Some(position);
+        }
+
+        let CurrentEditPrediction {
+            requested_by,
+            prediction,
+            ..
+        } = project_state.current_prediction.as_ref()?;
 
-impl<T> EditPredictionProviderHandle for Entity<T>
-where
-    T: EditPredictionProvider,
-{
-    fn name(&self) -> &'static str {
-        T::name()
+        if prediction.targets_buffer(buffer.read(cx)) {
+            Some(BufferEditPrediction::Local { prediction })
+        } else {
+            let show_jump = match requested_by {
+                PredictionRequestedBy::Buffer(requested_by_buffer_id) => {
+                    requested_by_buffer_id == &buffer.entity_id()
+                }
+                PredictionRequestedBy::DiagnosticsUpdate => true,
+            };
+
+            if show_jump {
+                Some(BufferEditPrediction::Jump { prediction })
+            } else {
+                None
+            }
+        }
     }
 
-    fn display_name(&self) -> &'static str {
-        T::display_name()
+    fn accept_current_prediction(&mut self, project: &Entity<Project>, cx: &mut Context<Self>) {
+        let custom_accept_url = env::var("ZED_ACCEPT_PREDICTION_URL").ok();
+        match self.edit_prediction_model {
+            EditPredictionModel::Zeta1 | EditPredictionModel::Zeta2 => {
+                if self.custom_predict_edits_url.is_some() && custom_accept_url.is_none() {
+                    return;
+                }
+            }
+            EditPredictionModel::Sweep | EditPredictionModel::Mercury => return,
+        }
+
+        let Some(project_state) = self.projects.get_mut(&project.entity_id()) else {
+            return;
+        };
+
+        let Some(prediction) = project_state.current_prediction.take() else {
+            return;
+        };
+        let request_id = prediction.prediction.id.to_string();
+        for pending_prediction in mem::take(&mut project_state.pending_predictions) {
+            project_state.cancel_pending_prediction(pending_prediction, cx);
+        }
+
+        let client = self.client.clone();
+        let llm_token = self.llm_token.clone();
+        let app_version = AppVersion::global(cx);
+        cx.spawn(async move |this, cx| {
+            let (url, require_auth) = if let Some(accept_edits_url) = custom_accept_url {
+                (http_client::Url::parse(&accept_edits_url)?, false)
+            } else {
+                (
+                    client
+                        .http_client()
+                        .build_zed_llm_url("/predict_edits/accept", &[])?,
+                    true,
+                )
+            };
+
+            let response = cx
+                .background_spawn(Self::send_api_request::<()>(
+                    move |builder| {
+                        let req = builder.uri(url.as_ref()).body(
+                            serde_json::to_string(&AcceptEditPredictionBody {
+                                request_id: request_id.clone(),
+                            })?
+                            .into(),
+                        );
+                        Ok(req?)
+                    },
+                    client,
+                    llm_token,
+                    app_version,
+                    require_auth,
+                ))
+                .await;
+
+            Self::handle_api_response(&this, response, cx)?;
+            anyhow::Ok(())
+        })
+        .detach_and_log_err(cx);
     }
 
-    fn show_completions_in_menu(&self) -> bool {
-        T::show_completions_in_menu()
+    async fn handle_rejected_predictions(
+        rx: UnboundedReceiver<EditPredictionRejection>,
+        client: Arc<Client>,
+        llm_token: LlmApiToken,
+        app_version: Version,
+        background_executor: BackgroundExecutor,
+    ) {
+        let mut rx = std::pin::pin!(rx.peekable());
+        let mut batched = Vec::new();
+
+        while let Some(rejection) = rx.next().await {
+            batched.push(rejection);
+
+            if batched.len() < MAX_EDIT_PREDICTION_REJECTIONS_PER_REQUEST / 2 {
+                select_biased! {
+                    next = rx.as_mut().peek().fuse() => {
+                        if next.is_some() {
+                            continue;
+                        }
+                    }
+                    () = background_executor.timer(REJECT_REQUEST_DEBOUNCE).fuse() => {},
+                }
+            }
+
+            let url = client
+                .http_client()
+                .build_zed_llm_url("/predict_edits/reject", &[])
+                .unwrap();
+
+            let flush_count = batched
+                .len()
+                // in case items have accumulated after failure
+                .min(MAX_EDIT_PREDICTION_REJECTIONS_PER_REQUEST);
+            let start = batched.len() - flush_count;
+
+            let body = RejectEditPredictionsBodyRef {
+                rejections: &batched[start..],
+            };
+
+            let result = Self::send_api_request::<()>(
+                |builder| {
+                    let req = builder
+                        .uri(url.as_ref())
+                        .body(serde_json::to_string(&body)?.into());
+                    anyhow::Ok(req?)
+                },
+                client.clone(),
+                llm_token.clone(),
+                app_version.clone(),
+                true,
+            )
+            .await;
+
+            if result.log_err().is_some() {
+                batched.drain(start..);
+            }
+        }
     }
 
-    fn show_tab_accept_marker(&self) -> bool {
-        T::show_tab_accept_marker()
+    fn reject_current_prediction(
+        &mut self,
+        reason: EditPredictionRejectReason,
+        project: &Entity<Project>,
+    ) {
+        if let Some(project_state) = self.projects.get_mut(&project.entity_id()) {
+            project_state.pending_predictions.clear();
+            if let Some(prediction) = project_state.current_prediction.take() {
+                self.reject_prediction(prediction.prediction.id, reason, prediction.was_shown);
+            }
+        };
     }
 
-    fn supports_jump_to_edit(&self) -> bool {
-        T::supports_jump_to_edit()
+    fn did_show_current_prediction(&mut self, project: &Entity<Project>, _cx: &mut Context<Self>) {
+        if let Some(project_state) = self.projects.get_mut(&project.entity_id()) {
+            if let Some(current_prediction) = project_state.current_prediction.as_mut() {
+                if !current_prediction.was_shown {
+                    current_prediction.was_shown = true;
+                    self.shown_predictions
+                        .push_front(current_prediction.prediction.clone());
+                    if self.shown_predictions.len() > 50 {
+                        let completion = self.shown_predictions.pop_back().unwrap();
+                        self.rated_predictions.remove(&completion.id);
+                    }
+                }
+            }
+        }
     }
 
-    fn data_collection_state(&self, cx: &App) -> DataCollectionState {
-        self.read(cx).data_collection_state(cx)
+    fn reject_prediction(
+        &mut self,
+        prediction_id: EditPredictionId,
+        reason: EditPredictionRejectReason,
+        was_shown: bool,
+    ) {
+        match self.edit_prediction_model {
+            EditPredictionModel::Zeta1 | EditPredictionModel::Zeta2 => {
+                if self.custom_predict_edits_url.is_some() {
+                    return;
+                }
+            }
+            EditPredictionModel::Sweep | EditPredictionModel::Mercury => return,
+        }
+
+        self.reject_predictions_tx
+            .unbounded_send(EditPredictionRejection {
+                request_id: prediction_id.to_string(),
+                reason,
+                was_shown,
+            })
+            .log_err();
     }
 
-    fn usage(&self, cx: &App) -> Option<EditPredictionUsage> {
-        self.read(cx).usage(cx)
+    fn is_refreshing(&self, project: &Entity<Project>) -> bool {
+        self.projects
+            .get(&project.entity_id())
+            .is_some_and(|project_state| !project_state.pending_predictions.is_empty())
     }
 
-    fn toggle_data_collection(&self, cx: &mut App) {
-        self.update(cx, |this, cx| this.toggle_data_collection(cx))
+    pub fn refresh_prediction_from_buffer(
+        &mut self,
+        project: Entity<Project>,
+        buffer: Entity<Buffer>,
+        position: language::Anchor,
+        cx: &mut Context<Self>,
+    ) {
+        self.queue_prediction_refresh(project.clone(), buffer.entity_id(), cx, move |this, cx| {
+            let Some(request_task) = this
+                .update(cx, |this, cx| {
+                    this.request_prediction(
+                        &project,
+                        &buffer,
+                        position,
+                        PredictEditsRequestTrigger::Other,
+                        cx,
+                    )
+                })
+                .log_err()
+            else {
+                return Task::ready(anyhow::Ok(None));
+            };
+
+            cx.spawn(async move |_cx| {
+                request_task.await.map(|prediction_result| {
+                    prediction_result.map(|prediction_result| {
+                        (
+                            prediction_result,
+                            PredictionRequestedBy::Buffer(buffer.entity_id()),
+                        )
+                    })
+                })
+            })
+        })
     }
 
-    fn is_enabled(
-        &self,
-        buffer: &Entity<Buffer>,
-        cursor_position: language::Anchor,
+    pub fn refresh_prediction_from_diagnostics(
+        &mut self,
+        project: Entity<Project>,
+        cx: &mut Context<Self>,
+    ) {
+        let Some(project_state) = self.projects.get_mut(&project.entity_id()) else {
+            return;
+        };
+
+        // Prefer predictions from buffer
+        if project_state.current_prediction.is_some() {
+            return;
+        };
+
+        self.queue_prediction_refresh(project.clone(), project.entity_id(), cx, move |this, cx| {
+            let Some((active_buffer, snapshot, cursor_point)) = this
+                .read_with(cx, |this, cx| {
+                    let project_state = this.projects.get(&project.entity_id())?;
+                    let (buffer, position) = project_state.active_buffer(&project, cx)?;
+                    let snapshot = buffer.read(cx).snapshot();
+
+                    if !Self::predictions_enabled_at(&snapshot, position, cx) {
+                        return None;
+                    }
+
+                    let cursor_point = position
+                        .map(|pos| pos.to_point(&snapshot))
+                        .unwrap_or_default();
+
+                    Some((buffer, snapshot, cursor_point))
+                })
+                .log_err()
+                .flatten()
+            else {
+                return Task::ready(anyhow::Ok(None));
+            };
+
+            cx.spawn(async move |cx| {
+                let Some((jump_buffer, jump_position)) = Self::next_diagnostic_location(
+                    active_buffer,
+                    &snapshot,
+                    Default::default(),
+                    cursor_point,
+                    &project,
+                    cx,
+                )
+                .await?
+                else {
+                    return anyhow::Ok(None);
+                };
+
+                let Some(prediction_result) = this
+                    .update(cx, |this, cx| {
+                        this.request_prediction(
+                            &project,
+                            &jump_buffer,
+                            jump_position,
+                            PredictEditsRequestTrigger::Diagnostics,
+                            cx,
+                        )
+                    })?
+                    .await?
+                else {
+                    return anyhow::Ok(None);
+                };
+
+                this.update(cx, |this, cx| {
+                    Some((
+                        if this
+                            .get_or_init_project(&project, cx)
+                            .current_prediction
+                            .is_none()
+                        {
+                            prediction_result
+                        } else {
+                            EditPredictionResult {
+                                id: prediction_result.id,
+                                prediction: Err(EditPredictionRejectReason::CurrentPreferred),
+                            }
+                        },
+                        PredictionRequestedBy::DiagnosticsUpdate,
+                    ))
+                })
+            })
+        });
+    }
+
+    fn predictions_enabled_at(
+        snapshot: &BufferSnapshot,
+        position: Option<language::Anchor>,
         cx: &App,
     ) -> bool {
-        self.read(cx).is_enabled(buffer, cursor_position, cx)
-    }
+        let file = snapshot.file();
+        let all_settings = all_language_settings(file, cx);
+        if !all_settings.show_edit_predictions(snapshot.language(), cx)
+            || file.is_some_and(|file| !all_settings.edit_predictions_enabled_for_file(file, cx))
+        {
+            return false;
+        }
+
+        if let Some(last_position) = position {
+            let settings = snapshot.settings_at(last_position, cx);
+
+            if !settings.edit_predictions_disabled_in.is_empty()
+                && let Some(scope) = snapshot.language_scope_at(last_position)
+                && let Some(scope_name) = scope.override_name()
+                && settings
+                    .edit_predictions_disabled_in
+                    .iter()
+                    .any(|s| s == scope_name)
+            {
+                return false;
+            }
+        }
 
-    fn is_refreshing(&self, cx: &App) -> bool {
-        self.read(cx).is_refreshing(cx)
+        true
     }
 
-    fn refresh(
-        &self,
-        buffer: Entity<Buffer>,
-        cursor_position: language::Anchor,
-        debounce: bool,
-        cx: &mut App,
+    #[cfg(not(test))]
+    pub const THROTTLE_TIMEOUT: Duration = Duration::from_millis(300);
+    #[cfg(test)]
+    pub const THROTTLE_TIMEOUT: Duration = Duration::ZERO;
+
+    fn queue_prediction_refresh(
+        &mut self,
+        project: Entity<Project>,
+        throttle_entity: EntityId,
+        cx: &mut Context<Self>,
+        do_refresh: impl FnOnce(
+            WeakEntity<Self>,
+            &mut AsyncApp,
+        )
+            -> Task<Result<Option<(EditPredictionResult, PredictionRequestedBy)>>>
+        + 'static,
     ) {
-        self.update(cx, |this, cx| {
-            this.refresh(buffer, cursor_position, debounce, cx)
-        })
+        let project_state = self.get_or_init_project(&project, cx);
+        let pending_prediction_id = project_state.next_pending_prediction_id;
+        project_state.next_pending_prediction_id += 1;
+        let last_request = project_state.last_prediction_refresh;
+
+        let task = cx.spawn(async move |this, cx| {
+            if let Some((last_entity, last_timestamp)) = last_request
+                && throttle_entity == last_entity
+                && let Some(timeout) =
+                    (last_timestamp + Self::THROTTLE_TIMEOUT).checked_duration_since(Instant::now())
+            {
+                cx.background_executor().timer(timeout).await;
+            }
+
+            // If this task was cancelled before the throttle timeout expired,
+            // do not perform a request.
+            let mut is_cancelled = true;
+            this.update(cx, |this, cx| {
+                let project_state = this.get_or_init_project(&project, cx);
+                if !project_state
+                    .cancelled_predictions
+                    .remove(&pending_prediction_id)
+                {
+                    project_state.last_prediction_refresh = Some((throttle_entity, Instant::now()));
+                    is_cancelled = false;
+                }
+            })
+            .ok();
+            if is_cancelled {
+                return None;
+            }
+
+            let new_prediction_result = do_refresh(this.clone(), cx).await.log_err().flatten();
+            let new_prediction_id = new_prediction_result
+                .as_ref()
+                .map(|(prediction, _)| prediction.id.clone());
+
+            // When a prediction completes, remove it from the pending list, and cancel
+            // any pending predictions that were enqueued before it.
+            this.update(cx, |this, cx| {
+                let project_state = this.get_or_init_project(&project, cx);
+
+                let is_cancelled = project_state
+                    .cancelled_predictions
+                    .remove(&pending_prediction_id);
+
+                let new_current_prediction = if !is_cancelled
+                    && let Some((prediction_result, requested_by)) = new_prediction_result
+                {
+                    match prediction_result.prediction {
+                        Ok(prediction) => {
+                            let new_prediction = CurrentEditPrediction {
+                                requested_by,
+                                prediction,
+                                was_shown: false,
+                            };
+
+                            if let Some(current_prediction) =
+                                project_state.current_prediction.as_ref()
+                            {
+                                if new_prediction.should_replace_prediction(&current_prediction, cx)
+                                {
+                                    this.reject_current_prediction(
+                                        EditPredictionRejectReason::Replaced,
+                                        &project,
+                                    );
+
+                                    Some(new_prediction)
+                                } else {
+                                    this.reject_prediction(
+                                        new_prediction.prediction.id,
+                                        EditPredictionRejectReason::CurrentPreferred,
+                                        false,
+                                    );
+                                    None
+                                }
+                            } else {
+                                Some(new_prediction)
+                            }
+                        }
+                        Err(reject_reason) => {
+                            this.reject_prediction(prediction_result.id, reject_reason, false);
+                            None
+                        }
+                    }
+                } else {
+                    None
+                };
+
+                let project_state = this.get_or_init_project(&project, cx);
+
+                if let Some(new_prediction) = new_current_prediction {
+                    project_state.current_prediction = Some(new_prediction);
+                }
+
+                let mut pending_predictions = mem::take(&mut project_state.pending_predictions);
+                for (ix, pending_prediction) in pending_predictions.iter().enumerate() {
+                    if pending_prediction.id == pending_prediction_id {
+                        pending_predictions.remove(ix);
+                        for pending_prediction in pending_predictions.drain(0..ix) {
+                            project_state.cancel_pending_prediction(pending_prediction, cx)
+                        }
+                        break;
+                    }
+                }
+                this.get_or_init_project(&project, cx).pending_predictions = pending_predictions;
+                cx.notify();
+            })
+            .ok();
+
+            new_prediction_id
+        });
+
+        if project_state.pending_predictions.len() <= 1 {
+            project_state.pending_predictions.push(PendingPrediction {
+                id: pending_prediction_id,
+                task,
+            });
+        } else if project_state.pending_predictions.len() == 2 {
+            let pending_prediction = project_state.pending_predictions.pop().unwrap();
+            project_state.pending_predictions.push(PendingPrediction {
+                id: pending_prediction_id,
+                task,
+            });
+            project_state.cancel_pending_prediction(pending_prediction, cx);
+        }
     }
 
-    fn cycle(
-        &self,
-        buffer: Entity<Buffer>,
-        cursor_position: language::Anchor,
-        direction: Direction,
-        cx: &mut App,
-    ) {
-        self.update(cx, |this, cx| {
-            this.cycle(buffer, cursor_position, direction, cx)
+    pub fn request_prediction(
+        &mut self,
+        project: &Entity<Project>,
+        active_buffer: &Entity<Buffer>,
+        position: language::Anchor,
+        trigger: PredictEditsRequestTrigger,
+        cx: &mut Context<Self>,
+    ) -> Task<Result<Option<EditPredictionResult>>> {
+        self.request_prediction_internal(
+            project.clone(),
+            active_buffer.clone(),
+            position,
+            trigger,
+            cx.has_flag::<Zeta2FeatureFlag>(),
+            cx,
+        )
+    }
+
+    fn request_prediction_internal(
+        &mut self,
+        project: Entity<Project>,
+        active_buffer: Entity<Buffer>,
+        position: language::Anchor,
+        trigger: PredictEditsRequestTrigger,
+        allow_jump: bool,
+        cx: &mut Context<Self>,
+    ) -> Task<Result<Option<EditPredictionResult>>> {
+        const DIAGNOSTIC_LINES_RANGE: u32 = 20;
+
+        self.get_or_init_project(&project, cx);
+        let project_state = self.projects.get(&project.entity_id()).unwrap();
+        let stored_events = project_state.events(cx);
+        let has_events = !stored_events.is_empty();
+        let events: Vec<Arc<zeta_prompt::Event>> =
+            stored_events.into_iter().map(|e| e.event).collect();
+        let debug_tx = project_state.debug_tx.clone();
+
+        let snapshot = active_buffer.read(cx).snapshot();
+        let cursor_point = position.to_point(&snapshot);
+        let diagnostic_search_start = cursor_point.row.saturating_sub(DIAGNOSTIC_LINES_RANGE);
+        let diagnostic_search_end = cursor_point.row + DIAGNOSTIC_LINES_RANGE;
+        let diagnostic_search_range =
+            Point::new(diagnostic_search_start, 0)..Point::new(diagnostic_search_end, 0);
+
+        let related_files = if self.use_context {
+            self.context_for_project(&project, cx)
+        } else {
+            Vec::new().into()
+        };
+
+        let inputs = EditPredictionModelInput {
+            project: project.clone(),
+            buffer: active_buffer.clone(),
+            snapshot: snapshot.clone(),
+            position,
+            events,
+            related_files,
+            recent_paths: project_state.recent_paths.clone(),
+            trigger,
+            diagnostic_search_range: diagnostic_search_range.clone(),
+            debug_tx,
+        };
+
+        let task = match self.edit_prediction_model {
+            EditPredictionModel::Zeta1 => zeta1::request_prediction_with_zeta1(self, inputs, cx),
+            EditPredictionModel::Zeta2 => zeta2::request_prediction_with_zeta2(self, inputs, cx),
+            EditPredictionModel::Sweep => self.sweep_ai.request_prediction_with_sweep(inputs, cx),
+            EditPredictionModel::Mercury => self.mercury.request_prediction(inputs, cx),
+        };
+
+        cx.spawn(async move |this, cx| {
+            let prediction = task.await?;
+
+            if prediction.is_none() && allow_jump {
+                let cursor_point = position.to_point(&snapshot);
+                if has_events
+                    && let Some((jump_buffer, jump_position)) = Self::next_diagnostic_location(
+                        active_buffer.clone(),
+                        &snapshot,
+                        diagnostic_search_range,
+                        cursor_point,
+                        &project,
+                        cx,
+                    )
+                    .await?
+                {
+                    return this
+                        .update(cx, |this, cx| {
+                            this.request_prediction_internal(
+                                project,
+                                jump_buffer,
+                                jump_position,
+                                trigger,
+                                false,
+                                cx,
+                            )
+                        })?
+                        .await;
+                }
+
+                return anyhow::Ok(None);
+            }
+
+            Ok(prediction)
         })
     }
 
-    fn accept(&self, cx: &mut App) {
-        self.update(cx, |this, cx| this.accept(cx))
+    async fn next_diagnostic_location(
+        active_buffer: Entity<Buffer>,
+        active_buffer_snapshot: &BufferSnapshot,
+        active_buffer_diagnostic_search_range: Range<Point>,
+        active_buffer_cursor_point: Point,
+        project: &Entity<Project>,
+        cx: &mut AsyncApp,
+    ) -> Result<Option<(Entity<Buffer>, language::Anchor)>> {
+        // find the closest diagnostic to the cursor that wasn't close enough to be included in the last request
+        let mut jump_location = active_buffer_snapshot
+            .diagnostic_groups(None)
+            .into_iter()
+            .filter_map(|(_, group)| {
+                let range = &group.entries[group.primary_ix]
+                    .range
+                    .to_point(&active_buffer_snapshot);
+                if range.overlaps(&active_buffer_diagnostic_search_range) {
+                    None
+                } else {
+                    Some(range.start)
+                }
+            })
+            .min_by_key(|probe| probe.row.abs_diff(active_buffer_cursor_point.row))
+            .map(|position| {
+                (
+                    active_buffer.clone(),
+                    active_buffer_snapshot.anchor_before(position),
+                )
+            });
+
+        if jump_location.is_none() {
+            let active_buffer_path = active_buffer.read_with(cx, |buffer, cx| {
+                let file = buffer.file()?;
+
+                Some(ProjectPath {
+                    worktree_id: file.worktree_id(cx),
+                    path: file.path().clone(),
+                })
+            })?;
+
+            let buffer_task = project.update(cx, |project, cx| {
+                let (path, _, _) = project
+                    .diagnostic_summaries(false, cx)
+                    .filter(|(path, _, _)| Some(path) != active_buffer_path.as_ref())
+                    .max_by_key(|(path, _, _)| {
+                        // find the buffer with errors that shares most parent directories
+                        path.path
+                            .components()
+                            .zip(
+                                active_buffer_path
+                                    .as_ref()
+                                    .map(|p| p.path.components())
+                                    .unwrap_or_default(),
+                            )
+                            .take_while(|(a, b)| a == b)
+                            .count()
+                    })?;
+
+                Some(project.open_buffer(path, cx))
+            })?;
+
+            if let Some(buffer_task) = buffer_task {
+                let closest_buffer = buffer_task.await?;
+
+                jump_location = closest_buffer
+                    .read_with(cx, |buffer, _cx| {
+                        buffer
+                            .buffer_diagnostics(None)
+                            .into_iter()
+                            .min_by_key(|entry| entry.diagnostic.severity)
+                            .map(|entry| entry.range.start)
+                    })?
+                    .map(|position| (closest_buffer, position));
+            }
+        }
+
+        anyhow::Ok(jump_location)
     }
 
-    fn discard(&self, cx: &mut App) {
-        self.update(cx, |this, cx| this.discard(cx))
+    async fn send_raw_llm_request(
+        request: open_ai::Request,
+        client: Arc<Client>,
+        llm_token: LlmApiToken,
+        app_version: Version,
+        #[cfg(feature = "cli-support")] eval_cache: Option<Arc<dyn EvalCache>>,
+        #[cfg(feature = "cli-support")] eval_cache_kind: EvalCacheEntryKind,
+    ) -> Result<(open_ai::Response, Option<EditPredictionUsage>)> {
+        let url = client
+            .http_client()
+            .build_zed_llm_url("/predict_edits/raw", &[])?;
+
+        #[cfg(feature = "cli-support")]
+        let cache_key = if let Some(cache) = eval_cache {
+            use collections::FxHasher;
+            use std::hash::{Hash, Hasher};
+
+            let mut hasher = FxHasher::default();
+            url.hash(&mut hasher);
+            let request_str = serde_json::to_string_pretty(&request)?;
+            request_str.hash(&mut hasher);
+            let hash = hasher.finish();
+
+            let key = (eval_cache_kind, hash);
+            if let Some(response_str) = cache.read(key) {
+                return Ok((serde_json::from_str(&response_str)?, None));
+            }
+
+            Some((cache, request_str, key))
+        } else {
+            None
+        };
+
+        let (response, usage) = Self::send_api_request(
+            |builder| {
+                let req = builder
+                    .uri(url.as_ref())
+                    .body(serde_json::to_string(&request)?.into());
+                Ok(req?)
+            },
+            client,
+            llm_token,
+            app_version,
+            true,
+        )
+        .await?;
+
+        #[cfg(feature = "cli-support")]
+        if let Some((cache, request, key)) = cache_key {
+            cache.write(key, &request, &serde_json::to_string_pretty(&response)?);
+        }
+
+        Ok((response, usage))
     }
 
-    fn did_show(&self, cx: &mut App) {
-        self.update(cx, |this, cx| this.did_show(cx))
+    fn handle_api_response<T>(
+        this: &WeakEntity<Self>,
+        response: Result<(T, Option<EditPredictionUsage>)>,
+        cx: &mut gpui::AsyncApp,
+    ) -> Result<T> {
+        match response {
+            Ok((data, usage)) => {
+                if let Some(usage) = usage {
+                    this.update(cx, |this, cx| {
+                        this.user_store.update(cx, |user_store, cx| {
+                            user_store.update_edit_prediction_usage(usage, cx);
+                        });
+                    })
+                    .ok();
+                }
+                Ok(data)
+            }
+            Err(err) => {
+                if err.is::<ZedUpdateRequiredError>() {
+                    cx.update(|cx| {
+                        this.update(cx, |this, _cx| {
+                            this.update_required = true;
+                        })
+                        .ok();
+
+                        let error_message: SharedString = err.to_string().into();
+                        show_app_notification(
+                            NotificationId::unique::<ZedUpdateRequiredError>(),
+                            cx,
+                            move |cx| {
+                                cx.new(|cx| {
+                                    ErrorMessagePrompt::new(error_message.clone(), cx)
+                                        .with_link_button("Update Zed", "https://zed.dev/releases")
+                                })
+                            },
+                        );
+                    })
+                    .ok();
+                }
+                Err(err)
+            }
+        }
     }
 
-    fn suggest(
-        &self,
-        buffer: &Entity<Buffer>,
-        cursor_position: language::Anchor,
-        cx: &mut App,
-    ) -> Option<EditPrediction> {
-        self.update(cx, |this, cx| this.suggest(buffer, cursor_position, cx))
-    }
-}
-
-/// Returns edits updated based on user edits since the old snapshot. None is returned if any user
-/// edit is not a prefix of a predicted insertion.
-pub fn interpolate_edits(
-    old_snapshot: &BufferSnapshot,
-    new_snapshot: &BufferSnapshot,
-    current_edits: &[(Range<Anchor>, Arc<str>)],
-) -> Option<Vec<(Range<Anchor>, Arc<str>)>> {
-    let mut edits = Vec::new();
-
-    let mut model_edits = current_edits.iter().peekable();
-    for user_edit in new_snapshot.edits_since::<usize>(&old_snapshot.version) {
-        while let Some((model_old_range, _)) = model_edits.peek() {
-            let model_old_range = model_old_range.to_offset(old_snapshot);
-            if model_old_range.end < user_edit.old.start {
-                let (model_old_range, model_new_text) = model_edits.next().unwrap();
-                edits.push((model_old_range.clone(), model_new_text.clone()));
+    async fn send_api_request<Res>(
+        build: impl Fn(http_client::http::request::Builder) -> Result<http_client::Request<AsyncBody>>,
+        client: Arc<Client>,
+        llm_token: LlmApiToken,
+        app_version: Version,
+        require_auth: bool,
+    ) -> Result<(Res, Option<EditPredictionUsage>)>
+    where
+        Res: DeserializeOwned,
+    {
+        let http_client = client.http_client();
+
+        let mut token = if require_auth {
+            Some(llm_token.acquire(&client).await?)
+        } else {
+            llm_token.acquire(&client).await.ok()
+        };
+        let mut did_retry = false;
+
+        loop {
+            let request_builder = http_client::Request::builder().method(Method::POST);
+
+            let mut request_builder = request_builder
+                .header("Content-Type", "application/json")
+                .header(ZED_VERSION_HEADER_NAME, app_version.to_string());
+
+            // Only add Authorization header if we have a token
+            if let Some(ref token_value) = token {
+                request_builder =
+                    request_builder.header("Authorization", format!("Bearer {}", token_value));
+            }
+
+            let request = build(request_builder)?;
+
+            let mut response = http_client.send(request).await?;
+
+            if let Some(minimum_required_version) = response
+                .headers()
+                .get(MINIMUM_REQUIRED_VERSION_HEADER_NAME)
+                .and_then(|version| Version::from_str(version.to_str().ok()?).ok())
+            {
+                anyhow::ensure!(
+                    app_version >= minimum_required_version,
+                    ZedUpdateRequiredError {
+                        minimum_version: minimum_required_version
+                    }
+                );
+            }
+
+            if response.status().is_success() {
+                let usage = EditPredictionUsage::from_headers(response.headers()).ok();
+
+                let mut body = Vec::new();
+                response.body_mut().read_to_end(&mut body).await?;
+                return Ok((serde_json::from_slice(&body)?, usage));
+            } else if !did_retry
+                && token.is_some()
+                && response
+                    .headers()
+                    .get(EXPIRED_LLM_TOKEN_HEADER_NAME)
+                    .is_some()
+            {
+                did_retry = true;
+                token = Some(llm_token.refresh(&client).await?);
             } else {
-                break;
+                let mut body = String::new();
+                response.body_mut().read_to_string(&mut body).await?;
+                anyhow::bail!(
+                    "Request failed with status: {:?}\nBody: {}",
+                    response.status(),
+                    body
+                );
             }
         }
+    }
 
-        if let Some((model_old_range, model_new_text)) = model_edits.peek() {
-            let model_old_offset_range = model_old_range.to_offset(old_snapshot);
-            if user_edit.old == model_old_offset_range {
-                let user_new_text = new_snapshot
-                    .text_for_range(user_edit.new.clone())
-                    .collect::<String>();
+    pub fn refresh_context(
+        &mut self,
+        project: &Entity<Project>,
+        buffer: &Entity<language::Buffer>,
+        cursor_position: language::Anchor,
+        cx: &mut Context<Self>,
+    ) {
+        if self.use_context {
+            self.get_or_init_project(project, cx)
+                .context
+                .update(cx, |store, cx| {
+                    store.refresh(buffer.clone(), cursor_position, cx);
+                });
+        }
+    }
 
-                if let Some(model_suffix) = model_new_text.strip_prefix(&user_new_text) {
-                    if !model_suffix.is_empty() {
-                        let anchor = old_snapshot.anchor_after(user_edit.old.end);
-                        edits.push((anchor..anchor, model_suffix.into()));
-                    }
+    #[cfg(feature = "cli-support")]
+    pub fn set_context_for_buffer(
+        &mut self,
+        project: &Entity<Project>,
+        related_files: Vec<RelatedFile>,
+        cx: &mut Context<Self>,
+    ) {
+        self.get_or_init_project(project, cx)
+            .context
+            .update(cx, |store, _| {
+                store.set_related_files(related_files);
+            });
+    }
+
+    fn is_file_open_source(
+        &self,
+        project: &Entity<Project>,
+        file: &Arc<dyn File>,
+        cx: &App,
+    ) -> bool {
+        if !file.is_local() || file.is_private() {
+            return false;
+        }
+        let Some(project_state) = self.projects.get(&project.entity_id()) else {
+            return false;
+        };
+        project_state
+            .license_detection_watchers
+            .get(&file.worktree_id(cx))
+            .as_ref()
+            .is_some_and(|watcher| watcher.is_project_open_source())
+    }
 
-                    model_edits.next();
-                    continue;
+    fn can_collect_file(&self, project: &Entity<Project>, file: &Arc<dyn File>, cx: &App) -> bool {
+        self.data_collection_choice.is_enabled() && self.is_file_open_source(project, file, cx)
+    }
+
+    fn can_collect_events(&self, events: &[Arc<zeta_prompt::Event>]) -> bool {
+        if !self.data_collection_choice.is_enabled() {
+            return false;
+        }
+        events.iter().all(|event| {
+            matches!(
+                event.as_ref(),
+                zeta_prompt::Event::BufferChange {
+                    in_open_source_repo: true,
+                    ..
                 }
+            )
+        })
+    }
+
+    fn load_data_collection_choice() -> DataCollectionChoice {
+        let choice = KEY_VALUE_STORE
+            .read_kvp(ZED_PREDICT_DATA_COLLECTION_CHOICE)
+            .log_err()
+            .flatten();
+
+        match choice.as_deref() {
+            Some("true") => DataCollectionChoice::Enabled,
+            Some("false") => DataCollectionChoice::Disabled,
+            Some(_) => {
+                log::error!("unknown value in '{ZED_PREDICT_DATA_COLLECTION_CHOICE}'");
+                DataCollectionChoice::NotAnswered
             }
+            None => DataCollectionChoice::NotAnswered,
+        }
+    }
+
+    fn toggle_data_collection_choice(&mut self, cx: &mut Context<Self>) {
+        self.data_collection_choice = self.data_collection_choice.toggle();
+        let new_choice = self.data_collection_choice;
+        db::write_and_log(cx, move || {
+            KEY_VALUE_STORE.write_kvp(
+                ZED_PREDICT_DATA_COLLECTION_CHOICE.into(),
+                new_choice.is_enabled().to_string(),
+            )
+        });
+    }
+
+    pub fn shown_predictions(&self) -> impl DoubleEndedIterator<Item = &EditPrediction> {
+        self.shown_predictions.iter()
+    }
+
+    pub fn shown_completions_len(&self) -> usize {
+        self.shown_predictions.len()
+    }
+
+    pub fn is_prediction_rated(&self, id: &EditPredictionId) -> bool {
+        self.rated_predictions.contains(id)
+    }
+
+    pub fn rate_prediction(
+        &mut self,
+        prediction: &EditPrediction,
+        rating: EditPredictionRating,
+        feedback: String,
+        cx: &mut Context<Self>,
+    ) {
+        self.rated_predictions.insert(prediction.id.clone());
+        telemetry::event!(
+            "Edit Prediction Rated",
+            rating,
+            inputs = prediction.inputs,
+            output = prediction.edit_preview.as_unified_diff(&prediction.edits),
+            feedback
+        );
+        self.client.telemetry().flush_events().detach();
+        cx.notify();
+    }
+
+    fn configure_context_retrieval(&mut self, cx: &mut Context<'_, EditPredictionStore>) {
+        self.use_context = cx.has_flag::<Zeta2FeatureFlag>()
+            && all_language_settings(None, cx).edit_predictions.use_context;
+    }
+}
+
+#[derive(Error, Debug)]
+#[error(
+    "You must update to Zed version {minimum_version} or higher to continue using edit predictions."
+)]
+pub struct ZedUpdateRequiredError {
+    minimum_version: Version,
+}
+
+#[cfg(feature = "cli-support")]
+pub type EvalCacheKey = (EvalCacheEntryKind, u64);
+
+#[cfg(feature = "cli-support")]
+#[derive(Debug, Clone, Copy, PartialEq)]
+pub enum EvalCacheEntryKind {
+    Context,
+    Search,
+    Prediction,
+}
+
+#[cfg(feature = "cli-support")]
+impl std::fmt::Display for EvalCacheEntryKind {
+    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+        match self {
+            EvalCacheEntryKind::Search => write!(f, "search"),
+            EvalCacheEntryKind::Context => write!(f, "context"),
+            EvalCacheEntryKind::Prediction => write!(f, "prediction"),
+        }
+    }
+}
+
+#[cfg(feature = "cli-support")]
+pub trait EvalCache: Send + Sync {
+    fn read(&self, key: EvalCacheKey) -> Option<String>;
+    fn write(&self, key: EvalCacheKey, input: &str, value: &str);
+}
+
+#[derive(Debug, Clone, Copy)]
+pub enum DataCollectionChoice {
+    NotAnswered,
+    Enabled,
+    Disabled,
+}
+
+impl DataCollectionChoice {
+    pub fn is_enabled(self) -> bool {
+        match self {
+            Self::Enabled => true,
+            Self::NotAnswered | Self::Disabled => false,
         }
+    }
 
-        return None;
+    pub fn is_answered(self) -> bool {
+        match self {
+            Self::Enabled | Self::Disabled => true,
+            Self::NotAnswered => false,
+        }
     }
 
-    edits.extend(model_edits.cloned());
+    #[must_use]
+    pub fn toggle(&self) -> DataCollectionChoice {
+        match self {
+            Self::Enabled => Self::Disabled,
+            Self::Disabled => Self::Enabled,
+            Self::NotAnswered => Self::Enabled,
+        }
+    }
+}
+
+impl From<bool> for DataCollectionChoice {
+    fn from(value: bool) -> Self {
+        match value {
+            true => DataCollectionChoice::Enabled,
+            false => DataCollectionChoice::Disabled,
+        }
+    }
+}
+
+struct ZedPredictUpsell;
+
+impl Dismissable for ZedPredictUpsell {
+    const KEY: &'static str = "dismissed-edit-predict-upsell";
+
+    fn dismissed() -> bool {
+        // To make this backwards compatible with older versions of Zed, we
+        // check if the user has seen the previous Edit Prediction Onboarding
+        // before, by checking the data collection choice which was written to
+        // the database once the user clicked on "Accept and Enable"
+        if KEY_VALUE_STORE
+            .read_kvp(ZED_PREDICT_DATA_COLLECTION_CHOICE)
+            .log_err()
+            .is_some_and(|s| s.is_some())
+        {
+            return true;
+        }
+
+        KEY_VALUE_STORE
+            .read_kvp(Self::KEY)
+            .log_err()
+            .is_some_and(|s| s.is_some())
+    }
+}
+
+pub fn should_show_upsell_modal() -> bool {
+    !ZedPredictUpsell::dismissed()
+}
+
+pub fn init(cx: &mut App) {
+    cx.observe_new(move |workspace: &mut Workspace, _, _cx| {
+        workspace.register_action(
+            move |workspace, _: &zed_actions::OpenZedPredictOnboarding, window, cx| {
+                ZedPredictModal::toggle(
+                    workspace,
+                    workspace.user_store().clone(),
+                    workspace.client().clone(),
+                    window,
+                    cx,
+                )
+            },
+        );
 
-    if edits.is_empty() { None } else { Some(edits) }
+        workspace.register_action(|workspace, _: &ResetOnboarding, _window, cx| {
+            update_settings_file(workspace.app_state().fs.clone(), cx, move |settings, _| {
+                settings
+                    .project
+                    .all_languages
+                    .features
+                    .get_or_insert_default()
+                    .edit_prediction_provider = Some(EditPredictionProvider::None)
+            });
+        });
+    })
+    .detach();
 }

crates/edit_prediction/src/edit_prediction_tests.rs 🔗

@@ -0,0 +1,2156 @@
+use super::*;
+use crate::{compute_diff_between_snapshots, udiff::apply_diff_to_string, zeta1::MAX_EVENT_TOKENS};
+use client::{UserStore, test::FakeServer};
+use clock::{FakeSystemClock, ReplicaId};
+use cloud_api_types::{CreateLlmTokenResponse, LlmToken};
+use cloud_llm_client::{
+    EditPredictionRejectReason, EditPredictionRejection, PredictEditsBody, PredictEditsResponse,
+    RejectEditPredictionsBody,
+};
+use futures::{
+    AsyncReadExt, StreamExt,
+    channel::{mpsc, oneshot},
+};
+use gpui::{
+    Entity, TestAppContext,
+    http_client::{FakeHttpClient, Response},
+};
+use indoc::indoc;
+use language::{Point, ToOffset as _};
+use lsp::LanguageServerId;
+use open_ai::Usage;
+use parking_lot::Mutex;
+use pretty_assertions::{assert_eq, assert_matches};
+use project::{FakeFs, Project};
+use serde_json::json;
+use settings::SettingsStore;
+use std::{path::Path, sync::Arc, time::Duration};
+use util::{path, rel_path::rel_path};
+use uuid::Uuid;
+use zeta_prompt::ZetaPromptInput;
+
+use crate::{BufferEditPrediction, EditPredictionId, EditPredictionStore, REJECT_REQUEST_DEBOUNCE};
+
+#[gpui::test]
+async fn test_current_state(cx: &mut TestAppContext) {
+    let (ep_store, mut requests) = init_test_with_fake_client(cx);
+    let fs = FakeFs::new(cx.executor());
+    fs.insert_tree(
+        "/root",
+        json!({
+            "1.txt": "Hello!\nHow\nBye\n",
+            "2.txt": "Hola!\nComo\nAdios\n"
+        }),
+    )
+    .await;
+    let project = Project::test(fs, vec![path!("/root").as_ref()], cx).await;
+
+    let buffer1 = project
+        .update(cx, |project, cx| {
+            let path = project.find_project_path(path!("/root/1.txt"), cx).unwrap();
+            project.set_active_path(Some(path.clone()), cx);
+            project.open_buffer(path, cx)
+        })
+        .await
+        .unwrap();
+    let snapshot1 = buffer1.read_with(cx, |buffer, _cx| buffer.snapshot());
+    let position = snapshot1.anchor_before(language::Point::new(1, 3));
+
+    ep_store.update(cx, |ep_store, cx| {
+        ep_store.register_project(&project, cx);
+        ep_store.register_buffer(&buffer1, &project, cx);
+    });
+
+    // Prediction for current file
+
+    ep_store.update(cx, |ep_store, cx| {
+        ep_store.refresh_prediction_from_buffer(project.clone(), buffer1.clone(), position, cx)
+    });
+    let (request, respond_tx) = requests.predict.next().await.unwrap();
+
+    respond_tx
+        .send(model_response(
+            request,
+            indoc! {r"
+                --- a/root/1.txt
+                +++ b/root/1.txt
+                @@ ... @@
+                 Hello!
+                -How
+                +How are you?
+                 Bye
+            "},
+        ))
+        .unwrap();
+
+    cx.run_until_parked();
+
+    ep_store.update(cx, |ep_store, cx| {
+        let prediction = ep_store
+            .prediction_at(&buffer1, None, &project, cx)
+            .unwrap();
+        assert_matches!(prediction, BufferEditPrediction::Local { .. });
+    });
+
+    ep_store.update(cx, |ep_store, _cx| {
+        ep_store.reject_current_prediction(EditPredictionRejectReason::Discarded, &project);
+    });
+
+    // Prediction for diagnostic in another file
+
+    let diagnostic = lsp::Diagnostic {
+        range: lsp::Range::new(lsp::Position::new(1, 1), lsp::Position::new(1, 5)),
+        severity: Some(lsp::DiagnosticSeverity::ERROR),
+        message: "Sentence is incomplete".to_string(),
+        ..Default::default()
+    };
+
+    project.update(cx, |project, cx| {
+        project.lsp_store().update(cx, |lsp_store, cx| {
+            lsp_store
+                .update_diagnostics(
+                    LanguageServerId(0),
+                    lsp::PublishDiagnosticsParams {
+                        uri: lsp::Uri::from_file_path(path!("/root/2.txt")).unwrap(),
+                        diagnostics: vec![diagnostic],
+                        version: None,
+                    },
+                    None,
+                    language::DiagnosticSourceKind::Pushed,
+                    &[],
+                    cx,
+                )
+                .unwrap();
+        });
+    });
+
+    let (request, respond_tx) = requests.predict.next().await.unwrap();
+    respond_tx
+        .send(model_response(
+            request,
+            indoc! {r#"
+                --- a/root/2.txt
+                +++ b/root/2.txt
+                @@ ... @@
+                 Hola!
+                -Como
+                +Como estas?
+                 Adios
+            "#},
+        ))
+        .unwrap();
+    cx.run_until_parked();
+
+    ep_store.update(cx, |ep_store, cx| {
+        let prediction = ep_store
+            .prediction_at(&buffer1, None, &project, cx)
+            .unwrap();
+        assert_matches!(
+            prediction,
+            BufferEditPrediction::Jump { prediction } if prediction.snapshot.file().unwrap().full_path(cx) == Path::new(path!("root/2.txt"))
+        );
+    });
+
+    let buffer2 = project
+        .update(cx, |project, cx| {
+            let path = project.find_project_path(path!("root/2.txt"), cx).unwrap();
+            project.open_buffer(path, cx)
+        })
+        .await
+        .unwrap();
+
+    ep_store.update(cx, |ep_store, cx| {
+        let prediction = ep_store
+            .prediction_at(&buffer2, None, &project, cx)
+            .unwrap();
+        assert_matches!(prediction, BufferEditPrediction::Local { .. });
+    });
+}
+
+#[gpui::test]
+async fn test_simple_request(cx: &mut TestAppContext) {
+    let (ep_store, mut requests) = init_test_with_fake_client(cx);
+    let fs = FakeFs::new(cx.executor());
+    fs.insert_tree(
+        "/root",
+        json!({
+            "foo.md":  "Hello!\nHow\nBye\n"
+        }),
+    )
+    .await;
+    let project = Project::test(fs, vec![path!("/root").as_ref()], cx).await;
+
+    let buffer = project
+        .update(cx, |project, cx| {
+            let path = project.find_project_path(path!("root/foo.md"), cx).unwrap();
+            project.open_buffer(path, cx)
+        })
+        .await
+        .unwrap();
+    let snapshot = buffer.read_with(cx, |buffer, _cx| buffer.snapshot());
+    let position = snapshot.anchor_before(language::Point::new(1, 3));
+
+    let prediction_task = ep_store.update(cx, |ep_store, cx| {
+        ep_store.request_prediction(&project, &buffer, position, Default::default(), cx)
+    });
+
+    let (request, respond_tx) = requests.predict.next().await.unwrap();
+
+    // TODO Put back when we have a structured request again
+    // assert_eq!(
+    //     request.excerpt_path.as_ref(),
+    //     Path::new(path!("root/foo.md"))
+    // );
+    // assert_eq!(
+    //     request.cursor_point,
+    //     Point {
+    //         line: Line(1),
+    //         column: 3
+    //     }
+    // );
+
+    respond_tx
+        .send(model_response(
+            request,
+            indoc! { r"
+                --- a/root/foo.md
+                +++ b/root/foo.md
+                @@ ... @@
+                 Hello!
+                -How
+                +How are you?
+                 Bye
+            "},
+        ))
+        .unwrap();
+
+    let prediction = prediction_task.await.unwrap().unwrap().prediction.unwrap();
+
+    assert_eq!(prediction.edits.len(), 1);
+    assert_eq!(
+        prediction.edits[0].0.to_point(&snapshot).start,
+        language::Point::new(1, 3)
+    );
+    assert_eq!(prediction.edits[0].1.as_ref(), " are you?");
+}
+
+#[gpui::test]
+async fn test_request_events(cx: &mut TestAppContext) {
+    let (ep_store, mut requests) = init_test_with_fake_client(cx);
+    let fs = FakeFs::new(cx.executor());
+    fs.insert_tree(
+        "/root",
+        json!({
+            "foo.md": "Hello!\n\nBye\n"
+        }),
+    )
+    .await;
+    let project = Project::test(fs, vec![path!("/root").as_ref()], cx).await;
+
+    let buffer = project
+        .update(cx, |project, cx| {
+            let path = project.find_project_path(path!("root/foo.md"), cx).unwrap();
+            project.open_buffer(path, cx)
+        })
+        .await
+        .unwrap();
+
+    ep_store.update(cx, |ep_store, cx| {
+        ep_store.register_buffer(&buffer, &project, cx);
+    });
+
+    buffer.update(cx, |buffer, cx| {
+        buffer.edit(vec![(7..7, "How")], None, cx);
+    });
+
+    let snapshot = buffer.read_with(cx, |buffer, _cx| buffer.snapshot());
+    let position = snapshot.anchor_before(language::Point::new(1, 3));
+
+    let prediction_task = ep_store.update(cx, |ep_store, cx| {
+        ep_store.request_prediction(&project, &buffer, position, Default::default(), cx)
+    });
+
+    let (request, respond_tx) = requests.predict.next().await.unwrap();
+
+    let prompt = prompt_from_request(&request);
+    assert!(
+        prompt.contains(indoc! {"
+        --- a/root/foo.md
+        +++ b/root/foo.md
+        @@ -1,3 +1,3 @@
+         Hello!
+        -
+        +How
+         Bye
+    "}),
+        "{prompt}"
+    );
+
+    respond_tx
+        .send(model_response(
+            request,
+            indoc! {r#"
+                --- a/root/foo.md
+                +++ b/root/foo.md
+                @@ ... @@
+                 Hello!
+                -How
+                +How are you?
+                 Bye
+        "#},
+        ))
+        .unwrap();
+
+    let prediction = prediction_task.await.unwrap().unwrap().prediction.unwrap();
+
+    assert_eq!(prediction.edits.len(), 1);
+    assert_eq!(prediction.edits[0].1.as_ref(), " are you?");
+}
+
+#[gpui::test]
+async fn test_edit_history_getter_pause_splits_last_event(cx: &mut TestAppContext) {
+    let (ep_store, _requests) = init_test_with_fake_client(cx);
+    let fs = FakeFs::new(cx.executor());
+    fs.insert_tree(
+        "/root",
+        json!({
+            "foo.md": "Hello!\n\nBye\n"
+        }),
+    )
+    .await;
+    let project = Project::test(fs, vec![path!("/root").as_ref()], cx).await;
+
+    let buffer = project
+        .update(cx, |project, cx| {
+            let path = project.find_project_path(path!("root/foo.md"), cx).unwrap();
+            project.open_buffer(path, cx)
+        })
+        .await
+        .unwrap();
+
+    ep_store.update(cx, |ep_store, cx| {
+        ep_store.register_buffer(&buffer, &project, cx);
+    });
+
+    // First burst: insert "How"
+    buffer.update(cx, |buffer, cx| {
+        buffer.edit(vec![(7..7, "How")], None, cx);
+    });
+
+    // Simulate a pause longer than the grouping threshold (e.g. 500ms).
+    cx.executor().advance_clock(LAST_CHANGE_GROUPING_TIME * 2);
+    cx.run_until_parked();
+
+    // Second burst: append " are you?" immediately after "How" on the same line.
+    //
+    // Keeping both bursts on the same line ensures the existing line-span coalescing logic
+    // groups them into a single `LastEvent`, allowing the pause-split getter to return two diffs.
+    buffer.update(cx, |buffer, cx| {
+        buffer.edit(vec![(10..10, " are you?")], None, cx);
+    });
+
+    // A second edit shortly after the first post-pause edit ensures the last edit timestamp is
+    // advanced after the pause boundary is recorded, making pause-splitting deterministic.
+    buffer.update(cx, |buffer, cx| {
+        buffer.edit(vec![(19..19, "!")], None, cx);
+    });
+
+    // Without time-based splitting, there is one event.
+    let events = ep_store.update(cx, |ep_store, cx| {
+        ep_store.edit_history_for_project(&project, cx)
+    });
+    assert_eq!(events.len(), 1);
+    let zeta_prompt::Event::BufferChange { diff, .. } = events[0].event.as_ref();
+    assert_eq!(
+        diff.as_str(),
+        indoc! {"
+            @@ -1,3 +1,3 @@
+             Hello!
+            -
+            +How are you?!
+             Bye
+        "}
+    );
+
+    // With time-based splitting, there are two distinct events.
+    let events = ep_store.update(cx, |ep_store, cx| {
+        ep_store.edit_history_for_project_with_pause_split_last_event(&project, cx)
+    });
+    assert_eq!(events.len(), 2);
+    let zeta_prompt::Event::BufferChange { diff, .. } = events[0].event.as_ref();
+    assert_eq!(
+        diff.as_str(),
+        indoc! {"
+            @@ -1,3 +1,3 @@
+             Hello!
+            -
+            +How
+             Bye
+        "}
+    );
+
+    let zeta_prompt::Event::BufferChange { diff, .. } = events[1].event.as_ref();
+    assert_eq!(
+        diff.as_str(),
+        indoc! {"
+            @@ -1,3 +1,3 @@
+             Hello!
+            -How
+            +How are you?!
+             Bye
+        "}
+    );
+}
+
+#[gpui::test]
+async fn test_empty_prediction(cx: &mut TestAppContext) {
+    let (ep_store, mut requests) = init_test_with_fake_client(cx);
+    let fs = FakeFs::new(cx.executor());
+    fs.insert_tree(
+        "/root",
+        json!({
+            "foo.md":  "Hello!\nHow\nBye\n"
+        }),
+    )
+    .await;
+    let project = Project::test(fs, vec![path!("/root").as_ref()], cx).await;
+
+    let buffer = project
+        .update(cx, |project, cx| {
+            let path = project.find_project_path(path!("root/foo.md"), cx).unwrap();
+            project.open_buffer(path, cx)
+        })
+        .await
+        .unwrap();
+    let snapshot = buffer.read_with(cx, |buffer, _cx| buffer.snapshot());
+    let position = snapshot.anchor_before(language::Point::new(1, 3));
+
+    ep_store.update(cx, |ep_store, cx| {
+        ep_store.refresh_prediction_from_buffer(project.clone(), buffer.clone(), position, cx);
+    });
+
+    let (request, respond_tx) = requests.predict.next().await.unwrap();
+    let response = model_response(request, "");
+    let id = response.id.clone();
+    respond_tx.send(response).unwrap();
+
+    cx.run_until_parked();
+
+    ep_store.update(cx, |ep_store, cx| {
+        assert!(
+            ep_store
+                .prediction_at(&buffer, None, &project, cx)
+                .is_none()
+        );
+    });
+
+    // prediction is reported as rejected
+    let (reject_request, _) = requests.reject.next().await.unwrap();
+
+    assert_eq!(
+        &reject_request.rejections,
+        &[EditPredictionRejection {
+            request_id: id,
+            reason: EditPredictionRejectReason::Empty,
+            was_shown: false
+        }]
+    );
+}
+
+#[gpui::test]
+async fn test_interpolated_empty(cx: &mut TestAppContext) {
+    let (ep_store, mut requests) = init_test_with_fake_client(cx);
+    let fs = FakeFs::new(cx.executor());
+    fs.insert_tree(
+        "/root",
+        json!({
+            "foo.md":  "Hello!\nHow\nBye\n"
+        }),
+    )
+    .await;
+    let project = Project::test(fs, vec![path!("/root").as_ref()], cx).await;
+
+    let buffer = project
+        .update(cx, |project, cx| {
+            let path = project.find_project_path(path!("root/foo.md"), cx).unwrap();
+            project.open_buffer(path, cx)
+        })
+        .await
+        .unwrap();
+    let snapshot = buffer.read_with(cx, |buffer, _cx| buffer.snapshot());
+    let position = snapshot.anchor_before(language::Point::new(1, 3));
+
+    ep_store.update(cx, |ep_store, cx| {
+        ep_store.refresh_prediction_from_buffer(project.clone(), buffer.clone(), position, cx);
+    });
+
+    let (request, respond_tx) = requests.predict.next().await.unwrap();
+
+    buffer.update(cx, |buffer, cx| {
+        buffer.set_text("Hello!\nHow are you?\nBye", cx);
+    });
+
+    let response = model_response(request, SIMPLE_DIFF);
+    let id = response.id.clone();
+    respond_tx.send(response).unwrap();
+
+    cx.run_until_parked();
+
+    ep_store.update(cx, |ep_store, cx| {
+        assert!(
+            ep_store
+                .prediction_at(&buffer, None, &project, cx)
+                .is_none()
+        );
+    });
+
+    // prediction is reported as rejected
+    let (reject_request, _) = requests.reject.next().await.unwrap();
+
+    assert_eq!(
+        &reject_request.rejections,
+        &[EditPredictionRejection {
+            request_id: id,
+            reason: EditPredictionRejectReason::InterpolatedEmpty,
+            was_shown: false
+        }]
+    );
+}
+
+const SIMPLE_DIFF: &str = indoc! { r"
+    --- a/root/foo.md
+    +++ b/root/foo.md
+    @@ ... @@
+     Hello!
+    -How
+    +How are you?
+     Bye
+"};
+
+#[gpui::test]
+async fn test_replace_current(cx: &mut TestAppContext) {
+    let (ep_store, mut requests) = init_test_with_fake_client(cx);
+    let fs = FakeFs::new(cx.executor());
+    fs.insert_tree(
+        "/root",
+        json!({
+            "foo.md":  "Hello!\nHow\nBye\n"
+        }),
+    )
+    .await;
+    let project = Project::test(fs, vec![path!("/root").as_ref()], cx).await;
+
+    let buffer = project
+        .update(cx, |project, cx| {
+            let path = project.find_project_path(path!("root/foo.md"), cx).unwrap();
+            project.open_buffer(path, cx)
+        })
+        .await
+        .unwrap();
+    let snapshot = buffer.read_with(cx, |buffer, _cx| buffer.snapshot());
+    let position = snapshot.anchor_before(language::Point::new(1, 3));
+
+    ep_store.update(cx, |ep_store, cx| {
+        ep_store.refresh_prediction_from_buffer(project.clone(), buffer.clone(), position, cx);
+    });
+
+    let (request, respond_tx) = requests.predict.next().await.unwrap();
+    let first_response = model_response(request, SIMPLE_DIFF);
+    let first_id = first_response.id.clone();
+    respond_tx.send(first_response).unwrap();
+
+    cx.run_until_parked();
+
+    ep_store.update(cx, |ep_store, cx| {
+        assert_eq!(
+            ep_store
+                .prediction_at(&buffer, None, &project, cx)
+                .unwrap()
+                .id
+                .0,
+            first_id
+        );
+    });
+
+    // a second request is triggered
+    ep_store.update(cx, |ep_store, cx| {
+        ep_store.refresh_prediction_from_buffer(project.clone(), buffer.clone(), position, cx);
+    });
+
+    let (request, respond_tx) = requests.predict.next().await.unwrap();
+    let second_response = model_response(request, SIMPLE_DIFF);
+    let second_id = second_response.id.clone();
+    respond_tx.send(second_response).unwrap();
+
+    cx.run_until_parked();
+
+    ep_store.update(cx, |ep_store, cx| {
+        // second replaces first
+        assert_eq!(
+            ep_store
+                .prediction_at(&buffer, None, &project, cx)
+                .unwrap()
+                .id
+                .0,
+            second_id
+        );
+    });
+
+    // first is reported as replaced
+    let (reject_request, _) = requests.reject.next().await.unwrap();
+
+    assert_eq!(
+        &reject_request.rejections,
+        &[EditPredictionRejection {
+            request_id: first_id,
+            reason: EditPredictionRejectReason::Replaced,
+            was_shown: false
+        }]
+    );
+}
+
+#[gpui::test]
+async fn test_current_preferred(cx: &mut TestAppContext) {
+    let (ep_store, mut requests) = init_test_with_fake_client(cx);
+    let fs = FakeFs::new(cx.executor());
+    fs.insert_tree(
+        "/root",
+        json!({
+            "foo.md":  "Hello!\nHow\nBye\n"
+        }),
+    )
+    .await;
+    let project = Project::test(fs, vec![path!("/root").as_ref()], cx).await;
+
+    let buffer = project
+        .update(cx, |project, cx| {
+            let path = project.find_project_path(path!("root/foo.md"), cx).unwrap();
+            project.open_buffer(path, cx)
+        })
+        .await
+        .unwrap();
+    let snapshot = buffer.read_with(cx, |buffer, _cx| buffer.snapshot());
+    let position = snapshot.anchor_before(language::Point::new(1, 3));
+
+    ep_store.update(cx, |ep_store, cx| {
+        ep_store.refresh_prediction_from_buffer(project.clone(), buffer.clone(), position, cx);
+    });
+
+    let (request, respond_tx) = requests.predict.next().await.unwrap();
+    let first_response = model_response(request, SIMPLE_DIFF);
+    let first_id = first_response.id.clone();
+    respond_tx.send(first_response).unwrap();
+
+    cx.run_until_parked();
+
+    ep_store.update(cx, |ep_store, cx| {
+        assert_eq!(
+            ep_store
+                .prediction_at(&buffer, None, &project, cx)
+                .unwrap()
+                .id
+                .0,
+            first_id
+        );
+    });
+
+    // a second request is triggered
+    ep_store.update(cx, |ep_store, cx| {
+        ep_store.refresh_prediction_from_buffer(project.clone(), buffer.clone(), position, cx);
+    });
+
+    let (request, respond_tx) = requests.predict.next().await.unwrap();
+    // worse than current prediction
+    let second_response = model_response(
+        request,
+        indoc! { r"
+            --- a/root/foo.md
+            +++ b/root/foo.md
+            @@ ... @@
+             Hello!
+            -How
+            +How are
+             Bye
+        "},
+    );
+    let second_id = second_response.id.clone();
+    respond_tx.send(second_response).unwrap();
+
+    cx.run_until_parked();
+
+    ep_store.update(cx, |ep_store, cx| {
+        // first is preferred over second
+        assert_eq!(
+            ep_store
+                .prediction_at(&buffer, None, &project, cx)
+                .unwrap()
+                .id
+                .0,
+            first_id
+        );
+    });
+
+    // second is reported as rejected
+    let (reject_request, _) = requests.reject.next().await.unwrap();
+
+    assert_eq!(
+        &reject_request.rejections,
+        &[EditPredictionRejection {
+            request_id: second_id,
+            reason: EditPredictionRejectReason::CurrentPreferred,
+            was_shown: false
+        }]
+    );
+}
+
+#[gpui::test]
+async fn test_cancel_earlier_pending_requests(cx: &mut TestAppContext) {
+    let (ep_store, mut requests) = init_test_with_fake_client(cx);
+    let fs = FakeFs::new(cx.executor());
+    fs.insert_tree(
+        "/root",
+        json!({
+            "foo.md":  "Hello!\nHow\nBye\n"
+        }),
+    )
+    .await;
+    let project = Project::test(fs, vec![path!("/root").as_ref()], cx).await;
+
+    let buffer = project
+        .update(cx, |project, cx| {
+            let path = project.find_project_path(path!("root/foo.md"), cx).unwrap();
+            project.open_buffer(path, cx)
+        })
+        .await
+        .unwrap();
+    let snapshot = buffer.read_with(cx, |buffer, _cx| buffer.snapshot());
+    let position = snapshot.anchor_before(language::Point::new(1, 3));
+
+    // start two refresh tasks
+    ep_store.update(cx, |ep_store, cx| {
+        ep_store.refresh_prediction_from_buffer(project.clone(), buffer.clone(), position, cx);
+    });
+
+    let (request1, respond_first) = requests.predict.next().await.unwrap();
+
+    ep_store.update(cx, |ep_store, cx| {
+        ep_store.refresh_prediction_from_buffer(project.clone(), buffer.clone(), position, cx);
+    });
+
+    let (request, respond_second) = requests.predict.next().await.unwrap();
+
+    // wait for throttle
+    cx.run_until_parked();
+
+    // second responds first
+    let second_response = model_response(request, SIMPLE_DIFF);
+    let second_id = second_response.id.clone();
+    respond_second.send(second_response).unwrap();
+
+    cx.run_until_parked();
+
+    ep_store.update(cx, |ep_store, cx| {
+        // current prediction is second
+        assert_eq!(
+            ep_store
+                .prediction_at(&buffer, None, &project, cx)
+                .unwrap()
+                .id
+                .0,
+            second_id
+        );
+    });
+
+    let first_response = model_response(request1, SIMPLE_DIFF);
+    let first_id = first_response.id.clone();
+    respond_first.send(first_response).unwrap();
+
+    cx.run_until_parked();
+
+    ep_store.update(cx, |ep_store, cx| {
+        // current prediction is still second, since first was cancelled
+        assert_eq!(
+            ep_store
+                .prediction_at(&buffer, None, &project, cx)
+                .unwrap()
+                .id
+                .0,
+            second_id
+        );
+    });
+
+    // first is reported as rejected
+    let (reject_request, _) = requests.reject.next().await.unwrap();
+
+    cx.run_until_parked();
+
+    assert_eq!(
+        &reject_request.rejections,
+        &[EditPredictionRejection {
+            request_id: first_id,
+            reason: EditPredictionRejectReason::Canceled,
+            was_shown: false
+        }]
+    );
+}
+
+#[gpui::test]
+async fn test_cancel_second_on_third_request(cx: &mut TestAppContext) {
+    let (ep_store, mut requests) = init_test_with_fake_client(cx);
+    let fs = FakeFs::new(cx.executor());
+    fs.insert_tree(
+        "/root",
+        json!({
+            "foo.md":  "Hello!\nHow\nBye\n"
+        }),
+    )
+    .await;
+    let project = Project::test(fs, vec![path!("/root").as_ref()], cx).await;
+
+    let buffer = project
+        .update(cx, |project, cx| {
+            let path = project.find_project_path(path!("root/foo.md"), cx).unwrap();
+            project.open_buffer(path, cx)
+        })
+        .await
+        .unwrap();
+    let snapshot = buffer.read_with(cx, |buffer, _cx| buffer.snapshot());
+    let position = snapshot.anchor_before(language::Point::new(1, 3));
+
+    // start two refresh tasks
+    ep_store.update(cx, |ep_store, cx| {
+        ep_store.refresh_prediction_from_buffer(project.clone(), buffer.clone(), position, cx);
+    });
+
+    let (request1, respond_first) = requests.predict.next().await.unwrap();
+
+    ep_store.update(cx, |ep_store, cx| {
+        ep_store.refresh_prediction_from_buffer(project.clone(), buffer.clone(), position, cx);
+    });
+
+    let (request2, respond_second) = requests.predict.next().await.unwrap();
+
+    // wait for throttle, so requests are sent
+    cx.run_until_parked();
+
+    ep_store.update(cx, |ep_store, cx| {
+        // start a third request
+        ep_store.refresh_prediction_from_buffer(project.clone(), buffer.clone(), position, cx);
+
+        // 2 are pending, so 2nd is cancelled
+        assert_eq!(
+            ep_store
+                .get_or_init_project(&project, cx)
+                .cancelled_predictions
+                .iter()
+                .copied()
+                .collect::<Vec<_>>(),
+            [1]
+        );
+    });
+
+    // wait for throttle
+    cx.run_until_parked();
+
+    let (request3, respond_third) = requests.predict.next().await.unwrap();
+
+    let first_response = model_response(request1, SIMPLE_DIFF);
+    let first_id = first_response.id.clone();
+    respond_first.send(first_response).unwrap();
+
+    cx.run_until_parked();
+
+    ep_store.update(cx, |ep_store, cx| {
+        // current prediction is first
+        assert_eq!(
+            ep_store
+                .prediction_at(&buffer, None, &project, cx)
+                .unwrap()
+                .id
+                .0,
+            first_id
+        );
+    });
+
+    let cancelled_response = model_response(request2, SIMPLE_DIFF);
+    let cancelled_id = cancelled_response.id.clone();
+    respond_second.send(cancelled_response).unwrap();
+
+    cx.run_until_parked();
+
+    ep_store.update(cx, |ep_store, cx| {
+        // current prediction is still first, since second was cancelled
+        assert_eq!(
+            ep_store
+                .prediction_at(&buffer, None, &project, cx)
+                .unwrap()
+                .id
+                .0,
+            first_id
+        );
+    });
+
+    let third_response = model_response(request3, SIMPLE_DIFF);
+    let third_response_id = third_response.id.clone();
+    respond_third.send(third_response).unwrap();
+
+    cx.run_until_parked();
+
+    ep_store.update(cx, |ep_store, cx| {
+        // third completes and replaces first
+        assert_eq!(
+            ep_store
+                .prediction_at(&buffer, None, &project, cx)
+                .unwrap()
+                .id
+                .0,
+            third_response_id
+        );
+    });
+
+    // second is reported as rejected
+    let (reject_request, _) = requests.reject.next().await.unwrap();
+
+    cx.run_until_parked();
+
+    assert_eq!(
+        &reject_request.rejections,
+        &[
+            EditPredictionRejection {
+                request_id: cancelled_id,
+                reason: EditPredictionRejectReason::Canceled,
+                was_shown: false
+            },
+            EditPredictionRejection {
+                request_id: first_id,
+                reason: EditPredictionRejectReason::Replaced,
+                was_shown: false
+            }
+        ]
+    );
+}
+
+#[gpui::test]
+async fn test_rejections_flushing(cx: &mut TestAppContext) {
+    let (ep_store, mut requests) = init_test_with_fake_client(cx);
+
+    ep_store.update(cx, |ep_store, _cx| {
+        ep_store.reject_prediction(
+            EditPredictionId("test-1".into()),
+            EditPredictionRejectReason::Discarded,
+            false,
+        );
+        ep_store.reject_prediction(
+            EditPredictionId("test-2".into()),
+            EditPredictionRejectReason::Canceled,
+            true,
+        );
+    });
+
+    cx.executor().advance_clock(REJECT_REQUEST_DEBOUNCE);
+    cx.run_until_parked();
+
+    let (reject_request, respond_tx) = requests.reject.next().await.unwrap();
+    respond_tx.send(()).unwrap();
+
+    // batched
+    assert_eq!(reject_request.rejections.len(), 2);
+    assert_eq!(
+        reject_request.rejections[0],
+        EditPredictionRejection {
+            request_id: "test-1".to_string(),
+            reason: EditPredictionRejectReason::Discarded,
+            was_shown: false
+        }
+    );
+    assert_eq!(
+        reject_request.rejections[1],
+        EditPredictionRejection {
+            request_id: "test-2".to_string(),
+            reason: EditPredictionRejectReason::Canceled,
+            was_shown: true
+        }
+    );
+
+    // Reaching batch size limit sends without debounce
+    ep_store.update(cx, |ep_store, _cx| {
+        for i in 0..70 {
+            ep_store.reject_prediction(
+                EditPredictionId(format!("batch-{}", i).into()),
+                EditPredictionRejectReason::Discarded,
+                false,
+            );
+        }
+    });
+
+    // First MAX/2 items are sent immediately
+    cx.run_until_parked();
+    let (reject_request, respond_tx) = requests.reject.next().await.unwrap();
+    respond_tx.send(()).unwrap();
+
+    assert_eq!(reject_request.rejections.len(), 50);
+    assert_eq!(reject_request.rejections[0].request_id, "batch-0");
+    assert_eq!(reject_request.rejections[49].request_id, "batch-49");
+
+    // Remaining items are debounced with the next batch
+    cx.executor().advance_clock(Duration::from_secs(15));
+    cx.run_until_parked();
+
+    let (reject_request, respond_tx) = requests.reject.next().await.unwrap();
+    respond_tx.send(()).unwrap();
+
+    assert_eq!(reject_request.rejections.len(), 20);
+    assert_eq!(reject_request.rejections[0].request_id, "batch-50");
+    assert_eq!(reject_request.rejections[19].request_id, "batch-69");
+
+    // Request failure
+    ep_store.update(cx, |ep_store, _cx| {
+        ep_store.reject_prediction(
+            EditPredictionId("retry-1".into()),
+            EditPredictionRejectReason::Discarded,
+            false,
+        );
+    });
+
+    cx.executor().advance_clock(REJECT_REQUEST_DEBOUNCE);
+    cx.run_until_parked();
+
+    let (reject_request, _respond_tx) = requests.reject.next().await.unwrap();
+    assert_eq!(reject_request.rejections.len(), 1);
+    assert_eq!(reject_request.rejections[0].request_id, "retry-1");
+    // Simulate failure
+    drop(_respond_tx);
+
+    // Add another rejection
+    ep_store.update(cx, |ep_store, _cx| {
+        ep_store.reject_prediction(
+            EditPredictionId("retry-2".into()),
+            EditPredictionRejectReason::Discarded,
+            false,
+        );
+    });
+
+    cx.executor().advance_clock(REJECT_REQUEST_DEBOUNCE);
+    cx.run_until_parked();
+
+    // Retry should include both the failed item and the new one
+    let (reject_request, respond_tx) = requests.reject.next().await.unwrap();
+    respond_tx.send(()).unwrap();
+
+    assert_eq!(reject_request.rejections.len(), 2);
+    assert_eq!(reject_request.rejections[0].request_id, "retry-1");
+    assert_eq!(reject_request.rejections[1].request_id, "retry-2");
+}
+
+// Skipped until we start including diagnostics in prompt
+// #[gpui::test]
+// async fn test_request_diagnostics(cx: &mut TestAppContext) {
+//     let (ep_store, mut req_rx) = init_test_with_fake_client(cx);
+//     let fs = FakeFs::new(cx.executor());
+//     fs.insert_tree(
+//         "/root",
+//         json!({
+//             "foo.md": "Hello!\nBye"
+//         }),
+//     )
+//     .await;
+//     let project = Project::test(fs, vec![path!("/root").as_ref()], cx).await;
+
+//     let path_to_buffer_uri = lsp::Uri::from_file_path(path!("/root/foo.md")).unwrap();
+//     let diagnostic = lsp::Diagnostic {
+//         range: lsp::Range::new(lsp::Position::new(1, 1), lsp::Position::new(1, 5)),
+//         severity: Some(lsp::DiagnosticSeverity::ERROR),
+//         message: "\"Hello\" deprecated. Use \"Hi\" instead".to_string(),
+//         ..Default::default()
+//     };
+
+//     project.update(cx, |project, cx| {
+//         project.lsp_store().update(cx, |lsp_store, cx| {
+//             // Create some diagnostics
+//             lsp_store
+//                 .update_diagnostics(
+//                     LanguageServerId(0),
+//                     lsp::PublishDiagnosticsParams {
+//                         uri: path_to_buffer_uri.clone(),
+//                         diagnostics: vec![diagnostic],
+//                         version: None,
+//                     },
+//                     None,
+//                     language::DiagnosticSourceKind::Pushed,
+//                     &[],
+//                     cx,
+//                 )
+//                 .unwrap();
+//         });
+//     });
+
+//     let buffer = project
+//         .update(cx, |project, cx| {
+//             let path = project.find_project_path(path!("root/foo.md"), cx).unwrap();
+//             project.open_buffer(path, cx)
+//         })
+//         .await
+//         .unwrap();
+
+//     let snapshot = buffer.read_with(cx, |buffer, _cx| buffer.snapshot());
+//     let position = snapshot.anchor_before(language::Point::new(0, 0));
+
+//     let _prediction_task = ep_store.update(cx, |ep_store, cx| {
+//         ep_store.request_prediction(&project, &buffer, position, cx)
+//     });
+
+//     let (request, _respond_tx) = req_rx.next().await.unwrap();
+
+//     assert_eq!(request.diagnostic_groups.len(), 1);
+//     let value = serde_json::from_str::<serde_json::Value>(request.diagnostic_groups[0].0.get())
+//         .unwrap();
+//     // We probably don't need all of this. TODO define a specific diagnostic type in predict_edits_v3
+//     assert_eq!(
+//         value,
+//         json!({
+//             "entries": [{
+//                 "range": {
+//                     "start": 8,
+//                     "end": 10
+//                 },
+//                 "diagnostic": {
+//                     "source": null,
+//                     "code": null,
+//                     "code_description": null,
+//                     "severity": 1,
+//                     "message": "\"Hello\" deprecated. Use \"Hi\" instead",
+//                     "markdown": null,
+//                     "group_id": 0,
+//                     "is_primary": true,
+//                     "is_disk_based": false,
+//                     "is_unnecessary": false,
+//                     "source_kind": "Pushed",
+//                     "data": null,
+//                     "underline": true
+//                 }
+//             }],
+//             "primary_ix": 0
+//         })
+//     );
+// }
+
+// Generate a model response that would apply the given diff to the active file.
+fn model_response(request: open_ai::Request, diff_to_apply: &str) -> open_ai::Response {
+    let prompt = match &request.messages[0] {
+        open_ai::RequestMessage::User {
+            content: open_ai::MessageContent::Plain(content),
+        } => content,
+        _ => panic!("unexpected request {request:?}"),
+    };
+
+    let open = "<editable_region>\n";
+    let close = "</editable_region>";
+    let cursor = "<|user_cursor|>";
+
+    let start_ix = open.len() + prompt.find(open).unwrap();
+    let end_ix = start_ix + &prompt[start_ix..].find(close).unwrap();
+    let excerpt = prompt[start_ix..end_ix].replace(cursor, "");
+    let new_excerpt = apply_diff_to_string(diff_to_apply, &excerpt).unwrap();
+
+    open_ai::Response {
+        id: Uuid::new_v4().to_string(),
+        object: "response".into(),
+        created: 0,
+        model: "model".into(),
+        choices: vec![open_ai::Choice {
+            index: 0,
+            message: open_ai::RequestMessage::Assistant {
+                content: Some(open_ai::MessageContent::Plain(new_excerpt)),
+                tool_calls: vec![],
+            },
+            finish_reason: None,
+        }],
+        usage: Usage {
+            prompt_tokens: 0,
+            completion_tokens: 0,
+            total_tokens: 0,
+        },
+    }
+}
+
+fn prompt_from_request(request: &open_ai::Request) -> &str {
+    assert_eq!(request.messages.len(), 1);
+    let open_ai::RequestMessage::User {
+        content: open_ai::MessageContent::Plain(content),
+        ..
+    } = &request.messages[0]
+    else {
+        panic!(
+            "Request does not have single user message of type Plain. {:#?}",
+            request
+        );
+    };
+    content
+}
+
+struct RequestChannels {
+    predict: mpsc::UnboundedReceiver<(open_ai::Request, oneshot::Sender<open_ai::Response>)>,
+    reject: mpsc::UnboundedReceiver<(RejectEditPredictionsBody, oneshot::Sender<()>)>,
+}
+
+fn init_test_with_fake_client(
+    cx: &mut TestAppContext,
+) -> (Entity<EditPredictionStore>, RequestChannels) {
+    cx.update(move |cx| {
+        let settings_store = SettingsStore::test(cx);
+        cx.set_global(settings_store);
+        zlog::init_test();
+
+        let (predict_req_tx, predict_req_rx) = mpsc::unbounded();
+        let (reject_req_tx, reject_req_rx) = mpsc::unbounded();
+
+        let http_client = FakeHttpClient::create({
+            move |req| {
+                let uri = req.uri().path().to_string();
+                let mut body = req.into_body();
+                let predict_req_tx = predict_req_tx.clone();
+                let reject_req_tx = reject_req_tx.clone();
+                async move {
+                    let resp = match uri.as_str() {
+                        "/client/llm_tokens" => serde_json::to_string(&json!({
+                            "token": "test"
+                        }))
+                        .unwrap(),
+                        "/predict_edits/raw" => {
+                            let mut buf = Vec::new();
+                            body.read_to_end(&mut buf).await.ok();
+                            let req = serde_json::from_slice(&buf).unwrap();
+
+                            let (res_tx, res_rx) = oneshot::channel();
+                            predict_req_tx.unbounded_send((req, res_tx)).unwrap();
+                            serde_json::to_string(&res_rx.await?).unwrap()
+                        }
+                        "/predict_edits/reject" => {
+                            let mut buf = Vec::new();
+                            body.read_to_end(&mut buf).await.ok();
+                            let req = serde_json::from_slice(&buf).unwrap();
+
+                            let (res_tx, res_rx) = oneshot::channel();
+                            reject_req_tx.unbounded_send((req, res_tx)).unwrap();
+                            serde_json::to_string(&res_rx.await?).unwrap()
+                        }
+                        _ => {
+                            panic!("Unexpected path: {}", uri)
+                        }
+                    };
+
+                    Ok(Response::builder().body(resp.into()).unwrap())
+                }
+            }
+        });
+
+        let client = client::Client::new(Arc::new(FakeSystemClock::new()), http_client, cx);
+        client.cloud_client().set_credentials(1, "test".into());
+
+        language_model::init(client.clone(), cx);
+
+        let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
+        let ep_store = EditPredictionStore::global(&client, &user_store, cx);
+
+        (
+            ep_store,
+            RequestChannels {
+                predict: predict_req_rx,
+                reject: reject_req_rx,
+            },
+        )
+    })
+}
+
+const BSD_0_TXT: &str = include_str!("../license_examples/0bsd.txt");
+
+#[gpui::test]
+async fn test_edit_prediction_basic_interpolation(cx: &mut TestAppContext) {
+    let buffer = cx.new(|cx| Buffer::local("Lorem ipsum dolor", cx));
+    let edits: Arc<[(Range<Anchor>, Arc<str>)]> = cx.update(|cx| {
+        to_completion_edits([(2..5, "REM".into()), (9..11, "".into())], &buffer, cx).into()
+    });
+
+    let edit_preview = cx
+        .read(|cx| buffer.read(cx).preview_edits(edits.clone(), cx))
+        .await;
+
+    let prediction = EditPrediction {
+        edits,
+        edit_preview,
+        buffer: buffer.clone(),
+        snapshot: cx.read(|cx| buffer.read(cx).snapshot()),
+        id: EditPredictionId("the-id".into()),
+        inputs: ZetaPromptInput {
+            events: Default::default(),
+            related_files: Default::default(),
+            cursor_path: Path::new("").into(),
+            cursor_excerpt: "".into(),
+            editable_range_in_excerpt: 0..0,
+            cursor_offset_in_excerpt: 0,
+        },
+        buffer_snapshotted_at: Instant::now(),
+        response_received_at: Instant::now(),
+    };
+
+    cx.update(|cx| {
+        assert_eq!(
+            from_completion_edits(
+                &prediction.interpolate(&buffer.read(cx).snapshot()).unwrap(),
+                &buffer,
+                cx
+            ),
+            vec![(2..5, "REM".into()), (9..11, "".into())]
+        );
+
+        buffer.update(cx, |buffer, cx| buffer.edit([(2..5, "")], None, cx));
+        assert_eq!(
+            from_completion_edits(
+                &prediction.interpolate(&buffer.read(cx).snapshot()).unwrap(),
+                &buffer,
+                cx
+            ),
+            vec![(2..2, "REM".into()), (6..8, "".into())]
+        );
+
+        buffer.update(cx, |buffer, cx| buffer.undo(cx));
+        assert_eq!(
+            from_completion_edits(
+                &prediction.interpolate(&buffer.read(cx).snapshot()).unwrap(),
+                &buffer,
+                cx
+            ),
+            vec![(2..5, "REM".into()), (9..11, "".into())]
+        );
+
+        buffer.update(cx, |buffer, cx| buffer.edit([(2..5, "R")], None, cx));
+        assert_eq!(
+            from_completion_edits(
+                &prediction.interpolate(&buffer.read(cx).snapshot()).unwrap(),
+                &buffer,
+                cx
+            ),
+            vec![(3..3, "EM".into()), (7..9, "".into())]
+        );
+
+        buffer.update(cx, |buffer, cx| buffer.edit([(3..3, "E")], None, cx));
+        assert_eq!(
+            from_completion_edits(
+                &prediction.interpolate(&buffer.read(cx).snapshot()).unwrap(),
+                &buffer,
+                cx
+            ),
+            vec![(4..4, "M".into()), (8..10, "".into())]
+        );
+
+        buffer.update(cx, |buffer, cx| buffer.edit([(4..4, "M")], None, cx));
+        assert_eq!(
+            from_completion_edits(
+                &prediction.interpolate(&buffer.read(cx).snapshot()).unwrap(),
+                &buffer,
+                cx
+            ),
+            vec![(9..11, "".into())]
+        );
+
+        buffer.update(cx, |buffer, cx| buffer.edit([(4..5, "")], None, cx));
+        assert_eq!(
+            from_completion_edits(
+                &prediction.interpolate(&buffer.read(cx).snapshot()).unwrap(),
+                &buffer,
+                cx
+            ),
+            vec![(4..4, "M".into()), (8..10, "".into())]
+        );
+
+        buffer.update(cx, |buffer, cx| buffer.edit([(8..10, "")], None, cx));
+        assert_eq!(
+            from_completion_edits(
+                &prediction.interpolate(&buffer.read(cx).snapshot()).unwrap(),
+                &buffer,
+                cx
+            ),
+            vec![(4..4, "M".into())]
+        );
+
+        buffer.update(cx, |buffer, cx| buffer.edit([(4..6, "")], None, cx));
+        assert_eq!(prediction.interpolate(&buffer.read(cx).snapshot()), None);
+    })
+}
+
+#[gpui::test]
+async fn test_clean_up_diff(cx: &mut TestAppContext) {
+    init_test(cx);
+
+    assert_eq!(
+        apply_edit_prediction(
+            indoc! {"
+                    fn main() {
+                        let word_1 = \"lorem\";
+                        let range = word.len()..word.len();
+                    }
+                "},
+            indoc! {"
+                    <|editable_region_start|>
+                    fn main() {
+                        let word_1 = \"lorem\";
+                        let range = word_1.len()..word_1.len();
+                    }
+
+                    <|editable_region_end|>
+                "},
+            cx,
+        )
+        .await,
+        indoc! {"
+                fn main() {
+                    let word_1 = \"lorem\";
+                    let range = word_1.len()..word_1.len();
+                }
+            "},
+    );
+
+    assert_eq!(
+        apply_edit_prediction(
+            indoc! {"
+                    fn main() {
+                        let story = \"the quick\"
+                    }
+                "},
+            indoc! {"
+                    <|editable_region_start|>
+                    fn main() {
+                        let story = \"the quick brown fox jumps over the lazy dog\";
+                    }
+
+                    <|editable_region_end|>
+                "},
+            cx,
+        )
+        .await,
+        indoc! {"
+                fn main() {
+                    let story = \"the quick brown fox jumps over the lazy dog\";
+                }
+            "},
+    );
+}
+
+#[gpui::test]
+async fn test_edit_prediction_end_of_buffer(cx: &mut TestAppContext) {
+    init_test(cx);
+
+    let buffer_content = "lorem\n";
+    let completion_response = indoc! {"
+            ```animals.js
+            <|start_of_file|>
+            <|editable_region_start|>
+            lorem
+            ipsum
+            <|editable_region_end|>
+            ```"};
+
+    assert_eq!(
+        apply_edit_prediction(buffer_content, completion_response, cx).await,
+        "lorem\nipsum"
+    );
+}
+
+#[gpui::test]
+async fn test_can_collect_data(cx: &mut TestAppContext) {
+    init_test(cx);
+
+    let fs = project::FakeFs::new(cx.executor());
+    fs.insert_tree(path!("/project"), json!({ "LICENSE": BSD_0_TXT }))
+        .await;
+
+    let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
+    let buffer = project
+        .update(cx, |project, cx| {
+            project.open_local_buffer(path!("/project/src/main.rs"), cx)
+        })
+        .await
+        .unwrap();
+
+    let (ep_store, captured_request, _) = make_test_ep_store(&project, cx).await;
+    ep_store.update(cx, |ep_store, _cx| {
+        ep_store.data_collection_choice = DataCollectionChoice::Enabled
+    });
+
+    run_edit_prediction(&buffer, &project, &ep_store, cx).await;
+    assert_eq!(
+        captured_request.lock().clone().unwrap().can_collect_data,
+        true
+    );
+
+    ep_store.update(cx, |ep_store, _cx| {
+        ep_store.data_collection_choice = DataCollectionChoice::Disabled
+    });
+
+    run_edit_prediction(&buffer, &project, &ep_store, cx).await;
+    assert_eq!(
+        captured_request.lock().clone().unwrap().can_collect_data,
+        false
+    );
+}
+
+#[gpui::test]
+async fn test_no_data_collection_for_remote_file(cx: &mut TestAppContext) {
+    init_test(cx);
+
+    let fs = project::FakeFs::new(cx.executor());
+    let project = Project::test(fs.clone(), [], cx).await;
+
+    let buffer = cx.new(|_cx| {
+        Buffer::remote(
+            language::BufferId::new(1).unwrap(),
+            ReplicaId::new(1),
+            language::Capability::ReadWrite,
+            "fn main() {\n    println!(\"Hello\");\n}",
+        )
+    });
+
+    let (ep_store, captured_request, _) = make_test_ep_store(&project, cx).await;
+    ep_store.update(cx, |ep_store, _cx| {
+        ep_store.data_collection_choice = DataCollectionChoice::Enabled
+    });
+
+    run_edit_prediction(&buffer, &project, &ep_store, cx).await;
+    assert_eq!(
+        captured_request.lock().clone().unwrap().can_collect_data,
+        false
+    );
+}
+
+#[gpui::test]
+async fn test_no_data_collection_for_private_file(cx: &mut TestAppContext) {
+    init_test(cx);
+
+    let fs = project::FakeFs::new(cx.executor());
+    fs.insert_tree(
+        path!("/project"),
+        json!({
+            "LICENSE": BSD_0_TXT,
+            ".env": "SECRET_KEY=secret"
+        }),
+    )
+    .await;
+
+    let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
+    let buffer = project
+        .update(cx, |project, cx| {
+            project.open_local_buffer("/project/.env", cx)
+        })
+        .await
+        .unwrap();
+
+    let (ep_store, captured_request, _) = make_test_ep_store(&project, cx).await;
+    ep_store.update(cx, |ep_store, _cx| {
+        ep_store.data_collection_choice = DataCollectionChoice::Enabled
+    });
+
+    run_edit_prediction(&buffer, &project, &ep_store, cx).await;
+    assert_eq!(
+        captured_request.lock().clone().unwrap().can_collect_data,
+        false
+    );
+}
+
+#[gpui::test]
+async fn test_no_data_collection_for_untitled_buffer(cx: &mut TestAppContext) {
+    init_test(cx);
+
+    let fs = project::FakeFs::new(cx.executor());
+    let project = Project::test(fs.clone(), [], cx).await;
+    let buffer = cx.new(|cx| Buffer::local("", cx));
+
+    let (ep_store, captured_request, _) = make_test_ep_store(&project, cx).await;
+    ep_store.update(cx, |ep_store, _cx| {
+        ep_store.data_collection_choice = DataCollectionChoice::Enabled
+    });
+
+    run_edit_prediction(&buffer, &project, &ep_store, cx).await;
+    assert_eq!(
+        captured_request.lock().clone().unwrap().can_collect_data,
+        false
+    );
+}
+
+#[gpui::test]
+async fn test_no_data_collection_when_closed_source(cx: &mut TestAppContext) {
+    init_test(cx);
+
+    let fs = project::FakeFs::new(cx.executor());
+    fs.insert_tree(path!("/project"), json!({ "main.rs": "fn main() {}" }))
+        .await;
+
+    let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
+    let buffer = project
+        .update(cx, |project, cx| {
+            project.open_local_buffer("/project/main.rs", cx)
+        })
+        .await
+        .unwrap();
+
+    let (ep_store, captured_request, _) = make_test_ep_store(&project, cx).await;
+    ep_store.update(cx, |ep_store, _cx| {
+        ep_store.data_collection_choice = DataCollectionChoice::Enabled
+    });
+
+    run_edit_prediction(&buffer, &project, &ep_store, cx).await;
+    assert_eq!(
+        captured_request.lock().clone().unwrap().can_collect_data,
+        false
+    );
+}
+
+#[gpui::test]
+async fn test_data_collection_status_changes_on_move(cx: &mut TestAppContext) {
+    init_test(cx);
+
+    let fs = project::FakeFs::new(cx.executor());
+    fs.insert_tree(
+        path!("/open_source_worktree"),
+        json!({ "LICENSE": BSD_0_TXT, "main.rs": "" }),
+    )
+    .await;
+    fs.insert_tree(path!("/closed_source_worktree"), json!({ "main.rs": "" }))
+        .await;
+
+    let project = Project::test(
+        fs.clone(),
+        [
+            path!("/open_source_worktree").as_ref(),
+            path!("/closed_source_worktree").as_ref(),
+        ],
+        cx,
+    )
+    .await;
+    let buffer = project
+        .update(cx, |project, cx| {
+            project.open_local_buffer(path!("/open_source_worktree/main.rs"), cx)
+        })
+        .await
+        .unwrap();
+
+    let (ep_store, captured_request, _) = make_test_ep_store(&project, cx).await;
+    ep_store.update(cx, |ep_store, _cx| {
+        ep_store.data_collection_choice = DataCollectionChoice::Enabled
+    });
+
+    run_edit_prediction(&buffer, &project, &ep_store, cx).await;
+    assert_eq!(
+        captured_request.lock().clone().unwrap().can_collect_data,
+        true
+    );
+
+    let closed_source_file = project
+        .update(cx, |project, cx| {
+            let worktree2 = project
+                .worktree_for_root_name("closed_source_worktree", cx)
+                .unwrap();
+            worktree2.update(cx, |worktree2, cx| {
+                worktree2.load_file(rel_path("main.rs"), cx)
+            })
+        })
+        .await
+        .unwrap()
+        .file;
+
+    buffer.update(cx, |buffer, cx| {
+        buffer.file_updated(closed_source_file, cx);
+    });
+
+    run_edit_prediction(&buffer, &project, &ep_store, cx).await;
+    assert_eq!(
+        captured_request.lock().clone().unwrap().can_collect_data,
+        false
+    );
+}
+
+#[gpui::test]
+async fn test_no_data_collection_for_events_in_uncollectable_buffers(cx: &mut TestAppContext) {
+    init_test(cx);
+
+    let fs = project::FakeFs::new(cx.executor());
+    fs.insert_tree(
+        path!("/worktree1"),
+        json!({ "LICENSE": BSD_0_TXT, "main.rs": "", "other.rs": "" }),
+    )
+    .await;
+    fs.insert_tree(path!("/worktree2"), json!({ "private.rs": "" }))
+        .await;
+
+    let project = Project::test(
+        fs.clone(),
+        [path!("/worktree1").as_ref(), path!("/worktree2").as_ref()],
+        cx,
+    )
+    .await;
+    let buffer = project
+        .update(cx, |project, cx| {
+            project.open_local_buffer(path!("/worktree1/main.rs"), cx)
+        })
+        .await
+        .unwrap();
+    let private_buffer = project
+        .update(cx, |project, cx| {
+            project.open_local_buffer(path!("/worktree2/file.rs"), cx)
+        })
+        .await
+        .unwrap();
+
+    let (ep_store, captured_request, _) = make_test_ep_store(&project, cx).await;
+    ep_store.update(cx, |ep_store, _cx| {
+        ep_store.data_collection_choice = DataCollectionChoice::Enabled
+    });
+
+    run_edit_prediction(&buffer, &project, &ep_store, cx).await;
+    assert_eq!(
+        captured_request.lock().clone().unwrap().can_collect_data,
+        true
+    );
+
+    // this has a side effect of registering the buffer to watch for edits
+    run_edit_prediction(&private_buffer, &project, &ep_store, cx).await;
+    assert_eq!(
+        captured_request.lock().clone().unwrap().can_collect_data,
+        false
+    );
+
+    private_buffer.update(cx, |private_buffer, cx| {
+        private_buffer.edit([(0..0, "An edit for the history!")], None, cx);
+    });
+
+    run_edit_prediction(&buffer, &project, &ep_store, cx).await;
+    assert_eq!(
+        captured_request.lock().clone().unwrap().can_collect_data,
+        false
+    );
+
+    // make an edit that uses too many bytes, causing private_buffer edit to not be able to be
+    // included
+    buffer.update(cx, |buffer, cx| {
+        buffer.edit(
+            [(
+                0..0,
+                " ".repeat(MAX_EVENT_TOKENS * cursor_excerpt::BYTES_PER_TOKEN_GUESS),
+            )],
+            None,
+            cx,
+        );
+    });
+
+    run_edit_prediction(&buffer, &project, &ep_store, cx).await;
+    assert_eq!(
+        captured_request.lock().clone().unwrap().can_collect_data,
+        true
+    );
+}
+
+fn init_test(cx: &mut TestAppContext) {
+    cx.update(|cx| {
+        let settings_store = SettingsStore::test(cx);
+        cx.set_global(settings_store);
+    });
+}
+
+async fn apply_edit_prediction(
+    buffer_content: &str,
+    completion_response: &str,
+    cx: &mut TestAppContext,
+) -> String {
+    let fs = project::FakeFs::new(cx.executor());
+    let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
+    let buffer = cx.new(|cx| Buffer::local(buffer_content, cx));
+    let (ep_store, _, response) = make_test_ep_store(&project, cx).await;
+    *response.lock() = completion_response.to_string();
+    let edit_prediction = run_edit_prediction(&buffer, &project, &ep_store, cx).await;
+    buffer.update(cx, |buffer, cx| {
+        buffer.edit(edit_prediction.edits.iter().cloned(), None, cx)
+    });
+    buffer.read_with(cx, |buffer, _| buffer.text())
+}
+
+async fn run_edit_prediction(
+    buffer: &Entity<Buffer>,
+    project: &Entity<Project>,
+    ep_store: &Entity<EditPredictionStore>,
+    cx: &mut TestAppContext,
+) -> EditPrediction {
+    let cursor = buffer.read_with(cx, |buffer, _| buffer.anchor_before(Point::new(1, 0)));
+    ep_store.update(cx, |ep_store, cx| {
+        ep_store.register_buffer(buffer, &project, cx)
+    });
+    cx.background_executor.run_until_parked();
+    let prediction_task = ep_store.update(cx, |ep_store, cx| {
+        ep_store.request_prediction(&project, buffer, cursor, Default::default(), cx)
+    });
+    prediction_task.await.unwrap().unwrap().prediction.unwrap()
+}
+
+async fn make_test_ep_store(
+    project: &Entity<Project>,
+    cx: &mut TestAppContext,
+) -> (
+    Entity<EditPredictionStore>,
+    Arc<Mutex<Option<PredictEditsBody>>>,
+    Arc<Mutex<String>>,
+) {
+    let default_response = indoc! {"
+            ```main.rs
+            <|start_of_file|>
+            <|editable_region_start|>
+            hello world
+            <|editable_region_end|>
+            ```"
+    };
+    let captured_request: Arc<Mutex<Option<PredictEditsBody>>> = Arc::new(Mutex::new(None));
+    let completion_response: Arc<Mutex<String>> =
+        Arc::new(Mutex::new(default_response.to_string()));
+    let http_client = FakeHttpClient::create({
+        let captured_request = captured_request.clone();
+        let completion_response = completion_response.clone();
+        let mut next_request_id = 0;
+        move |req| {
+            let captured_request = captured_request.clone();
+            let completion_response = completion_response.clone();
+            async move {
+                match (req.method(), req.uri().path()) {
+                    (&Method::POST, "/client/llm_tokens") => Ok(http_client::Response::builder()
+                        .status(200)
+                        .body(
+                            serde_json::to_string(&CreateLlmTokenResponse {
+                                token: LlmToken("the-llm-token".to_string()),
+                            })
+                            .unwrap()
+                            .into(),
+                        )
+                        .unwrap()),
+                    (&Method::POST, "/predict_edits/v2") => {
+                        let mut request_body = String::new();
+                        req.into_body().read_to_string(&mut request_body).await?;
+                        *captured_request.lock() =
+                            Some(serde_json::from_str(&request_body).unwrap());
+                        next_request_id += 1;
+                        Ok(http_client::Response::builder()
+                            .status(200)
+                            .body(
+                                serde_json::to_string(&PredictEditsResponse {
+                                    request_id: format!("request-{next_request_id}"),
+                                    output_excerpt: completion_response.lock().clone(),
+                                })
+                                .unwrap()
+                                .into(),
+                            )
+                            .unwrap())
+                    }
+                    _ => Ok(http_client::Response::builder()
+                        .status(404)
+                        .body("Not Found".into())
+                        .unwrap()),
+                }
+            }
+        }
+    });
+
+    let client = cx.update(|cx| Client::new(Arc::new(FakeSystemClock::new()), http_client, cx));
+    cx.update(|cx| {
+        RefreshLlmTokenListener::register(client.clone(), cx);
+    });
+    let _server = FakeServer::for_client(42, &client, cx).await;
+
+    let ep_store = cx.new(|cx| {
+        let mut ep_store = EditPredictionStore::new(client, project.read(cx).user_store(), cx);
+        ep_store.set_edit_prediction_model(EditPredictionModel::Zeta1);
+
+        let worktrees = project.read(cx).worktrees(cx).collect::<Vec<_>>();
+        for worktree in worktrees {
+            let worktree_id = worktree.read(cx).id();
+            ep_store
+                .get_or_init_project(project, cx)
+                .license_detection_watchers
+                .entry(worktree_id)
+                .or_insert_with(|| Rc::new(LicenseDetectionWatcher::new(&worktree, cx)));
+        }
+
+        ep_store
+    });
+
+    (ep_store, captured_request, completion_response)
+}
+
+fn to_completion_edits(
+    iterator: impl IntoIterator<Item = (Range<usize>, Arc<str>)>,
+    buffer: &Entity<Buffer>,
+    cx: &App,
+) -> Vec<(Range<Anchor>, Arc<str>)> {
+    let buffer = buffer.read(cx);
+    iterator
+        .into_iter()
+        .map(|(range, text)| {
+            (
+                buffer.anchor_after(range.start)..buffer.anchor_before(range.end),
+                text,
+            )
+        })
+        .collect()
+}
+
+fn from_completion_edits(
+    editor_edits: &[(Range<Anchor>, Arc<str>)],
+    buffer: &Entity<Buffer>,
+    cx: &App,
+) -> Vec<(Range<usize>, Arc<str>)> {
+    let buffer = buffer.read(cx);
+    editor_edits
+        .iter()
+        .map(|(range, text)| {
+            (
+                range.start.to_offset(buffer)..range.end.to_offset(buffer),
+                text.clone(),
+            )
+        })
+        .collect()
+}
+
+#[gpui::test]
+async fn test_unauthenticated_without_custom_url_blocks_prediction_impl(cx: &mut TestAppContext) {
+    init_test(cx);
+
+    let fs = FakeFs::new(cx.executor());
+    fs.insert_tree(
+        "/project",
+        serde_json::json!({
+            "main.rs": "fn main() {\n    \n}\n"
+        }),
+    )
+    .await;
+
+    let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
+
+    let http_client = FakeHttpClient::create(|_req| async move {
+        Ok(gpui::http_client::Response::builder()
+            .status(401)
+            .body("Unauthorized".into())
+            .unwrap())
+    });
+
+    let client =
+        cx.update(|cx| client::Client::new(Arc::new(FakeSystemClock::new()), http_client, cx));
+    cx.update(|cx| {
+        language_model::RefreshLlmTokenListener::register(client.clone(), cx);
+    });
+
+    let ep_store = cx.new(|cx| EditPredictionStore::new(client, project.read(cx).user_store(), cx));
+
+    let buffer = project
+        .update(cx, |project, cx| {
+            let path = project
+                .find_project_path(path!("/project/main.rs"), cx)
+                .unwrap();
+            project.open_buffer(path, cx)
+        })
+        .await
+        .unwrap();
+
+    let cursor = buffer.read_with(cx, |buffer, _| buffer.anchor_before(Point::new(1, 4)));
+    ep_store.update(cx, |ep_store, cx| {
+        ep_store.register_buffer(&buffer, &project, cx)
+    });
+    cx.background_executor.run_until_parked();
+
+    let completion_task = ep_store.update(cx, |ep_store, cx| {
+        ep_store.set_edit_prediction_model(EditPredictionModel::Zeta1);
+        ep_store.request_prediction(&project, &buffer, cursor, Default::default(), cx)
+    });
+
+    let result = completion_task.await;
+    assert!(
+        result.is_err(),
+        "Without authentication and without custom URL, prediction should fail"
+    );
+}
+
+#[gpui::test]
+async fn test_unauthenticated_with_custom_url_allows_prediction_impl(cx: &mut TestAppContext) {
+    init_test(cx);
+
+    let fs = FakeFs::new(cx.executor());
+    fs.insert_tree(
+        "/project",
+        serde_json::json!({
+            "main.rs": "fn main() {\n    \n}\n"
+        }),
+    )
+    .await;
+
+    let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
+
+    let predict_called = Arc::new(std::sync::atomic::AtomicBool::new(false));
+    let predict_called_clone = predict_called.clone();
+
+    let http_client = FakeHttpClient::create({
+        move |req| {
+            let uri = req.uri().path().to_string();
+            let predict_called = predict_called_clone.clone();
+            async move {
+                if uri.contains("predict") {
+                    predict_called.store(true, std::sync::atomic::Ordering::SeqCst);
+                    Ok(gpui::http_client::Response::builder()
+                        .body(
+                            serde_json::to_string(&open_ai::Response {
+                                id: "test-123".to_string(),
+                                object: "chat.completion".to_string(),
+                                created: 0,
+                                model: "test".to_string(),
+                                usage: open_ai::Usage {
+                                    prompt_tokens: 0,
+                                    completion_tokens: 0,
+                                    total_tokens: 0,
+                                },
+                                choices: vec![open_ai::Choice {
+                                    index: 0,
+                                    message: open_ai::RequestMessage::Assistant {
+                                        content: Some(open_ai::MessageContent::Plain(
+                                            indoc! {"
+                                                ```main.rs
+                                                <|start_of_file|>
+                                                <|editable_region_start|>
+                                                fn main() {
+                                                    println!(\"Hello, world!\");
+                                                }
+                                                <|editable_region_end|>
+                                                ```
+                                            "}
+                                            .to_string(),
+                                        )),
+                                        tool_calls: vec![],
+                                    },
+                                    finish_reason: Some("stop".to_string()),
+                                }],
+                            })
+                            .unwrap()
+                            .into(),
+                        )
+                        .unwrap())
+                } else {
+                    Ok(gpui::http_client::Response::builder()
+                        .status(401)
+                        .body("Unauthorized".into())
+                        .unwrap())
+                }
+            }
+        }
+    });
+
+    let client =
+        cx.update(|cx| client::Client::new(Arc::new(FakeSystemClock::new()), http_client, cx));
+    cx.update(|cx| {
+        language_model::RefreshLlmTokenListener::register(client.clone(), cx);
+    });
+
+    let ep_store = cx.new(|cx| EditPredictionStore::new(client, project.read(cx).user_store(), cx));
+
+    let buffer = project
+        .update(cx, |project, cx| {
+            let path = project
+                .find_project_path(path!("/project/main.rs"), cx)
+                .unwrap();
+            project.open_buffer(path, cx)
+        })
+        .await
+        .unwrap();
+
+    let cursor = buffer.read_with(cx, |buffer, _| buffer.anchor_before(Point::new(1, 4)));
+    ep_store.update(cx, |ep_store, cx| {
+        ep_store.register_buffer(&buffer, &project, cx)
+    });
+    cx.background_executor.run_until_parked();
+
+    let completion_task = ep_store.update(cx, |ep_store, cx| {
+        ep_store.set_custom_predict_edits_url(Url::parse("http://test/predict").unwrap());
+        ep_store.set_edit_prediction_model(EditPredictionModel::Zeta1);
+        ep_store.request_prediction(&project, &buffer, cursor, Default::default(), cx)
+    });
+
+    let _ = completion_task.await;
+
+    assert!(
+        predict_called.load(std::sync::atomic::Ordering::SeqCst),
+        "With custom URL, predict endpoint should be called even without authentication"
+    );
+}
+
+#[gpui::test]
+fn test_compute_diff_between_snapshots(cx: &mut TestAppContext) {
+    let buffer = cx.new(|cx| {
+        Buffer::local(
+            indoc! {"
+                zero
+                one
+                two
+                three
+                four
+                five
+                six
+                seven
+                eight
+                nine
+                ten
+                eleven
+                twelve
+                thirteen
+                fourteen
+                fifteen
+                sixteen
+                seventeen
+                eighteen
+                nineteen
+                twenty
+                twenty-one
+                twenty-two
+                twenty-three
+                twenty-four
+            "},
+            cx,
+        )
+    });
+
+    let old_snapshot = buffer.read_with(cx, |buffer, _| buffer.text_snapshot());
+
+    buffer.update(cx, |buffer, cx| {
+        let point = Point::new(12, 0);
+        buffer.edit([(point..point, "SECOND INSERTION\n")], None, cx);
+        let point = Point::new(8, 0);
+        buffer.edit([(point..point, "FIRST INSERTION\n")], None, cx);
+    });
+
+    let new_snapshot = buffer.read_with(cx, |buffer, _| buffer.text_snapshot());
+
+    let diff = compute_diff_between_snapshots(&old_snapshot, &new_snapshot).unwrap();
+
+    assert_eq!(
+        diff,
+        indoc! {"
+            @@ -6,10 +6,12 @@
+             five
+             six
+             seven
+            +FIRST INSERTION
+             eight
+             nine
+             ten
+             eleven
+            +SECOND INSERTION
+             twelve
+             thirteen
+             fourteen
+            "}
+    );
+}
+
+#[ctor::ctor]
+fn init_logger() {
+    zlog::init_test();
+}

crates/edit_prediction/src/example_spec.rs 🔗

@@ -0,0 +1,212 @@
+use serde::{Deserialize, Serialize};
+use std::{fmt::Write as _, mem, path::Path, sync::Arc};
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub struct ExampleSpec {
+    #[serde(default)]
+    pub name: String,
+    pub repository_url: String,
+    pub revision: String,
+    #[serde(default)]
+    pub uncommitted_diff: String,
+    pub cursor_path: Arc<Path>,
+    pub cursor_position: String,
+    pub edit_history: String,
+    pub expected_patch: String,
+}
+
+const UNCOMMITTED_DIFF_HEADING: &str = "Uncommitted Diff";
+const EDIT_HISTORY_HEADING: &str = "Edit History";
+const CURSOR_POSITION_HEADING: &str = "Cursor Position";
+const EXPECTED_PATCH_HEADING: &str = "Expected Patch";
+const EXPECTED_CONTEXT_HEADING: &str = "Expected Context";
+const REPOSITORY_URL_FIELD: &str = "repository_url";
+const REVISION_FIELD: &str = "revision";
+
+impl ExampleSpec {
+    /// Format this example spec as markdown.
+    pub fn to_markdown(&self) -> String {
+        let mut markdown = String::new();
+
+        _ = writeln!(markdown, "# {}", self.name);
+        markdown.push('\n');
+
+        _ = writeln!(markdown, "repository_url = {}", self.repository_url);
+        _ = writeln!(markdown, "revision = {}", self.revision);
+        markdown.push('\n');
+
+        if !self.uncommitted_diff.is_empty() {
+            _ = writeln!(markdown, "## {}", UNCOMMITTED_DIFF_HEADING);
+            _ = writeln!(markdown);
+            _ = writeln!(markdown, "```diff");
+            markdown.push_str(&self.uncommitted_diff);
+            if !markdown.ends_with('\n') {
+                markdown.push('\n');
+            }
+            _ = writeln!(markdown, "```");
+            markdown.push('\n');
+        }
+
+        _ = writeln!(markdown, "## {}", EDIT_HISTORY_HEADING);
+        _ = writeln!(markdown);
+
+        if self.edit_history.is_empty() {
+            _ = writeln!(markdown, "(No edit history)");
+            _ = writeln!(markdown);
+        } else {
+            _ = writeln!(markdown, "```diff");
+            markdown.push_str(&self.edit_history);
+            if !markdown.ends_with('\n') {
+                markdown.push('\n');
+            }
+            _ = writeln!(markdown, "```");
+            markdown.push('\n');
+        }
+
+        _ = writeln!(markdown, "## {}", CURSOR_POSITION_HEADING);
+        _ = writeln!(markdown);
+        _ = writeln!(markdown, "```{}", self.cursor_path.to_string_lossy());
+        markdown.push_str(&self.cursor_position);
+        if !markdown.ends_with('\n') {
+            markdown.push('\n');
+        }
+        _ = writeln!(markdown, "```");
+        markdown.push('\n');
+
+        _ = writeln!(markdown, "## {}", EXPECTED_PATCH_HEADING);
+        markdown.push('\n');
+        _ = writeln!(markdown, "```diff");
+        markdown.push_str(&self.expected_patch);
+        if !markdown.ends_with('\n') {
+            markdown.push('\n');
+        }
+        _ = writeln!(markdown, "```");
+        markdown.push('\n');
+
+        markdown
+    }
+
+    /// Parse an example spec from markdown.
+    pub fn from_markdown(name: String, input: &str) -> anyhow::Result<Self> {
+        use pulldown_cmark::{CodeBlockKind, CowStr, Event, HeadingLevel, Parser, Tag, TagEnd};
+
+        let parser = Parser::new(input);
+
+        let mut spec = ExampleSpec {
+            name,
+            repository_url: String::new(),
+            revision: String::new(),
+            uncommitted_diff: String::new(),
+            cursor_path: Path::new("").into(),
+            cursor_position: String::new(),
+            edit_history: String::new(),
+            expected_patch: String::new(),
+        };
+
+        let mut text = String::new();
+        let mut block_info: CowStr = "".into();
+
+        #[derive(PartialEq)]
+        enum Section {
+            Start,
+            UncommittedDiff,
+            EditHistory,
+            CursorPosition,
+            ExpectedExcerpts,
+            ExpectedPatch,
+            Other,
+        }
+
+        let mut current_section = Section::Start;
+
+        for event in parser {
+            match event {
+                Event::Text(line) => {
+                    text.push_str(&line);
+
+                    if let Section::Start = current_section
+                        && let Some((field, value)) = line.split_once('=')
+                    {
+                        match field.trim() {
+                            REPOSITORY_URL_FIELD => {
+                                spec.repository_url = value.trim().to_string();
+                            }
+                            REVISION_FIELD => {
+                                spec.revision = value.trim().to_string();
+                            }
+                            _ => {}
+                        }
+                    }
+                }
+                Event::End(TagEnd::Heading(HeadingLevel::H2)) => {
+                    let title = mem::take(&mut text);
+                    current_section = if title.eq_ignore_ascii_case(UNCOMMITTED_DIFF_HEADING) {
+                        Section::UncommittedDiff
+                    } else if title.eq_ignore_ascii_case(EDIT_HISTORY_HEADING) {
+                        Section::EditHistory
+                    } else if title.eq_ignore_ascii_case(CURSOR_POSITION_HEADING) {
+                        Section::CursorPosition
+                    } else if title.eq_ignore_ascii_case(EXPECTED_PATCH_HEADING) {
+                        Section::ExpectedPatch
+                    } else if title.eq_ignore_ascii_case(EXPECTED_CONTEXT_HEADING) {
+                        Section::ExpectedExcerpts
+                    } else {
+                        Section::Other
+                    };
+                }
+                Event::End(TagEnd::Heading(HeadingLevel::H3)) => {
+                    mem::take(&mut text);
+                }
+                Event::End(TagEnd::Heading(HeadingLevel::H4)) => {
+                    mem::take(&mut text);
+                }
+                Event::End(TagEnd::Heading(level)) => {
+                    anyhow::bail!("Unexpected heading level: {level}");
+                }
+                Event::Start(Tag::CodeBlock(kind)) => {
+                    match kind {
+                        CodeBlockKind::Fenced(info) => {
+                            block_info = info;
+                        }
+                        CodeBlockKind::Indented => {
+                            anyhow::bail!("Unexpected indented codeblock");
+                        }
+                    };
+                }
+                Event::Start(_) => {
+                    text.clear();
+                    block_info = "".into();
+                }
+                Event::End(TagEnd::CodeBlock) => {
+                    let block_info = block_info.trim();
+                    match current_section {
+                        Section::UncommittedDiff => {
+                            spec.uncommitted_diff = mem::take(&mut text);
+                        }
+                        Section::EditHistory => {
+                            spec.edit_history.push_str(&mem::take(&mut text));
+                        }
+                        Section::CursorPosition => {
+                            spec.cursor_path = Path::new(block_info).into();
+                            spec.cursor_position = mem::take(&mut text);
+                        }
+                        Section::ExpectedExcerpts => {
+                            mem::take(&mut text);
+                        }
+                        Section::ExpectedPatch => {
+                            spec.expected_patch = mem::take(&mut text);
+                        }
+                        Section::Start | Section::Other => {}
+                    }
+                }
+                _ => {}
+            }
+        }
+
+        if spec.cursor_path.as_ref() == Path::new("") || spec.cursor_position.is_empty() {
+            anyhow::bail!("Missing cursor position codeblock");
+        }
+
+        Ok(spec)
+    }
+}

crates/zeta/src/license_detection.rs → crates/edit_prediction/src/license_detection.rs 🔗

@@ -735,6 +735,7 @@ mod tests {
             true,
             fs.clone(),
             Default::default(),
+            true,
             &mut cx.to_async(),
         )
         .await
@@ -758,6 +759,7 @@ mod tests {
             true,
             fs.clone(),
             Default::default(),
+            true,
             &mut cx.to_async(),
         )
         .await
@@ -816,6 +818,7 @@ mod tests {
             true,
             fs.clone(),
             Default::default(),
+            true,
             &mut cx.to_async(),
         )
         .await

crates/edit_prediction/src/mercury.rs 🔗

@@ -0,0 +1,322 @@
+use crate::{
+    DebugEvent, EditPredictionFinishedDebugEvent, EditPredictionId, EditPredictionModelInput,
+    EditPredictionStartedDebugEvent, open_ai_response::text_from_response,
+    prediction::EditPredictionResult,
+};
+use anyhow::{Context as _, Result};
+use futures::AsyncReadExt as _;
+use gpui::{
+    App, AppContext as _, Entity, Global, SharedString, Task,
+    http_client::{self, AsyncBody, Method},
+};
+use language::{OffsetRangeExt as _, ToOffset, ToPoint as _};
+use language_model::{ApiKeyState, EnvVar, env_var};
+use std::{mem, ops::Range, path::Path, sync::Arc, time::Instant};
+use zeta_prompt::ZetaPromptInput;
+
+const MERCURY_API_URL: &str = "https://api.inceptionlabs.ai/v1/edit/completions";
+const MAX_CONTEXT_TOKENS: usize = 150;
+const MAX_REWRITE_TOKENS: usize = 350;
+
+pub struct Mercury {
+    pub api_token: Entity<ApiKeyState>,
+}
+
+impl Mercury {
+    pub fn new(cx: &mut App) -> Self {
+        Mercury {
+            api_token: mercury_api_token(cx),
+        }
+    }
+
+    pub(crate) fn request_prediction(
+        &self,
+        EditPredictionModelInput {
+            buffer,
+            snapshot,
+            position,
+            events,
+            related_files,
+            debug_tx,
+            ..
+        }: EditPredictionModelInput,
+        cx: &mut App,
+    ) -> Task<Result<Option<EditPredictionResult>>> {
+        self.api_token.update(cx, |key_state, cx| {
+            _ = key_state.load_if_needed(MERCURY_CREDENTIALS_URL, |s| s, cx);
+        });
+        let Some(api_token) = self.api_token.read(cx).key(&MERCURY_CREDENTIALS_URL) else {
+            return Task::ready(Ok(None));
+        };
+        let full_path: Arc<Path> = snapshot
+            .file()
+            .map(|file| file.full_path(cx))
+            .unwrap_or_else(|| "untitled".into())
+            .into();
+
+        let http_client = cx.http_client();
+        let cursor_point = position.to_point(&snapshot);
+        let buffer_snapshotted_at = Instant::now();
+        let active_buffer = buffer.clone();
+
+        let result = cx.background_spawn(async move {
+            let (editable_range, context_range) =
+                crate::cursor_excerpt::editable_and_context_ranges_for_cursor_position(
+                    cursor_point,
+                    &snapshot,
+                    MAX_CONTEXT_TOKENS,
+                    MAX_REWRITE_TOKENS,
+                );
+
+            let context_offset_range = context_range.to_offset(&snapshot);
+
+            let editable_offset_range = editable_range.to_offset(&snapshot);
+
+            let inputs = zeta_prompt::ZetaPromptInput {
+                events,
+                related_files,
+                cursor_offset_in_excerpt: cursor_point.to_offset(&snapshot)
+                    - context_range.start.to_offset(&snapshot),
+                cursor_path: full_path.clone(),
+                cursor_excerpt: snapshot
+                    .text_for_range(context_range)
+                    .collect::<String>()
+                    .into(),
+                editable_range_in_excerpt: (editable_offset_range.start
+                    - context_offset_range.start)
+                    ..(editable_offset_range.end - context_offset_range.start),
+            };
+
+            let prompt = build_prompt(&inputs);
+
+            if let Some(debug_tx) = &debug_tx {
+                debug_tx
+                    .unbounded_send(DebugEvent::EditPredictionStarted(
+                        EditPredictionStartedDebugEvent {
+                            buffer: active_buffer.downgrade(),
+                            prompt: Some(prompt.clone()),
+                            position,
+                        },
+                    ))
+                    .ok();
+            }
+
+            let request_body = open_ai::Request {
+                model: "mercury-coder".into(),
+                messages: vec![open_ai::RequestMessage::User {
+                    content: open_ai::MessageContent::Plain(prompt),
+                }],
+                stream: false,
+                max_completion_tokens: None,
+                stop: vec![],
+                temperature: None,
+                tool_choice: None,
+                parallel_tool_calls: None,
+                tools: vec![],
+                prompt_cache_key: None,
+                reasoning_effort: None,
+            };
+
+            let buf = serde_json::to_vec(&request_body)?;
+            let body: AsyncBody = buf.into();
+
+            let request = http_client::Request::builder()
+                .uri(MERCURY_API_URL)
+                .header("Content-Type", "application/json")
+                .header("Authorization", format!("Bearer {}", api_token))
+                .header("Connection", "keep-alive")
+                .method(Method::POST)
+                .body(body)
+                .context("Failed to create request")?;
+
+            let mut response = http_client
+                .send(request)
+                .await
+                .context("Failed to send request")?;
+
+            let mut body: Vec<u8> = Vec::new();
+            response
+                .body_mut()
+                .read_to_end(&mut body)
+                .await
+                .context("Failed to read response body")?;
+
+            let response_received_at = Instant::now();
+            if !response.status().is_success() {
+                anyhow::bail!(
+                    "Request failed with status: {:?}\nBody: {}",
+                    response.status(),
+                    String::from_utf8_lossy(&body),
+                );
+            };
+
+            let mut response: open_ai::Response =
+                serde_json::from_slice(&body).context("Failed to parse response")?;
+
+            let id = mem::take(&mut response.id);
+            let response_str = text_from_response(response).unwrap_or_default();
+
+            if let Some(debug_tx) = &debug_tx {
+                debug_tx
+                    .unbounded_send(DebugEvent::EditPredictionFinished(
+                        EditPredictionFinishedDebugEvent {
+                            buffer: active_buffer.downgrade(),
+                            model_output: Some(response_str.clone()),
+                            position,
+                        },
+                    ))
+                    .ok();
+            }
+
+            let response_str = response_str.strip_prefix("```\n").unwrap_or(&response_str);
+            let response_str = response_str.strip_suffix("\n```").unwrap_or(&response_str);
+
+            let mut edits = Vec::new();
+            const NO_PREDICTION_OUTPUT: &str = "None";
+
+            if response_str != NO_PREDICTION_OUTPUT {
+                let old_text = snapshot
+                    .text_for_range(editable_offset_range.clone())
+                    .collect::<String>();
+                edits.extend(
+                    language::text_diff(&old_text, &response_str)
+                        .into_iter()
+                        .map(|(range, text)| {
+                            (
+                                snapshot.anchor_after(editable_offset_range.start + range.start)
+                                    ..snapshot
+                                        .anchor_before(editable_offset_range.start + range.end),
+                                text,
+                            )
+                        }),
+                );
+            }
+
+            anyhow::Ok((id, edits, snapshot, response_received_at, inputs))
+        });
+
+        cx.spawn(async move |cx| {
+            let (id, edits, old_snapshot, response_received_at, inputs) =
+                result.await.context("Mercury edit prediction failed")?;
+            anyhow::Ok(Some(
+                EditPredictionResult::new(
+                    EditPredictionId(id.into()),
+                    &buffer,
+                    &old_snapshot,
+                    edits.into(),
+                    buffer_snapshotted_at,
+                    response_received_at,
+                    inputs,
+                    cx,
+                )
+                .await,
+            ))
+        })
+    }
+}
+
+fn build_prompt(inputs: &ZetaPromptInput) -> String {
+    const RECENTLY_VIEWED_SNIPPETS_START: &str = "<|recently_viewed_code_snippets|>\n";
+    const RECENTLY_VIEWED_SNIPPETS_END: &str = "<|/recently_viewed_code_snippets|>\n";
+    const RECENTLY_VIEWED_SNIPPET_START: &str = "<|recently_viewed_code_snippet|>\n";
+    const RECENTLY_VIEWED_SNIPPET_END: &str = "<|/recently_viewed_code_snippet|>\n";
+    const CURRENT_FILE_CONTENT_START: &str = "<|current_file_content|>\n";
+    const CURRENT_FILE_CONTENT_END: &str = "<|/current_file_content|>\n";
+    const CODE_TO_EDIT_START: &str = "<|code_to_edit|>\n";
+    const CODE_TO_EDIT_END: &str = "<|/code_to_edit|>\n";
+    const EDIT_DIFF_HISTORY_START: &str = "<|edit_diff_history|>\n";
+    const EDIT_DIFF_HISTORY_END: &str = "<|/edit_diff_history|>\n";
+    const CURSOR_TAG: &str = "<|cursor|>";
+    const CODE_SNIPPET_FILE_PATH_PREFIX: &str = "code_snippet_file_path: ";
+    const CURRENT_FILE_PATH_PREFIX: &str = "current_file_path: ";
+
+    let mut prompt = String::new();
+
+    push_delimited(
+        &mut prompt,
+        RECENTLY_VIEWED_SNIPPETS_START..RECENTLY_VIEWED_SNIPPETS_END,
+        |prompt| {
+            for related_file in inputs.related_files.iter() {
+                for related_excerpt in &related_file.excerpts {
+                    push_delimited(
+                        prompt,
+                        RECENTLY_VIEWED_SNIPPET_START..RECENTLY_VIEWED_SNIPPET_END,
+                        |prompt| {
+                            prompt.push_str(CODE_SNIPPET_FILE_PATH_PREFIX);
+                            prompt.push_str(related_file.path.to_string_lossy().as_ref());
+                            prompt.push('\n');
+                            prompt.push_str(&related_excerpt.text.to_string());
+                        },
+                    );
+                }
+            }
+        },
+    );
+
+    push_delimited(
+        &mut prompt,
+        CURRENT_FILE_CONTENT_START..CURRENT_FILE_CONTENT_END,
+        |prompt| {
+            prompt.push_str(CURRENT_FILE_PATH_PREFIX);
+            prompt.push_str(inputs.cursor_path.as_os_str().to_string_lossy().as_ref());
+            prompt.push('\n');
+
+            prompt.push_str(&inputs.cursor_excerpt[0..inputs.editable_range_in_excerpt.start]);
+            push_delimited(prompt, CODE_TO_EDIT_START..CODE_TO_EDIT_END, |prompt| {
+                prompt.push_str(
+                    &inputs.cursor_excerpt
+                        [inputs.editable_range_in_excerpt.start..inputs.cursor_offset_in_excerpt],
+                );
+                prompt.push_str(CURSOR_TAG);
+                prompt.push_str(
+                    &inputs.cursor_excerpt
+                        [inputs.cursor_offset_in_excerpt..inputs.editable_range_in_excerpt.end],
+                );
+            });
+            prompt.push_str(&inputs.cursor_excerpt[inputs.editable_range_in_excerpt.end..]);
+        },
+    );
+
+    push_delimited(
+        &mut prompt,
+        EDIT_DIFF_HISTORY_START..EDIT_DIFF_HISTORY_END,
+        |prompt| {
+            for event in inputs.events.iter() {
+                zeta_prompt::write_event(prompt, &event);
+            }
+        },
+    );
+
+    prompt
+}
+
+fn push_delimited(prompt: &mut String, delimiters: Range<&str>, cb: impl FnOnce(&mut String)) {
+    prompt.push_str(delimiters.start);
+    cb(prompt);
+    prompt.push_str(delimiters.end);
+}
+
+pub const MERCURY_CREDENTIALS_URL: SharedString =
+    SharedString::new_static("https://api.inceptionlabs.ai/v1/edit/completions");
+pub const MERCURY_CREDENTIALS_USERNAME: &str = "mercury-api-token";
+pub static MERCURY_TOKEN_ENV_VAR: std::sync::LazyLock<EnvVar> = env_var!("MERCURY_AI_TOKEN");
+
+struct GlobalMercuryApiKey(Entity<ApiKeyState>);
+
+impl Global for GlobalMercuryApiKey {}
+
+pub fn mercury_api_token(cx: &mut App) -> Entity<ApiKeyState> {
+    if let Some(global) = cx.try_global::<GlobalMercuryApiKey>() {
+        return global.0.clone();
+    }
+    let entity =
+        cx.new(|_| ApiKeyState::new(MERCURY_CREDENTIALS_URL, MERCURY_TOKEN_ENV_VAR.clone()));
+    cx.set_global(GlobalMercuryApiKey(entity.clone()));
+    entity
+}
+
+pub fn load_mercury_api_token(cx: &mut App) -> Task<Result<(), language_model::AuthenticateError>> {
+    mercury_api_token(cx).update(cx, |key_state, cx| {
+        key_state.load_if_needed(MERCURY_CREDENTIALS_URL, |s| s, cx)
+    })
+}

crates/zeta/src/onboarding_modal.rs → crates/edit_prediction/src/onboarding_modal.rs 🔗

@@ -131,8 +131,8 @@ impl Render for ZedPredictModal {
                 onboarding_event!("Cancelled", trigger = "Action");
                 cx.emit(DismissEvent);
             }))
-            .on_any_mouse_down(cx.listener(|this, _: &MouseDownEvent, window, _cx| {
-                this.focus_handle.focus(window);
+            .on_any_mouse_down(cx.listener(|this, _: &MouseDownEvent, window, cx| {
+                this.focus_handle.focus(window, cx);
             }))
             .child(
                 div()

crates/edit_prediction/src/open_ai_response.rs 🔗

@@ -0,0 +1,31 @@
+pub fn text_from_response(mut res: open_ai::Response) -> Option<String> {
+    let choice = res.choices.pop()?;
+    let output_text = match choice.message {
+        open_ai::RequestMessage::Assistant {
+            content: Some(open_ai::MessageContent::Plain(content)),
+            ..
+        } => content,
+        open_ai::RequestMessage::Assistant {
+            content: Some(open_ai::MessageContent::Multipart(mut content)),
+            ..
+        } => {
+            if content.is_empty() {
+                log::error!("No output from Baseten completion response");
+                return None;
+            }
+
+            match content.remove(0) {
+                open_ai::MessagePart::Text { text } => text,
+                open_ai::MessagePart::Image { .. } => {
+                    log::error!("Expected text, got an image");
+                    return None;
+                }
+            }
+        }
+        _ => {
+            log::error!("Invalid response message: {:?}", choice.message);
+            return None;
+        }
+    };
+    Some(output_text)
+}

crates/zeta/src/prediction.rs → crates/edit_prediction/src/prediction.rs 🔗

@@ -1,14 +1,14 @@
 use std::{
     ops::Range,
-    path::Path,
     sync::Arc,
     time::{Duration, Instant},
 };
 
 use cloud_llm_client::EditPredictionRejectReason;
+use edit_prediction_types::interpolate_edits;
 use gpui::{AsyncApp, Entity, SharedString};
-use language::{Anchor, Buffer, BufferSnapshot, EditPreview, OffsetRangeExt, TextBufferSnapshot};
-use serde::Serialize;
+use language::{Anchor, Buffer, BufferSnapshot, EditPreview, TextBufferSnapshot};
+use zeta_prompt::ZetaPromptInput;
 
 #[derive(Clone, Default, Debug, PartialEq, Eq, Hash)]
 pub struct EditPredictionId(pub SharedString);
@@ -39,7 +39,7 @@ impl EditPredictionResult {
         edits: Arc<[(Range<Anchor>, Arc<str>)]>,
         buffer_snapshotted_at: Instant,
         response_received_at: Instant,
-        inputs: EditPredictionInputs,
+        inputs: ZetaPromptInput,
         cx: &mut AsyncApp,
     ) -> Self {
         if edits.is_empty() {
@@ -53,7 +53,7 @@ impl EditPredictionResult {
             .read_with(cx, |buffer, cx| {
                 let new_snapshot = buffer.snapshot();
                 let edits: Arc<[_]> =
-                    interpolate_edits(&edited_buffer_snapshot, &new_snapshot, edits)?.into();
+                    interpolate_edits(&edited_buffer_snapshot, &new_snapshot, &edits)?.into();
 
                 Some((edits.clone(), new_snapshot, buffer.preview_edits(edits, cx)))
             })
@@ -93,15 +93,7 @@ pub struct EditPrediction {
     pub buffer: Entity<Buffer>,
     pub buffer_snapshotted_at: Instant,
     pub response_received_at: Instant,
-    pub inputs: EditPredictionInputs,
-}
-
-#[derive(Debug, Clone, Serialize)]
-pub struct EditPredictionInputs {
-    pub events: Vec<Arc<cloud_llm_client::predict_edits_v3::Event>>,
-    pub included_files: Vec<cloud_llm_client::predict_edits_v3::IncludedFile>,
-    pub cursor_point: cloud_llm_client::predict_edits_v3::Point,
-    pub cursor_path: Arc<Path>,
+    pub inputs: zeta_prompt::ZetaPromptInput,
 }
 
 impl EditPrediction {
@@ -109,7 +101,7 @@ impl EditPrediction {
         &self,
         new_snapshot: &TextBufferSnapshot,
     ) -> Option<Vec<(Range<Anchor>, Arc<str>)>> {
-        interpolate_edits(&self.snapshot, new_snapshot, self.edits.clone())
+        interpolate_edits(&self.snapshot, new_snapshot, &self.edits)
     }
 
     pub fn targets_buffer(&self, buffer: &Buffer) -> bool {
@@ -130,57 +122,14 @@ impl std::fmt::Debug for EditPrediction {
     }
 }
 
-pub fn interpolate_edits(
-    old_snapshot: &TextBufferSnapshot,
-    new_snapshot: &TextBufferSnapshot,
-    current_edits: Arc<[(Range<Anchor>, Arc<str>)]>,
-) -> Option<Vec<(Range<Anchor>, Arc<str>)>> {
-    let mut edits = Vec::new();
-
-    let mut model_edits = current_edits.iter().peekable();
-    for user_edit in new_snapshot.edits_since::<usize>(&old_snapshot.version) {
-        while let Some((model_old_range, _)) = model_edits.peek() {
-            let model_old_range = model_old_range.to_offset(old_snapshot);
-            if model_old_range.end < user_edit.old.start {
-                let (model_old_range, model_new_text) = model_edits.next().unwrap();
-                edits.push((model_old_range.clone(), model_new_text.clone()));
-            } else {
-                break;
-            }
-        }
-
-        if let Some((model_old_range, model_new_text)) = model_edits.peek() {
-            let model_old_offset_range = model_old_range.to_offset(old_snapshot);
-            if user_edit.old == model_old_offset_range {
-                let user_new_text = new_snapshot
-                    .text_for_range(user_edit.new.clone())
-                    .collect::<String>();
-
-                if let Some(model_suffix) = model_new_text.strip_prefix(&user_new_text) {
-                    if !model_suffix.is_empty() {
-                        let anchor = old_snapshot.anchor_after(user_edit.old.end);
-                        edits.push((anchor..anchor, model_suffix.into()));
-                    }
-
-                    model_edits.next();
-                    continue;
-                }
-            }
-        }
-
-        return None;
-    }
-
-    edits.extend(model_edits.cloned());
-
-    if edits.is_empty() { None } else { Some(edits) }
-}
-
 #[cfg(test)]
 mod tests {
+    use std::path::Path;
+
     use super::*;
     use gpui::{App, Entity, TestAppContext, prelude::*};
     use language::{Buffer, ToOffset as _};
+    use zeta_prompt::ZetaPromptInput;
 
     #[gpui::test]
     async fn test_edit_prediction_basic_interpolation(cx: &mut TestAppContext) {
@@ -199,14 +148,13 @@ mod tests {
             snapshot: cx.read(|cx| buffer.read(cx).snapshot()),
             buffer: buffer.clone(),
             edit_preview,
-            inputs: EditPredictionInputs {
+            inputs: ZetaPromptInput {
                 events: vec![],
-                included_files: vec![],
-                cursor_point: cloud_llm_client::predict_edits_v3::Point {
-                    line: cloud_llm_client::predict_edits_v3::Line(0),
-                    column: 0,
-                },
+                related_files: vec![].into(),
                 cursor_path: Path::new("path.txt").into(),
+                cursor_offset_in_excerpt: 0,
+                cursor_excerpt: "".into(),
+                editable_range_in_excerpt: 0..0,
             },
             buffer_snapshotted_at: Instant::now(),
             response_received_at: Instant::now(),

crates/zeta/src/sweep_ai.rs → crates/edit_prediction/src/sweep_ai.rs 🔗

@@ -1,81 +1,70 @@
-use anyhow::{Context as _, Result};
-use cloud_llm_client::predict_edits_v3::Event;
-use credentials_provider::CredentialsProvider;
-use futures::{AsyncReadExt as _, FutureExt, future::Shared};
+use anyhow::Result;
+use futures::AsyncReadExt as _;
 use gpui::{
-    App, AppContext as _, Entity, Task,
+    App, AppContext as _, Entity, Global, SharedString, Task,
     http_client::{self, AsyncBody, Method},
 };
-use language::{Buffer, BufferSnapshot, Point, ToOffset as _, ToPoint as _};
+use language::{Point, ToOffset as _};
+use language_model::{ApiKeyState, EnvVar, env_var};
 use lsp::DiagnosticSeverity;
-use project::{Project, ProjectPath};
 use serde::{Deserialize, Serialize};
 use std::{
-    collections::VecDeque,
     fmt::{self, Write as _},
-    ops::Range,
     path::Path,
     sync::Arc,
     time::Instant,
 };
 
-use crate::{EditPredictionId, EditPredictionInputs, prediction::EditPredictionResult};
+use crate::{EditPredictionId, EditPredictionModelInput, prediction::EditPredictionResult};
 
 const SWEEP_API_URL: &str = "https://autocomplete.sweep.dev/backend/next_edit_autocomplete";
 
 pub struct SweepAi {
-    pub api_token: Shared<Task<Option<String>>>,
+    pub api_token: Entity<ApiKeyState>,
     pub debug_info: Arc<str>,
 }
 
 impl SweepAi {
-    pub fn new(cx: &App) -> Self {
+    pub fn new(cx: &mut App) -> Self {
         SweepAi {
-            api_token: load_api_token(cx).shared(),
+            api_token: sweep_api_token(cx),
             debug_info: debug_info(cx),
         }
     }
 
-    pub fn set_api_token(&mut self, api_token: Option<String>, cx: &mut App) -> Task<Result<()>> {
-        self.api_token = Task::ready(api_token.clone()).shared();
-        store_api_token_in_keychain(api_token, cx)
-    }
-
     pub fn request_prediction_with_sweep(
         &self,
-        project: &Entity<Project>,
-        active_buffer: &Entity<Buffer>,
-        snapshot: BufferSnapshot,
-        position: language::Anchor,
-        events: Vec<Arc<Event>>,
-        recent_paths: &VecDeque<ProjectPath>,
-        diagnostic_search_range: Range<Point>,
+        inputs: EditPredictionModelInput,
         cx: &mut App,
     ) -> Task<Result<Option<EditPredictionResult>>> {
         let debug_info = self.debug_info.clone();
-        let Some(api_token) = self.api_token.clone().now_or_never().flatten() else {
+        self.api_token.update(cx, |key_state, cx| {
+            _ = key_state.load_if_needed(SWEEP_CREDENTIALS_URL, |s| s, cx);
+        });
+        let Some(api_token) = self.api_token.read(cx).key(&SWEEP_CREDENTIALS_URL) else {
             return Task::ready(Ok(None));
         };
-        let full_path: Arc<Path> = snapshot
+        let full_path: Arc<Path> = inputs
+            .snapshot
             .file()
             .map(|file| file.full_path(cx))
             .unwrap_or_else(|| "untitled".into())
             .into();
 
-        let project_file = project::File::from_dyn(snapshot.file());
+        let project_file = project::File::from_dyn(inputs.snapshot.file());
         let repo_name = project_file
             .map(|file| file.worktree.read(cx).root_name_str())
             .unwrap_or("untitled")
             .into();
-        let offset = position.to_offset(&snapshot);
+        let offset = inputs.position.to_offset(&inputs.snapshot);
 
-        let recent_buffers = recent_paths.iter().cloned();
+        let recent_buffers = inputs.recent_paths.iter().cloned();
         let http_client = cx.http_client();
 
         let recent_buffer_snapshots = recent_buffers
             .filter_map(|project_path| {
-                let buffer = project.read(cx).get_open_buffer(&project_path, cx)?;
-                if active_buffer == &buffer {
+                let buffer = inputs.project.read(cx).get_open_buffer(&project_path, cx)?;
+                if inputs.buffer == buffer {
                     None
                 } else {
                     Some(buffer.read(cx).snapshot())
@@ -84,14 +73,13 @@ impl SweepAi {
             .take(3)
             .collect::<Vec<_>>();
 
-        let cursor_point = position.to_point(&snapshot);
         let buffer_snapshotted_at = Instant::now();
 
         let result = cx.background_spawn(async move {
-            let text = snapshot.text();
+            let text = inputs.snapshot.text();
 
             let mut recent_changes = String::new();
-            for event in &events {
+            for event in &inputs.events {
                 write_event(event.as_ref(), &mut recent_changes).unwrap();
             }
 
@@ -120,7 +108,23 @@ impl SweepAi {
                 })
                 .collect::<Vec<_>>();
 
-            let diagnostic_entries = snapshot.diagnostics_in_range(diagnostic_search_range, false);
+            let retrieval_chunks = inputs
+                .related_files
+                .iter()
+                .flat_map(|related_file| {
+                    related_file.excerpts.iter().map(|excerpt| FileChunk {
+                        file_path: related_file.path.to_string_lossy().to_string(),
+                        start_line: excerpt.row_range.start as usize,
+                        end_line: excerpt.row_range.end as usize,
+                        content: excerpt.text.to_string(),
+                        timestamp: None,
+                    })
+                })
+                .collect();
+
+            let diagnostic_entries = inputs
+                .snapshot
+                .diagnostics_in_range(inputs.diagnostic_search_range, false);
             let mut diagnostic_content = String::new();
             let mut diagnostic_count = 0;
 
@@ -168,7 +172,7 @@ impl SweepAi {
                 multiple_suggestions: false,
                 branch: None,
                 file_chunks,
-                retrieval_chunks: vec![],
+                retrieval_chunks,
                 recent_user_actions: vec![],
                 use_bytes: true,
                 // TODO
@@ -180,21 +184,14 @@ impl SweepAi {
             serde_json::to_writer(writer, &request_body)?;
             let body: AsyncBody = buf.into();
 
-            let inputs = EditPredictionInputs {
-                events,
-                included_files: vec![cloud_llm_client::predict_edits_v3::IncludedFile {
-                    path: full_path.clone(),
-                    max_row: cloud_llm_client::predict_edits_v3::Line(snapshot.max_point().row),
-                    excerpts: vec![cloud_llm_client::predict_edits_v3::Excerpt {
-                        start_line: cloud_llm_client::predict_edits_v3::Line(0),
-                        text: request_body.file_contents.into(),
-                    }],
-                }],
-                cursor_point: cloud_llm_client::predict_edits_v3::Point {
-                    column: cursor_point.column,
-                    line: cloud_llm_client::predict_edits_v3::Line(cursor_point.row),
-                },
+            let ep_inputs = zeta_prompt::ZetaPromptInput {
+                events: inputs.events,
+                related_files: inputs.related_files.clone(),
                 cursor_path: full_path.clone(),
+                cursor_excerpt: request_body.file_contents.into(),
+                // we actually don't know
+                editable_range_in_excerpt: 0..inputs.snapshot.len(),
+                cursor_offset_in_excerpt: request_body.cursor_position,
             };
 
             let request = http_client::Request::builder()
@@ -222,15 +219,20 @@ impl SweepAi {
 
             let response: AutocompleteResponse = serde_json::from_slice(&body)?;
 
-            let old_text = snapshot
+            let old_text = inputs
+                .snapshot
                 .text_for_range(response.start_index..response.end_index)
                 .collect::<String>();
             let edits = language::text_diff(&old_text, &response.completion)
                 .into_iter()
                 .map(|(range, text)| {
                     (
-                        snapshot.anchor_after(response.start_index + range.start)
-                            ..snapshot.anchor_before(response.start_index + range.end),
+                        inputs
+                            .snapshot
+                            .anchor_after(response.start_index + range.start)
+                            ..inputs
+                                .snapshot
+                                .anchor_before(response.start_index + range.end),
                         text,
                     )
                 })
@@ -239,13 +241,13 @@ impl SweepAi {
             anyhow::Ok((
                 response.autocomplete_id,
                 edits,
-                snapshot,
+                inputs.snapshot,
                 response_received_at,
-                inputs,
+                ep_inputs,
             ))
         });
 
-        let buffer = active_buffer.clone();
+        let buffer = inputs.buffer.clone();
 
         cx.spawn(async move |cx| {
             let (id, edits, old_snapshot, response_received_at, inputs) = result.await?;
@@ -266,46 +268,28 @@ impl SweepAi {
     }
 }
 
-pub const SWEEP_CREDENTIALS_URL: &str = "https://autocomplete.sweep.dev";
+pub const SWEEP_CREDENTIALS_URL: SharedString =
+    SharedString::new_static("https://autocomplete.sweep.dev");
 pub const SWEEP_CREDENTIALS_USERNAME: &str = "sweep-api-token";
+pub static SWEEP_AI_TOKEN_ENV_VAR: std::sync::LazyLock<EnvVar> = env_var!("SWEEP_AI_TOKEN");
 
-pub fn load_api_token(cx: &App) -> Task<Option<String>> {
-    if let Some(api_token) = std::env::var("SWEEP_AI_TOKEN")
-        .ok()
-        .filter(|value| !value.is_empty())
-    {
-        return Task::ready(Some(api_token));
+struct GlobalSweepApiKey(Entity<ApiKeyState>);
+
+impl Global for GlobalSweepApiKey {}
+
+pub fn sweep_api_token(cx: &mut App) -> Entity<ApiKeyState> {
+    if let Some(global) = cx.try_global::<GlobalSweepApiKey>() {
+        return global.0.clone();
     }
-    let credentials_provider = <dyn CredentialsProvider>::global(cx);
-    cx.spawn(async move |cx| {
-        let (_, credentials) = credentials_provider
-            .read_credentials(SWEEP_CREDENTIALS_URL, &cx)
-            .await
-            .ok()??;
-        String::from_utf8(credentials).ok()
-    })
+    let entity =
+        cx.new(|_| ApiKeyState::new(SWEEP_CREDENTIALS_URL, SWEEP_AI_TOKEN_ENV_VAR.clone()));
+    cx.set_global(GlobalSweepApiKey(entity.clone()));
+    entity
 }
 
-fn store_api_token_in_keychain(api_token: Option<String>, cx: &App) -> Task<Result<()>> {
-    let credentials_provider = <dyn CredentialsProvider>::global(cx);
-
-    cx.spawn(async move |cx| {
-        if let Some(api_token) = api_token {
-            credentials_provider
-                .write_credentials(
-                    SWEEP_CREDENTIALS_URL,
-                    SWEEP_CREDENTIALS_USERNAME,
-                    api_token.as_bytes(),
-                    cx,
-                )
-                .await
-                .context("Failed to save Sweep API token to system keychain")
-        } else {
-            credentials_provider
-                .delete_credentials(SWEEP_CREDENTIALS_URL, cx)
-                .await
-                .context("Failed to delete Sweep API token from system keychain")
-        }
+pub fn load_sweep_api_token(cx: &mut App) -> Task<Result<(), language_model::AuthenticateError>> {
+    sweep_api_token(cx).update(cx, |key_state, cx| {
+        key_state.load_if_needed(SWEEP_CREDENTIALS_URL, |s| s, cx)
     })
 }
 
@@ -320,7 +304,7 @@ struct AutocompleteRequest {
     pub cursor_position: usize,
     pub original_file_contents: String,
     pub file_chunks: Vec<FileChunk>,
-    pub retrieval_chunks: Vec<RetrievalChunk>,
+    pub retrieval_chunks: Vec<FileChunk>,
     pub recent_user_actions: Vec<UserAction>,
     pub multiple_suggestions: bool,
     pub privacy_mode_enabled: bool,
@@ -337,15 +321,6 @@ struct FileChunk {
     pub timestamp: Option<u64>,
 }
 
-#[derive(Debug, Clone, Serialize)]
-struct RetrievalChunk {
-    pub file_path: String,
-    pub start_line: usize,
-    pub end_line: usize,
-    pub content: String,
-    pub timestamp: u64,
-}
-
 #[derive(Debug, Clone, Serialize)]
 struct UserAction {
     pub action_type: ActionType,
@@ -397,12 +372,9 @@ struct AdditionalCompletion {
     pub finish_reason: Option<String>,
 }
 
-fn write_event(
-    event: &cloud_llm_client::predict_edits_v3::Event,
-    f: &mut impl fmt::Write,
-) -> fmt::Result {
+fn write_event(event: &zeta_prompt::Event, f: &mut impl fmt::Write) -> fmt::Result {
     match event {
-        cloud_llm_client::predict_edits_v3::Event::BufferChange {
+        zeta_prompt::Event::BufferChange {
             old_path,
             path,
             diff,

crates/zeta/src/udiff.rs → crates/edit_prediction/src/udiff.rs 🔗

@@ -14,87 +14,48 @@ use anyhow::anyhow;
 use collections::HashMap;
 use gpui::AsyncApp;
 use gpui::Entity;
-use language::{Anchor, Buffer, BufferSnapshot, OffsetRangeExt as _, TextBufferSnapshot};
-use project::Project;
+use language::{Anchor, Buffer, OffsetRangeExt as _, TextBufferSnapshot};
+use project::{Project, ProjectPath};
+use util::paths::PathStyle;
+use util::rel_path::RelPath;
 
-pub async fn parse_diff<'a>(
-    diff_str: &'a str,
-    get_buffer: impl Fn(&Path) -> Option<(&'a BufferSnapshot, &'a [Range<Anchor>])> + Send,
-) -> Result<(&'a BufferSnapshot, Vec<(Range<Anchor>, Arc<str>)>)> {
-    let mut diff = DiffParser::new(diff_str);
-    let mut edited_buffer = None;
-    let mut edits = Vec::new();
-
-    while let Some(event) = diff.next()? {
-        match event {
-            DiffEvent::Hunk {
-                path: file_path,
-                hunk,
-            } => {
-                let (buffer, ranges) = match edited_buffer {
-                    None => {
-                        edited_buffer = get_buffer(&Path::new(file_path.as_ref()));
-                        edited_buffer
-                            .as_ref()
-                            .context("Model tried to edit a file that wasn't included")?
-                    }
-                    Some(ref current) => current,
-                };
-
-                edits.extend(
-                    resolve_hunk_edits_in_buffer(hunk, &buffer.text, ranges)
-                        .with_context(|| format!("Diff:\n{diff_str}"))?,
-                );
-            }
-            DiffEvent::FileEnd { renamed_to } => {
-                let (buffer, _) = edited_buffer
-                    .take()
-                    .context("Got a FileEnd event before an Hunk event")?;
-
-                if renamed_to.is_some() {
-                    anyhow::bail!("edit predictions cannot rename files");
-                }
-
-                if diff.next()?.is_some() {
-                    anyhow::bail!("Edited more than one file");
-                }
-
-                return Ok((buffer, edits));
-            }
-        }
-    }
-
-    Err(anyhow::anyhow!("No EOF"))
-}
-
-#[derive(Debug)]
-pub struct OpenedBuffers<'a>(#[allow(unused)] HashMap<Cow<'a, str>, Entity<Buffer>>);
+#[derive(Clone, Debug)]
+pub struct OpenedBuffers(#[allow(unused)] HashMap<String, Entity<Buffer>>);
 
 #[must_use]
-pub async fn apply_diff<'a>(
-    diff_str: &'a str,
+pub async fn apply_diff(
+    diff_str: &str,
     project: &Entity<Project>,
     cx: &mut AsyncApp,
-) -> Result<OpenedBuffers<'a>> {
+) -> Result<OpenedBuffers> {
     let mut included_files = HashMap::default();
 
+    let worktree_id = project.read_with(cx, |project, cx| {
+        anyhow::Ok(
+            project
+                .visible_worktrees(cx)
+                .next()
+                .context("no worktrees")?
+                .read(cx)
+                .id(),
+        )
+    })??;
+
     for line in diff_str.lines() {
         let diff_line = DiffLine::parse(line);
 
         if let DiffLine::OldPath { path } = diff_line {
             let buffer = project
                 .update(cx, |project, cx| {
-                    let project_path =
-                        project
-                            .find_project_path(path.as_ref(), cx)
-                            .with_context(|| {
-                                format!("Failed to find worktree for new path: {}", path)
-                            })?;
+                    let project_path = ProjectPath {
+                        worktree_id,
+                        path: RelPath::new(Path::new(path.as_ref()), PathStyle::Posix)?.into_arc(),
+                    };
                     anyhow::Ok(project.open_buffer(project_path, cx))
                 })??
                 .await?;
 
-            included_files.insert(path, buffer);
+            included_files.insert(path.to_string(), buffer);
         }
     }
 
@@ -113,7 +74,7 @@ pub async fn apply_diff<'a>(
                 let (buffer, ranges) = match current_file {
                     None => {
                         let buffer = included_files
-                            .get_mut(&file_path)
+                            .get_mut(file_path.as_ref())
                             .expect("Opened all files in diff");
 
                         current_file = Some((buffer, ranges.as_slice()));
@@ -167,6 +128,29 @@ pub async fn apply_diff<'a>(
     Ok(OpenedBuffers(included_files))
 }
 
+pub fn apply_diff_to_string(diff_str: &str, text: &str) -> Result<String> {
+    let mut diff = DiffParser::new(diff_str);
+
+    let mut text = text.to_string();
+
+    while let Some(event) = diff.next()? {
+        match event {
+            DiffEvent::Hunk { hunk, .. } => {
+                let hunk_offset = text
+                    .find(&hunk.context)
+                    .ok_or_else(|| anyhow!("couldn't resolve hunk {:?}", hunk.context))?;
+                for edit in hunk.edits.iter().rev() {
+                    let range = (hunk_offset + edit.range.start)..(hunk_offset + edit.range.end);
+                    text.replace_range(range, &edit.text);
+                }
+            }
+            DiffEvent::FileEnd { .. } => {}
+        }
+    }
+
+    Ok(text)
+}
+
 struct PatchFile<'a> {
     old_path: Cow<'a, str>,
     new_path: Cow<'a, str>,
@@ -492,7 +476,6 @@ mod tests {
     use super::*;
     use gpui::TestAppContext;
     use indoc::indoc;
-    use language::Point;
     use pretty_assertions::assert_eq;
     use project::{FakeFs, Project};
     use serde_json::json;
@@ -754,38 +737,38 @@ mod tests {
         let project = Project::test(fs, [path!("/root").as_ref()], cx).await;
 
         let diff = indoc! {r#"
-            --- a/root/file1
-            +++ b/root/file1
+            --- a/file1
+            +++ b/file1
              one
              two
             -three
             +3
              four
              five
-            --- a/root/file1
-            +++ b/root/file1
+            --- a/file1
+            +++ b/file1
              3
             -four
             -five
             +4
             +5
-            --- a/root/file1
-            +++ b/root/file1
+            --- a/file1
+            +++ b/file1
             -one
             -two
              3
              4
-            --- a/root/file2
-            +++ b/root/file2
+            --- a/file2
+            +++ b/file2
             +5
              six
-            --- a/root/file2
-            +++ b/root/file2
+            --- a/file2
+            +++ b/file2
              seven
             +7.5
              eight
-            --- a/root/file2
-            +++ b/root/file2
+            --- a/file2
+            +++ b/file2
              ten
             +11
         "#};
@@ -817,137 +800,6 @@ mod tests {
         });
     }
 
-    #[gpui::test]
-    async fn test_apply_diff_non_unique(cx: &mut TestAppContext) {
-        let fs = init_test(cx);
-
-        let buffer_1_text = indoc! {r#"
-            one
-            two
-            three
-            four
-            five
-            one
-            two
-            three
-            four
-            five
-        "# };
-
-        fs.insert_tree(
-            path!("/root"),
-            json!({
-                "file1": buffer_1_text,
-            }),
-        )
-        .await;
-
-        let project = Project::test(fs, [path!("/root").as_ref()], cx).await;
-        let buffer = project
-            .update(cx, |project, cx| {
-                project.open_local_buffer(path!("/root/file1"), cx)
-            })
-            .await
-            .unwrap();
-        let buffer_snapshot = buffer.read_with(cx, |buffer, _| buffer.snapshot());
-
-        let diff = indoc! {r#"
-            --- a/root/file1
-            +++ b/root/file1
-             one
-             two
-            -three
-            +3
-             four
-             five
-        "#};
-
-        let final_text = indoc! {r#"
-            one
-            two
-            three
-            four
-            five
-            one
-            two
-            3
-            four
-            five
-        "#};
-
-        apply_diff(diff, &project, &mut cx.to_async())
-            .await
-            .expect_err("Non-unique edits should fail");
-
-        let ranges = [buffer_snapshot.anchor_before(Point::new(1, 0))
-            ..buffer_snapshot.anchor_after(buffer_snapshot.max_point())];
-
-        let (edited_snapshot, edits) = parse_diff(diff, |_path| Some((&buffer_snapshot, &ranges)))
-            .await
-            .unwrap();
-
-        assert_eq!(edited_snapshot.remote_id(), buffer_snapshot.remote_id());
-        buffer.update(cx, |buffer, cx| {
-            buffer.edit(edits, None, cx);
-            assert_eq!(buffer.text(), final_text);
-        });
-    }
-
-    #[gpui::test]
-    async fn test_parse_diff_with_edits_within_line(cx: &mut TestAppContext) {
-        let fs = init_test(cx);
-
-        let buffer_1_text = indoc! {r#"
-            one two three four
-            five six seven eight
-            nine ten eleven twelve
-        "# };
-
-        fs.insert_tree(
-            path!("/root"),
-            json!({
-                "file1": buffer_1_text,
-            }),
-        )
-        .await;
-
-        let project = Project::test(fs, [path!("/root").as_ref()], cx).await;
-        let buffer = project
-            .update(cx, |project, cx| {
-                project.open_local_buffer(path!("/root/file1"), cx)
-            })
-            .await
-            .unwrap();
-        let buffer_snapshot = buffer.read_with(cx, |buffer, _| buffer.snapshot());
-
-        let diff = indoc! {r#"
-            --- a/root/file1
-            +++ b/root/file1
-             one two three four
-            -five six seven eight
-            +five SIX seven eight!
-             nine ten eleven twelve
-        "#};
-
-        let (buffer, edits) = parse_diff(diff, |_path| {
-            Some((&buffer_snapshot, &[(Anchor::MIN..Anchor::MAX)] as &[_]))
-        })
-        .await
-        .unwrap();
-
-        let edits = edits
-            .into_iter()
-            .map(|(range, text)| (range.to_point(&buffer), text))
-            .collect::<Vec<_>>();
-        assert_eq!(
-            edits,
-            &[
-                (Point::new(1, 5)..Point::new(1, 8), "SIX".into()),
-                (Point::new(1, 20)..Point::new(1, 20), "!".into())
-            ]
-        );
-    }
-
     #[gpui::test]
     async fn test_apply_diff_unique_via_previous_context(cx: &mut TestAppContext) {
         let fs = init_test(cx);
@@ -985,8 +837,8 @@ mod tests {
         let project = Project::test(fs, [path!("/root").as_ref()], cx).await;
 
         let diff = indoc! {r#"
-            --- a/root/file1
-            +++ b/root/file1
+            --- a/file1
+            +++ b/file1
              one
              two
             -three

crates/edit_prediction/src/zed_edit_prediction_delegate.rs 🔗

@@ -0,0 +1,230 @@
+use std::{cmp, sync::Arc};
+
+use client::{Client, UserStore};
+use cloud_llm_client::EditPredictionRejectReason;
+use edit_prediction_types::{DataCollectionState, EditPredictionDelegate};
+use gpui::{App, Entity, prelude::*};
+use language::{Buffer, ToPoint as _};
+use project::Project;
+
+use crate::{BufferEditPrediction, EditPredictionModel, EditPredictionStore};
+
+pub struct ZedEditPredictionDelegate {
+    store: Entity<EditPredictionStore>,
+    project: Entity<Project>,
+    singleton_buffer: Option<Entity<Buffer>>,
+}
+
+impl ZedEditPredictionDelegate {
+    pub fn new(
+        project: Entity<Project>,
+        singleton_buffer: Option<Entity<Buffer>>,
+        client: &Arc<Client>,
+        user_store: &Entity<UserStore>,
+        cx: &mut Context<Self>,
+    ) -> Self {
+        let store = EditPredictionStore::global(client, user_store, cx);
+        store.update(cx, |store, cx| {
+            store.register_project(&project, cx);
+        });
+
+        cx.observe(&store, |_this, _ep_store, cx| {
+            cx.notify();
+        })
+        .detach();
+
+        Self {
+            project: project,
+            store: store,
+            singleton_buffer,
+        }
+    }
+}
+
+impl EditPredictionDelegate for ZedEditPredictionDelegate {
+    fn name() -> &'static str {
+        "zed-predict"
+    }
+
+    fn display_name() -> &'static str {
+        "Zed's Edit Predictions"
+    }
+
+    fn show_predictions_in_menu() -> bool {
+        true
+    }
+
+    fn show_tab_accept_marker() -> bool {
+        true
+    }
+
+    fn data_collection_state(&self, cx: &App) -> DataCollectionState {
+        if let Some(buffer) = &self.singleton_buffer
+            && let Some(file) = buffer.read(cx).file()
+        {
+            let is_project_open_source =
+                self.store
+                    .read(cx)
+                    .is_file_open_source(&self.project, file, cx);
+            if self.store.read(cx).data_collection_choice.is_enabled() {
+                DataCollectionState::Enabled {
+                    is_project_open_source,
+                }
+            } else {
+                DataCollectionState::Disabled {
+                    is_project_open_source,
+                }
+            }
+        } else {
+            return DataCollectionState::Disabled {
+                is_project_open_source: false,
+            };
+        }
+    }
+
+    fn toggle_data_collection(&mut self, cx: &mut App) {
+        self.store.update(cx, |store, cx| {
+            store.toggle_data_collection_choice(cx);
+        });
+    }
+
+    fn usage(&self, cx: &App) -> Option<client::EditPredictionUsage> {
+        self.store.read(cx).usage(cx)
+    }
+
+    fn is_enabled(
+        &self,
+        _buffer: &Entity<language::Buffer>,
+        _cursor_position: language::Anchor,
+        cx: &App,
+    ) -> bool {
+        let store = self.store.read(cx);
+        if store.edit_prediction_model == EditPredictionModel::Sweep {
+            store.has_sweep_api_token(cx)
+        } else {
+            true
+        }
+    }
+
+    fn is_refreshing(&self, cx: &App) -> bool {
+        self.store.read(cx).is_refreshing(&self.project)
+    }
+
+    fn refresh(
+        &mut self,
+        buffer: Entity<language::Buffer>,
+        cursor_position: language::Anchor,
+        _debounce: bool,
+        cx: &mut Context<Self>,
+    ) {
+        let store = self.store.read(cx);
+
+        if store.user_store.read_with(cx, |user_store, _cx| {
+            user_store.account_too_young() || user_store.has_overdue_invoices()
+        }) {
+            return;
+        }
+
+        self.store.update(cx, |store, cx| {
+            if let Some(current) =
+                store.prediction_at(&buffer, Some(cursor_position), &self.project, cx)
+                && let BufferEditPrediction::Local { prediction } = current
+                && prediction.interpolate(buffer.read(cx)).is_some()
+            {
+                return;
+            }
+
+            store.refresh_context(&self.project, &buffer, cursor_position, cx);
+            store.refresh_prediction_from_buffer(self.project.clone(), buffer, cursor_position, cx)
+        });
+    }
+
+    fn accept(&mut self, cx: &mut Context<Self>) {
+        self.store.update(cx, |store, cx| {
+            store.accept_current_prediction(&self.project, cx);
+        });
+    }
+
+    fn discard(&mut self, cx: &mut Context<Self>) {
+        self.store.update(cx, |store, _cx| {
+            store.reject_current_prediction(EditPredictionRejectReason::Discarded, &self.project);
+        });
+    }
+
+    fn did_show(&mut self, cx: &mut Context<Self>) {
+        self.store.update(cx, |store, cx| {
+            store.did_show_current_prediction(&self.project, cx);
+        });
+    }
+
+    fn suggest(
+        &mut self,
+        buffer: &Entity<language::Buffer>,
+        cursor_position: language::Anchor,
+        cx: &mut Context<Self>,
+    ) -> Option<edit_prediction_types::EditPrediction> {
+        self.store.update(cx, |store, cx| {
+            let prediction =
+                store.prediction_at(buffer, Some(cursor_position), &self.project, cx)?;
+
+            let prediction = match prediction {
+                BufferEditPrediction::Local { prediction } => prediction,
+                BufferEditPrediction::Jump { prediction } => {
+                    return Some(edit_prediction_types::EditPrediction::Jump {
+                        id: Some(prediction.id.to_string().into()),
+                        snapshot: prediction.snapshot.clone(),
+                        target: prediction.edits.first().unwrap().0.start,
+                    });
+                }
+            };
+
+            let buffer = buffer.read(cx);
+            let snapshot = buffer.snapshot();
+
+            let Some(edits) = prediction.interpolate(&snapshot) else {
+                store.reject_current_prediction(
+                    EditPredictionRejectReason::InterpolatedEmpty,
+                    &self.project,
+                );
+                return None;
+            };
+
+            let cursor_row = cursor_position.to_point(&snapshot).row;
+            let (closest_edit_ix, (closest_edit_range, _)) =
+                edits.iter().enumerate().min_by_key(|(_, (range, _))| {
+                    let distance_from_start =
+                        cursor_row.abs_diff(range.start.to_point(&snapshot).row);
+                    let distance_from_end = cursor_row.abs_diff(range.end.to_point(&snapshot).row);
+                    cmp::min(distance_from_start, distance_from_end)
+                })?;
+
+            let mut edit_start_ix = closest_edit_ix;
+            for (range, _) in edits[..edit_start_ix].iter().rev() {
+                let distance_from_closest_edit = closest_edit_range.start.to_point(&snapshot).row
+                    - range.end.to_point(&snapshot).row;
+                if distance_from_closest_edit <= 1 {
+                    edit_start_ix -= 1;
+                } else {
+                    break;
+                }
+            }
+
+            let mut edit_end_ix = closest_edit_ix + 1;
+            for (range, _) in &edits[edit_end_ix..] {
+                let distance_from_closest_edit = range.start.to_point(buffer).row
+                    - closest_edit_range.end.to_point(&snapshot).row;
+                if distance_from_closest_edit <= 1 {
+                    edit_end_ix += 1;
+                } else {
+                    break;
+                }
+            }
+
+            Some(edit_prediction_types::EditPrediction::Local {
+                id: Some(prediction.id.to_string().into()),
+                edits: edits[edit_start_ix..edit_end_ix].to_vec(),
+                edit_preview: Some(prediction.edit_preview.clone()),
+            })
+        })
+    }
+}

crates/zeta/src/zeta1.rs → crates/edit_prediction/src/zeta1.rs 🔗

@@ -1,24 +1,23 @@
-mod input_excerpt;
-
 use std::{fmt::Write, ops::Range, path::Path, sync::Arc, time::Instant};
 
 use crate::{
-    EditPredictionId, ZedUpdateRequiredError, Zeta,
-    prediction::{EditPredictionInputs, EditPredictionResult},
+    DebugEvent, EditPredictionFinishedDebugEvent, EditPredictionId, EditPredictionModelInput,
+    EditPredictionStartedDebugEvent, EditPredictionStore, ZedUpdateRequiredError,
+    cursor_excerpt::{editable_and_context_ranges_for_cursor_position, guess_token_count},
+    prediction::EditPredictionResult,
 };
 use anyhow::{Context as _, Result};
 use cloud_llm_client::{
     PredictEditsBody, PredictEditsGitInfo, PredictEditsRequestTrigger, PredictEditsResponse,
-    predict_edits_v3::Event,
 };
 use gpui::{App, AppContext as _, AsyncApp, Context, Entity, SharedString, Task};
-use input_excerpt::excerpt_for_cursor_position;
 use language::{
-    Anchor, Buffer, BufferSnapshot, OffsetRangeExt as _, Point, ToPoint as _, text_diff,
+    Anchor, Buffer, BufferSnapshot, OffsetRangeExt as _, Point, ToOffset, ToPoint as _, text_diff,
 };
 use project::{Project, ProjectPath};
 use release_channel::AppVersion;
 use workspace::notifications::{ErrorMessagePrompt, NotificationId, show_app_notification};
+use zeta_prompt::{Event, ZetaPromptInput};
 
 const CURSOR_MARKER: &str = "<|user_cursor_is_here|>";
 const START_OF_FILE_MARKER: &str = "<|start_of_file|>";
@@ -30,25 +29,28 @@ pub(crate) const MAX_REWRITE_TOKENS: usize = 350;
 pub(crate) const MAX_EVENT_TOKENS: usize = 500;
 
 pub(crate) fn request_prediction_with_zeta1(
-    zeta: &mut Zeta,
-    project: &Entity<Project>,
-    buffer: &Entity<Buffer>,
-    snapshot: BufferSnapshot,
-    position: language::Anchor,
-    events: Vec<Arc<Event>>,
-    trigger: PredictEditsRequestTrigger,
-    cx: &mut Context<Zeta>,
+    store: &mut EditPredictionStore,
+    EditPredictionModelInput {
+        project,
+        buffer,
+        snapshot,
+        position,
+        events,
+        trigger,
+        debug_tx,
+        ..
+    }: EditPredictionModelInput,
+    cx: &mut Context<EditPredictionStore>,
 ) -> Task<Result<Option<EditPredictionResult>>> {
-    let buffer = buffer.clone();
     let buffer_snapshotted_at = Instant::now();
-    let client = zeta.client.clone();
-    let llm_token = zeta.llm_token.clone();
+    let client = store.client.clone();
+    let llm_token = store.llm_token.clone();
     let app_version = AppVersion::global(cx);
 
     let (git_info, can_collect_file) = if let Some(file) = snapshot.file() {
-        let can_collect_file = zeta.can_collect_file(project, file, cx);
+        let can_collect_file = store.can_collect_file(&project, file, cx);
         let git_info = if can_collect_file {
-            git_info_for_file(project, &ProjectPath::from_file(file.as_ref(), cx), cx)
+            git_info_for_file(&project, &ProjectPath::from_file(file.as_ref(), cx), cx)
         } else {
             None
         };
@@ -76,6 +78,19 @@ pub(crate) fn request_prediction_with_zeta1(
         cx,
     );
 
+    let (uri, require_auth) = match &store.custom_predict_edits_url {
+        Some(custom_url) => (custom_url.clone(), false),
+        None => {
+            match client
+                .http_client()
+                .build_zed_llm_url("/predict_edits/v2", &[])
+            {
+                Ok(url) => (url.into(), true),
+                Err(err) => return Task::ready(Err(err)),
+            }
+        }
+    };
+
     cx.spawn(async move |this, cx| {
         let GatherContextOutput {
             mut body,
@@ -100,63 +115,54 @@ pub(crate) fn request_prediction_with_zeta1(
             body.input_excerpt
         );
 
-        let http_client = client.http_client();
-
-        let response = Zeta::send_api_request::<PredictEditsResponse>(
+        let response = EditPredictionStore::send_api_request::<PredictEditsResponse>(
             |request| {
-                let uri = if let Ok(predict_edits_url) = std::env::var("ZED_PREDICT_EDITS_URL") {
-                    predict_edits_url
-                } else {
-                    http_client
-                        .build_zed_llm_url("/predict_edits/v2", &[])?
-                        .as_str()
-                        .into()
-                };
                 Ok(request
-                    .uri(uri)
+                    .uri(uri.as_str())
                     .body(serde_json::to_string(&body)?.into())?)
             },
             client,
             llm_token,
             app_version,
+            require_auth,
         )
         .await;
 
-        let inputs = EditPredictionInputs {
+        let context_start_offset = context_range.start.to_offset(&snapshot);
+        let editable_offset_range = editable_range.to_offset(&snapshot);
+
+        let inputs = ZetaPromptInput {
             events: included_events.into(),
-            included_files: vec![cloud_llm_client::predict_edits_v3::IncludedFile {
-                path: full_path.clone(),
-                max_row: cloud_llm_client::predict_edits_v3::Line(snapshot.max_point().row),
-                excerpts: vec![cloud_llm_client::predict_edits_v3::Excerpt {
-                    start_line: cloud_llm_client::predict_edits_v3::Line(context_range.start.row),
-                    text: snapshot
-                        .text_for_range(context_range)
-                        .collect::<String>()
-                        .into(),
-                }],
-            }],
-            cursor_point: cloud_llm_client::predict_edits_v3::Point {
-                column: cursor_point.column,
-                line: cloud_llm_client::predict_edits_v3::Line(cursor_point.row),
-            },
+            related_files: vec![].into(),
             cursor_path: full_path,
+            cursor_excerpt: snapshot
+                .text_for_range(context_range)
+                .collect::<String>()
+                .into(),
+            editable_range_in_excerpt: (editable_range.start - context_start_offset)
+                ..(editable_offset_range.end - context_start_offset),
+            cursor_offset_in_excerpt: cursor_point.to_offset(&snapshot) - context_start_offset,
         };
 
-        // let response = perform_predict_edits(PerformPredictEditsParams {
-        //     client,
-        //     llm_token,
-        //     app_version,
-        //     body,
-        // })
-        // .await;
+        if let Some(debug_tx) = &debug_tx {
+            debug_tx
+                .unbounded_send(DebugEvent::EditPredictionStarted(
+                    EditPredictionStartedDebugEvent {
+                        buffer: buffer.downgrade(),
+                        prompt: Some(serde_json::to_string(&inputs).unwrap()),
+                        position,
+                    },
+                ))
+                .ok();
+        }
 
         let (response, usage) = match response {
             Ok(response) => response,
             Err(err) => {
                 if err.is::<ZedUpdateRequiredError>() {
                     cx.update(|cx| {
-                        this.update(cx, |zeta, _cx| {
-                            zeta.update_required = true;
+                        this.update(cx, |ep_store, _cx| {
+                            ep_store.update_required = true;
                         })
                         .ok();
 
@@ -191,6 +197,18 @@ pub(crate) fn request_prediction_with_zeta1(
             .ok();
         }
 
+        if let Some(debug_tx) = &debug_tx {
+            debug_tx
+                .unbounded_send(DebugEvent::EditPredictionFinished(
+                    EditPredictionFinishedDebugEvent {
+                        buffer: buffer.downgrade(),
+                        model_output: Some(response.output_excerpt.clone()),
+                        position,
+                    },
+                ))
+                .ok();
+        }
+
         let edit_prediction = process_completion_response(
             response,
             buffer,
@@ -228,7 +246,7 @@ fn process_completion_response(
     buffer: Entity<Buffer>,
     snapshot: &BufferSnapshot,
     editable_range: Range<usize>,
-    inputs: EditPredictionInputs,
+    inputs: ZetaPromptInput,
     buffer_snapshotted_at: Instant,
     received_response_at: Instant,
     cx: &AsyncApp,
@@ -495,10 +513,159 @@ pub fn format_event(event: &Event) -> String {
     }
 }
 
-/// Typical number of string bytes per token for the purposes of limiting model input. This is
-/// intentionally low to err on the side of underestimating limits.
-pub(crate) const BYTES_PER_TOKEN_GUESS: usize = 3;
+#[derive(Debug)]
+pub struct InputExcerpt {
+    pub context_range: Range<Point>,
+    pub editable_range: Range<Point>,
+    pub prompt: String,
+}
+
+pub fn excerpt_for_cursor_position(
+    position: Point,
+    path: &str,
+    snapshot: &BufferSnapshot,
+    editable_region_token_limit: usize,
+    context_token_limit: usize,
+) -> InputExcerpt {
+    let (editable_range, context_range) = editable_and_context_ranges_for_cursor_position(
+        position,
+        snapshot,
+        editable_region_token_limit,
+        context_token_limit,
+    );
+
+    let mut prompt = String::new();
+
+    writeln!(&mut prompt, "```{path}").unwrap();
+    if context_range.start == Point::zero() {
+        writeln!(&mut prompt, "{START_OF_FILE_MARKER}").unwrap();
+    }
+
+    for chunk in snapshot.chunks(context_range.start..editable_range.start, false) {
+        prompt.push_str(chunk.text);
+    }
+
+    push_editable_range(position, snapshot, editable_range.clone(), &mut prompt);
+
+    for chunk in snapshot.chunks(editable_range.end..context_range.end, false) {
+        prompt.push_str(chunk.text);
+    }
+    write!(prompt, "\n```").unwrap();
+
+    InputExcerpt {
+        context_range,
+        editable_range,
+        prompt,
+    }
+}
+
+fn push_editable_range(
+    cursor_position: Point,
+    snapshot: &BufferSnapshot,
+    editable_range: Range<Point>,
+    prompt: &mut String,
+) {
+    writeln!(prompt, "{EDITABLE_REGION_START_MARKER}").unwrap();
+    for chunk in snapshot.chunks(editable_range.start..cursor_position, false) {
+        prompt.push_str(chunk.text);
+    }
+    prompt.push_str(CURSOR_MARKER);
+    for chunk in snapshot.chunks(cursor_position..editable_range.end, false) {
+        prompt.push_str(chunk.text);
+    }
+    write!(prompt, "\n{EDITABLE_REGION_END_MARKER}").unwrap();
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use gpui::{App, AppContext};
+    use indoc::indoc;
+    use language::Buffer;
+
+    #[gpui::test]
+    fn test_excerpt_for_cursor_position(cx: &mut App) {
+        let text = indoc! {r#"
+            fn foo() {
+                let x = 42;
+                println!("Hello, world!");
+            }
+
+            fn bar() {
+                let x = 42;
+                let mut sum = 0;
+                for i in 0..x {
+                    sum += i;
+                }
+                println!("Sum: {}", sum);
+                return sum;
+            }
+
+            fn generate_random_numbers() -> Vec<i32> {
+                let mut rng = rand::thread_rng();
+                let mut numbers = Vec::new();
+                for _ in 0..5 {
+                    numbers.push(rng.random_range(1..101));
+                }
+                numbers
+            }
+        "#};
+        let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(language::rust_lang(), cx));
+        let snapshot = buffer.read(cx).snapshot();
+
+        // Ensure we try to fit the largest possible syntax scope, resorting to line-based expansion
+        // when a larger scope doesn't fit the editable region.
+        let excerpt = excerpt_for_cursor_position(Point::new(12, 5), "main.rs", &snapshot, 50, 32);
+        assert_eq!(
+            excerpt.prompt,
+            indoc! {r#"
+            ```main.rs
+                let x = 42;
+                println!("Hello, world!");
+            <|editable_region_start|>
+            }
+
+            fn bar() {
+                let x = 42;
+                let mut sum = 0;
+                for i in 0..x {
+                    sum += i;
+                }
+                println!("Sum: {}", sum);
+                r<|user_cursor_is_here|>eturn sum;
+            }
+
+            fn generate_random_numbers() -> Vec<i32> {
+            <|editable_region_end|>
+                let mut rng = rand::thread_rng();
+                let mut numbers = Vec::new();
+            ```"#}
+        );
 
-fn guess_token_count(bytes: usize) -> usize {
-    bytes / BYTES_PER_TOKEN_GUESS
+        // The `bar` function won't fit within the editable region, so we resort to line-based expansion.
+        let excerpt = excerpt_for_cursor_position(Point::new(12, 5), "main.rs", &snapshot, 40, 32);
+        assert_eq!(
+            excerpt.prompt,
+            indoc! {r#"
+            ```main.rs
+            fn bar() {
+                let x = 42;
+                let mut sum = 0;
+            <|editable_region_start|>
+                for i in 0..x {
+                    sum += i;
+                }
+                println!("Sum: {}", sum);
+                r<|user_cursor_is_here|>eturn sum;
+            }
+
+            fn generate_random_numbers() -> Vec<i32> {
+                let mut rng = rand::thread_rng();
+            <|editable_region_end|>
+                let mut numbers = Vec::new();
+                for _ in 0..5 {
+                    numbers.push(rng.random_range(1..101));
+            ```"#}
+        );
+    }
 }

crates/edit_prediction/src/zeta2.rs 🔗

@@ -0,0 +1,243 @@
+#[cfg(feature = "cli-support")]
+use crate::EvalCacheEntryKind;
+use crate::open_ai_response::text_from_response;
+use crate::prediction::EditPredictionResult;
+use crate::{
+    DebugEvent, EDIT_PREDICTIONS_MODEL_ID, EditPredictionFinishedDebugEvent, EditPredictionId,
+    EditPredictionModelInput, EditPredictionStartedDebugEvent, EditPredictionStore,
+};
+use anyhow::{Result, anyhow};
+use cloud_llm_client::EditPredictionRejectReason;
+use gpui::{Task, prelude::*};
+use language::{OffsetRangeExt as _, ToOffset as _, ToPoint};
+use release_channel::AppVersion;
+use std::{path::Path, sync::Arc, time::Instant};
+use zeta_prompt::CURSOR_MARKER;
+use zeta_prompt::format_zeta_prompt;
+
+const MAX_CONTEXT_TOKENS: usize = 150;
+const MAX_REWRITE_TOKENS: usize = 350;
+
+pub fn request_prediction_with_zeta2(
+    store: &mut EditPredictionStore,
+    EditPredictionModelInput {
+        buffer,
+        snapshot,
+        position,
+        related_files,
+        events,
+        debug_tx,
+        ..
+    }: EditPredictionModelInput,
+    cx: &mut Context<EditPredictionStore>,
+) -> Task<Result<Option<EditPredictionResult>>> {
+    let buffer_snapshotted_at = Instant::now();
+
+    let Some(excerpt_path) = snapshot
+        .file()
+        .map(|file| -> Arc<Path> { file.full_path(cx).into() })
+    else {
+        return Task::ready(Err(anyhow!("No file path for excerpt")));
+    };
+
+    let client = store.client.clone();
+    let llm_token = store.llm_token.clone();
+    let app_version = AppVersion::global(cx);
+
+    #[cfg(feature = "cli-support")]
+    let eval_cache = store.eval_cache.clone();
+
+    let request_task = cx.background_spawn({
+        async move {
+            let cursor_offset = position.to_offset(&snapshot);
+            let (editable_offset_range, prompt_input) = zeta2_prompt_input(
+                &snapshot,
+                related_files,
+                events,
+                excerpt_path,
+                cursor_offset,
+            );
+
+            let prompt = format_zeta_prompt(&prompt_input);
+
+            if let Some(debug_tx) = &debug_tx {
+                debug_tx
+                    .unbounded_send(DebugEvent::EditPredictionStarted(
+                        EditPredictionStartedDebugEvent {
+                            buffer: buffer.downgrade(),
+                            prompt: Some(prompt.clone()),
+                            position,
+                        },
+                    ))
+                    .ok();
+            }
+
+            let request = open_ai::Request {
+                model: EDIT_PREDICTIONS_MODEL_ID.clone(),
+                messages: vec![open_ai::RequestMessage::User {
+                    content: open_ai::MessageContent::Plain(prompt),
+                }],
+                stream: false,
+                max_completion_tokens: None,
+                stop: Default::default(),
+                temperature: Default::default(),
+                tool_choice: None,
+                parallel_tool_calls: None,
+                tools: vec![],
+                prompt_cache_key: None,
+                reasoning_effort: None,
+            };
+
+            log::trace!("Sending edit prediction request");
+
+            let response = EditPredictionStore::send_raw_llm_request(
+                request,
+                client,
+                llm_token,
+                app_version,
+                #[cfg(feature = "cli-support")]
+                eval_cache,
+                #[cfg(feature = "cli-support")]
+                EvalCacheEntryKind::Prediction,
+            )
+            .await;
+            let received_response_at = Instant::now();
+
+            log::trace!("Got edit prediction response");
+
+            let (res, usage) = response?;
+            let request_id = EditPredictionId(res.id.clone().into());
+            let Some(mut output_text) = text_from_response(res) else {
+                return Ok((Some((request_id, None)), usage));
+            };
+
+            if let Some(debug_tx) = &debug_tx {
+                debug_tx
+                    .unbounded_send(DebugEvent::EditPredictionFinished(
+                        EditPredictionFinishedDebugEvent {
+                            buffer: buffer.downgrade(),
+                            position,
+                            model_output: Some(output_text.clone()),
+                        },
+                    ))
+                    .ok();
+            }
+
+            if output_text.contains(CURSOR_MARKER) {
+                log::trace!("Stripping out {CURSOR_MARKER} from response");
+                output_text = output_text.replace(CURSOR_MARKER, "");
+            }
+
+            let old_text = snapshot
+                .text_for_range(editable_offset_range.clone())
+                .collect::<String>();
+            let edits: Vec<_> = language::text_diff(&old_text, &output_text)
+                .into_iter()
+                .map(|(range, text)| {
+                    (
+                        snapshot.anchor_after(editable_offset_range.start + range.start)
+                            ..snapshot.anchor_before(editable_offset_range.start + range.end),
+                        text,
+                    )
+                })
+                .collect();
+
+            anyhow::Ok((
+                Some((
+                    request_id,
+                    Some((
+                        prompt_input,
+                        buffer,
+                        snapshot.clone(),
+                        edits,
+                        received_response_at,
+                    )),
+                )),
+                usage,
+            ))
+        }
+    });
+
+    cx.spawn(async move |this, cx| {
+        let Some((id, prediction)) =
+            EditPredictionStore::handle_api_response(&this, request_task.await, cx)?
+        else {
+            return Ok(None);
+        };
+
+        let Some((inputs, edited_buffer, edited_buffer_snapshot, edits, received_response_at)) =
+            prediction
+        else {
+            return Ok(Some(EditPredictionResult {
+                id,
+                prediction: Err(EditPredictionRejectReason::Empty),
+            }));
+        };
+
+        Ok(Some(
+            EditPredictionResult::new(
+                id,
+                &edited_buffer,
+                &edited_buffer_snapshot,
+                edits.into(),
+                buffer_snapshotted_at,
+                received_response_at,
+                inputs,
+                cx,
+            )
+            .await,
+        ))
+    })
+}
+
+pub fn zeta2_prompt_input(
+    snapshot: &language::BufferSnapshot,
+    related_files: Arc<[zeta_prompt::RelatedFile]>,
+    events: Vec<Arc<zeta_prompt::Event>>,
+    excerpt_path: Arc<Path>,
+    cursor_offset: usize,
+) -> (std::ops::Range<usize>, zeta_prompt::ZetaPromptInput) {
+    let cursor_point = cursor_offset.to_point(snapshot);
+
+    let (editable_range, context_range) =
+        crate::cursor_excerpt::editable_and_context_ranges_for_cursor_position(
+            cursor_point,
+            snapshot,
+            MAX_CONTEXT_TOKENS,
+            MAX_REWRITE_TOKENS,
+        );
+
+    let context_start_offset = context_range.start.to_offset(snapshot);
+    let editable_offset_range = editable_range.to_offset(snapshot);
+    let cursor_offset_in_excerpt = cursor_offset - context_start_offset;
+    let editable_range_in_excerpt = (editable_offset_range.start - context_start_offset)
+        ..(editable_offset_range.end - context_start_offset);
+
+    let prompt_input = zeta_prompt::ZetaPromptInput {
+        cursor_path: excerpt_path,
+        cursor_excerpt: snapshot
+            .text_for_range(context_range)
+            .collect::<String>()
+            .into(),
+        editable_range_in_excerpt,
+        cursor_offset_in_excerpt,
+        events,
+        related_files,
+    };
+    (editable_offset_range, prompt_input)
+}
+
+#[cfg(feature = "cli-support")]
+pub fn zeta2_output_for_patch(input: &zeta_prompt::ZetaPromptInput, patch: &str) -> Result<String> {
+    let text = &input.cursor_excerpt;
+    let editable_region = input.editable_range_in_excerpt.clone();
+    let old_prefix = &text[..editable_region.start];
+    let old_suffix = &text[editable_region.end..];
+
+    let new = crate::udiff::apply_diff_to_string(patch, text)?;
+    if !new.starts_with(old_prefix) || !new.ends_with(old_suffix) {
+        anyhow::bail!("Patch shouldn't affect text outside of editable region");
+    }
+
+    Ok(new[editable_region.start..new.len() - old_suffix.len()].to_string())
+}

crates/edit_prediction_button/src/sweep_api_token_modal.rs 🔗

@@ -1,84 +0,0 @@
-use gpui::{
-    DismissEvent, Entity, EventEmitter, FocusHandle, Focusable, IntoElement, ParentElement, Render,
-};
-use ui::{Button, ButtonStyle, Clickable, Headline, HeadlineSize, prelude::*};
-use ui_input::InputField;
-use workspace::ModalView;
-use zeta::Zeta;
-
-pub struct SweepApiKeyModal {
-    api_key_input: Entity<InputField>,
-    focus_handle: FocusHandle,
-}
-
-impl SweepApiKeyModal {
-    pub fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
-        let api_key_input = cx.new(|cx| InputField::new(window, cx, "Enter your Sweep API token"));
-
-        Self {
-            api_key_input,
-            focus_handle: cx.focus_handle(),
-        }
-    }
-
-    fn cancel(&mut self, _: &menu::Cancel, _window: &mut Window, cx: &mut Context<Self>) {
-        cx.emit(DismissEvent);
-    }
-
-    fn confirm(&mut self, _: &menu::Confirm, _window: &mut Window, cx: &mut Context<Self>) {
-        let api_key = self.api_key_input.read(cx).text(cx);
-        let api_key = (!api_key.trim().is_empty()).then_some(api_key);
-
-        if let Some(zeta) = Zeta::try_global(cx) {
-            zeta.update(cx, |zeta, cx| {
-                zeta.sweep_ai
-                    .set_api_token(api_key, cx)
-                    .detach_and_log_err(cx);
-            });
-        }
-
-        cx.emit(DismissEvent);
-    }
-}
-
-impl EventEmitter<DismissEvent> for SweepApiKeyModal {}
-
-impl ModalView for SweepApiKeyModal {}
-
-impl Focusable for SweepApiKeyModal {
-    fn focus_handle(&self, _cx: &App) -> FocusHandle {
-        self.focus_handle.clone()
-    }
-}
-
-impl Render for SweepApiKeyModal {
-    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
-        v_flex()
-            .key_context("SweepApiKeyModal")
-            .on_action(cx.listener(Self::cancel))
-            .on_action(cx.listener(Self::confirm))
-            .elevation_2(cx)
-            .w(px(400.))
-            .p_4()
-            .gap_3()
-            .child(Headline::new("Sweep API Token").size(HeadlineSize::Small))
-            .child(self.api_key_input.clone())
-            .child(
-                h_flex()
-                    .justify_end()
-                    .gap_2()
-                    .child(Button::new("cancel", "Cancel").on_click(cx.listener(
-                        |_, _, _window, cx| {
-                            cx.emit(DismissEvent);
-                        },
-                    )))
-                    .child(
-                        Button::new("save", "Save")
-                            .style(ButtonStyle::Filled)
-                            .on_click(cx.listener(|this, _, window, cx| {
-                                this.confirm(&menu::Confirm, window, cx);
-                            })),
-                    ),
-            )
-    }
-}

crates/zeta_cli/Cargo.toml → crates/edit_prediction_cli/Cargo.toml 🔗

@@ -1,5 +1,5 @@
 [package]
-name = "zeta_cli"
+name = "edit_prediction_cli"
 version = "0.1.0"
 edition.workspace = true
 publish.workspace = true
@@ -9,38 +9,37 @@ license = "GPL-3.0-or-later"
 workspace = true
 
 [[bin]]
-name = "zeta"
+name = "ep"
 path = "src/main.rs"
 
 [dependencies]
-
 anyhow.workspace = true
+anthropic.workspace = true
+http_client.workspace = true
 chrono.workspace = true
 clap.workspace = true
 client.workspace = true
 cloud_llm_client.workspace= true
-cloud_zeta2_prompt.workspace= true
 collections.workspace = true
 debug_adapter_extension.workspace = true
-edit_prediction_context.workspace = true
+dirs.workspace = true
 extension.workspace = true
 fs.workspace = true
 futures.workspace = true
 gpui.workspace = true
 gpui_tokio.workspace = true
+indoc.workspace = true
 language.workspace = true
 language_extension.workspace = true
 language_model.workspace = true
 language_models.workspace = true
 languages = { workspace = true, features = ["load-grammars"] }
+libc.workspace = true
 log.workspace = true
 node_runtime.workspace = true
-ordered-float.workspace = true
 paths.workspace = true
-polars = { version = "0.51", features = ["lazy", "dtype-struct", "parquet"] }
 project.workspace = true
 prompt_store.workspace = true
-pulldown-cmark.workspace = true
 release_channel.workspace = true
 reqwest_client.workspace = true
 serde.workspace = true
@@ -48,13 +47,22 @@ serde_json.workspace = true
 settings.workspace = true
 shellexpand.workspace = true
 smol.workspace = true
-soa-rs = "0.8.1"
+sqlez.workspace = true
+sqlez_macros.workspace = true
 terminal_view.workspace = true
-toml.workspace = true
 util.workspace = true
 watch.workspace = true
-zeta = { workspace = true, features = ["eval-support"] }
-zlog.workspace = true
+edit_prediction = { workspace = true, features = ["cli-support"] }
+wasmtime.workspace = true
+zeta_prompt.workspace = true
+
+# Wasmtime is included as a dependency in order to enable the same
+# features that are enabled in Zed.
+#
+# If we don't enable these features we get crashes when creating
+# a Tree-sitter WasmStore.
+[package.metadata.cargo-machete]
+ignored = ["wasmtime"]
 
 [dev-dependencies]
 indoc.workspace = true

crates/edit_prediction_cli/src/anthropic_client.rs 🔗

@@ -0,0 +1,418 @@
+use anthropic::{
+    ANTHROPIC_API_URL, Message, Request as AnthropicRequest, RequestContent,
+    Response as AnthropicResponse, Role, non_streaming_completion,
+};
+use anyhow::Result;
+use http_client::HttpClient;
+use indoc::indoc;
+use reqwest_client::ReqwestClient;
+use sqlez::bindable::Bind;
+use sqlez::bindable::StaticColumnCount;
+use sqlez_macros::sql;
+use std::hash::Hash;
+use std::hash::Hasher;
+use std::path::Path;
+use std::sync::Arc;
+
+pub struct PlainLlmClient {
+    http_client: Arc<dyn HttpClient>,
+    api_key: String,
+}
+
+impl PlainLlmClient {
+    fn new() -> Result<Self> {
+        let http_client: Arc<dyn http_client::HttpClient> = Arc::new(ReqwestClient::new());
+        let api_key = std::env::var("ANTHROPIC_API_KEY")
+            .map_err(|_| anyhow::anyhow!("ANTHROPIC_API_KEY environment variable not set"))?;
+        Ok(Self {
+            http_client,
+            api_key,
+        })
+    }
+
+    async fn generate(
+        &self,
+        model: &str,
+        max_tokens: u64,
+        messages: Vec<Message>,
+    ) -> Result<AnthropicResponse> {
+        let request = AnthropicRequest {
+            model: model.to_string(),
+            max_tokens,
+            messages,
+            tools: Vec::new(),
+            thinking: None,
+            tool_choice: None,
+            system: None,
+            metadata: None,
+            stop_sequences: Vec::new(),
+            temperature: None,
+            top_k: None,
+            top_p: None,
+        };
+
+        let response = non_streaming_completion(
+            self.http_client.as_ref(),
+            ANTHROPIC_API_URL,
+            &self.api_key,
+            request,
+            None,
+        )
+        .await
+        .map_err(|e| anyhow::anyhow!("{:?}", e))?;
+
+        Ok(response)
+    }
+}
+
+pub struct BatchingLlmClient {
+    connection: sqlez::connection::Connection,
+    http_client: Arc<dyn HttpClient>,
+    api_key: String,
+}
+
+struct CacheRow {
+    request_hash: String,
+    request: Option<String>,
+    response: Option<String>,
+    batch_id: Option<String>,
+}
+
+impl StaticColumnCount for CacheRow {
+    fn column_count() -> usize {
+        4
+    }
+}
+
+impl Bind for CacheRow {
+    fn bind(&self, statement: &sqlez::statement::Statement, start_index: i32) -> Result<i32> {
+        let next_index = statement.bind(&self.request_hash, start_index)?;
+        let next_index = statement.bind(&self.request, next_index)?;
+        let next_index = statement.bind(&self.response, next_index)?;
+        let next_index = statement.bind(&self.batch_id, next_index)?;
+        Ok(next_index)
+    }
+}
+
+#[derive(serde::Serialize, serde::Deserialize)]
+struct SerializableRequest {
+    model: String,
+    max_tokens: u64,
+    messages: Vec<SerializableMessage>,
+}
+
+#[derive(serde::Serialize, serde::Deserialize)]
+struct SerializableMessage {
+    role: String,
+    content: String,
+}
+
+impl BatchingLlmClient {
+    fn new(cache_path: &Path) -> Result<Self> {
+        let http_client: Arc<dyn http_client::HttpClient> = Arc::new(ReqwestClient::new());
+        let api_key = std::env::var("ANTHROPIC_API_KEY")
+            .map_err(|_| anyhow::anyhow!("ANTHROPIC_API_KEY environment variable not set"))?;
+
+        let connection = sqlez::connection::Connection::open_file(&cache_path.to_str().unwrap());
+        let mut statement = sqlez::statement::Statement::prepare(
+            &connection,
+            indoc! {"
+                CREATE TABLE IF NOT EXISTS cache (
+                    request_hash TEXT PRIMARY KEY,
+                    request TEXT,
+                    response TEXT,
+                    batch_id TEXT
+                );
+                "},
+        )?;
+        statement.exec()?;
+        drop(statement);
+
+        Ok(Self {
+            connection,
+            http_client,
+            api_key,
+        })
+    }
+
+    pub fn lookup(
+        &self,
+        model: &str,
+        max_tokens: u64,
+        messages: &[Message],
+    ) -> Result<Option<AnthropicResponse>> {
+        let request_hash_str = Self::request_hash(model, max_tokens, messages);
+        let response: Vec<String> = self.connection.select_bound(
+            &sql!(SELECT response FROM cache WHERE request_hash = ?1 AND response IS NOT NULL;),
+        )?(request_hash_str.as_str())?;
+        Ok(response
+            .into_iter()
+            .next()
+            .and_then(|text| serde_json::from_str(&text).ok()))
+    }
+
+    pub fn mark_for_batch(&self, model: &str, max_tokens: u64, messages: &[Message]) -> Result<()> {
+        let request_hash = Self::request_hash(model, max_tokens, messages);
+
+        let serializable_messages: Vec<SerializableMessage> = messages
+            .iter()
+            .map(|msg| SerializableMessage {
+                role: match msg.role {
+                    Role::User => "user".to_string(),
+                    Role::Assistant => "assistant".to_string(),
+                },
+                content: message_content_to_string(&msg.content),
+            })
+            .collect();
+
+        let serializable_request = SerializableRequest {
+            model: model.to_string(),
+            max_tokens,
+            messages: serializable_messages,
+        };
+
+        let request = Some(serde_json::to_string(&serializable_request)?);
+        let cache_row = CacheRow {
+            request_hash,
+            request,
+            response: None,
+            batch_id: None,
+        };
+        self.connection.exec_bound(sql!(
+            INSERT OR IGNORE INTO cache(request_hash, request, response, batch_id) VALUES (?, ?, ?, ?)))?(
+            cache_row,
+        )
+    }
+
+    async fn generate(
+        &self,
+        model: &str,
+        max_tokens: u64,
+        messages: Vec<Message>,
+    ) -> Result<Option<AnthropicResponse>> {
+        let response = self.lookup(model, max_tokens, &messages)?;
+        if let Some(response) = response {
+            return Ok(Some(response));
+        }
+
+        self.mark_for_batch(model, max_tokens, &messages)?;
+
+        Ok(None)
+    }
+
+    /// Uploads pending requests as a new batch; downloads finished batches if any.
+    async fn sync_batches(&self) -> Result<()> {
+        self.upload_pending_requests().await?;
+        self.download_finished_batches().await
+    }
+
+    async fn download_finished_batches(&self) -> Result<()> {
+        let q = sql!(SELECT DISTINCT batch_id FROM cache WHERE batch_id IS NOT NULL AND response IS NULL);
+        let batch_ids: Vec<String> = self.connection.select(q)?()?;
+
+        for batch_id in batch_ids {
+            let batch_status = anthropic::batches::retrieve_batch(
+                self.http_client.as_ref(),
+                ANTHROPIC_API_URL,
+                &self.api_key,
+                &batch_id,
+            )
+            .await
+            .map_err(|e| anyhow::anyhow!("{:?}", e))?;
+
+            log::info!(
+                "Batch {} status: {}",
+                batch_id,
+                batch_status.processing_status
+            );
+
+            if batch_status.processing_status == "ended" {
+                let results = anthropic::batches::retrieve_batch_results(
+                    self.http_client.as_ref(),
+                    ANTHROPIC_API_URL,
+                    &self.api_key,
+                    &batch_id,
+                )
+                .await
+                .map_err(|e| anyhow::anyhow!("{:?}", e))?;
+
+                let mut success_count = 0;
+                for result in results {
+                    let request_hash = result
+                        .custom_id
+                        .strip_prefix("req_hash_")
+                        .unwrap_or(&result.custom_id)
+                        .to_string();
+
+                    match result.result {
+                        anthropic::batches::BatchResult::Succeeded { message } => {
+                            let response_json = serde_json::to_string(&message)?;
+                            let q = sql!(UPDATE cache SET response = ? WHERE request_hash = ?);
+                            self.connection.exec_bound(q)?((response_json, request_hash))?;
+                            success_count += 1;
+                        }
+                        anthropic::batches::BatchResult::Errored { error } => {
+                            log::error!("Batch request {} failed: {:?}", request_hash, error);
+                        }
+                        anthropic::batches::BatchResult::Canceled => {
+                            log::warn!("Batch request {} was canceled", request_hash);
+                        }
+                        anthropic::batches::BatchResult::Expired => {
+                            log::warn!("Batch request {} expired", request_hash);
+                        }
+                    }
+                }
+                log::info!("Downloaded {} successful requests", success_count);
+            }
+        }
+
+        Ok(())
+    }
+
+    async fn upload_pending_requests(&self) -> Result<String> {
+        let q = sql!(
+        SELECT request_hash, request FROM cache WHERE batch_id IS NULL AND response IS NULL
+        );
+
+        let rows: Vec<(String, String)> = self.connection.select(q)?()?;
+
+        if rows.is_empty() {
+            return Ok(String::new());
+        }
+
+        let batch_requests = rows
+            .iter()
+            .map(|(hash, request_str)| {
+                let serializable_request: SerializableRequest =
+                    serde_json::from_str(&request_str).unwrap();
+
+                let messages: Vec<Message> = serializable_request
+                    .messages
+                    .into_iter()
+                    .map(|msg| Message {
+                        role: match msg.role.as_str() {
+                            "user" => Role::User,
+                            "assistant" => Role::Assistant,
+                            _ => Role::User,
+                        },
+                        content: vec![RequestContent::Text {
+                            text: msg.content,
+                            cache_control: None,
+                        }],
+                    })
+                    .collect();
+
+                let params = AnthropicRequest {
+                    model: serializable_request.model,
+                    max_tokens: serializable_request.max_tokens,
+                    messages,
+                    tools: Vec::new(),
+                    thinking: None,
+                    tool_choice: None,
+                    system: None,
+                    metadata: None,
+                    stop_sequences: Vec::new(),
+                    temperature: None,
+                    top_k: None,
+                    top_p: None,
+                };
+
+                let custom_id = format!("req_hash_{}", hash);
+                anthropic::batches::BatchRequest { custom_id, params }
+            })
+            .collect::<Vec<_>>();
+
+        let batch_len = batch_requests.len();
+        let batch = anthropic::batches::create_batch(
+            self.http_client.as_ref(),
+            ANTHROPIC_API_URL,
+            &self.api_key,
+            anthropic::batches::CreateBatchRequest {
+                requests: batch_requests,
+            },
+        )
+        .await
+        .map_err(|e| anyhow::anyhow!("{:?}", e))?;
+
+        let q = sql!(
+            UPDATE cache SET batch_id = ? WHERE batch_id is NULL
+        );
+        self.connection.exec_bound(q)?(batch.id.as_str())?;
+
+        log::info!("Uploaded batch with {} requests", batch_len);
+
+        Ok(batch.id)
+    }
+
+    fn request_hash(model: &str, max_tokens: u64, messages: &[Message]) -> String {
+        let mut hasher = std::hash::DefaultHasher::new();
+        model.hash(&mut hasher);
+        max_tokens.hash(&mut hasher);
+        for msg in messages {
+            message_content_to_string(&msg.content).hash(&mut hasher);
+        }
+        let request_hash = hasher.finish();
+        format!("{request_hash:016x}")
+    }
+}
+
+fn message_content_to_string(content: &[RequestContent]) -> String {
+    content
+        .iter()
+        .filter_map(|c| match c {
+            RequestContent::Text { text, .. } => Some(text.clone()),
+            _ => None,
+        })
+        .collect::<Vec<String>>()
+        .join("\n")
+}
+
+pub enum AnthropicClient {
+    // No batching
+    Plain(PlainLlmClient),
+    Batch(BatchingLlmClient),
+    Dummy,
+}
+
+impl AnthropicClient {
+    pub fn plain() -> Result<Self> {
+        Ok(Self::Plain(PlainLlmClient::new()?))
+    }
+
+    pub fn batch(cache_path: &Path) -> Result<Self> {
+        Ok(Self::Batch(BatchingLlmClient::new(cache_path)?))
+    }
+
+    #[allow(dead_code)]
+    pub fn dummy() -> Self {
+        Self::Dummy
+    }
+
+    pub async fn generate(
+        &self,
+        model: &str,
+        max_tokens: u64,
+        messages: Vec<Message>,
+    ) -> Result<Option<AnthropicResponse>> {
+        match self {
+            AnthropicClient::Plain(plain_llm_client) => plain_llm_client
+                .generate(model, max_tokens, messages)
+                .await
+                .map(Some),
+            AnthropicClient::Batch(batching_llm_client) => {
+                batching_llm_client
+                    .generate(model, max_tokens, messages)
+                    .await
+            }
+            AnthropicClient::Dummy => panic!("Dummy LLM client is not expected to be used"),
+        }
+    }
+
+    pub async fn sync_batches(&self) -> Result<()> {
+        match self {
+            AnthropicClient::Plain(_) => Ok(()),
+            AnthropicClient::Batch(batching_llm_client) => batching_llm_client.sync_batches().await,
+            AnthropicClient::Dummy => panic!("Dummy LLM client is not expected to be used"),
+        }
+    }
+}

crates/edit_prediction_cli/src/distill.rs 🔗

@@ -0,0 +1,22 @@
+use anyhow::{Result, anyhow};
+use std::mem;
+
+use crate::example::Example;
+
+pub async fn run_distill(example: &mut Example) -> Result<()> {
+    let [prediction]: [_; 1] =
+        mem::take(&mut example.predictions)
+            .try_into()
+            .map_err(|preds: Vec<_>| {
+                anyhow!(
+                    "Example has {} predictions, but it should have exactly one",
+                    preds.len()
+                )
+            })?;
+
+    example.spec.expected_patch = prediction.actual_patch;
+    example.prompt = None;
+    example.predictions = Vec::new();
+    example.score = Vec::new();
+    Ok(())
+}

crates/edit_prediction_cli/src/example.rs 🔗

@@ -0,0 +1,250 @@
+use crate::{PredictionProvider, PromptFormat, metrics::ClassificationMetrics};
+use anyhow::{Context as _, Result};
+use collections::HashMap;
+use edit_prediction::example_spec::ExampleSpec;
+use edit_prediction::udiff::OpenedBuffers;
+use gpui::Entity;
+use http_client::Url;
+use language::{Anchor, Buffer};
+use project::Project;
+use serde::{Deserialize, Serialize};
+use std::sync::Arc;
+use std::{
+    borrow::Cow,
+    io::{Read, Write},
+    path::{Path, PathBuf},
+};
+use zeta_prompt::RelatedFile;
+
+#[derive(Clone, Debug, Serialize, Deserialize)]
+pub struct Example {
+    #[serde(flatten)]
+    pub spec: ExampleSpec,
+
+    /// The full content of the file where an edit is being predicted, and the
+    /// actual cursor offset.
+    #[serde(skip_serializing_if = "Option::is_none")]
+    pub buffer: Option<ExampleBuffer>,
+
+    /// The context retrieved for the prediction. This requires the worktree to
+    /// be loaded and the language server to be started.
+    #[serde(skip_serializing_if = "Option::is_none")]
+    pub context: Option<ExampleContext>,
+
+    /// The input and expected output from the edit prediction model.
+    #[serde(skip_serializing_if = "Option::is_none")]
+    pub prompt: Option<ExamplePrompt>,
+
+    /// The actual predictions from the model.
+    #[serde(default, skip_serializing_if = "Vec::is_empty")]
+    pub predictions: Vec<ExamplePrediction>,
+
+    /// The scores, for how well the actual predictions match the expected
+    /// predictions.
+    #[serde(default, skip_serializing_if = "Vec::is_empty")]
+    pub score: Vec<ExampleScore>,
+
+    /// The application state used to process this example.
+    #[serde(skip)]
+    pub state: Option<ExampleState>,
+}
+
+#[derive(Clone, Debug)]
+pub struct ExampleState {
+    pub project: Entity<Project>,
+    pub buffer: Entity<Buffer>,
+    pub cursor_position: Anchor,
+    pub _open_buffers: OpenedBuffers,
+}
+
+#[derive(Clone, Debug, Serialize, Deserialize)]
+pub struct ExampleContext {
+    pub files: Arc<[RelatedFile]>,
+}
+
+#[derive(Clone, Debug, Serialize, Deserialize)]
+pub struct ExampleBuffer {
+    pub content: String,
+    pub cursor_row: u32,
+    pub cursor_column: u32,
+    pub cursor_offset: usize,
+}
+
+#[derive(Clone, Debug, Serialize, Deserialize)]
+pub struct ExamplePrompt {
+    pub input: String,
+    pub expected_output: String,
+    pub format: PromptFormat,
+}
+
+#[derive(Clone, Debug, Serialize, Deserialize)]
+pub struct ExamplePrediction {
+    pub actual_patch: String,
+    pub actual_output: String,
+    pub provider: PredictionProvider,
+}
+
+#[derive(Clone, Debug, Serialize, Deserialize)]
+pub struct ExampleScore {
+    pub delta_chr_f: f32,
+    pub line_match: ClassificationMetrics,
+}
+
+impl Example {
+    pub fn repo_name(&self) -> Result<(Cow<'_, str>, Cow<'_, str>)> {
+        // git@github.com:owner/repo.git
+        if self.spec.repository_url.contains('@') {
+            let (owner, repo) = self
+                .spec
+                .repository_url
+                .split_once(':')
+                .context("expected : in git url")?
+                .1
+                .split_once('/')
+                .context("expected / in git url")?;
+            Ok((
+                Cow::Borrowed(owner),
+                Cow::Borrowed(repo.trim_end_matches(".git")),
+            ))
+        // http://github.com/owner/repo.git
+        } else {
+            let url = Url::parse(&self.spec.repository_url)?;
+            let mut segments = url.path_segments().context("empty http url")?;
+            let owner = segments
+                .next()
+                .context("expected owner path segment")?
+                .to_string();
+            let repo = segments
+                .next()
+                .context("expected repo path segment")?
+                .trim_end_matches(".git")
+                .to_string();
+            assert!(segments.next().is_none());
+
+            Ok((owner.into(), repo.into()))
+        }
+    }
+}
+
+pub fn read_examples(inputs: &[PathBuf]) -> Vec<Example> {
+    let mut examples = Vec::new();
+
+    let stdin_path: PathBuf = PathBuf::from("-");
+
+    let inputs = if inputs.is_empty() {
+        &[stdin_path]
+    } else {
+        inputs
+    };
+
+    for path in inputs {
+        let is_stdin = path.as_path() == Path::new("-");
+        let content = if is_stdin {
+            let mut buffer = String::new();
+            std::io::stdin()
+                .read_to_string(&mut buffer)
+                .expect("Failed to read from stdin");
+            buffer
+        } else {
+            std::fs::read_to_string(path)
+                .unwrap_or_else(|_| panic!("Failed to read path: {:?}", &path))
+        };
+        let filename = path.file_stem().unwrap().to_string_lossy().to_string();
+        let ext = if !is_stdin {
+            path.extension()
+                .map(|ext| ext.to_string_lossy().to_string())
+                .unwrap_or_else(|| panic!("{} should have an extension", path.display()))
+        } else {
+            "jsonl".to_string()
+        };
+
+        match ext.as_ref() {
+            "json" => {
+                let mut example =
+                    serde_json::from_str::<Example>(&content).unwrap_or_else(|error| {
+                        panic!("Failed to parse example file: {}\n{error}", path.display())
+                    });
+                if example.spec.name.is_empty() {
+                    example.spec.name = filename;
+                }
+                examples.push(example);
+            }
+            "jsonl" => examples.extend(
+                content
+                    .lines()
+                    .enumerate()
+                    .map(|(line_ix, line)| {
+                        let mut example =
+                            serde_json::from_str::<Example>(line).unwrap_or_else(|error| {
+                                panic!(
+                                    "Failed to parse example on {}:{}\n{error}",
+                                    path.display(),
+                                    line_ix + 1
+                                )
+                            });
+                        if example.spec.name.is_empty() {
+                            example.spec.name = format!("{filename}-{line_ix}")
+                        }
+                        example
+                    })
+                    .collect::<Vec<Example>>(),
+            ),
+            "md" => {
+                examples.push(parse_markdown_example(filename, &content).unwrap());
+            }
+            ext => {
+                panic!("{} has invalid example extension `{ext}`", path.display())
+            }
+        }
+    }
+
+    sort_examples_by_repo_and_rev(&mut examples);
+    examples
+}
+
+pub fn write_examples(examples: &[Example], output_path: Option<&PathBuf>) {
+    let mut content = String::new();
+    for example in examples {
+        let line = serde_json::to_string(example).unwrap();
+        content.push_str(&line);
+        content.push('\n');
+    }
+    if let Some(output_path) = output_path {
+        std::fs::write(output_path, content).expect("Failed to write examples");
+    } else {
+        std::io::stdout().write_all(&content.as_bytes()).unwrap();
+    }
+}
+
+pub fn sort_examples_by_repo_and_rev(examples: &mut [Example]) {
+    examples.sort_by(|a, b| {
+        a.spec
+            .repository_url
+            .cmp(&b.spec.repository_url)
+            .then(b.spec.revision.cmp(&a.spec.revision))
+    });
+}
+
+pub fn group_examples_by_repo(examples: &mut [Example]) -> Vec<Vec<&mut Example>> {
+    let mut examples_by_repo = HashMap::default();
+    for example in examples.iter_mut() {
+        examples_by_repo
+            .entry(example.spec.repository_url.clone())
+            .or_insert_with(Vec::new)
+            .push(example);
+    }
+    examples_by_repo.into_values().collect()
+}
+
+fn parse_markdown_example(name: String, input: &str) -> Result<Example> {
+    let spec = ExampleSpec::from_markdown(name, input)?;
+    Ok(Example {
+        spec,
+        buffer: None,
+        context: None,
+        prompt: None,
+        predictions: Vec::new(),
+        score: Vec::new(),
+        state: None,
+    })
+}

crates/edit_prediction_cli/src/format_prompt.rs 🔗

@@ -0,0 +1,293 @@
+use crate::{
+    PromptFormat,
+    example::{Example, ExamplePrompt},
+    headless::EpAppState,
+    load_project::run_load_project,
+    progress::{Progress, Step},
+    retrieve_context::run_context_retrieval,
+};
+use anyhow::{Context as _, Result, ensure};
+use edit_prediction::{
+    EditPredictionStore,
+    zeta2::{zeta2_output_for_patch, zeta2_prompt_input},
+};
+use gpui::AsyncApp;
+use std::sync::Arc;
+use zeta_prompt::format_zeta_prompt;
+
+pub async fn run_format_prompt(
+    example: &mut Example,
+    prompt_format: PromptFormat,
+    app_state: Arc<EpAppState>,
+    mut cx: AsyncApp,
+) -> Result<()> {
+    run_context_retrieval(example, app_state.clone(), cx.clone()).await?;
+
+    let _step_progress = Progress::global().start(Step::FormatPrompt, &example.spec.name);
+
+    match prompt_format {
+        PromptFormat::Teacher => {
+            let prompt = TeacherPrompt::format_prompt(example);
+            example.prompt = Some(ExamplePrompt {
+                input: prompt,
+                expected_output: example.spec.expected_patch.clone(), // TODO
+                format: prompt_format,
+            });
+        }
+        PromptFormat::Zeta2 => {
+            run_load_project(example, app_state, cx.clone()).await?;
+
+            let ep_store = cx.update(|cx| {
+                EditPredictionStore::try_global(cx).context("EditPredictionStore not initialized")
+            })??;
+
+            let state = example.state.as_ref().context("state must be set")?;
+            let snapshot = state.buffer.read_with(&cx, |buffer, _| buffer.snapshot())?;
+            let project = state.project.clone();
+            let (_, input) = ep_store.update(&mut cx, |ep_store, cx| {
+                let events = ep_store
+                    .edit_history_for_project(&project, cx)
+                    .into_iter()
+                    .map(|e| e.event)
+                    .collect();
+                anyhow::Ok(zeta2_prompt_input(
+                    &snapshot,
+                    example
+                        .context
+                        .as_ref()
+                        .context("context must be set")?
+                        .files
+                        .clone(),
+                    events,
+                    example.spec.cursor_path.clone(),
+                    example
+                        .buffer
+                        .as_ref()
+                        .context("buffer must be set")?
+                        .cursor_offset,
+                ))
+            })??;
+            let prompt = format_zeta_prompt(&input);
+            let expected_output =
+                zeta2_output_for_patch(&input, &example.spec.expected_patch.clone())?;
+            example.prompt = Some(ExamplePrompt {
+                input: prompt,
+                expected_output,
+                format: prompt_format,
+            });
+        }
+    };
+    Ok(())
+}
+
+pub struct TeacherPrompt;
+
+impl TeacherPrompt {
+    const PROMPT: &str = include_str!("teacher.prompt.md");
+    pub(crate) const EDITABLE_REGION_START: &str = "<|editable_region_start|>\n";
+    pub(crate) const EDITABLE_REGION_END: &str = "<|editable_region_end|>";
+
+    /// Truncate edit history to this number of last lines
+    const MAX_HISTORY_LINES: usize = 128;
+
+    pub fn format_prompt(example: &Example) -> String {
+        let edit_history = Self::format_edit_history(&example.spec.edit_history);
+        let context = Self::format_context(example);
+        let editable_region = Self::format_editable_region(example);
+
+        let prompt = Self::PROMPT
+            .replace("{{context}}", &context)
+            .replace("{{edit_history}}", &edit_history)
+            .replace("{{editable_region}}", &editable_region);
+
+        prompt
+    }
+
+    pub fn parse(example: &Example, response: &str) -> Result<String> {
+        // Ideally, we should always be able to find cursor position in the retrieved context.
+        // In reality, sometimes we don't find it for these reasons:
+        // 1. `example.cursor_position` contains _more_ context than included in the retrieved context
+        //    (can be fixed by getting cursor coordinates at the load_example stage)
+        // 2. Context retriever just didn't include cursor line.
+        //
+        // In that case, fallback to using `cursor_position` as excerpt.
+        let cursor_file = &example
+            .buffer
+            .as_ref()
+            .context("`buffer` should be filled in in the context collection step")?
+            .content;
+
+        // Extract updated (new) editable region from the model response
+        let new_editable_region = extract_last_codeblock(response);
+
+        // Reconstruct old editable region we sent to the model
+        let old_editable_region = Self::format_editable_region(example);
+        let old_editable_region = Self::extract_editable_region(&old_editable_region);
+        ensure!(
+            cursor_file.contains(&old_editable_region),
+            "Something's wrong: editable_region is not found in the cursor file"
+        );
+
+        // Apply editable region to a larger context and compute diff.
+        // This is needed to get a better context lines around the editable region
+        let edited_file = cursor_file.replace(&old_editable_region, &new_editable_region);
+        let diff = language::unified_diff(&cursor_file, &edited_file);
+
+        let diff = indoc::formatdoc! {"
+            --- a/{path}
+            +++ b/{path}
+            {diff}",
+            path = example.spec.cursor_path.to_string_lossy(),
+            diff = diff,
+        };
+
+        Ok(diff)
+    }
+
+    fn format_edit_history(edit_history: &str) -> String {
+        // Strip comments ("garbage lines") from edit history
+        let lines = edit_history
+            .lines()
+            .filter(|&s| Self::is_udiff_content_line(s))
+            .collect::<Vec<_>>();
+
+        let history_lines = if lines.len() > Self::MAX_HISTORY_LINES {
+            &lines[lines.len() - Self::MAX_HISTORY_LINES..]
+        } else {
+            &lines
+        };
+
+        if history_lines.is_empty() {
+            return "(No edit history)".to_string();
+        }
+
+        history_lines.join("\n")
+    }
+
+    fn format_context(example: &Example) -> String {
+        assert!(example.context.is_some(), "Missing context retriever step");
+
+        let mut prompt = String::new();
+        zeta_prompt::write_related_files(&mut prompt, &example.context.as_ref().unwrap().files);
+
+        prompt
+    }
+
+    fn format_editable_region(example: &Example) -> String {
+        let mut result = String::new();
+
+        let path_str = example.spec.cursor_path.to_string_lossy();
+        result.push_str(&format!("`````path=\"{path_str}\"\n"));
+        result.push_str(Self::EDITABLE_REGION_START);
+
+        // TODO: control number of lines around cursor
+        result.push_str(&example.spec.cursor_position);
+        if !example.spec.cursor_position.ends_with('\n') {
+            result.push('\n');
+        }
+
+        result.push_str(&format!("{}\n", Self::EDITABLE_REGION_END));
+        result.push_str("`````");
+
+        result
+    }
+
+    fn extract_editable_region(text: &str) -> String {
+        let start = text
+            .find(Self::EDITABLE_REGION_START)
+            .map_or(0, |pos| pos + Self::EDITABLE_REGION_START.len());
+        let end = text.find(Self::EDITABLE_REGION_END).unwrap_or(text.len());
+
+        let region = &text[start..end];
+
+        region.replace("<|user_cursor|>", "")
+    }
+
+    fn is_udiff_content_line(s: &str) -> bool {
+        s.starts_with("-")
+            || s.starts_with("+")
+            || s.starts_with(" ")
+            || s.starts_with("---")
+            || s.starts_with("+++")
+            || s.starts_with("@@")
+    }
+}
+
+fn extract_last_codeblock(text: &str) -> String {
+    let mut last_block = None;
+    let mut search_start = 0;
+
+    while let Some(start) = text[search_start..].find("```") {
+        let start = start + search_start;
+        let bytes = text.as_bytes();
+        let mut backtick_end = start;
+
+        while backtick_end < bytes.len() && bytes[backtick_end] == b'`' {
+            backtick_end += 1;
+        }
+
+        let backtick_count = backtick_end - start;
+        let closing_backticks = "`".repeat(backtick_count);
+
+        while backtick_end < bytes.len() && bytes[backtick_end] != b'\n' {
+            backtick_end += 1;
+        }
+
+        if let Some(end_pos) = text[backtick_end..].find(&closing_backticks) {
+            let code_block = &text[backtick_end + 1..backtick_end + end_pos];
+            last_block = Some(code_block.to_string());
+            search_start = backtick_end + end_pos + backtick_count;
+        } else {
+            break;
+        }
+    }
+
+    last_block.unwrap_or_else(|| text.to_string())
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    #[test]
+    fn test_extract_last_code_block() {
+        let text = indoc::indoc! {"
+            Some thinking
+
+            ```
+            first block
+            ```
+
+            `````path='something' lines=1:2
+            last block
+            `````
+            "};
+        let last_block = extract_last_codeblock(text);
+        assert_eq!(last_block, "last block\n");
+    }
+
+    #[test]
+    fn test_extract_editable_region() {
+        let text = indoc::indoc! {"
+            some lines
+            are
+            here
+            <|editable_region_start|>
+            one
+            two three
+
+            <|editable_region_end|>
+            more
+            lines here
+            "};
+        let parsed = TeacherPrompt::extract_editable_region(text);
+        assert_eq!(
+            parsed,
+            indoc::indoc! {"
+            one
+            two three
+
+            "}
+        );
+    }
+}

crates/zeta_cli/src/headless.rs → crates/edit_prediction_cli/src/headless.rs 🔗

@@ -1,4 +1,5 @@
 use client::{Client, ProxySettings, UserStore};
+use collections::HashMap;
 use extension::ExtensionHostProxy;
 use fs::RealFs;
 use gpui::http_client::read_proxy_from_env;
@@ -7,25 +8,38 @@ use gpui_tokio::Tokio;
 use language::LanguageRegistry;
 use language_extension::LspAccess;
 use node_runtime::{NodeBinaryOptions, NodeRuntime};
-use project::project_settings::ProjectSettings;
+use project::{Project, project_settings::ProjectSettings};
 use release_channel::{AppCommitSha, AppVersion};
 use reqwest_client::ReqwestClient;
 use settings::{Settings, SettingsStore};
 use std::path::PathBuf;
-use std::sync::Arc;
+use std::sync::{Arc, Mutex};
 use util::ResultExt as _;
 
 /// Headless subset of `workspace::AppState`.
-pub struct ZetaCliAppState {
+pub struct EpAppState {
     pub languages: Arc<LanguageRegistry>,
     pub client: Arc<Client>,
     pub user_store: Entity<UserStore>,
     pub fs: Arc<dyn fs::Fs>,
     pub node_runtime: NodeRuntime,
+    pub project_cache: ProjectCache,
 }
 
-// TODO: dedupe with crates/eval/src/eval.rs
-pub fn init(cx: &mut App) -> ZetaCliAppState {
+#[derive(Default)]
+pub struct ProjectCache(Mutex<HashMap<String, Entity<Project>>>);
+
+impl ProjectCache {
+    pub fn insert(&self, repository_url: String, project: Entity<Project>) {
+        self.0.lock().unwrap().insert(repository_url, project);
+    }
+
+    pub fn get(&self, repository_url: &String) -> Option<Entity<Project>> {
+        self.0.lock().unwrap().get(repository_url).cloned()
+    }
+}
+
+pub fn init(cx: &mut App) -> EpAppState {
     let app_commit_sha = option_env!("ZED_COMMIT_SHA").map(|s| AppCommitSha::new(s.to_owned()));
 
     let app_version = AppVersion::load(
@@ -112,11 +126,14 @@ pub fn init(cx: &mut App) -> ZetaCliAppState {
     prompt_store::init(cx);
     terminal_view::init(cx);
 
-    ZetaCliAppState {
+    let project_cache = ProjectCache::default();
+
+    EpAppState {
         languages,
         client,
         user_store,
         fs,
         node_runtime,
+        project_cache,
     }
 }

crates/edit_prediction_cli/src/load_project.rs 🔗

@@ -0,0 +1,357 @@
+use crate::{
+    example::{Example, ExampleBuffer, ExampleState},
+    headless::EpAppState,
+    paths::{REPOS_DIR, WORKTREES_DIR},
+    progress::{InfoStyle, Progress, Step, StepProgress},
+};
+use anyhow::{Context as _, Result};
+use collections::HashMap;
+use edit_prediction::EditPredictionStore;
+use edit_prediction::udiff::OpenedBuffers;
+use futures::{
+    AsyncWriteExt as _,
+    lock::{Mutex, OwnedMutexGuard},
+};
+use gpui::{AsyncApp, Entity};
+use language::{Anchor, Buffer, LanguageNotFound, ToOffset, ToPoint};
+use project::buffer_store::BufferStoreEvent;
+use project::{Project, ProjectPath};
+use std::{
+    cell::RefCell,
+    fs,
+    path::{Path, PathBuf},
+    sync::Arc,
+};
+use util::{paths::PathStyle, rel_path::RelPath};
+use zeta_prompt::CURSOR_MARKER;
+
+pub async fn run_load_project(
+    example: &mut Example,
+    app_state: Arc<EpAppState>,
+    mut cx: AsyncApp,
+) -> Result<()> {
+    if example.state.is_some() {
+        return Ok(());
+    }
+
+    let progress = Progress::global().start(Step::LoadProject, &example.spec.name);
+
+    let project = setup_project(example, &app_state, &progress, &mut cx).await?;
+
+    let _open_buffers = apply_edit_history(example, &project, &mut cx).await?;
+
+    let (buffer, cursor_position) = cursor_position(example, &project, &mut cx).await?;
+    let (example_buffer, language_name) = buffer.read_with(&cx, |buffer, _cx| {
+        let cursor_point = cursor_position.to_point(&buffer);
+        let language_name = buffer
+            .language()
+            .map(|l| l.name().to_string())
+            .unwrap_or_else(|| "Unknown".to_string());
+        (
+            ExampleBuffer {
+                content: buffer.text(),
+                cursor_row: cursor_point.row,
+                cursor_column: cursor_point.column,
+                cursor_offset: cursor_position.to_offset(&buffer),
+            },
+            language_name,
+        )
+    })?;
+
+    progress.set_info(language_name, InfoStyle::Normal);
+
+    example.buffer = Some(example_buffer);
+    example.state = Some(ExampleState {
+        buffer,
+        project,
+        cursor_position,
+        _open_buffers,
+    });
+    Ok(())
+}
+
+async fn cursor_position(
+    example: &Example,
+    project: &Entity<Project>,
+    cx: &mut AsyncApp,
+) -> Result<(Entity<Buffer>, Anchor)> {
+    let language_registry = project.read_with(cx, |project, _| project.languages().clone())?;
+    let result = language_registry
+        .load_language_for_file_path(&example.spec.cursor_path)
+        .await;
+
+    if let Err(error) = result
+        && !error.is::<LanguageNotFound>()
+    {
+        return Err(error);
+    }
+
+    let worktree = project.read_with(cx, |project, cx| {
+        project
+            .visible_worktrees(cx)
+            .next()
+            .context("No visible worktrees")
+    })??;
+
+    let cursor_path = RelPath::new(&example.spec.cursor_path, PathStyle::Posix)
+        .context("Failed to create RelPath")?
+        .into_arc();
+    let cursor_buffer = project
+        .update(cx, |project, cx| {
+            project.open_buffer(
+                ProjectPath {
+                    worktree_id: worktree.read(cx).id(),
+                    path: cursor_path,
+                },
+                cx,
+            )
+        })?
+        .await?;
+    let cursor_offset_within_excerpt = example
+        .spec
+        .cursor_position
+        .find(CURSOR_MARKER)
+        .context("missing cursor marker")?;
+    let mut cursor_excerpt = example.spec.cursor_position.clone();
+    cursor_excerpt.replace_range(
+        cursor_offset_within_excerpt..(cursor_offset_within_excerpt + CURSOR_MARKER.len()),
+        "",
+    );
+    let excerpt_offset = cursor_buffer.read_with(cx, |buffer, _cx| {
+        let text = buffer.text();
+
+        let mut matches = text.match_indices(&cursor_excerpt);
+        let (excerpt_offset, _) = matches.next().with_context(|| {
+            format!(
+                "\nExcerpt:\n\n{cursor_excerpt}\nBuffer text:\n{text}\n.Example: {}\nCursor excerpt did not exist in buffer.",
+                example.spec.name
+            )
+        })?;
+        anyhow::ensure!(
+            matches.next().is_none(),
+            "More than one cursor position match found for {}",
+            &example.spec.name
+        );
+        Ok(excerpt_offset)
+    })??;
+
+    let cursor_offset = excerpt_offset + cursor_offset_within_excerpt;
+    let cursor_anchor =
+        cursor_buffer.read_with(cx, |buffer, _| buffer.anchor_after(cursor_offset))?;
+
+    Ok((cursor_buffer, cursor_anchor))
+}
+
+async fn setup_project(
+    example: &mut Example,
+    app_state: &Arc<EpAppState>,
+    step_progress: &StepProgress,
+    cx: &mut AsyncApp,
+) -> Result<Entity<Project>> {
+    let ep_store = cx
+        .update(|cx| EditPredictionStore::try_global(cx))?
+        .context("Store should be initialized at init")?;
+
+    let worktree_path = setup_worktree(example, step_progress).await?;
+
+    if let Some(project) = app_state.project_cache.get(&example.spec.repository_url) {
+        ep_store.update(cx, |ep_store, _| {
+            ep_store.clear_history_for_project(&project);
+        })?;
+        let buffer_store = project.read_with(cx, |project, _| project.buffer_store().clone())?;
+        let buffers = buffer_store.read_with(cx, |buffer_store, _| {
+            buffer_store.buffers().collect::<Vec<_>>()
+        })?;
+        for buffer in buffers {
+            buffer
+                .update(cx, |buffer, cx| buffer.reload(cx))?
+                .await
+                .ok();
+        }
+        return Ok(project);
+    }
+
+    let project = cx.update(|cx| {
+        Project::local(
+            app_state.client.clone(),
+            app_state.node_runtime.clone(),
+            app_state.user_store.clone(),
+            app_state.languages.clone(),
+            app_state.fs.clone(),
+            None,
+            false,
+            cx,
+        )
+    })?;
+
+    project
+        .update(cx, |project, cx| {
+            project.disable_worktree_scanner(cx);
+            project.create_worktree(&worktree_path, true, cx)
+        })?
+        .await?;
+
+    app_state
+        .project_cache
+        .insert(example.spec.repository_url.clone(), project.clone());
+
+    let buffer_store = project.read_with(cx, |project, _| project.buffer_store().clone())?;
+    cx.subscribe(&buffer_store, {
+        let project = project.clone();
+        move |_, event, cx| match event {
+            BufferStoreEvent::BufferAdded(buffer) => {
+                ep_store.update(cx, |store, cx| store.register_buffer(&buffer, &project, cx));
+            }
+            _ => {}
+        }
+    })?
+    .detach();
+
+    Ok(project)
+}
+
+async fn setup_worktree(example: &Example, step_progress: &StepProgress) -> Result<PathBuf> {
+    let (repo_owner, repo_name) = example.repo_name().context("failed to get repo name")?;
+    let repo_dir = REPOS_DIR.join(repo_owner.as_ref()).join(repo_name.as_ref());
+    let worktree_path = WORKTREES_DIR
+        .join(repo_owner.as_ref())
+        .join(repo_name.as_ref());
+    let repo_lock = lock_repo(&repo_dir).await;
+
+    if !repo_dir.is_dir() {
+        step_progress.set_substatus(format!("cloning {}", repo_name));
+        fs::create_dir_all(&repo_dir)?;
+        run_git(&repo_dir, &["init"]).await?;
+        run_git(
+            &repo_dir,
+            &["remote", "add", "origin", &example.spec.repository_url],
+        )
+        .await?;
+    }
+
+    // Resolve the example to a revision, fetching it if needed.
+    let revision = run_git(
+        &repo_dir,
+        &[
+            "rev-parse",
+            &format!("{}^{{commit}}", example.spec.revision),
+        ],
+    )
+    .await;
+    let revision = if let Ok(revision) = revision {
+        revision
+    } else {
+        step_progress.set_substatus("fetching");
+        if run_git(
+            &repo_dir,
+            &["fetch", "--depth", "1", "origin", &example.spec.revision],
+        )
+        .await
+        .is_err()
+        {
+            run_git(&repo_dir, &["fetch", "origin"]).await?;
+        }
+        let revision = run_git(&repo_dir, &["rev-parse", "FETCH_HEAD"]).await?;
+        revision
+    };
+
+    // Create the worktree for this example if needed.
+    step_progress.set_substatus("preparing worktree");
+    if worktree_path.is_dir() {
+        run_git(&worktree_path, &["clean", "--force", "-d"]).await?;
+        run_git(&worktree_path, &["reset", "--hard", "HEAD"]).await?;
+        run_git(&worktree_path, &["checkout", revision.as_str()]).await?;
+    } else {
+        let worktree_path_string = worktree_path.to_string_lossy();
+        run_git(
+            &repo_dir,
+            &["branch", "-f", &example.spec.name, revision.as_str()],
+        )
+        .await?;
+        run_git(
+            &repo_dir,
+            &[
+                "worktree",
+                "add",
+                "-f",
+                &worktree_path_string,
+                &example.spec.name,
+            ],
+        )
+        .await?;
+    }
+    drop(repo_lock);
+
+    // Apply the uncommitted diff for this example.
+    if !example.spec.uncommitted_diff.is_empty() {
+        step_progress.set_substatus("applying diff");
+        let mut apply_process = smol::process::Command::new("git")
+            .current_dir(&worktree_path)
+            .args(&["apply", "-"])
+            .stdin(std::process::Stdio::piped())
+            .spawn()?;
+
+        let mut stdin = apply_process.stdin.take().context("Failed to get stdin")?;
+        stdin
+            .write_all(example.spec.uncommitted_diff.as_bytes())
+            .await?;
+        stdin.close().await?;
+        drop(stdin);
+
+        let apply_result = apply_process.output().await?;
+        anyhow::ensure!(
+            apply_result.status.success(),
+            "Failed to apply uncommitted diff patch with status: {}\nstderr:\n{}\nstdout:\n{}",
+            apply_result.status,
+            String::from_utf8_lossy(&apply_result.stderr),
+            String::from_utf8_lossy(&apply_result.stdout),
+        );
+    }
+
+    step_progress.clear_substatus();
+    Ok(worktree_path)
+}
+
+async fn apply_edit_history(
+    example: &Example,
+    project: &Entity<Project>,
+    cx: &mut AsyncApp,
+) -> Result<OpenedBuffers> {
+    edit_prediction::udiff::apply_diff(&example.spec.edit_history, project, cx).await
+}
+
+thread_local! {
+    static REPO_LOCKS: RefCell<HashMap<PathBuf, Arc<Mutex<()>>>> = RefCell::new(HashMap::default());
+}
+
+#[must_use]
+pub async fn lock_repo(path: impl AsRef<Path>) -> OwnedMutexGuard<()> {
+    REPO_LOCKS
+        .with(|cell| {
+            cell.borrow_mut()
+                .entry(path.as_ref().to_path_buf())
+                .or_default()
+                .clone()
+        })
+        .lock_owned()
+        .await
+}
+
+async fn run_git(repo_path: &Path, args: &[&str]) -> Result<String> {
+    let output = smol::process::Command::new("git")
+        .current_dir(repo_path)
+        .args(args)
+        .output()
+        .await?;
+
+    anyhow::ensure!(
+        output.status.success(),
+        "`git {}` within `{}` failed with status: {}\nstderr:\n{}\nstdout:\n{}",
+        args.join(" "),
+        repo_path.display(),
+        output.status,
+        String::from_utf8_lossy(&output.stderr),
+        String::from_utf8_lossy(&output.stdout),
+    );
+    Ok(String::from_utf8(output.stdout)?.trim().to_string())
+}

crates/edit_prediction_cli/src/main.rs 🔗

@@ -0,0 +1,343 @@
+mod anthropic_client;
+mod distill;
+mod example;
+mod format_prompt;
+mod headless;
+mod load_project;
+mod metrics;
+mod paths;
+mod predict;
+mod progress;
+mod retrieve_context;
+mod score;
+
+use clap::{Args, CommandFactory, Parser, Subcommand, ValueEnum};
+use edit_prediction::EditPredictionStore;
+use gpui::Application;
+use reqwest_client::ReqwestClient;
+use serde::{Deserialize, Serialize};
+use std::fmt::Display;
+use std::{path::PathBuf, sync::Arc};
+
+use crate::distill::run_distill;
+use crate::example::{group_examples_by_repo, read_examples, write_examples};
+use crate::format_prompt::run_format_prompt;
+use crate::load_project::run_load_project;
+use crate::paths::FAILED_EXAMPLES_DIR;
+use crate::predict::run_prediction;
+use crate::progress::Progress;
+use crate::retrieve_context::run_context_retrieval;
+use crate::score::run_scoring;
+
+#[derive(Parser, Debug)]
+#[command(name = "ep")]
+struct EpArgs {
+    #[arg(long, default_value_t = false)]
+    printenv: bool,
+    #[clap(long, default_value_t = 10, global = true)]
+    max_parallelism: usize,
+    #[command(subcommand)]
+    command: Option<Command>,
+    #[clap(global = true)]
+    inputs: Vec<PathBuf>,
+    #[arg(long, short, global = true)]
+    output: Option<PathBuf>,
+    #[arg(long, short, global = true)]
+    in_place: bool,
+    #[arg(long, short, global = true)]
+    failfast: bool,
+}
+
+#[derive(Subcommand, Debug)]
+enum Command {
+    /// Parse markdown examples and output a combined .jsonl file
+    ParseExample,
+    /// Create git worktrees for each example and load file contents
+    LoadProject,
+    /// Retrieve context for input examples.
+    Context,
+    /// Generate a prompt string for a specific model
+    FormatPrompt(FormatPromptArgs),
+    /// Runs edit prediction
+    Predict(PredictArgs),
+    /// Computes a score based on actual and expected patches
+    Score(PredictArgs),
+    /// Prepares a distillation dataset by copying expected outputs to
+    /// predicted outputs and removing actual outputs and prompts.
+    Distill,
+    /// Print aggregated scores
+    Eval(PredictArgs),
+    /// Remove git repositories and worktrees
+    Clean,
+}
+
+impl Display for Command {
+    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+        match self {
+            Command::ParseExample => write!(f, "parse-example"),
+            Command::LoadProject => write!(f, "load-project"),
+            Command::Context => write!(f, "context"),
+            Command::FormatPrompt(format_prompt_args) => write!(
+                f,
+                "format-prompt --prompt-format={}",
+                format_prompt_args
+                    .prompt_format
+                    .to_possible_value()
+                    .unwrap()
+                    .get_name()
+            ),
+            Command::Predict(predict_args) => {
+                write!(
+                    f,
+                    "predict --provider={:?}",
+                    predict_args
+                        .provider
+                        .to_possible_value()
+                        .unwrap()
+                        .get_name()
+                )
+            }
+            Command::Score(predict_args) => {
+                write!(
+                    f,
+                    "score --provider={:?}",
+                    predict_args
+                        .provider
+                        .to_possible_value()
+                        .unwrap()
+                        .get_name()
+                )
+            }
+            Command::Distill => write!(f, "distill"),
+            Command::Eval(predict_args) => write!(
+                f,
+                "eval --provider={:?}",
+                predict_args
+                    .provider
+                    .to_possible_value()
+                    .unwrap()
+                    .get_name()
+            ),
+            Command::Clean => write!(f, "clean"),
+        }
+    }
+}
+
+#[derive(Debug, Args)]
+struct FormatPromptArgs {
+    #[clap(long)]
+    prompt_format: PromptFormat,
+}
+
+#[derive(Clone, Copy, Debug, ValueEnum, Serialize, Deserialize)]
+enum PromptFormat {
+    Teacher,
+    Zeta2,
+}
+
+#[derive(Debug, Args)]
+struct PredictArgs {
+    #[clap(long)]
+    provider: PredictionProvider,
+    #[clap(long, default_value_t = 1)]
+    repetitions: usize,
+}
+
+#[derive(Clone, Copy, Debug, ValueEnum, Serialize, Deserialize)]
+enum PredictionProvider {
+    Sweep,
+    Mercury,
+    Zeta1,
+    Zeta2,
+    Teacher,
+    TeacherNonBatching,
+}
+
+impl EpArgs {
+    fn output_path(&self) -> Option<PathBuf> {
+        if self.in_place {
+            if self.inputs.len() == 1 {
+                self.inputs.first().cloned()
+            } else {
+                panic!("--in-place requires exactly one input file")
+            }
+        } else {
+            self.output.clone()
+        }
+    }
+}
+
+fn main() {
+    let args = EpArgs::parse();
+
+    if args.printenv {
+        ::util::shell_env::print_env();
+        return;
+    }
+
+    let output = args.output_path();
+    let command = match args.command {
+        Some(cmd) => cmd,
+        None => {
+            EpArgs::command().print_help().unwrap();
+            return;
+        }
+    };
+
+    match &command {
+        Command::Clean => {
+            std::fs::remove_dir_all(&*paths::DATA_DIR).unwrap();
+            return;
+        }
+        _ => {}
+    }
+
+    let mut examples = read_examples(&args.inputs);
+    let http_client = Arc::new(ReqwestClient::new());
+    let app = Application::headless().with_http_client(http_client);
+
+    app.run(move |cx| {
+        let app_state = Arc::new(headless::init(cx));
+        EditPredictionStore::global(&app_state.client, &app_state.user_store, cx);
+
+        cx.spawn(async move |cx| {
+            let result = async {
+                if let Command::Predict(args) = &command {
+                    predict::sync_batches(&args.provider).await?;
+                }
+
+                let total_examples = examples.len();
+                Progress::global().set_total_examples(total_examples);
+
+                let mut grouped_examples = group_examples_by_repo(&mut examples);
+                let example_batches = grouped_examples.chunks_mut(args.max_parallelism);
+
+                for example_batch in example_batches {
+                    let futures = example_batch.into_iter().map(|repo_examples| async {
+                        for example in repo_examples.iter_mut() {
+                            let result = async {
+                                match &command {
+                                    Command::ParseExample => {}
+                                    Command::LoadProject => {
+                                        run_load_project(example, app_state.clone(), cx.clone())
+                                            .await?;
+                                    }
+                                    Command::Context => {
+                                        run_context_retrieval(
+                                            example,
+                                            app_state.clone(),
+                                            cx.clone(),
+                                        )
+                                        .await?;
+                                    }
+                                    Command::FormatPrompt(args) => {
+                                        run_format_prompt(
+                                            example,
+                                            args.prompt_format,
+                                            app_state.clone(),
+                                            cx.clone(),
+                                        )
+                                        .await?;
+                                    }
+                                    Command::Predict(args) => {
+                                        run_prediction(
+                                            example,
+                                            Some(args.provider),
+                                            args.repetitions,
+                                            app_state.clone(),
+                                            cx.clone(),
+                                        )
+                                        .await?;
+                                    }
+                                    Command::Distill => {
+                                        run_distill(example).await?;
+                                    }
+                                    Command::Score(args) | Command::Eval(args) => {
+                                        run_scoring(example, &args, app_state.clone(), cx.clone())
+                                            .await?;
+                                    }
+                                    Command::Clean => {
+                                        unreachable!()
+                                    }
+                                }
+                                anyhow::Ok(())
+                            }
+                            .await;
+
+                            if let Err(e) = result {
+                                Progress::global().increment_failed();
+                                let failed_example_path =
+                                    FAILED_EXAMPLES_DIR.join(format!("{}.json", example.spec.name));
+                                app_state
+                                    .fs
+                                    .write(
+                                        &failed_example_path,
+                                        &serde_json::to_vec_pretty(&example).unwrap(),
+                                    )
+                                    .await
+                                    .unwrap();
+                                let err_path = FAILED_EXAMPLES_DIR
+                                    .join(format!("{}_err.txt", example.spec.name));
+                                app_state
+                                    .fs
+                                    .write(&err_path, e.to_string().as_bytes())
+                                    .await
+                                    .unwrap();
+
+                                let msg = format!(
+                                    indoc::indoc! {"
+                                        While processing {}:
+
+                                        {:?}
+
+                                        Written to: \x1b[36m{}\x1b[0m
+
+                                        Explore this example data with:
+                                            fx \x1b[36m{}\x1b[0m
+
+                                        Re-run this example with:
+                                            cargo run -p edit_prediction_cli -- {} \x1b[36m{}\x1b[0m
+                                    "},
+                                    example.spec.name,
+                                    e,
+                                    err_path.display(),
+                                    failed_example_path.display(),
+                                    command,
+                                    failed_example_path.display(),
+                                );
+                                if args.failfast || total_examples == 1 {
+                                    Progress::global().finalize();
+                                    panic!("{}", msg);
+                                } else {
+                                    log::error!("{}", msg);
+                                }
+                            }
+                        }
+                    });
+                    futures::future::join_all(futures).await;
+                }
+                Progress::global().finalize();
+
+                if args.output.is_some() || !matches!(command, Command::Eval(_)) {
+                    write_examples(&examples, output.as_ref());
+                }
+
+                match &command {
+                    Command::Predict(args) => predict::sync_batches(&args.provider).await?,
+                    Command::Eval(_) => score::print_report(&examples),
+                    _ => (),
+                };
+
+                anyhow::Ok(())
+            }
+            .await;
+
+            if let Err(e) = result {
+                panic!("Fatal error: {:?}", e);
+            }
+
+            let _ = cx.update(|cx| cx.quit());
+        })
+        .detach();
+    });
+}

crates/zeta_cli/src/metrics.rs → crates/edit_prediction_cli/src/metrics.rs 🔗

@@ -1,30 +1,34 @@
 use collections::{HashMap, HashSet};
-use zeta::udiff::DiffLine;
+use edit_prediction::udiff::DiffLine;
+use serde::{Deserialize, Serialize};
 
 type Counts = HashMap<String, usize>;
 type CountsDelta = HashMap<String, isize>;
 
-#[derive(Default, Debug, Clone)]
-pub struct Scores {
+#[derive(Default, Debug, Clone, Serialize, Deserialize)]
+pub struct ClassificationMetrics {
     pub true_positives: usize,
     pub false_positives: usize,
     pub false_negatives: usize,
 }
 
-impl Scores {
-    pub fn from_sets(expected: &HashSet<String>, actual: &HashSet<String>) -> Scores {
+impl ClassificationMetrics {
+    pub fn from_sets(
+        expected: &HashSet<String>,
+        actual: &HashSet<String>,
+    ) -> ClassificationMetrics {
         let true_positives = expected.intersection(actual).count();
         let false_positives = actual.difference(expected).count();
         let false_negatives = expected.difference(actual).count();
 
-        Scores {
+        ClassificationMetrics {
             true_positives,
             false_positives,
             false_negatives,
         }
     }
 
-    pub fn from_counts(expected: &Counts, actual: &Counts) -> Scores {
+    pub fn from_counts(expected: &Counts, actual: &Counts) -> ClassificationMetrics {
         let mut true_positives = 0;
         let mut false_positives = 0;
         let mut false_negatives = 0;
@@ -45,32 +49,16 @@ impl Scores {
             }
         }
 
-        Scores {
+        ClassificationMetrics {
             true_positives,
             false_positives,
             false_negatives,
         }
     }
 
-    pub fn to_markdown(&self) -> String {
-        format!(
-            "
-Precision       : {:.4}
-Recall          : {:.4}
-F1 Score        : {:.4}
-True Positives  : {}
-False Positives : {}
-False Negatives : {}",
-            self.precision(),
-            self.recall(),
-            self.f1_score(),
-            self.true_positives,
-            self.false_positives,
-            self.false_negatives
-        )
-    }
-
-    pub fn aggregate<'a>(scores: impl Iterator<Item = &'a Scores>) -> Scores {
+    pub fn aggregate<'a>(
+        scores: impl Iterator<Item = &'a ClassificationMetrics>,
+    ) -> ClassificationMetrics {
         let mut true_positives = 0;
         let mut false_positives = 0;
         let mut false_negatives = 0;
@@ -81,7 +69,7 @@ False Negatives : {}",
             false_negatives += score.false_negatives;
         }
 
-        Scores {
+        ClassificationMetrics {
             true_positives,
             false_positives,
             false_negatives,
@@ -115,7 +103,10 @@ False Negatives : {}",
     }
 }
 
-pub fn line_match_score(expected_patch: &[DiffLine], actual_patch: &[DiffLine]) -> Scores {
+pub fn line_match_score(
+    expected_patch: &[DiffLine],
+    actual_patch: &[DiffLine],
+) -> ClassificationMetrics {
     let expected_change_lines = expected_patch
         .iter()
         .filter(|line| matches!(line, DiffLine::Addition(_) | DiffLine::Deletion(_)))
@@ -128,7 +119,7 @@ pub fn line_match_score(expected_patch: &[DiffLine], actual_patch: &[DiffLine])
         .map(|line| line.to_string())
         .collect();
 
-    Scores::from_sets(&expected_change_lines, &actual_change_lines)
+    ClassificationMetrics::from_sets(&expected_change_lines, &actual_change_lines)
 }
 
 enum ChrfWhitespace {
@@ -204,7 +195,7 @@ pub fn delta_chr_f(expected: &[DiffLine], actual: &[DiffLine]) -> f64 {
         let expected_counts = ngram_delta_to_counts(&expected_delta);
         let actual_counts = ngram_delta_to_counts(&actual_delta);
 
-        let score = Scores::from_counts(&expected_counts, &actual_counts);
+        let score = ClassificationMetrics::from_counts(&expected_counts, &actual_counts);
         total_precision += score.precision();
         total_recall += score.recall();
     }
@@ -287,7 +278,7 @@ fn count_ngrams(text: &str, n: usize) -> Counts {
 #[cfg(test)]
 mod test {
     use super::*;
-    use zeta::udiff::DiffLine;
+    use edit_prediction::udiff::DiffLine;
 
     #[test]
     fn test_delta_chr_f_perfect_match() {

crates/edit_prediction_cli/src/paths.rs 🔗

@@ -0,0 +1,27 @@
+use std::{
+    path::{Path, PathBuf},
+    sync::LazyLock,
+};
+
+pub static DATA_DIR: LazyLock<PathBuf> = LazyLock::new(|| {
+    let dir = dirs::home_dir().unwrap().join(".zed_ep");
+    ensure_dir(&dir)
+});
+pub static CACHE_DIR: LazyLock<PathBuf> = LazyLock::new(|| ensure_dir(&DATA_DIR.join("cache")));
+pub static REPOS_DIR: LazyLock<PathBuf> = LazyLock::new(|| ensure_dir(&DATA_DIR.join("repos")));
+pub static WORKTREES_DIR: LazyLock<PathBuf> =
+    LazyLock::new(|| ensure_dir(&DATA_DIR.join("worktrees")));
+pub static RUN_DIR: LazyLock<PathBuf> = LazyLock::new(|| {
+    DATA_DIR
+        .join("runs")
+        .join(chrono::Local::now().format("%d-%m-%y-%H_%M_%S").to_string())
+});
+pub static LATEST_EXAMPLE_RUN_DIR: LazyLock<PathBuf> = LazyLock::new(|| DATA_DIR.join("latest"));
+pub static LLM_CACHE_DB: LazyLock<PathBuf> = LazyLock::new(|| CACHE_DIR.join("llm_cache.sqlite"));
+pub static FAILED_EXAMPLES_DIR: LazyLock<PathBuf> =
+    LazyLock::new(|| ensure_dir(&RUN_DIR.join("failed")));
+
+fn ensure_dir(path: &Path) -> PathBuf {
+    std::fs::create_dir_all(path).expect("Failed to create directory");
+    path.to_path_buf()
+}

crates/edit_prediction_cli/src/predict.rs 🔗

@@ -0,0 +1,291 @@
+use crate::{
+    PredictionProvider, PromptFormat,
+    anthropic_client::AnthropicClient,
+    example::{Example, ExamplePrediction},
+    format_prompt::{TeacherPrompt, run_format_prompt},
+    headless::EpAppState,
+    load_project::run_load_project,
+    paths::{LATEST_EXAMPLE_RUN_DIR, RUN_DIR},
+    progress::{InfoStyle, Progress, Step},
+    retrieve_context::run_context_retrieval,
+};
+use anyhow::Context as _;
+use edit_prediction::{DebugEvent, EditPredictionStore};
+use futures::{FutureExt as _, StreamExt as _, future::Shared};
+use gpui::{AppContext as _, AsyncApp, Task};
+use std::{
+    fs,
+    sync::{
+        Arc, Mutex, OnceLock,
+        atomic::{AtomicUsize, Ordering::SeqCst},
+    },
+};
+
+pub async fn run_prediction(
+    example: &mut Example,
+    provider: Option<PredictionProvider>,
+    repetition_count: usize,
+    app_state: Arc<EpAppState>,
+    mut cx: AsyncApp,
+) -> anyhow::Result<()> {
+    if !example.predictions.is_empty() {
+        return Ok(());
+    }
+
+    let provider = provider.context("provider is required")?;
+
+    run_context_retrieval(example, app_state.clone(), cx.clone()).await?;
+
+    if matches!(
+        provider,
+        PredictionProvider::Teacher | PredictionProvider::TeacherNonBatching
+    ) {
+        let _step_progress = Progress::global().start(Step::Predict, &example.spec.name);
+
+        if example.prompt.is_none() {
+            run_format_prompt(example, PromptFormat::Teacher, app_state.clone(), cx).await?;
+        }
+
+        let batched = matches!(provider, PredictionProvider::Teacher);
+        return predict_anthropic(example, repetition_count, batched).await;
+    }
+
+    run_load_project(example, app_state.clone(), cx.clone()).await?;
+
+    let _step_progress = Progress::global().start(Step::Predict, &example.spec.name);
+
+    if matches!(
+        provider,
+        PredictionProvider::Zeta1 | PredictionProvider::Zeta2
+    ) {
+        static AUTHENTICATED: OnceLock<Shared<Task<()>>> = OnceLock::new();
+        AUTHENTICATED
+            .get_or_init(|| {
+                let client = app_state.client.clone();
+                cx.spawn(async move |cx| {
+                    if let Err(e) = client.sign_in_with_optional_connect(true, cx).await {
+                        eprintln!("Authentication failed: {}", e);
+                    }
+                })
+                .shared()
+            })
+            .clone()
+            .await;
+    }
+
+    let ep_store = cx.update(|cx| {
+        EditPredictionStore::try_global(cx).context("EditPredictionStore not initialized")
+    })??;
+
+    ep_store.update(&mut cx, |store, _cx| {
+        let model = match provider {
+            PredictionProvider::Zeta1 => edit_prediction::EditPredictionModel::Zeta1,
+            PredictionProvider::Zeta2 => edit_prediction::EditPredictionModel::Zeta2,
+            PredictionProvider::Sweep => edit_prediction::EditPredictionModel::Sweep,
+            PredictionProvider::Mercury => edit_prediction::EditPredictionModel::Mercury,
+            PredictionProvider::Teacher | PredictionProvider::TeacherNonBatching => {
+                unreachable!()
+            }
+        };
+        store.set_edit_prediction_model(model);
+    })?;
+    let state = example.state.as_ref().context("state must be set")?;
+    let run_dir = RUN_DIR.join(&example.spec.name);
+
+    let updated_example = Arc::new(Mutex::new(example.clone()));
+    let current_run_ix = Arc::new(AtomicUsize::new(0));
+
+    let mut debug_rx =
+        ep_store.update(&mut cx, |store, cx| store.debug_info(&state.project, cx))?;
+    let debug_task = cx.background_spawn({
+        let updated_example = updated_example.clone();
+        let current_run_ix = current_run_ix.clone();
+        let run_dir = run_dir.clone();
+        async move {
+            while let Some(event) = debug_rx.next().await {
+                let run_ix = current_run_ix.load(SeqCst);
+                let mut updated_example = updated_example.lock().unwrap();
+
+                let run_dir = if repetition_count > 1 {
+                    run_dir.join(format!("{:03}", run_ix))
+                } else {
+                    run_dir.clone()
+                };
+
+                match event {
+                    DebugEvent::EditPredictionStarted(request) => {
+                        assert_eq!(updated_example.predictions.len(), run_ix + 1);
+
+                        if let Some(prompt) = request.prompt {
+                            fs::write(run_dir.join("prediction_prompt.md"), &prompt)?;
+                        }
+                    }
+                    DebugEvent::EditPredictionFinished(request) => {
+                        assert_eq!(updated_example.predictions.len(), run_ix + 1);
+
+                        if let Some(output) = request.model_output {
+                            fs::write(run_dir.join("prediction_response.md"), &output)?;
+                            updated_example
+                                .predictions
+                                .last_mut()
+                                .unwrap()
+                                .actual_output = output;
+                        }
+                        if run_ix >= repetition_count {
+                            break;
+                        }
+                    }
+                    _ => {}
+                }
+            }
+            anyhow::Ok(())
+        }
+    });
+
+    for ix in 0..repetition_count {
+        current_run_ix.store(ix, SeqCst);
+        let run_dir = if repetition_count > 1 {
+            run_dir.join(format!("{:03}", ix))
+        } else {
+            run_dir.clone()
+        };
+
+        fs::create_dir_all(&run_dir)?;
+        if LATEST_EXAMPLE_RUN_DIR.is_symlink() {
+            fs::remove_file(&*LATEST_EXAMPLE_RUN_DIR)?;
+        }
+        #[cfg(unix)]
+        std::os::unix::fs::symlink(&run_dir, &*LATEST_EXAMPLE_RUN_DIR)?;
+        #[cfg(windows)]
+        std::os::windows::fs::symlink_dir(&run_dir, &*LATEST_EXAMPLE_RUN_DIR)?;
+
+        updated_example
+            .lock()
+            .unwrap()
+            .predictions
+            .push(ExamplePrediction {
+                actual_patch: String::new(),
+                actual_output: String::new(),
+                provider,
+            });
+
+        let prediction = ep_store
+            .update(&mut cx, |store, cx| {
+                store.request_prediction(
+                    &state.project,
+                    &state.buffer,
+                    state.cursor_position,
+                    cloud_llm_client::PredictEditsRequestTrigger::Cli,
+                    cx,
+                )
+            })?
+            .await?;
+
+        let actual_patch = prediction
+            .and_then(|prediction| {
+                let prediction = prediction.prediction.ok()?;
+                prediction.edit_preview.as_unified_diff(&prediction.edits)
+            })
+            .unwrap_or_default();
+
+        let has_prediction = !actual_patch.is_empty();
+
+        updated_example
+            .lock()
+            .unwrap()
+            .predictions
+            .last_mut()
+            .unwrap()
+            .actual_patch = actual_patch;
+
+        if ix == repetition_count - 1 {
+            let (info, style) = if has_prediction {
+                ("predicted", InfoStyle::Normal)
+            } else {
+                ("no prediction", InfoStyle::Warning)
+            };
+            _step_progress.set_info(info, style);
+        }
+    }
+
+    ep_store.update(&mut cx, |store, _| {
+        store.remove_project(&state.project);
+    })?;
+    debug_task.await?;
+
+    *example = Arc::into_inner(updated_example)
+        .ok_or_else(|| anyhow::anyhow!("Failed to unwrap Arc"))?
+        .into_inner()
+        .map_err(|_| anyhow::anyhow!("Failed to unwrap Mutex"))?;
+    Ok(())
+}
+
+async fn predict_anthropic(
+    example: &mut Example,
+    _repetition_count: usize,
+    batched: bool,
+) -> anyhow::Result<()> {
+    let llm_model_name = "claude-sonnet-4-5";
+    let max_tokens = 16384;
+    let llm_client = if batched {
+        AnthropicClient::batch(&crate::paths::LLM_CACHE_DB.as_ref())
+    } else {
+        AnthropicClient::plain()
+    };
+    let llm_client = llm_client.context("Failed to create LLM client")?;
+
+    let prompt = example.prompt.as_ref().context("Prompt is required")?;
+
+    let messages = vec![anthropic::Message {
+        role: anthropic::Role::User,
+        content: vec![anthropic::RequestContent::Text {
+            text: prompt.input.clone(),
+            cache_control: None,
+        }],
+    }];
+
+    let Some(response) = llm_client
+        .generate(llm_model_name, max_tokens, messages)
+        .await?
+    else {
+        // Request stashed for batched processing
+        return Ok(());
+    };
+
+    let actual_output = response
+        .content
+        .into_iter()
+        .filter_map(|content| match content {
+            anthropic::ResponseContent::Text { text } => Some(text),
+            _ => None,
+        })
+        .collect::<Vec<String>>()
+        .join("\n");
+
+    let actual_patch = TeacherPrompt::parse(example, &actual_output)?;
+
+    let prediction = ExamplePrediction {
+        actual_patch,
+        actual_output,
+        provider: PredictionProvider::Teacher,
+    };
+
+    example.predictions.push(prediction);
+    Ok(())
+}
+
+pub async fn sync_batches(provider: &PredictionProvider) -> anyhow::Result<()> {
+    match provider {
+        PredictionProvider::Teacher => {
+            let cache_path = crate::paths::LLM_CACHE_DB.as_ref();
+            let llm_client =
+                AnthropicClient::batch(cache_path).context("Failed to create LLM client")?;
+            llm_client
+                .sync_batches()
+                .await
+                .context("Failed to sync batches")?;
+        }
+        _ => (),
+    };
+    Ok(())
+}

crates/edit_prediction_cli/src/progress.rs 🔗

@@ -0,0 +1,508 @@
+use std::{
+    borrow::Cow,
+    collections::HashMap,
+    io::{IsTerminal, Write},
+    sync::{Arc, Mutex, OnceLock},
+    time::{Duration, Instant},
+};
+
+use log::{Level, Log, Metadata, Record};
+
+pub struct Progress {
+    inner: Mutex<ProgressInner>,
+}
+
+struct ProgressInner {
+    completed: Vec<CompletedTask>,
+    in_progress: HashMap<String, InProgressTask>,
+    is_tty: bool,
+    terminal_width: usize,
+    max_example_name_len: usize,
+    status_lines_displayed: usize,
+    total_examples: usize,
+    failed_examples: usize,
+    last_line_is_logging: bool,
+}
+
+#[derive(Clone)]
+struct InProgressTask {
+    step: Step,
+    started_at: Instant,
+    substatus: Option<String>,
+    info: Option<(String, InfoStyle)>,
+}
+
+struct CompletedTask {
+    step: Step,
+    example_name: String,
+    duration: Duration,
+    info: Option<(String, InfoStyle)>,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
+pub enum Step {
+    LoadProject,
+    Context,
+    FormatPrompt,
+    Predict,
+    Score,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum InfoStyle {
+    Normal,
+    Warning,
+}
+
+impl Step {
+    pub fn label(&self) -> &'static str {
+        match self {
+            Step::LoadProject => "Load",
+            Step::Context => "Context",
+            Step::FormatPrompt => "Format",
+            Step::Predict => "Predict",
+            Step::Score => "Score",
+        }
+    }
+
+    fn color_code(&self) -> &'static str {
+        match self {
+            Step::LoadProject => "\x1b[33m",
+            Step::Context => "\x1b[35m",
+            Step::FormatPrompt => "\x1b[34m",
+            Step::Predict => "\x1b[32m",
+            Step::Score => "\x1b[31m",
+        }
+    }
+}
+
+static GLOBAL: OnceLock<Arc<Progress>> = OnceLock::new();
+static LOGGER: ProgressLogger = ProgressLogger;
+
+const MARGIN: usize = 4;
+const MAX_STATUS_LINES: usize = 10;
+
+impl Progress {
+    /// Returns the global Progress instance, initializing it if necessary.
+    pub fn global() -> Arc<Progress> {
+        GLOBAL
+            .get_or_init(|| {
+                let progress = Arc::new(Self {
+                    inner: Mutex::new(ProgressInner {
+                        completed: Vec::new(),
+                        in_progress: HashMap::new(),
+                        is_tty: std::io::stderr().is_terminal(),
+                        terminal_width: get_terminal_width(),
+                        max_example_name_len: 0,
+                        status_lines_displayed: 0,
+                        total_examples: 0,
+                        failed_examples: 0,
+                        last_line_is_logging: false,
+                    }),
+                });
+                let _ = log::set_logger(&LOGGER);
+                log::set_max_level(log::LevelFilter::Error);
+                progress
+            })
+            .clone()
+    }
+
+    pub fn set_total_examples(&self, total: usize) {
+        let mut inner = self.inner.lock().unwrap();
+        inner.total_examples = total;
+    }
+
+    pub fn increment_failed(&self) {
+        let mut inner = self.inner.lock().unwrap();
+        inner.failed_examples += 1;
+    }
+
+    /// Prints a message to stderr, clearing and redrawing status lines to avoid corruption.
+    /// This should be used for any output that needs to appear above the status lines.
+    fn log(&self, message: &str) {
+        let mut inner = self.inner.lock().unwrap();
+        Self::clear_status_lines(&mut inner);
+
+        if !inner.last_line_is_logging {
+            let reset = "\x1b[0m";
+            let dim = "\x1b[2m";
+            let divider = "─".repeat(inner.terminal_width.saturating_sub(MARGIN));
+            eprintln!("{dim}{divider}{reset}");
+            inner.last_line_is_logging = true;
+        }
+
+        eprintln!("{}", message);
+    }
+
+    pub fn start(self: &Arc<Self>, step: Step, example_name: &str) -> StepProgress {
+        let mut inner = self.inner.lock().unwrap();
+
+        Self::clear_status_lines(&mut inner);
+
+        inner.max_example_name_len = inner.max_example_name_len.max(example_name.len());
+        inner.in_progress.insert(
+            example_name.to_string(),
+            InProgressTask {
+                step,
+                started_at: Instant::now(),
+                substatus: None,
+                info: None,
+            },
+        );
+
+        Self::print_status_lines(&mut inner);
+
+        StepProgress {
+            progress: self.clone(),
+            step,
+            example_name: example_name.to_string(),
+        }
+    }
+
+    fn finish(&self, step: Step, example_name: &str) {
+        let mut inner = self.inner.lock().unwrap();
+
+        let Some(task) = inner.in_progress.remove(example_name) else {
+            return;
+        };
+
+        if task.step == step {
+            inner.completed.push(CompletedTask {
+                step: task.step,
+                example_name: example_name.to_string(),
+                duration: task.started_at.elapsed(),
+                info: task.info,
+            });
+
+            Self::clear_status_lines(&mut inner);
+            Self::print_logging_closing_divider(&mut inner);
+            Self::print_completed(&inner, inner.completed.last().unwrap());
+            Self::print_status_lines(&mut inner);
+        } else {
+            inner.in_progress.insert(example_name.to_string(), task);
+        }
+    }
+
+    fn print_logging_closing_divider(inner: &mut ProgressInner) {
+        if inner.last_line_is_logging {
+            let reset = "\x1b[0m";
+            let dim = "\x1b[2m";
+            let divider = "─".repeat(inner.terminal_width.saturating_sub(MARGIN));
+            eprintln!("{dim}{divider}{reset}");
+            inner.last_line_is_logging = false;
+        }
+    }
+
+    fn clear_status_lines(inner: &mut ProgressInner) {
+        if inner.is_tty && inner.status_lines_displayed > 0 {
+            // Move up and clear each line we previously displayed
+            for _ in 0..inner.status_lines_displayed {
+                eprint!("\x1b[A\x1b[K");
+            }
+            let _ = std::io::stderr().flush();
+            inner.status_lines_displayed = 0;
+        }
+    }
+
+    fn print_completed(inner: &ProgressInner, task: &CompletedTask) {
+        let duration = format_duration(task.duration);
+        let name_width = inner.max_example_name_len;
+
+        if inner.is_tty {
+            let reset = "\x1b[0m";
+            let bold = "\x1b[1m";
+            let dim = "\x1b[2m";
+
+            let yellow = "\x1b[33m";
+            let info_part = task
+                .info
+                .as_ref()
+                .map(|(s, style)| {
+                    if *style == InfoStyle::Warning {
+                        format!("{yellow}{s}{reset}")
+                    } else {
+                        s.to_string()
+                    }
+                })
+                .unwrap_or_default();
+
+            let prefix = format!(
+                "{bold}{color}{label:>12}{reset} {name:<name_width$} {dim}│{reset} {info_part}",
+                color = task.step.color_code(),
+                label = task.step.label(),
+                name = task.example_name,
+            );
+
+            let duration_with_margin = format!("{duration} ");
+            let padding_needed = inner
+                .terminal_width
+                .saturating_sub(MARGIN)
+                .saturating_sub(duration_with_margin.len())
+                .saturating_sub(strip_ansi_len(&prefix));
+            let padding = " ".repeat(padding_needed);
+
+            eprintln!("{prefix}{padding}{dim}{duration_with_margin}{reset}");
+        } else {
+            let info_part = task
+                .info
+                .as_ref()
+                .map(|(s, _)| format!(" | {}", s))
+                .unwrap_or_default();
+
+            eprintln!(
+                "{label:>12} {name:<name_width$}{info_part} {duration}",
+                label = task.step.label(),
+                name = task.example_name,
+            );
+        }
+    }
+
+    fn print_status_lines(inner: &mut ProgressInner) {
+        if !inner.is_tty || inner.in_progress.is_empty() {
+            inner.status_lines_displayed = 0;
+            return;
+        }
+
+        let reset = "\x1b[0m";
+        let bold = "\x1b[1m";
+        let dim = "\x1b[2m";
+
+        // Build the done/in-progress/total label
+        let done_count = inner.completed.len();
+        let in_progress_count = inner.in_progress.len();
+        let failed_count = inner.failed_examples;
+
+        let failed_label = if failed_count > 0 {
+            format!(" {} failed ", failed_count)
+        } else {
+            String::new()
+        };
+
+        let range_label = format!(
+            " {}/{}/{} ",
+            done_count, in_progress_count, inner.total_examples
+        );
+
+        // Print a divider line with failed count on left, range label on right
+        let failed_visible_len = strip_ansi_len(&failed_label);
+        let range_visible_len = range_label.len();
+        let middle_divider_len = inner
+            .terminal_width
+            .saturating_sub(MARGIN * 2)
+            .saturating_sub(failed_visible_len)
+            .saturating_sub(range_visible_len);
+        let left_divider = "─".repeat(MARGIN);
+        let middle_divider = "─".repeat(middle_divider_len);
+        let right_divider = "─".repeat(MARGIN);
+        eprintln!(
+            "{dim}{left_divider}{reset}{failed_label}{dim}{middle_divider}{reset}{range_label}{dim}{right_divider}{reset}"
+        );
+
+        let mut tasks: Vec<_> = inner.in_progress.iter().collect();
+        tasks.sort_by_key(|(name, _)| *name);
+
+        let total_tasks = tasks.len();
+        let mut lines_printed = 0;
+
+        for (name, task) in tasks.iter().take(MAX_STATUS_LINES) {
+            let elapsed = format_duration(task.started_at.elapsed());
+            let substatus_part = task
+                .substatus
+                .as_ref()
+                .map(|s| truncate_with_ellipsis(s, 30))
+                .unwrap_or_default();
+
+            let step_label = task.step.label();
+            let step_color = task.step.color_code();
+            let name_width = inner.max_example_name_len;
+
+            let prefix = format!(
+                "{bold}{step_color}{step_label:>12}{reset} {name:<name_width$} {dim}│{reset} {substatus_part}",
+                name = name,
+            );
+
+            let duration_with_margin = format!("{elapsed} ");
+            let padding_needed = inner
+                .terminal_width
+                .saturating_sub(MARGIN)
+                .saturating_sub(duration_with_margin.len())
+                .saturating_sub(strip_ansi_len(&prefix));
+            let padding = " ".repeat(padding_needed);
+
+            eprintln!("{prefix}{padding}{dim}{duration_with_margin}{reset}");
+            lines_printed += 1;
+        }
+
+        // Show "+N more" on its own line if there are more tasks
+        if total_tasks > MAX_STATUS_LINES {
+            let remaining = total_tasks - MAX_STATUS_LINES;
+            eprintln!("{:>12} +{remaining} more", "");
+            lines_printed += 1;
+        }
+
+        inner.status_lines_displayed = lines_printed + 1; // +1 for the divider line
+        let _ = std::io::stderr().flush();
+    }
+
+    pub fn finalize(&self) {
+        let mut inner = self.inner.lock().unwrap();
+        Self::clear_status_lines(&mut inner);
+
+        // Print summary if there were failures
+        if inner.failed_examples > 0 {
+            let total_processed = inner.completed.len() + inner.failed_examples;
+            let percentage = if total_processed > 0 {
+                inner.failed_examples as f64 / total_processed as f64 * 100.0
+            } else {
+                0.0
+            };
+            eprintln!(
+                "\n{} of {} examples failed ({:.1}%)",
+                inner.failed_examples, total_processed, percentage
+            );
+        }
+    }
+}
+
+pub struct StepProgress {
+    progress: Arc<Progress>,
+    step: Step,
+    example_name: String,
+}
+
+impl StepProgress {
+    pub fn set_substatus(&self, substatus: impl Into<Cow<'static, str>>) {
+        let mut inner = self.progress.inner.lock().unwrap();
+        if let Some(task) = inner.in_progress.get_mut(&self.example_name) {
+            task.substatus = Some(substatus.into().into_owned());
+            Progress::clear_status_lines(&mut inner);
+            Progress::print_status_lines(&mut inner);
+        }
+    }
+
+    pub fn clear_substatus(&self) {
+        let mut inner = self.progress.inner.lock().unwrap();
+        if let Some(task) = inner.in_progress.get_mut(&self.example_name) {
+            task.substatus = None;
+            Progress::clear_status_lines(&mut inner);
+            Progress::print_status_lines(&mut inner);
+        }
+    }
+
+    pub fn set_info(&self, info: impl Into<String>, style: InfoStyle) {
+        let mut inner = self.progress.inner.lock().unwrap();
+        if let Some(task) = inner.in_progress.get_mut(&self.example_name) {
+            task.info = Some((info.into(), style));
+        }
+    }
+}
+
+impl Drop for StepProgress {
+    fn drop(&mut self) {
+        self.progress.finish(self.step, &self.example_name);
+    }
+}
+
+struct ProgressLogger;
+
+impl Log for ProgressLogger {
+    fn enabled(&self, metadata: &Metadata) -> bool {
+        metadata.level() <= Level::Info
+    }
+
+    fn log(&self, record: &Record) {
+        if !self.enabled(record.metadata()) {
+            return;
+        }
+
+        let level_color = match record.level() {
+            Level::Error => "\x1b[31m",
+            Level::Warn => "\x1b[33m",
+            Level::Info => "\x1b[32m",
+            Level::Debug => "\x1b[34m",
+            Level::Trace => "\x1b[35m",
+        };
+        let reset = "\x1b[0m";
+        let bold = "\x1b[1m";
+
+        let level_label = match record.level() {
+            Level::Error => "Error",
+            Level::Warn => "Warn",
+            Level::Info => "Info",
+            Level::Debug => "Debug",
+            Level::Trace => "Trace",
+        };
+
+        let message = format!(
+            "{bold}{level_color}{level_label:>12}{reset} {}",
+            record.args()
+        );
+
+        if let Some(progress) = GLOBAL.get() {
+            progress.log(&message);
+        } else {
+            eprintln!("{}", message);
+        }
+    }
+
+    fn flush(&self) {
+        let _ = std::io::stderr().flush();
+    }
+}
+
+#[cfg(unix)]
+fn get_terminal_width() -> usize {
+    unsafe {
+        let mut winsize: libc::winsize = std::mem::zeroed();
+        if libc::ioctl(libc::STDERR_FILENO, libc::TIOCGWINSZ, &mut winsize) == 0
+            && winsize.ws_col > 0
+        {
+            winsize.ws_col as usize
+        } else {
+            80
+        }
+    }
+}
+
+#[cfg(not(unix))]
+fn get_terminal_width() -> usize {
+    80
+}
+
+fn strip_ansi_len(s: &str) -> usize {
+    let mut len = 0;
+    let mut in_escape = false;
+    for c in s.chars() {
+        if c == '\x1b' {
+            in_escape = true;
+        } else if in_escape {
+            if c == 'm' {
+                in_escape = false;
+            }
+        } else {
+            len += 1;
+        }
+    }
+    len
+}
+
+fn truncate_with_ellipsis(s: &str, max_len: usize) -> String {
+    if s.len() <= max_len {
+        s.to_string()
+    } else {
+        format!("{}…", &s[..max_len.saturating_sub(1)])
+    }
+}
+
+fn format_duration(duration: Duration) -> String {
+    const MINUTE_IN_MILLIS: f32 = 60. * 1000.;
+
+    let millis = duration.as_millis() as f32;
+    if millis < 1000.0 {
+        format!("{}ms", millis)
+    } else if millis < MINUTE_IN_MILLIS {
+        format!("{:.1}s", millis / 1_000.0)
+    } else {
+        format!("{:.1}m", millis / MINUTE_IN_MILLIS)
+    }
+}

crates/edit_prediction_cli/src/retrieve_context.rs 🔗

@@ -0,0 +1,192 @@
+use crate::{
+    example::{Example, ExampleContext},
+    headless::EpAppState,
+    load_project::run_load_project,
+    progress::{InfoStyle, Progress, Step, StepProgress},
+};
+use anyhow::Context as _;
+use collections::HashSet;
+use edit_prediction::{DebugEvent, EditPredictionStore};
+use futures::{FutureExt as _, StreamExt as _, channel::mpsc};
+use gpui::{AsyncApp, Entity};
+use language::Buffer;
+use project::Project;
+use std::sync::Arc;
+use std::time::Duration;
+
+pub async fn run_context_retrieval(
+    example: &mut Example,
+    app_state: Arc<EpAppState>,
+    mut cx: AsyncApp,
+) -> anyhow::Result<()> {
+    if example.context.is_some() {
+        return Ok(());
+    }
+
+    run_load_project(example, app_state.clone(), cx.clone()).await?;
+
+    let step_progress: Arc<StepProgress> = Progress::global()
+        .start(Step::Context, &example.spec.name)
+        .into();
+
+    let state = example.state.as_ref().unwrap();
+    let project = state.project.clone();
+
+    let _lsp_handle = project.update(&mut cx, |project, cx| {
+        project.register_buffer_with_language_servers(&state.buffer, cx)
+    })?;
+    wait_for_language_servers_to_start(&project, &state.buffer, &step_progress, &mut cx).await?;
+
+    let ep_store = cx.update(|cx| {
+        EditPredictionStore::try_global(cx).context("EditPredictionStore not initialized")
+    })??;
+
+    let mut events = ep_store.update(&mut cx, |store, cx| {
+        store.register_buffer(&state.buffer, &project, cx);
+        store.set_use_context(true);
+        store.refresh_context(&project, &state.buffer, state.cursor_position, cx);
+        store.debug_info(&project, cx)
+    })?;
+
+    while let Some(event) = events.next().await {
+        match event {
+            DebugEvent::ContextRetrievalFinished(_) => {
+                break;
+            }
+            _ => {}
+        }
+    }
+
+    let context_files =
+        ep_store.update(&mut cx, |store, cx| store.context_for_project(&project, cx))?;
+
+    let excerpt_count: usize = context_files.iter().map(|f| f.excerpts.len()).sum();
+    step_progress.set_info(format!("{} excerpts", excerpt_count), InfoStyle::Normal);
+
+    example.context = Some(ExampleContext {
+        files: context_files,
+    });
+    Ok(())
+}
+
+async fn wait_for_language_servers_to_start(
+    project: &Entity<Project>,
+    buffer: &Entity<Buffer>,
+    step_progress: &Arc<StepProgress>,
+    cx: &mut AsyncApp,
+) -> anyhow::Result<()> {
+    let lsp_store = project.read_with(cx, |project, _| project.lsp_store())?;
+
+    let (language_server_ids, mut starting_language_server_ids) = buffer
+        .update(cx, |buffer, cx| {
+            lsp_store.update(cx, |lsp_store, cx| {
+                let ids = lsp_store.language_servers_for_local_buffer(buffer, cx);
+                let starting_ids = ids
+                    .iter()
+                    .copied()
+                    .filter(|id| !lsp_store.language_server_statuses.contains_key(&id))
+                    .collect::<HashSet<_>>();
+                (ids, starting_ids)
+            })
+        })
+        .unwrap_or_default();
+
+    step_progress.set_substatus(format!("waiting for {} LSPs", language_server_ids.len()));
+
+    let timeout = cx
+        .background_executor()
+        .timer(Duration::from_secs(60 * 5))
+        .shared();
+
+    let (mut tx, mut rx) = mpsc::channel(language_server_ids.len());
+    let added_subscription = cx.subscribe(project, {
+        let step_progress = step_progress.clone();
+        move |_, event, _| match event {
+            project::Event::LanguageServerAdded(language_server_id, name, _) => {
+                step_progress.set_substatus(format!("LSP started: {}", name));
+                tx.try_send(*language_server_id).ok();
+            }
+            _ => {}
+        }
+    });
+
+    while !starting_language_server_ids.is_empty() {
+        futures::select! {
+            language_server_id = rx.next() => {
+                if let Some(id) = language_server_id {
+                    starting_language_server_ids.remove(&id);
+                }
+            },
+            _ = timeout.clone().fuse() => {
+                return Err(anyhow::anyhow!("LSP wait timed out after 5 minutes"));
+            }
+        }
+    }
+
+    drop(added_subscription);
+
+    if !language_server_ids.is_empty() {
+        project
+            .update(cx, |project, cx| project.save_buffer(buffer.clone(), cx))?
+            .detach();
+    }
+
+    let (mut tx, mut rx) = mpsc::channel(language_server_ids.len());
+    let subscriptions = [
+        cx.subscribe(&lsp_store, {
+            let step_progress = step_progress.clone();
+            move |_, event, _| {
+                if let project::LspStoreEvent::LanguageServerUpdate {
+                    message:
+                        client::proto::update_language_server::Variant::WorkProgress(
+                            client::proto::LspWorkProgress {
+                                message: Some(message),
+                                ..
+                            },
+                        ),
+                    ..
+                } = event
+                {
+                    step_progress.set_substatus(message.clone());
+                }
+            }
+        }),
+        cx.subscribe(project, {
+            let step_progress = step_progress.clone();
+            move |_, event, cx| match event {
+                project::Event::DiskBasedDiagnosticsFinished { language_server_id } => {
+                    let lsp_store = lsp_store.read(cx);
+                    let name = lsp_store
+                        .language_server_adapter_for_id(*language_server_id)
+                        .unwrap()
+                        .name();
+                    step_progress.set_substatus(format!("LSP idle: {}", name));
+                    tx.try_send(*language_server_id).ok();
+                }
+                _ => {}
+            }
+        }),
+    ];
+
+    project
+        .update(cx, |project, cx| project.save_buffer(buffer.clone(), cx))?
+        .await?;
+
+    let mut pending_language_server_ids = HashSet::from_iter(language_server_ids.into_iter());
+    while !pending_language_server_ids.is_empty() {
+        futures::select! {
+            language_server_id = rx.next() => {
+                if let Some(id) = language_server_id {
+                    pending_language_server_ids.remove(&id);
+                }
+            },
+            _ = timeout.clone().fuse() => {
+                return Err(anyhow::anyhow!("LSP wait timed out after 5 minutes"));
+            }
+        }
+    }
+
+    drop(subscriptions);
+    step_progress.clear_substatus();
+    Ok(())
+}

crates/edit_prediction_cli/src/score.rs 🔗

@@ -0,0 +1,123 @@
+use crate::{
+    PredictArgs,
+    example::{Example, ExampleScore},
+    headless::EpAppState,
+    metrics::{self, ClassificationMetrics},
+    predict::run_prediction,
+    progress::{Progress, Step},
+};
+use edit_prediction::udiff::DiffLine;
+use gpui::AsyncApp;
+use std::sync::Arc;
+
+pub async fn run_scoring(
+    example: &mut Example,
+    args: &PredictArgs,
+    app_state: Arc<EpAppState>,
+    cx: AsyncApp,
+) -> anyhow::Result<()> {
+    run_prediction(
+        example,
+        Some(args.provider),
+        args.repetitions,
+        app_state,
+        cx,
+    )
+    .await?;
+
+    let _progress = Progress::global().start(Step::Score, &example.spec.name);
+
+    let expected_patch = parse_patch(&example.spec.expected_patch);
+
+    let mut scores = vec![];
+
+    for pred in &example.predictions {
+        let actual_patch = parse_patch(&pred.actual_patch);
+        let line_match = metrics::line_match_score(&expected_patch, &actual_patch);
+        let delta_chr_f = metrics::delta_chr_f(&expected_patch, &actual_patch) as f32;
+
+        scores.push(ExampleScore {
+            delta_chr_f,
+            line_match,
+        });
+    }
+
+    example.score = scores;
+    Ok(())
+}
+
+fn parse_patch(patch: &str) -> Vec<DiffLine<'_>> {
+    patch.lines().map(DiffLine::parse).collect()
+}
+
+pub fn print_report(examples: &[Example]) {
+    eprintln!(
+        "──────────────────────────────────────────────────────────────────────────────────────"
+    );
+    eprintln!(
+        "{:<30} {:>4} {:>4} {:>4} {:>10} {:>8} {:>8} {:>10}",
+        "Example name", "TP", "FP", "FN", "Precision", "Recall", "F1", "DeltaChrF"
+    );
+    eprintln!(
+        "──────────────────────────────────────────────────────────────────────────────────────"
+    );
+
+    let mut all_line_match_scores = Vec::new();
+    let mut all_delta_chr_f_scores = Vec::new();
+
+    for example in examples {
+        for score in example.score.iter() {
+            let line_match = &score.line_match;
+
+            eprintln!(
+                "{:<30} {:>4} {:>4} {:>4} {:>9.2}% {:>7.2}% {:>7.2}% {:>9.2}",
+                truncate_name(&example.spec.name, 30),
+                line_match.true_positives,
+                line_match.false_positives,
+                line_match.false_negatives,
+                line_match.precision() * 100.0,
+                line_match.recall() * 100.0,
+                line_match.f1_score() * 100.0,
+                score.delta_chr_f
+            );
+
+            all_line_match_scores.push(line_match.clone());
+            all_delta_chr_f_scores.push(score.delta_chr_f);
+        }
+    }
+
+    eprintln!(
+        "──────────────────────────────────────────────────────────────────────────────────────"
+    );
+
+    if !all_line_match_scores.is_empty() {
+        let total_line_match = ClassificationMetrics::aggregate(all_line_match_scores.iter());
+        let avg_delta_chr_f: f32 =
+            all_delta_chr_f_scores.iter().sum::<f32>() / all_delta_chr_f_scores.len() as f32;
+
+        eprintln!(
+            "{:<30} {:>4} {:>4} {:>4} {:>9.2}% {:>7.2}% {:>7.2}% {:>9.2}",
+            "TOTAL",
+            total_line_match.true_positives,
+            total_line_match.false_positives,
+            total_line_match.false_negatives,
+            total_line_match.precision() * 100.0,
+            total_line_match.recall() * 100.0,
+            total_line_match.f1_score() * 100.0,
+            avg_delta_chr_f
+        );
+        eprintln!(
+            "──────────────────────────────────────────────────────────────────────────────────────"
+        );
+    }
+
+    eprintln!("\n");
+}
+
+fn truncate_name(name: &str, max_len: usize) -> String {
+    if name.len() <= max_len {
+        name.to_string()
+    } else {
+        format!("{}...", &name[..max_len - 3])
+    }
+}

crates/edit_prediction_cli/src/teacher.prompt.md 🔗

@@ -0,0 +1,53 @@
+# Instructions
+
+You are a code completion assistant helping a programmer finish their work. Your task is to:
+
+1. Analyze the edit history to understand what the programmer is trying to achieve
+2. Identify any incomplete refactoring or changes that need to be finished
+3. Make the remaining edits that a human programmer would logically make next (by rewriting the corresponding code sections)
+4. Apply systematic changes consistently across the entire codebase - if you see a pattern starting, complete it everywhere.
+
+Focus on:
+- Understanding the intent behind the changes (e.g., improving error handling, refactoring APIs, fixing bugs)
+- Completing any partially-applied changes across the codebase
+- Ensuring consistency with the programming style and patterns already established
+- Making edits that maintain or improve code quality
+- If the programmer started refactoring one instance of a pattern, find and update ALL similar instances
+- Don't write a lot of code if you're not sure what to do
+
+Rules:
+- Do not just mechanically apply patterns - reason about what changes make sense given the context and the programmer's apparent goals.
+- Do not just fix syntax errors - look for the broader refactoring pattern and apply it systematically throughout the code.
+- Keep existing formatting unless it's absolutely necessary 
+
+Input format:
+- You receive small code fragments called context (structs, field definitions, function signatures, etc.). They may or may not be relevant.
+- Never modify the context code.
+- You also receive a code snippet between <|editable_region_start|> and <|editable_region_end|>. This is the editable region.
+- The cursor position is marked with <|user_cursor|>.
+
+Output format:
+- Return the entire editable region, applying any edits you make.
+- Remove the <|user_cursor|> marker.
+- Wrap the edited code in a block of exactly five backticks.
+
+Output example:
+`````
+    // `zed --askpass` Makes zed operate in nc/netcat mode for use with askpass
+    if let Some(socket) = &args.askpass {{
+        askpass::main(socket);
+        return Ok(());
+    }}
+`````
+
+## User Edits History
+
+{{edit_history}}
+
+## Code Context
+
+{{context}}
+
+## Editable region
+
+{{editable_region}}

crates/edit_prediction_context/Cargo.toml 🔗

@@ -12,41 +12,33 @@ workspace = true
 path = "src/edit_prediction_context.rs"
 
 [dependencies]
+parking_lot.workspace = true
 anyhow.workspace = true
-arrayvec.workspace = true
 cloud_llm_client.workspace = true
 collections.workspace = true
 futures.workspace = true
 gpui.workspace = true
-hashbrown.workspace = true
-indoc.workspace = true
-itertools.workspace = true
 language.workspace = true
-log.workspace = true
-ordered-float.workspace = true
-postage.workspace = true
+lsp.workspace = true
 project.workspace = true
-regex.workspace = true
+log.workspace = true
 serde.workspace = true
-slotmap.workspace = true
-strum.workspace = true
-text.workspace = true
+smallvec.workspace = true
 tree-sitter.workspace = true
 util.workspace = true
+zeta_prompt.workspace = true
 
 [dev-dependencies]
-clap.workspace = true
+env_logger.workspace = true
+indoc.workspace = true
 futures.workspace = true
 gpui = { workspace = true, features = ["test-support"] }
-indoc.workspace = true
 language = { workspace = true, features = ["test-support"] }
+lsp = { workspace = true, features = ["test-support"] }
 pretty_assertions.workspace = true
 project = {workspace= true, features = ["test-support"]}
 serde_json.workspace = true
 settings = {workspace= true, features = ["test-support"]}
 text = { workspace = true, features = ["test-support"] }
-tree-sitter-c.workspace = true
-tree-sitter-cpp.workspace = true
-tree-sitter-go.workspace = true
 util = { workspace = true, features = ["test-support"] }
 zlog.workspace = true

crates/edit_prediction_context/src/assemble_excerpts.rs 🔗

@@ -0,0 +1,156 @@
+use language::{BufferSnapshot, OffsetRangeExt as _, Point};
+use std::ops::Range;
+use zeta_prompt::RelatedExcerpt;
+
+#[cfg(not(test))]
+const MAX_OUTLINE_ITEM_BODY_SIZE: usize = 512;
+#[cfg(test)]
+const MAX_OUTLINE_ITEM_BODY_SIZE: usize = 24;
+
+pub fn assemble_excerpts(
+    buffer: &BufferSnapshot,
+    mut input_ranges: Vec<Range<Point>>,
+) -> Vec<RelatedExcerpt> {
+    merge_ranges(&mut input_ranges);
+
+    let mut outline_ranges = Vec::new();
+    let outline_items = buffer.outline_items_as_points_containing(0..buffer.len(), false, None);
+    let mut outline_ix = 0;
+    for input_range in &mut input_ranges {
+        *input_range = clip_range_to_lines(input_range, false, buffer);
+
+        while let Some(outline_item) = outline_items.get(outline_ix) {
+            let item_range = clip_range_to_lines(&outline_item.range, false, buffer);
+
+            if item_range.start > input_range.start {
+                break;
+            }
+
+            if item_range.end > input_range.start {
+                let body_range = outline_item
+                    .body_range(buffer)
+                    .map(|body| clip_range_to_lines(&body, true, buffer))
+                    .filter(|body_range| {
+                        body_range.to_offset(buffer).len() > MAX_OUTLINE_ITEM_BODY_SIZE
+                    });
+
+                add_outline_item(
+                    item_range.clone(),
+                    body_range.clone(),
+                    buffer,
+                    &mut outline_ranges,
+                );
+
+                if let Some(body_range) = body_range
+                    && input_range.start < body_range.start
+                {
+                    let mut child_outline_ix = outline_ix + 1;
+                    while let Some(next_outline_item) = outline_items.get(child_outline_ix) {
+                        if next_outline_item.range.end > body_range.end {
+                            break;
+                        }
+                        if next_outline_item.depth == outline_item.depth + 1 {
+                            let next_item_range =
+                                clip_range_to_lines(&next_outline_item.range, false, buffer);
+
+                            add_outline_item(
+                                next_item_range,
+                                next_outline_item
+                                    .body_range(buffer)
+                                    .map(|body| clip_range_to_lines(&body, true, buffer)),
+                                buffer,
+                                &mut outline_ranges,
+                            );
+                        }
+                        child_outline_ix += 1;
+                    }
+                }
+            }
+
+            outline_ix += 1;
+        }
+    }
+
+    input_ranges.extend_from_slice(&outline_ranges);
+    merge_ranges(&mut input_ranges);
+
+    input_ranges
+        .into_iter()
+        .map(|range| RelatedExcerpt {
+            row_range: range.start.row..range.end.row,
+            text: buffer.text_for_range(range).collect(),
+        })
+        .collect()
+}
+
+fn clip_range_to_lines(
+    range: &Range<Point>,
+    inward: bool,
+    buffer: &BufferSnapshot,
+) -> Range<Point> {
+    let mut range = range.clone();
+    if inward {
+        if range.start.column > 0 {
+            range.start.column = buffer.line_len(range.start.row);
+        }
+        range.end.column = 0;
+    } else {
+        range.start.column = 0;
+        if range.end.column > 0 {
+            range.end.column = buffer.line_len(range.end.row);
+        }
+    }
+    range
+}
+
+fn add_outline_item(
+    mut item_range: Range<Point>,
+    body_range: Option<Range<Point>>,
+    buffer: &BufferSnapshot,
+    outline_ranges: &mut Vec<Range<Point>>,
+) {
+    if let Some(mut body_range) = body_range {
+        if body_range.start.column > 0 {
+            body_range.start.column = buffer.line_len(body_range.start.row);
+        }
+        body_range.end.column = 0;
+
+        let head_range = item_range.start..body_range.start;
+        if head_range.start < head_range.end {
+            outline_ranges.push(head_range);
+        }
+
+        let tail_range = body_range.end..item_range.end;
+        if tail_range.start < tail_range.end {
+            outline_ranges.push(tail_range);
+        }
+    } else {
+        item_range.start.column = 0;
+        item_range.end.column = buffer.line_len(item_range.end.row);
+        outline_ranges.push(item_range);
+    }
+}
+
+pub fn merge_ranges(ranges: &mut Vec<Range<Point>>) {
+    ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start).then(b.end.cmp(&a.end)));
+
+    let mut index = 1;
+    while index < ranges.len() {
+        let mut prev_range_end = ranges[index - 1].end;
+        if prev_range_end.column > 0 {
+            prev_range_end += Point::new(1, 0);
+        }
+
+        if (prev_range_end + Point::new(1, 0))
+            .cmp(&ranges[index].start)
+            .is_ge()
+        {
+            let removed = ranges.remove(index);
+            if removed.end.cmp(&ranges[index - 1].end).is_gt() {
+                ranges[index - 1].end = removed.end;
+            }
+        } else {
+            index += 1;
+        }
+    }
+}

crates/edit_prediction_context/src/declaration.rs 🔗

@@ -1,350 +0,0 @@
-use cloud_llm_client::predict_edits_v3::{self, Line};
-use language::{Language, LanguageId};
-use project::ProjectEntryId;
-use std::ops::Range;
-use std::sync::Arc;
-use std::{borrow::Cow, path::Path};
-use text::{Bias, BufferId, Rope};
-use util::paths::{path_ends_with, strip_path_suffix};
-use util::rel_path::RelPath;
-
-use crate::outline::OutlineDeclaration;
-
-#[derive(Debug, Clone, Eq, PartialEq, Hash)]
-pub struct Identifier {
-    pub name: Arc<str>,
-    pub language_id: LanguageId,
-}
-
-slotmap::new_key_type! {
-    pub struct DeclarationId;
-}
-
-#[derive(Debug, Clone)]
-pub enum Declaration {
-    File {
-        project_entry_id: ProjectEntryId,
-        declaration: FileDeclaration,
-        cached_path: CachedDeclarationPath,
-    },
-    Buffer {
-        project_entry_id: ProjectEntryId,
-        buffer_id: BufferId,
-        rope: Rope,
-        declaration: BufferDeclaration,
-        cached_path: CachedDeclarationPath,
-    },
-}
-
-const ITEM_TEXT_TRUNCATION_LENGTH: usize = 1024;
-
-impl Declaration {
-    pub fn identifier(&self) -> &Identifier {
-        match self {
-            Declaration::File { declaration, .. } => &declaration.identifier,
-            Declaration::Buffer { declaration, .. } => &declaration.identifier,
-        }
-    }
-
-    pub fn parent(&self) -> Option<DeclarationId> {
-        match self {
-            Declaration::File { declaration, .. } => declaration.parent,
-            Declaration::Buffer { declaration, .. } => declaration.parent,
-        }
-    }
-
-    pub fn as_buffer(&self) -> Option<&BufferDeclaration> {
-        match self {
-            Declaration::File { .. } => None,
-            Declaration::Buffer { declaration, .. } => Some(declaration),
-        }
-    }
-
-    pub fn as_file(&self) -> Option<&FileDeclaration> {
-        match self {
-            Declaration::Buffer { .. } => None,
-            Declaration::File { declaration, .. } => Some(declaration),
-        }
-    }
-
-    pub fn project_entry_id(&self) -> ProjectEntryId {
-        match self {
-            Declaration::File {
-                project_entry_id, ..
-            } => *project_entry_id,
-            Declaration::Buffer {
-                project_entry_id, ..
-            } => *project_entry_id,
-        }
-    }
-
-    pub fn cached_path(&self) -> &CachedDeclarationPath {
-        match self {
-            Declaration::File { cached_path, .. } => cached_path,
-            Declaration::Buffer { cached_path, .. } => cached_path,
-        }
-    }
-
-    pub fn item_range(&self) -> Range<usize> {
-        match self {
-            Declaration::File { declaration, .. } => declaration.item_range.clone(),
-            Declaration::Buffer { declaration, .. } => declaration.item_range.clone(),
-        }
-    }
-
-    pub fn item_line_range(&self) -> Range<Line> {
-        match self {
-            Declaration::File { declaration, .. } => declaration.item_line_range.clone(),
-            Declaration::Buffer {
-                declaration, rope, ..
-            } => {
-                Line(rope.offset_to_point(declaration.item_range.start).row)
-                    ..Line(rope.offset_to_point(declaration.item_range.end).row)
-            }
-        }
-    }
-
-    pub fn item_text(&self) -> (Cow<'_, str>, bool) {
-        match self {
-            Declaration::File { declaration, .. } => (
-                declaration.text.as_ref().into(),
-                declaration.text_is_truncated,
-            ),
-            Declaration::Buffer {
-                rope, declaration, ..
-            } => (
-                rope.chunks_in_range(declaration.item_range.clone())
-                    .collect::<Cow<str>>(),
-                declaration.item_range_is_truncated,
-            ),
-        }
-    }
-
-    pub fn signature_text(&self) -> (Cow<'_, str>, bool) {
-        match self {
-            Declaration::File { declaration, .. } => (
-                declaration.text[self.signature_range_in_item_text()].into(),
-                declaration.signature_is_truncated,
-            ),
-            Declaration::Buffer {
-                rope, declaration, ..
-            } => (
-                rope.chunks_in_range(declaration.signature_range.clone())
-                    .collect::<Cow<str>>(),
-                declaration.signature_range_is_truncated,
-            ),
-        }
-    }
-
-    pub fn signature_range(&self) -> Range<usize> {
-        match self {
-            Declaration::File { declaration, .. } => declaration.signature_range.clone(),
-            Declaration::Buffer { declaration, .. } => declaration.signature_range.clone(),
-        }
-    }
-
-    pub fn signature_line_range(&self) -> Range<Line> {
-        match self {
-            Declaration::File { declaration, .. } => declaration.signature_line_range.clone(),
-            Declaration::Buffer {
-                declaration, rope, ..
-            } => {
-                Line(rope.offset_to_point(declaration.signature_range.start).row)
-                    ..Line(rope.offset_to_point(declaration.signature_range.end).row)
-            }
-        }
-    }
-
-    pub fn signature_range_in_item_text(&self) -> Range<usize> {
-        let signature_range = self.signature_range();
-        let item_range = self.item_range();
-        signature_range.start.saturating_sub(item_range.start)
-            ..(signature_range.end.saturating_sub(item_range.start)).min(item_range.len())
-    }
-}
-
-fn expand_range_to_line_boundaries_and_truncate(
-    range: &Range<usize>,
-    limit: usize,
-    rope: &Rope,
-) -> (Range<usize>, Range<predict_edits_v3::Line>, bool) {
-    let mut point_range = rope.offset_to_point(range.start)..rope.offset_to_point(range.end);
-    point_range.start.column = 0;
-    point_range.end.row += 1;
-    point_range.end.column = 0;
-
-    let mut item_range =
-        rope.point_to_offset(point_range.start)..rope.point_to_offset(point_range.end);
-    let is_truncated = item_range.len() > limit;
-    if is_truncated {
-        item_range.end = item_range.start + limit;
-    }
-    item_range.end = rope.clip_offset(item_range.end, Bias::Left);
-
-    let line_range =
-        predict_edits_v3::Line(point_range.start.row)..predict_edits_v3::Line(point_range.end.row);
-    (item_range, line_range, is_truncated)
-}
-
-#[derive(Debug, Clone)]
-pub struct FileDeclaration {
-    pub parent: Option<DeclarationId>,
-    pub identifier: Identifier,
-    /// offset range of the declaration in the file, expanded to line boundaries and truncated
-    pub item_range: Range<usize>,
-    /// line range of the declaration in the file, potentially truncated
-    pub item_line_range: Range<predict_edits_v3::Line>,
-    /// text of `item_range`
-    pub text: Arc<str>,
-    /// whether `text` was truncated
-    pub text_is_truncated: bool,
-    /// offset range of the signature in the file, expanded to line boundaries and truncated
-    pub signature_range: Range<usize>,
-    /// line range of the signature in the file, truncated
-    pub signature_line_range: Range<Line>,
-    /// whether `signature` was truncated
-    pub signature_is_truncated: bool,
-}
-
-impl FileDeclaration {
-    pub fn from_outline(declaration: OutlineDeclaration, rope: &Rope) -> FileDeclaration {
-        let (item_range_in_file, item_line_range_in_file, text_is_truncated) =
-            expand_range_to_line_boundaries_and_truncate(
-                &declaration.item_range,
-                ITEM_TEXT_TRUNCATION_LENGTH,
-                rope,
-            );
-
-        let (mut signature_range_in_file, signature_line_range, mut signature_is_truncated) =
-            expand_range_to_line_boundaries_and_truncate(
-                &declaration.signature_range,
-                ITEM_TEXT_TRUNCATION_LENGTH,
-                rope,
-            );
-
-        if signature_range_in_file.start < item_range_in_file.start {
-            signature_range_in_file.start = item_range_in_file.start;
-            signature_is_truncated = true;
-        }
-        if signature_range_in_file.end > item_range_in_file.end {
-            signature_range_in_file.end = item_range_in_file.end;
-            signature_is_truncated = true;
-        }
-
-        FileDeclaration {
-            parent: None,
-            identifier: declaration.identifier,
-            signature_range: signature_range_in_file,
-            signature_line_range,
-            signature_is_truncated,
-            text: rope
-                .chunks_in_range(item_range_in_file.clone())
-                .collect::<String>()
-                .into(),
-            text_is_truncated,
-            item_range: item_range_in_file,
-            item_line_range: item_line_range_in_file,
-        }
-    }
-}
-
-#[derive(Debug, Clone)]
-pub struct BufferDeclaration {
-    pub parent: Option<DeclarationId>,
-    pub identifier: Identifier,
-    pub item_range: Range<usize>,
-    pub item_range_is_truncated: bool,
-    pub signature_range: Range<usize>,
-    pub signature_range_is_truncated: bool,
-}
-
-impl BufferDeclaration {
-    pub fn from_outline(declaration: OutlineDeclaration, rope: &Rope) -> Self {
-        let (item_range, _item_line_range, item_range_is_truncated) =
-            expand_range_to_line_boundaries_and_truncate(
-                &declaration.item_range,
-                ITEM_TEXT_TRUNCATION_LENGTH,
-                rope,
-            );
-        let (signature_range, _signature_line_range, signature_range_is_truncated) =
-            expand_range_to_line_boundaries_and_truncate(
-                &declaration.signature_range,
-                ITEM_TEXT_TRUNCATION_LENGTH,
-                rope,
-            );
-        Self {
-            parent: None,
-            identifier: declaration.identifier,
-            item_range,
-            item_range_is_truncated,
-            signature_range,
-            signature_range_is_truncated,
-        }
-    }
-}
-
-#[derive(Debug, Clone)]
-pub struct CachedDeclarationPath {
-    pub worktree_abs_path: Arc<Path>,
-    pub rel_path: Arc<RelPath>,
-    /// The relative path of the file, possibly stripped according to `import_path_strip_regex`.
-    pub rel_path_after_regex_stripping: Arc<RelPath>,
-}
-
-impl CachedDeclarationPath {
-    pub fn new(
-        worktree_abs_path: Arc<Path>,
-        path: &Arc<RelPath>,
-        language: Option<&Arc<Language>>,
-    ) -> Self {
-        let rel_path = path.clone();
-        let rel_path_after_regex_stripping = if let Some(language) = language
-            && let Some(strip_regex) = language.config().import_path_strip_regex.as_ref()
-            && let Ok(stripped) = RelPath::unix(&Path::new(
-                strip_regex.replace_all(rel_path.as_unix_str(), "").as_ref(),
-            )) {
-            Arc::from(stripped)
-        } else {
-            rel_path.clone()
-        };
-        CachedDeclarationPath {
-            worktree_abs_path,
-            rel_path,
-            rel_path_after_regex_stripping,
-        }
-    }
-
-    #[cfg(test)]
-    pub fn new_for_test(worktree_abs_path: &str, rel_path: &str) -> Self {
-        let rel_path: Arc<RelPath> = util::rel_path::rel_path(rel_path).into();
-        CachedDeclarationPath {
-            worktree_abs_path: std::path::PathBuf::from(worktree_abs_path).into(),
-            rel_path_after_regex_stripping: rel_path.clone(),
-            rel_path,
-        }
-    }
-
-    pub fn ends_with_posix_path(&self, path: &Path) -> bool {
-        if path.as_os_str().len() <= self.rel_path_after_regex_stripping.as_unix_str().len() {
-            path_ends_with(self.rel_path_after_regex_stripping.as_std_path(), path)
-        } else {
-            if let Some(remaining) =
-                strip_path_suffix(path, self.rel_path_after_regex_stripping.as_std_path())
-            {
-                path_ends_with(&self.worktree_abs_path, remaining)
-            } else {
-                false
-            }
-        }
-    }
-
-    pub fn equals_absolute_path(&self, path: &Path) -> bool {
-        if let Some(remaining) =
-            strip_path_suffix(path, &self.rel_path_after_regex_stripping.as_std_path())
-        {
-            self.worktree_abs_path.as_ref() == remaining
-        } else {
-            false
-        }
-    }
-}

crates/edit_prediction_context/src/declaration_scoring.rs 🔗

@@ -1,539 +0,0 @@
-use cloud_llm_client::predict_edits_v3::DeclarationScoreComponents;
-use collections::HashMap;
-use language::BufferSnapshot;
-use ordered_float::OrderedFloat;
-use project::ProjectEntryId;
-use serde::Serialize;
-use std::{cmp::Reverse, ops::Range, path::Path, sync::Arc};
-use strum::EnumIter;
-use text::{Point, ToPoint};
-use util::RangeExt as _;
-
-use crate::{
-    CachedDeclarationPath, Declaration, EditPredictionExcerpt, Identifier,
-    imports::{Import, Imports, Module},
-    reference::{Reference, ReferenceRegion},
-    syntax_index::SyntaxIndexState,
-    text_similarity::{Occurrences, jaccard_similarity, weighted_overlap_coefficient},
-};
-
-const MAX_IDENTIFIER_DECLARATION_COUNT: usize = 16;
-
-#[derive(Clone, Debug, PartialEq, Eq)]
-pub struct EditPredictionScoreOptions {
-    pub omit_excerpt_overlaps: bool,
-}
-
-#[derive(Clone, Debug)]
-pub struct ScoredDeclaration {
-    /// identifier used by the local reference
-    pub identifier: Identifier,
-    pub declaration: Declaration,
-    pub components: DeclarationScoreComponents,
-}
-
-#[derive(EnumIter, Clone, Copy, PartialEq, Eq, Hash, Debug)]
-pub enum DeclarationStyle {
-    Signature,
-    Declaration,
-}
-
-#[derive(Clone, Debug, Serialize, Default)]
-pub struct DeclarationScores {
-    pub signature: f32,
-    pub declaration: f32,
-    pub retrieval: f32,
-}
-
-impl ScoredDeclaration {
-    /// Returns the score for this declaration with the specified style.
-    pub fn score(&self, style: DeclarationStyle) -> f32 {
-        // TODO: handle truncation
-
-        // Score related to how likely this is the correct declaration, range 0 to 1
-        let retrieval = self.retrieval_score();
-
-        // Score related to the distance between the reference and cursor, range 0 to 1
-        let distance_score = if self.components.is_referenced_nearby {
-            1.0 / (1.0 + self.components.reference_line_distance as f32 / 10.0).powf(2.0)
-        } else {
-            // same score as ~14 lines away, rationale is to not overly penalize references from parent signatures
-            0.5
-        };
-
-        // For now instead of linear combination, the scores are just multiplied together.
-        let combined_score = 10.0 * retrieval * distance_score;
-
-        match style {
-            DeclarationStyle::Signature => {
-                combined_score * self.components.excerpt_vs_signature_weighted_overlap
-            }
-            DeclarationStyle::Declaration => {
-                2.0 * combined_score * self.components.excerpt_vs_item_weighted_overlap
-            }
-        }
-    }
-
-    pub fn retrieval_score(&self) -> f32 {
-        let mut score = if self.components.is_same_file {
-            10.0 / self.components.same_file_declaration_count as f32
-        } else if self.components.path_import_match_count > 0 {
-            3.0
-        } else if self.components.wildcard_path_import_match_count > 0 {
-            1.0
-        } else if self.components.normalized_import_similarity > 0.0 {
-            self.components.normalized_import_similarity
-        } else if self.components.normalized_wildcard_import_similarity > 0.0 {
-            0.5 * self.components.normalized_wildcard_import_similarity
-        } else {
-            1.0 / self.components.declaration_count as f32
-        };
-        score *= 1. + self.components.included_by_others as f32 / 2.;
-        score *= 1. + self.components.includes_others as f32 / 4.;
-        score
-    }
-
-    pub fn size(&self, style: DeclarationStyle) -> usize {
-        match &self.declaration {
-            Declaration::File { declaration, .. } => match style {
-                DeclarationStyle::Signature => declaration.signature_range.len(),
-                DeclarationStyle::Declaration => declaration.text.len(),
-            },
-            Declaration::Buffer { declaration, .. } => match style {
-                DeclarationStyle::Signature => declaration.signature_range.len(),
-                DeclarationStyle::Declaration => declaration.item_range.len(),
-            },
-        }
-    }
-
-    pub fn score_density(&self, style: DeclarationStyle) -> f32 {
-        self.score(style) / self.size(style) as f32
-    }
-}
-
-pub fn scored_declarations(
-    options: &EditPredictionScoreOptions,
-    index: &SyntaxIndexState,
-    excerpt: &EditPredictionExcerpt,
-    excerpt_occurrences: &Occurrences,
-    adjacent_occurrences: &Occurrences,
-    imports: &Imports,
-    identifier_to_references: HashMap<Identifier, Vec<Reference>>,
-    cursor_offset: usize,
-    current_buffer: &BufferSnapshot,
-) -> Vec<ScoredDeclaration> {
-    let cursor_point = cursor_offset.to_point(&current_buffer);
-
-    let mut wildcard_import_occurrences = Vec::new();
-    let mut wildcard_import_paths = Vec::new();
-    for wildcard_import in imports.wildcard_modules.iter() {
-        match wildcard_import {
-            Module::Namespace(namespace) => {
-                wildcard_import_occurrences.push(namespace.occurrences())
-            }
-            Module::SourceExact(path) => wildcard_import_paths.push(path),
-            Module::SourceFuzzy(path) => {
-                wildcard_import_occurrences.push(Occurrences::from_path(&path))
-            }
-        }
-    }
-
-    let mut scored_declarations = Vec::new();
-    let mut project_entry_id_to_outline_ranges: HashMap<ProjectEntryId, Vec<Range<usize>>> =
-        HashMap::default();
-    for (identifier, references) in identifier_to_references {
-        let mut import_occurrences = Vec::new();
-        let mut import_paths = Vec::new();
-        let mut found_external_identifier: Option<&Identifier> = None;
-
-        if let Some(imports) = imports.identifier_to_imports.get(&identifier) {
-            // only use alias when it's the only import, could be generalized if some language
-            // has overlapping aliases
-            //
-            // TODO: when an aliased declaration is included in the prompt, should include the
-            // aliasing in the prompt.
-            //
-            // TODO: For SourceFuzzy consider having componentwise comparison that pays
-            // attention to ordering.
-            if let [
-                Import::Alias {
-                    module,
-                    external_identifier,
-                },
-            ] = imports.as_slice()
-            {
-                match module {
-                    Module::Namespace(namespace) => {
-                        import_occurrences.push(namespace.occurrences())
-                    }
-                    Module::SourceExact(path) => import_paths.push(path),
-                    Module::SourceFuzzy(path) => {
-                        import_occurrences.push(Occurrences::from_path(&path))
-                    }
-                }
-                found_external_identifier = Some(&external_identifier);
-            } else {
-                for import in imports {
-                    match import {
-                        Import::Direct { module } => match module {
-                            Module::Namespace(namespace) => {
-                                import_occurrences.push(namespace.occurrences())
-                            }
-                            Module::SourceExact(path) => import_paths.push(path),
-                            Module::SourceFuzzy(path) => {
-                                import_occurrences.push(Occurrences::from_path(&path))
-                            }
-                        },
-                        Import::Alias { .. } => {}
-                    }
-                }
-            }
-        }
-
-        let identifier_to_lookup = found_external_identifier.unwrap_or(&identifier);
-        // TODO: update this to be able to return more declarations? Especially if there is the
-        // ability to quickly filter a large list (based on imports)
-        let identifier_declarations = index
-            .declarations_for_identifier::<MAX_IDENTIFIER_DECLARATION_COUNT>(&identifier_to_lookup);
-        let declaration_count = identifier_declarations.len();
-
-        if declaration_count == 0 {
-            continue;
-        }
-
-        // TODO: option to filter out other candidates when same file / import match
-        let mut checked_declarations = Vec::with_capacity(declaration_count);
-        for (declaration_id, declaration) in identifier_declarations {
-            match declaration {
-                Declaration::Buffer {
-                    buffer_id,
-                    declaration: buffer_declaration,
-                    ..
-                } => {
-                    if buffer_id == &current_buffer.remote_id() {
-                        let already_included_in_prompt =
-                            range_intersection(&buffer_declaration.item_range, &excerpt.range)
-                                .is_some()
-                                || excerpt
-                                    .parent_declarations
-                                    .iter()
-                                    .any(|(excerpt_parent, _)| excerpt_parent == &declaration_id);
-                        if !options.omit_excerpt_overlaps || !already_included_in_prompt {
-                            let declaration_line = buffer_declaration
-                                .item_range
-                                .start
-                                .to_point(current_buffer)
-                                .row;
-                            let declaration_line_distance =
-                                (cursor_point.row as i32 - declaration_line as i32).unsigned_abs();
-                            checked_declarations.push(CheckedDeclaration {
-                                declaration,
-                                same_file_line_distance: Some(declaration_line_distance),
-                                path_import_match_count: 0,
-                                wildcard_path_import_match_count: 0,
-                            });
-                        }
-                        continue;
-                    } else {
-                    }
-                }
-                Declaration::File { .. } => {}
-            }
-            let declaration_path = declaration.cached_path();
-            let path_import_match_count = import_paths
-                .iter()
-                .filter(|import_path| {
-                    declaration_path_matches_import(&declaration_path, import_path)
-                })
-                .count();
-            let wildcard_path_import_match_count = wildcard_import_paths
-                .iter()
-                .filter(|import_path| {
-                    declaration_path_matches_import(&declaration_path, import_path)
-                })
-                .count();
-            checked_declarations.push(CheckedDeclaration {
-                declaration,
-                same_file_line_distance: None,
-                path_import_match_count,
-                wildcard_path_import_match_count,
-            });
-        }
-
-        let mut max_import_similarity = 0.0;
-        let mut max_wildcard_import_similarity = 0.0;
-
-        let mut scored_declarations_for_identifier = Vec::with_capacity(checked_declarations.len());
-        for checked_declaration in checked_declarations {
-            let same_file_declaration_count =
-                index.file_declaration_count(checked_declaration.declaration);
-
-            let declaration = score_declaration(
-                &identifier,
-                &references,
-                checked_declaration,
-                same_file_declaration_count,
-                declaration_count,
-                &excerpt_occurrences,
-                &adjacent_occurrences,
-                &import_occurrences,
-                &wildcard_import_occurrences,
-                cursor_point,
-                current_buffer,
-            );
-
-            if declaration.components.import_similarity > max_import_similarity {
-                max_import_similarity = declaration.components.import_similarity;
-            }
-
-            if declaration.components.wildcard_import_similarity > max_wildcard_import_similarity {
-                max_wildcard_import_similarity = declaration.components.wildcard_import_similarity;
-            }
-
-            project_entry_id_to_outline_ranges
-                .entry(declaration.declaration.project_entry_id())
-                .or_default()
-                .push(declaration.declaration.item_range());
-            scored_declarations_for_identifier.push(declaration);
-        }
-
-        if max_import_similarity > 0.0 || max_wildcard_import_similarity > 0.0 {
-            for declaration in scored_declarations_for_identifier.iter_mut() {
-                if max_import_similarity > 0.0 {
-                    declaration.components.max_import_similarity = max_import_similarity;
-                    declaration.components.normalized_import_similarity =
-                        declaration.components.import_similarity / max_import_similarity;
-                }
-                if max_wildcard_import_similarity > 0.0 {
-                    declaration.components.normalized_wildcard_import_similarity =
-                        declaration.components.wildcard_import_similarity
-                            / max_wildcard_import_similarity;
-                }
-            }
-        }
-
-        scored_declarations.extend(scored_declarations_for_identifier);
-    }
-
-    // TODO: Inform this via import / retrieval scores of outline items
-    // TODO: Consider using a sweepline
-    for scored_declaration in scored_declarations.iter_mut() {
-        let project_entry_id = scored_declaration.declaration.project_entry_id();
-        let Some(ranges) = project_entry_id_to_outline_ranges.get(&project_entry_id) else {
-            continue;
-        };
-        for range in ranges {
-            if range.contains_inclusive(&scored_declaration.declaration.item_range()) {
-                scored_declaration.components.included_by_others += 1
-            } else if scored_declaration
-                .declaration
-                .item_range()
-                .contains_inclusive(range)
-            {
-                scored_declaration.components.includes_others += 1
-            }
-        }
-    }
-
-    scored_declarations.sort_unstable_by_key(|declaration| {
-        Reverse(OrderedFloat(
-            declaration.score(DeclarationStyle::Declaration),
-        ))
-    });
-
-    scored_declarations
-}
-
-struct CheckedDeclaration<'a> {
-    declaration: &'a Declaration,
-    same_file_line_distance: Option<u32>,
-    path_import_match_count: usize,
-    wildcard_path_import_match_count: usize,
-}
-
-fn declaration_path_matches_import(
-    declaration_path: &CachedDeclarationPath,
-    import_path: &Arc<Path>,
-) -> bool {
-    if import_path.is_absolute() {
-        declaration_path.equals_absolute_path(import_path)
-    } else {
-        declaration_path.ends_with_posix_path(import_path)
-    }
-}
-
-fn range_intersection<T: Ord + Clone>(a: &Range<T>, b: &Range<T>) -> Option<Range<T>> {
-    let start = a.start.clone().max(b.start.clone());
-    let end = a.end.clone().min(b.end.clone());
-    if start < end {
-        Some(Range { start, end })
-    } else {
-        None
-    }
-}
-
-fn score_declaration(
-    identifier: &Identifier,
-    references: &[Reference],
-    checked_declaration: CheckedDeclaration,
-    same_file_declaration_count: usize,
-    declaration_count: usize,
-    excerpt_occurrences: &Occurrences,
-    adjacent_occurrences: &Occurrences,
-    import_occurrences: &[Occurrences],
-    wildcard_import_occurrences: &[Occurrences],
-    cursor: Point,
-    current_buffer: &BufferSnapshot,
-) -> ScoredDeclaration {
-    let CheckedDeclaration {
-        declaration,
-        same_file_line_distance,
-        path_import_match_count,
-        wildcard_path_import_match_count,
-    } = checked_declaration;
-
-    let is_referenced_nearby = references
-        .iter()
-        .any(|r| r.region == ReferenceRegion::Nearby);
-    let is_referenced_in_breadcrumb = references
-        .iter()
-        .any(|r| r.region == ReferenceRegion::Breadcrumb);
-    let reference_count = references.len();
-    let reference_line_distance = references
-        .iter()
-        .map(|r| {
-            let reference_line = r.range.start.to_point(current_buffer).row as i32;
-            (cursor.row as i32 - reference_line).unsigned_abs()
-        })
-        .min()
-        .unwrap();
-
-    let is_same_file = same_file_line_distance.is_some();
-    let declaration_line_distance = same_file_line_distance.unwrap_or(u32::MAX);
-
-    let item_source_occurrences = Occurrences::within_string(&declaration.item_text().0);
-    let item_signature_occurrences = Occurrences::within_string(&declaration.signature_text().0);
-    let excerpt_vs_item_jaccard = jaccard_similarity(excerpt_occurrences, &item_source_occurrences);
-    let excerpt_vs_signature_jaccard =
-        jaccard_similarity(excerpt_occurrences, &item_signature_occurrences);
-    let adjacent_vs_item_jaccard =
-        jaccard_similarity(adjacent_occurrences, &item_source_occurrences);
-    let adjacent_vs_signature_jaccard =
-        jaccard_similarity(adjacent_occurrences, &item_signature_occurrences);
-
-    let excerpt_vs_item_weighted_overlap =
-        weighted_overlap_coefficient(excerpt_occurrences, &item_source_occurrences);
-    let excerpt_vs_signature_weighted_overlap =
-        weighted_overlap_coefficient(excerpt_occurrences, &item_signature_occurrences);
-    let adjacent_vs_item_weighted_overlap =
-        weighted_overlap_coefficient(adjacent_occurrences, &item_source_occurrences);
-    let adjacent_vs_signature_weighted_overlap =
-        weighted_overlap_coefficient(adjacent_occurrences, &item_signature_occurrences);
-
-    let mut import_similarity = 0f32;
-    let mut wildcard_import_similarity = 0f32;
-    if !import_occurrences.is_empty() || !wildcard_import_occurrences.is_empty() {
-        let cached_path = declaration.cached_path();
-        let path_occurrences = Occurrences::from_worktree_path(
-            cached_path
-                .worktree_abs_path
-                .file_name()
-                .map(|f| f.to_string_lossy()),
-            &cached_path.rel_path,
-        );
-        import_similarity = import_occurrences
-            .iter()
-            .map(|namespace_occurrences| {
-                OrderedFloat(jaccard_similarity(namespace_occurrences, &path_occurrences))
-            })
-            .max()
-            .map(|similarity| similarity.into_inner())
-            .unwrap_or_default();
-
-        // TODO: Consider something other than max
-        wildcard_import_similarity = wildcard_import_occurrences
-            .iter()
-            .map(|namespace_occurrences| {
-                OrderedFloat(jaccard_similarity(namespace_occurrences, &path_occurrences))
-            })
-            .max()
-            .map(|similarity| similarity.into_inner())
-            .unwrap_or_default();
-    }
-
-    // TODO: Consider adding declaration_file_count
-    let score_components = DeclarationScoreComponents {
-        is_same_file,
-        is_referenced_nearby,
-        is_referenced_in_breadcrumb,
-        reference_line_distance,
-        declaration_line_distance,
-        reference_count,
-        same_file_declaration_count,
-        declaration_count,
-        excerpt_vs_item_jaccard,
-        excerpt_vs_signature_jaccard,
-        adjacent_vs_item_jaccard,
-        adjacent_vs_signature_jaccard,
-        excerpt_vs_item_weighted_overlap,
-        excerpt_vs_signature_weighted_overlap,
-        adjacent_vs_item_weighted_overlap,
-        adjacent_vs_signature_weighted_overlap,
-        path_import_match_count,
-        wildcard_path_import_match_count,
-        import_similarity,
-        max_import_similarity: 0.0,
-        normalized_import_similarity: 0.0,
-        wildcard_import_similarity,
-        normalized_wildcard_import_similarity: 0.0,
-        included_by_others: 0,
-        includes_others: 0,
-    };
-
-    ScoredDeclaration {
-        identifier: identifier.clone(),
-        declaration: declaration.clone(),
-        components: score_components,
-    }
-}
-
-#[cfg(test)]
-mod test {
-    use super::*;
-
-    #[test]
-    fn test_declaration_path_matches() {
-        let declaration_path =
-            CachedDeclarationPath::new_for_test("/home/user/project", "src/maths.ts");
-
-        assert!(declaration_path_matches_import(
-            &declaration_path,
-            &Path::new("maths.ts").into()
-        ));
-
-        assert!(declaration_path_matches_import(
-            &declaration_path,
-            &Path::new("project/src/maths.ts").into()
-        ));
-
-        assert!(declaration_path_matches_import(
-            &declaration_path,
-            &Path::new("user/project/src/maths.ts").into()
-        ));
-
-        assert!(declaration_path_matches_import(
-            &declaration_path,
-            &Path::new("/home/user/project/src/maths.ts").into()
-        ));
-
-        assert!(!declaration_path_matches_import(
-            &declaration_path,
-            &Path::new("other.ts").into()
-        ));
-
-        assert!(!declaration_path_matches_import(
-            &declaration_path,
-            &Path::new("/home/user/project/src/other.ts").into()
-        ));
-    }
-}

crates/edit_prediction_context/src/edit_prediction_context.rs 🔗

@@ -1,335 +1,474 @@
-mod declaration;
-mod declaration_scoring;
+use crate::assemble_excerpts::assemble_excerpts;
+use anyhow::Result;
+use collections::HashMap;
+use futures::{FutureExt, StreamExt as _, channel::mpsc, future};
+use gpui::{App, AppContext, AsyncApp, Context, Entity, EventEmitter, Task, WeakEntity};
+use language::{Anchor, Buffer, BufferSnapshot, OffsetRangeExt as _, Point, ToOffset as _};
+use project::{LocationLink, Project, ProjectPath};
+use smallvec::SmallVec;
+use std::{
+    collections::hash_map,
+    ops::Range,
+    path::Path,
+    sync::Arc,
+    time::{Duration, Instant},
+};
+use util::{RangeExt as _, ResultExt};
+
+mod assemble_excerpts;
+#[cfg(test)]
+mod edit_prediction_context_tests;
 mod excerpt;
-mod imports;
-mod outline;
-mod reference;
-mod syntax_index;
-pub mod text_similarity;
+#[cfg(test)]
+mod fake_definition_lsp;
 
-use std::{path::Path, sync::Arc};
+pub use cloud_llm_client::predict_edits_v3::Line;
+pub use excerpt::{EditPredictionExcerpt, EditPredictionExcerptOptions, EditPredictionExcerptText};
+pub use zeta_prompt::{RelatedExcerpt, RelatedFile};
 
-use cloud_llm_client::predict_edits_v3;
-use collections::HashMap;
-use gpui::{App, AppContext as _, Entity, Task};
-use language::BufferSnapshot;
-use text::{Point, ToOffset as _};
-
-pub use declaration::*;
-pub use declaration_scoring::*;
-pub use excerpt::*;
-pub use imports::*;
-pub use reference::*;
-pub use syntax_index::*;
-
-pub use predict_edits_v3::Line;
-
-#[derive(Clone, Debug, PartialEq)]
-pub struct EditPredictionContextOptions {
-    pub use_imports: bool,
-    pub excerpt: EditPredictionExcerptOptions,
-    pub score: EditPredictionScoreOptions,
-    pub max_retrieved_declarations: u8,
+const IDENTIFIER_LINE_COUNT: u32 = 3;
+
+pub struct RelatedExcerptStore {
+    project: WeakEntity<Project>,
+    related_files: Arc<[RelatedFile]>,
+    related_file_buffers: Vec<Entity<Buffer>>,
+    cache: HashMap<Identifier, Arc<CacheEntry>>,
+    update_tx: mpsc::UnboundedSender<(Entity<Buffer>, Anchor)>,
+    identifier_line_count: u32,
+}
+
+pub enum RelatedExcerptStoreEvent {
+    StartedRefresh,
+    FinishedRefresh {
+        cache_hit_count: usize,
+        cache_miss_count: usize,
+        mean_definition_latency: Duration,
+        max_definition_latency: Duration,
+    },
+}
+
+#[derive(Clone, Debug, PartialEq, Eq, Hash)]
+struct Identifier {
+    pub name: String,
+    pub range: Range<Anchor>,
+}
+
+enum DefinitionTask {
+    CacheHit(Arc<CacheEntry>),
+    CacheMiss(Task<Result<Option<Vec<LocationLink>>>>),
+}
+
+#[derive(Debug)]
+struct CacheEntry {
+    definitions: SmallVec<[CachedDefinition; 1]>,
 }
 
 #[derive(Clone, Debug)]
-pub struct EditPredictionContext {
-    pub excerpt: EditPredictionExcerpt,
-    pub excerpt_text: EditPredictionExcerptText,
-    pub cursor_point: Point,
-    pub declarations: Vec<ScoredDeclaration>,
+struct CachedDefinition {
+    path: ProjectPath,
+    buffer: Entity<Buffer>,
+    anchor_range: Range<Anchor>,
 }
 
-impl EditPredictionContext {
-    pub fn gather_context_in_background(
-        cursor_point: Point,
-        buffer: BufferSnapshot,
-        options: EditPredictionContextOptions,
-        syntax_index: Option<Entity<SyntaxIndex>>,
-        cx: &mut App,
-    ) -> Task<Option<Self>> {
-        let parent_abs_path = project::File::from_dyn(buffer.file()).and_then(|f| {
-            let mut path = f.worktree.read(cx).absolutize(&f.path);
-            if path.pop() { Some(path) } else { None }
-        });
+const DEBOUNCE_DURATION: Duration = Duration::from_millis(100);
+
+impl EventEmitter<RelatedExcerptStoreEvent> for RelatedExcerptStore {}
+
+impl RelatedExcerptStore {
+    pub fn new(project: &Entity<Project>, cx: &mut Context<Self>) -> Self {
+        let (update_tx, mut update_rx) = mpsc::unbounded::<(Entity<Buffer>, Anchor)>();
+        cx.spawn(async move |this, cx| {
+            let executor = cx.background_executor().clone();
+            while let Some((mut buffer, mut position)) = update_rx.next().await {
+                let mut timer = executor.timer(DEBOUNCE_DURATION).fuse();
+                loop {
+                    futures::select_biased! {
+                        next = update_rx.next() => {
+                            if let Some((new_buffer, new_position)) = next {
+                                buffer = new_buffer;
+                                position = new_position;
+                                timer = executor.timer(DEBOUNCE_DURATION).fuse();
+                            } else {
+                                return anyhow::Ok(());
+                            }
+                        }
+                        _ = timer => break,
+                    }
+                }
 
-        if let Some(syntax_index) = syntax_index {
-            let index_state =
-                syntax_index.read_with(cx, |index, _cx| Arc::downgrade(index.state()));
-            cx.background_spawn(async move {
-                let parent_abs_path = parent_abs_path.as_deref();
-                let index_state = index_state.upgrade()?;
-                let index_state = index_state.lock().await;
-                Self::gather_context(
-                    cursor_point,
-                    &buffer,
-                    parent_abs_path,
-                    &options,
-                    Some(&index_state),
-                )
-            })
-        } else {
-            cx.background_spawn(async move {
-                let parent_abs_path = parent_abs_path.as_deref();
-                Self::gather_context(cursor_point, &buffer, parent_abs_path, &options, None)
-            })
+                Self::fetch_excerpts(this.clone(), buffer, position, cx).await?;
+            }
+            anyhow::Ok(())
+        })
+        .detach_and_log_err(cx);
+
+        RelatedExcerptStore {
+            project: project.downgrade(),
+            update_tx,
+            related_files: Vec::new().into(),
+            related_file_buffers: Vec::new(),
+            cache: Default::default(),
+            identifier_line_count: IDENTIFIER_LINE_COUNT,
         }
     }
 
-    pub fn gather_context(
-        cursor_point: Point,
-        buffer: &BufferSnapshot,
-        parent_abs_path: Option<&Path>,
-        options: &EditPredictionContextOptions,
-        index_state: Option<&SyntaxIndexState>,
-    ) -> Option<Self> {
-        let imports = if options.use_imports {
-            Imports::gather(&buffer, parent_abs_path)
-        } else {
-            Imports::default()
-        };
-        Self::gather_context_with_references_fn(
-            cursor_point,
-            buffer,
-            &imports,
-            options,
-            index_state,
-            references_in_excerpt,
-        )
+    pub fn set_identifier_line_count(&mut self, count: u32) {
+        self.identifier_line_count = count;
     }
 
-    pub fn gather_context_with_references_fn(
-        cursor_point: Point,
-        buffer: &BufferSnapshot,
-        imports: &Imports,
-        options: &EditPredictionContextOptions,
-        index_state: Option<&SyntaxIndexState>,
-        get_references: impl FnOnce(
-            &EditPredictionExcerpt,
-            &EditPredictionExcerptText,
-            &BufferSnapshot,
-        ) -> HashMap<Identifier, Vec<Reference>>,
-    ) -> Option<Self> {
-        let excerpt = EditPredictionExcerpt::select_from_buffer(
-            cursor_point,
-            buffer,
-            &options.excerpt,
-            index_state,
-        )?;
-        let excerpt_text = excerpt.text(buffer);
-
-        let declarations = if options.max_retrieved_declarations > 0
-            && let Some(index_state) = index_state
-        {
-            let excerpt_occurrences =
-                text_similarity::Occurrences::within_string(&excerpt_text.body);
-
-            let adjacent_start = Point::new(cursor_point.row.saturating_sub(2), 0);
-            let adjacent_end = Point::new(cursor_point.row + 1, 0);
-            let adjacent_occurrences = text_similarity::Occurrences::within_string(
-                &buffer
-                    .text_for_range(adjacent_start..adjacent_end)
-                    .collect::<String>(),
-            );
+    pub fn refresh(&mut self, buffer: Entity<Buffer>, position: Anchor, _: &mut Context<Self>) {
+        self.update_tx.unbounded_send((buffer, position)).ok();
+    }
 
-            let cursor_offset_in_file = cursor_point.to_offset(buffer);
+    pub fn related_files(&self) -> Arc<[RelatedFile]> {
+        self.related_files.clone()
+    }
 
-            let references = get_references(&excerpt, &excerpt_text, buffer);
+    pub fn related_files_with_buffers(
+        &self,
+    ) -> impl Iterator<Item = (RelatedFile, Entity<Buffer>)> {
+        self.related_files
+            .iter()
+            .cloned()
+            .zip(self.related_file_buffers.iter().cloned())
+    }
 
-            let mut declarations = scored_declarations(
-                &options.score,
-                &index_state,
-                &excerpt,
-                &excerpt_occurrences,
-                &adjacent_occurrences,
-                &imports,
-                references,
-                cursor_offset_in_file,
-                buffer,
-            );
-            // TODO [zeta2] if we need this when we ship, we should probably do it in a smarter way
-            declarations.truncate(options.max_retrieved_declarations as usize);
-            declarations
-        } else {
-            vec![]
+    pub fn set_related_files(&mut self, files: Vec<RelatedFile>) {
+        self.related_files = files.into();
+    }
+
+    async fn fetch_excerpts(
+        this: WeakEntity<Self>,
+        buffer: Entity<Buffer>,
+        position: Anchor,
+        cx: &mut AsyncApp,
+    ) -> Result<()> {
+        let (project, snapshot, identifier_line_count) = this.read_with(cx, |this, cx| {
+            (
+                this.project.upgrade(),
+                buffer.read(cx).snapshot(),
+                this.identifier_line_count,
+            )
+        })?;
+        let Some(project) = project else {
+            return Ok(());
         };
 
-        Some(Self {
-            excerpt,
-            excerpt_text,
-            cursor_point,
-            declarations,
-        })
-    }
-}
+        let file = snapshot.file().cloned();
+        if let Some(file) = &file {
+            log::debug!("retrieving_context buffer:{}", file.path().as_unix_str());
+        }
 
-#[cfg(test)]
-mod tests {
-    use super::*;
-    use std::sync::Arc;
-
-    use gpui::{Entity, TestAppContext};
-    use indoc::indoc;
-    use language::{Language, LanguageConfig, LanguageId, LanguageMatcher, tree_sitter_rust};
-    use project::{FakeFs, Project};
-    use serde_json::json;
-    use settings::SettingsStore;
-    use util::path;
-
-    use crate::{EditPredictionExcerptOptions, SyntaxIndex};
-
-    #[gpui::test]
-    async fn test_call_site(cx: &mut TestAppContext) {
-        let (project, index, _rust_lang_id) = init_test(cx).await;
-
-        let buffer = project
-            .update(cx, |project, cx| {
-                let project_path = project.find_project_path("c.rs", cx).unwrap();
-                project.open_buffer(project_path, cx)
-            })
-            .await
-            .unwrap();
-
-        cx.run_until_parked();
-
-        // first process_data call site
-        let cursor_point = language::Point::new(8, 21);
-        let buffer_snapshot = buffer.read_with(cx, |buffer, _| buffer.snapshot());
-
-        let context = cx
-            .update(|cx| {
-                EditPredictionContext::gather_context_in_background(
-                    cursor_point,
-                    buffer_snapshot,
-                    EditPredictionContextOptions {
-                        use_imports: true,
-                        excerpt: EditPredictionExcerptOptions {
-                            max_bytes: 60,
-                            min_bytes: 10,
-                            target_before_cursor_over_total_bytes: 0.5,
-                        },
-                        score: EditPredictionScoreOptions {
-                            omit_excerpt_overlaps: true,
-                        },
-                        max_retrieved_declarations: u8::MAX,
-                    },
-                    Some(index.clone()),
-                    cx,
-                )
+        this.update(cx, |_, cx| {
+            cx.emit(RelatedExcerptStoreEvent::StartedRefresh);
+        })?;
+
+        let identifiers = cx
+            .background_spawn(async move {
+                identifiers_for_position(&snapshot, position, identifier_line_count)
             })
-            .await
-            .unwrap();
+            .await;
+
+        let async_cx = cx.clone();
+        let start_time = Instant::now();
+        let futures = this.update(cx, |this, cx| {
+            identifiers
+                .into_iter()
+                .filter_map(|identifier| {
+                    let task = if let Some(entry) = this.cache.get(&identifier) {
+                        DefinitionTask::CacheHit(entry.clone())
+                    } else {
+                        DefinitionTask::CacheMiss(
+                            this.project
+                                .update(cx, |project, cx| {
+                                    project.definitions(&buffer, identifier.range.start, cx)
+                                })
+                                .ok()?,
+                        )
+                    };
+
+                    let cx = async_cx.clone();
+                    let project = project.clone();
+                    Some(async move {
+                        match task {
+                            DefinitionTask::CacheHit(cache_entry) => {
+                                Some((identifier, cache_entry, None))
+                            }
+                            DefinitionTask::CacheMiss(task) => {
+                                let locations = task.await.log_err()??;
+                                let duration = start_time.elapsed();
+                                cx.update(|cx| {
+                                    (
+                                        identifier,
+                                        Arc::new(CacheEntry {
+                                            definitions: locations
+                                                .into_iter()
+                                                .filter_map(|location| {
+                                                    process_definition(location, &project, cx)
+                                                })
+                                                .collect(),
+                                        }),
+                                        Some(duration),
+                                    )
+                                })
+                                .ok()
+                            }
+                        }
+                    })
+                })
+                .collect::<Vec<_>>()
+        })?;
+
+        let mut cache_hit_count = 0;
+        let mut cache_miss_count = 0;
+        let mut mean_definition_latency = Duration::ZERO;
+        let mut max_definition_latency = Duration::ZERO;
+        let mut new_cache = HashMap::default();
+        new_cache.reserve(futures.len());
+        for (identifier, entry, duration) in future::join_all(futures).await.into_iter().flatten() {
+            new_cache.insert(identifier, entry);
+            if let Some(duration) = duration {
+                cache_miss_count += 1;
+                mean_definition_latency += duration;
+                max_definition_latency = max_definition_latency.max(duration);
+            } else {
+                cache_hit_count += 1;
+            }
+        }
+        mean_definition_latency /= cache_miss_count.max(1) as u32;
 
-        let mut snippet_identifiers = context
-            .declarations
-            .iter()
-            .map(|snippet| snippet.identifier.name.as_ref())
-            .collect::<Vec<_>>();
-        snippet_identifiers.sort();
-        assert_eq!(snippet_identifiers, vec!["main", "process_data"]);
-        drop(buffer);
-    }
+        let (new_cache, related_files, related_file_buffers) =
+            rebuild_related_files(&project, new_cache, cx).await?;
 
-    async fn init_test(
-        cx: &mut TestAppContext,
-    ) -> (Entity<Project>, Entity<SyntaxIndex>, LanguageId) {
-        cx.update(|cx| {
-            let settings_store = SettingsStore::test(cx);
-            cx.set_global(settings_store);
-        });
+        if let Some(file) = &file {
+            log::debug!(
+                "finished retrieving context buffer:{}, latency:{:?}",
+                file.path().as_unix_str(),
+                start_time.elapsed()
+            );
+        }
 
-        let fs = FakeFs::new(cx.executor());
-        fs.insert_tree(
-            path!("/root"),
-            json!({
-                "a.rs": indoc! {r#"
-                    fn main() {
-                        let x = 1;
-                        let y = 2;
-                        let z = add(x, y);
-                        println!("Result: {}", z);
-                    }
+        this.update(cx, |this, cx| {
+            this.cache = new_cache;
+            this.related_files = related_files.into();
+            this.related_file_buffers = related_file_buffers;
+            cx.emit(RelatedExcerptStoreEvent::FinishedRefresh {
+                cache_hit_count,
+                cache_miss_count,
+                mean_definition_latency,
+                max_definition_latency,
+            });
+        })?;
+
+        anyhow::Ok(())
+    }
+}
 
-                    fn add(a: i32, b: i32) -> i32 {
-                        a + b
-                    }
-                "#},
-                "b.rs": indoc! {"
-                    pub struct Config {
-                        pub name: String,
-                        pub value: i32,
+async fn rebuild_related_files(
+    project: &Entity<Project>,
+    new_entries: HashMap<Identifier, Arc<CacheEntry>>,
+    cx: &mut AsyncApp,
+) -> Result<(
+    HashMap<Identifier, Arc<CacheEntry>>,
+    Vec<RelatedFile>,
+    Vec<Entity<Buffer>>,
+)> {
+    let mut snapshots = HashMap::default();
+    let mut worktree_root_names = HashMap::default();
+    for entry in new_entries.values() {
+        for definition in &entry.definitions {
+            if let hash_map::Entry::Vacant(e) = snapshots.entry(definition.buffer.entity_id()) {
+                definition
+                    .buffer
+                    .read_with(cx, |buffer, _| buffer.parsing_idle())?
+                    .await;
+                e.insert(
+                    definition
+                        .buffer
+                        .read_with(cx, |buffer, _| buffer.snapshot())?,
+                );
+            }
+            let worktree_id = definition.path.worktree_id;
+            if let hash_map::Entry::Vacant(e) =
+                worktree_root_names.entry(definition.path.worktree_id)
+            {
+                project.read_with(cx, |project, cx| {
+                    if let Some(worktree) = project.worktree_for_id(worktree_id, cx) {
+                        e.insert(worktree.read(cx).root_name().as_unix_str().to_string());
                     }
+                })?;
+            }
+        }
+    }
 
-                    impl Config {
-                        pub fn new(name: String, value: i32) -> Self {
-                            Config { name, value }
-                        }
-                    }
-                "},
-                "c.rs": indoc! {r#"
-                    use std::collections::HashMap;
-
-                    fn main() {
-                        let args: Vec<String> = std::env::args().collect();
-                        let data: Vec<i32> = args[1..]
-                            .iter()
-                            .filter_map(|s| s.parse().ok())
-                            .collect();
-                        let result = process_data(data);
-                        println!("{:?}", result);
-                    }
+    Ok(cx
+        .background_spawn(async move {
+            let mut files = Vec::new();
+            let mut ranges_by_buffer = HashMap::<_, Vec<Range<Point>>>::default();
+            let mut paths_by_buffer = HashMap::default();
+            for entry in new_entries.values() {
+                for definition in &entry.definitions {
+                    let Some(snapshot) = snapshots.get(&definition.buffer.entity_id()) else {
+                        continue;
+                    };
+                    paths_by_buffer.insert(definition.buffer.entity_id(), definition.path.clone());
+                    ranges_by_buffer
+                        .entry(definition.buffer.clone())
+                        .or_default()
+                        .push(definition.anchor_range.to_point(snapshot));
+                }
+            }
+
+            for (buffer, ranges) in ranges_by_buffer {
+                let Some(snapshot) = snapshots.get(&buffer.entity_id()) else {
+                    continue;
+                };
+                let Some(project_path) = paths_by_buffer.get(&buffer.entity_id()) else {
+                    continue;
+                };
+                let excerpts = assemble_excerpts(snapshot, ranges);
+                let Some(root_name) = worktree_root_names.get(&project_path.worktree_id) else {
+                    continue;
+                };
+
+                let path = Path::new(&format!(
+                    "{}/{}",
+                    root_name,
+                    project_path.path.as_unix_str()
+                ))
+                .into();
+
+                files.push((
+                    buffer,
+                    RelatedFile {
+                        path,
+                        excerpts,
+                        max_row: snapshot.max_point().row,
+                    },
+                ));
+            }
 
-                    fn process_data(data: Vec<i32>) -> HashMap<i32, usize> {
-                        let mut counts = HashMap::new();
-                        for value in data {
-                            *counts.entry(value).or_insert(0) += 1;
-                        }
-                        counts
-                    }
+            files.sort_by_key(|(_, file)| file.path.clone());
+            let (related_buffers, related_files) = files.into_iter().unzip();
 
-                    #[cfg(test)]
-                    mod tests {
-                        use super::*;
+            (new_entries, related_files, related_buffers)
+        })
+        .await)
+}
 
-                        #[test]
-                        fn test_process_data() {
-                            let data = vec![1, 2, 2, 3];
-                            let result = process_data(data);
-                            assert_eq!(result.get(&2), Some(&2));
-                        }
-                    }
-                "#}
-            }),
-        )
-        .await;
-        let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
-        let language_registry = project.read_with(cx, |project, _| project.languages().clone());
-        let lang = rust_lang();
-        let lang_id = lang.id();
-        language_registry.add(Arc::new(lang));
-
-        let file_indexing_parallelism = 2;
-        let index = cx.new(|cx| SyntaxIndex::new(&project, file_indexing_parallelism, cx));
-        cx.run_until_parked();
-
-        (project, index, lang_id)
+const MAX_TARGET_LEN: usize = 128;
+
+fn process_definition(
+    location: LocationLink,
+    project: &Entity<Project>,
+    cx: &mut App,
+) -> Option<CachedDefinition> {
+    let buffer = location.target.buffer.read(cx);
+    let anchor_range = location.target.range;
+    let file = buffer.file()?;
+    let worktree = project.read(cx).worktree_for_id(file.worktree_id(cx), cx)?;
+    if worktree.read(cx).is_single_file() {
+        return None;
     }
 
-    fn rust_lang() -> Language {
-        Language::new(
-            LanguageConfig {
-                name: "Rust".into(),
-                matcher: LanguageMatcher {
-                    path_suffixes: vec!["rs".to_string()],
-                    ..Default::default()
-                },
-                ..Default::default()
-            },
-            Some(tree_sitter_rust::LANGUAGE.into()),
-        )
-        .with_highlights_query(include_str!("../../languages/src/rust/highlights.scm"))
-        .unwrap()
-        .with_outline_query(include_str!("../../languages/src/rust/outline.scm"))
-        .unwrap()
+    // If the target range is large, it likely means we requested the definition of an entire module.
+    // For individual definitions, the target range should be small as it only covers the symbol.
+    let buffer = location.target.buffer.read(cx);
+    let target_len = anchor_range.to_offset(&buffer).len();
+    if target_len > MAX_TARGET_LEN {
+        return None;
     }
+
+    Some(CachedDefinition {
+        path: ProjectPath {
+            worktree_id: file.worktree_id(cx),
+            path: file.path().clone(),
+        },
+        buffer: location.target.buffer,
+        anchor_range,
+    })
+}
+
+/// Gets all of the identifiers that are present in the given line, and its containing
+/// outline items.
+fn identifiers_for_position(
+    buffer: &BufferSnapshot,
+    position: Anchor,
+    identifier_line_count: u32,
+) -> Vec<Identifier> {
+    let offset = position.to_offset(buffer);
+    let point = buffer.offset_to_point(offset);
+
+    // Search for identifiers on lines adjacent to the cursor.
+    let start = Point::new(point.row.saturating_sub(identifier_line_count), 0);
+    let end = Point::new(point.row + identifier_line_count + 1, 0).min(buffer.max_point());
+    let line_range = start..end;
+    let mut ranges = vec![line_range.to_offset(&buffer)];
+
+    // Search for identifiers mentioned in headers/signatures of containing outline items.
+    let outline_items = buffer.outline_items_as_offsets_containing(offset..offset, false, None);
+    for item in outline_items {
+        if let Some(body_range) = item.body_range(&buffer) {
+            ranges.push(item.range.start..body_range.start.to_offset(&buffer));
+        } else {
+            ranges.push(item.range.clone());
+        }
+    }
+
+    ranges.sort_by(|a, b| a.start.cmp(&b.start).then(b.end.cmp(&a.end)));
+    ranges.dedup_by(|a, b| {
+        if a.start <= b.end {
+            b.start = b.start.min(a.start);
+            b.end = b.end.max(a.end);
+            true
+        } else {
+            false
+        }
+    });
+
+    let mut identifiers = Vec::new();
+    let outer_range =
+        ranges.first().map_or(0, |r| r.start)..ranges.last().map_or(buffer.len(), |r| r.end);
+
+    let mut captures = buffer
+        .syntax
+        .captures(outer_range.clone(), &buffer.text, |grammar| {
+            grammar
+                .highlights_config
+                .as_ref()
+                .map(|config| &config.query)
+        });
+
+    for range in ranges {
+        captures.set_byte_range(range.start..outer_range.end);
+
+        let mut last_range = None;
+        while let Some(capture) = captures.peek() {
+            let node_range = capture.node.byte_range();
+            if node_range.start > range.end {
+                break;
+            }
+            let config = captures.grammars()[capture.grammar_index]
+                .highlights_config
+                .as_ref();
+
+            if let Some(config) = config
+                && config.identifier_capture_indices.contains(&capture.index)
+                && range.contains_inclusive(&node_range)
+                && Some(&node_range) != last_range.as_ref()
+            {
+                let name = buffer.text_for_range(node_range.clone()).collect();
+                identifiers.push(Identifier {
+                    range: buffer.anchor_after(node_range.start)
+                        ..buffer.anchor_before(node_range.end),
+                    name,
+                });
+                last_range = Some(node_range);
+            }
+
+            captures.advance();
+        }
+    }
+
+    identifiers
 }

crates/edit_prediction_context/src/edit_prediction_context_tests.rs 🔗

@@ -0,0 +1,510 @@
+use super::*;
+use futures::channel::mpsc::UnboundedReceiver;
+use gpui::TestAppContext;
+use indoc::indoc;
+use language::{Point, ToPoint as _, rust_lang};
+use lsp::FakeLanguageServer;
+use project::{FakeFs, LocationLink, Project};
+use serde_json::json;
+use settings::SettingsStore;
+use std::fmt::Write as _;
+use util::{path, test::marked_text_ranges};
+
+#[gpui::test]
+async fn test_edit_prediction_context(cx: &mut TestAppContext) {
+    init_test(cx);
+    let fs = FakeFs::new(cx.executor());
+    fs.insert_tree(path!("/root"), test_project_1()).await;
+
+    let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
+    let mut servers = setup_fake_lsp(&project, cx);
+
+    let (buffer, _handle) = project
+        .update(cx, |project, cx| {
+            project.open_local_buffer_with_lsp(path!("/root/src/main.rs"), cx)
+        })
+        .await
+        .unwrap();
+
+    let _server = servers.next().await.unwrap();
+    cx.run_until_parked();
+
+    let related_excerpt_store = cx.new(|cx| RelatedExcerptStore::new(&project, cx));
+    related_excerpt_store.update(cx, |store, cx| {
+        let position = {
+            let buffer = buffer.read(cx);
+            let offset = buffer.text().find("todo").unwrap();
+            buffer.anchor_before(offset)
+        };
+
+        store.set_identifier_line_count(0);
+        store.refresh(buffer.clone(), position, cx);
+    });
+
+    cx.executor().advance_clock(DEBOUNCE_DURATION);
+    related_excerpt_store.update(cx, |store, _| {
+        let excerpts = store.related_files();
+        assert_related_files(
+            &excerpts,
+            &[
+                (
+                    "root/src/company.rs",
+                    &[indoc! {"
+                        pub struct Company {
+                            owner: Arc<Person>,
+                            address: Address,
+                        }"}],
+                ),
+                (
+                    "root/src/main.rs",
+                    &[
+                        indoc! {"
+                        pub struct Session {
+                            company: Arc<Company>,
+                        }
+
+                        impl Session {
+                            pub fn set_company(&mut self, company: Arc<Company>) {"},
+                        indoc! {"
+                            }
+                        }"},
+                    ],
+                ),
+                (
+                    "root/src/person.rs",
+                    &[
+                        indoc! {"
+                        impl Person {
+                            pub fn get_first_name(&self) -> &str {
+                                &self.first_name
+                            }"},
+                        "}",
+                    ],
+                ),
+            ],
+        );
+    });
+}
+
+#[gpui::test]
+fn test_assemble_excerpts(cx: &mut TestAppContext) {
+    let table = [
+        (
+            indoc! {r#"
+                struct User {
+                    first_name: String,
+                    «last_name»: String,
+                    age: u32,
+                    email: String,
+                    create_at: Instant,
+                }
+
+                impl User {
+                    pub fn first_name(&self) -> String {
+                        self.first_name.clone()
+                    }
+
+                    pub fn full_name(&self) -> String {
+                «        format!("{} {}", self.first_name, self.last_name)
+                »    }
+                }
+            "#},
+            indoc! {r#"
+                struct User {
+                    first_name: String,
+                    last_name: String,
+                …
+                }
+
+                impl User {
+                …
+                    pub fn full_name(&self) -> String {
+                        format!("{} {}", self.first_name, self.last_name)
+                    }
+                }
+            "#},
+        ),
+        (
+            indoc! {r#"
+                struct «User» {
+                    first_name: String,
+                    last_name: String,
+                    age: u32,
+                }
+
+                impl User {
+                    // methods
+                }
+            "#},
+            indoc! {r#"
+                struct User {
+                    first_name: String,
+                    last_name: String,
+                    age: u32,
+                }
+                …
+            "#},
+        ),
+        (
+            indoc! {r#"
+                trait «FooProvider» {
+                    const NAME: &'static str;
+
+                    fn provide_foo(&self, id: usize) -> Foo;
+
+                    fn provide_foo_batched(&self, ids: &[usize]) -> Vec<Foo> {
+                            ids.iter()
+                            .map(|id| self.provide_foo(*id))
+                            .collect()
+                    }
+
+                    fn sync(&self);
+                }
+                "#
+            },
+            indoc! {r#"
+                trait FooProvider {
+                    const NAME: &'static str;
+
+                    fn provide_foo(&self, id: usize) -> Foo;
+
+                    fn provide_foo_batched(&self, ids: &[usize]) -> Vec<Foo> {
+                …
+                    }
+
+                    fn sync(&self);
+                }
+            "#},
+        ),
+        (
+            indoc! {r#"
+                trait «Something» {
+                    fn method1(&self, id: usize) -> Foo;
+
+                    fn method2(&self, ids: &[usize]) -> Vec<Foo> {
+                            struct Helper1 {
+                            field1: usize,
+                            }
+
+                            struct Helper2 {
+                            field2: usize,
+                            }
+
+                            struct Helper3 {
+                            filed2: usize,
+                        }
+                    }
+
+                    fn sync(&self);
+                }
+                "#
+            },
+            indoc! {r#"
+                trait Something {
+                    fn method1(&self, id: usize) -> Foo;
+
+                    fn method2(&self, ids: &[usize]) -> Vec<Foo> {
+                …
+                    }
+
+                    fn sync(&self);
+                }
+            "#},
+        ),
+    ];
+
+    for (input, expected_output) in table {
+        let (input, ranges) = marked_text_ranges(&input, false);
+        let buffer = cx.new(|cx| Buffer::local(input, cx).with_language(rust_lang(), cx));
+        buffer.read_with(cx, |buffer, _cx| {
+            let ranges: Vec<Range<Point>> = ranges
+                .into_iter()
+                .map(|range| range.to_point(&buffer))
+                .collect();
+
+            let excerpts = assemble_excerpts(&buffer.snapshot(), ranges);
+
+            let output = format_excerpts(buffer, &excerpts);
+            assert_eq!(output, expected_output);
+        });
+    }
+}
+
+#[gpui::test]
+async fn test_fake_definition_lsp(cx: &mut TestAppContext) {
+    init_test(cx);
+
+    let fs = FakeFs::new(cx.executor());
+    fs.insert_tree(path!("/root"), test_project_1()).await;
+
+    let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
+    let mut servers = setup_fake_lsp(&project, cx);
+
+    let (buffer, _handle) = project
+        .update(cx, |project, cx| {
+            project.open_local_buffer_with_lsp(path!("/root/src/main.rs"), cx)
+        })
+        .await
+        .unwrap();
+
+    let _server = servers.next().await.unwrap();
+    cx.run_until_parked();
+
+    let buffer_text = buffer.read_with(cx, |buffer, _| buffer.text());
+
+    let definitions = project
+        .update(cx, |project, cx| {
+            let offset = buffer_text.find("Address {").unwrap();
+            project.definitions(&buffer, offset, cx)
+        })
+        .await
+        .unwrap()
+        .unwrap();
+    assert_definitions(&definitions, &["pub struct Address {"], cx);
+
+    let definitions = project
+        .update(cx, |project, cx| {
+            let offset = buffer_text.find("State::CA").unwrap();
+            project.definitions(&buffer, offset, cx)
+        })
+        .await
+        .unwrap()
+        .unwrap();
+    assert_definitions(&definitions, &["pub enum State {"], cx);
+
+    let definitions = project
+        .update(cx, |project, cx| {
+            let offset = buffer_text.find("to_string()").unwrap();
+            project.definitions(&buffer, offset, cx)
+        })
+        .await
+        .unwrap()
+        .unwrap();
+    assert_definitions(&definitions, &["pub fn to_string(&self) -> String {"], cx);
+}
+
+fn init_test(cx: &mut TestAppContext) {
+    let settings_store = cx.update(|cx| SettingsStore::test(cx));
+    cx.set_global(settings_store);
+    env_logger::try_init().ok();
+}
+
+fn setup_fake_lsp(
+    project: &Entity<Project>,
+    cx: &mut TestAppContext,
+) -> UnboundedReceiver<FakeLanguageServer> {
+    let (language_registry, fs) = project.read_with(cx, |project, _| {
+        (project.languages().clone(), project.fs().clone())
+    });
+    let language = rust_lang();
+    language_registry.add(language.clone());
+    fake_definition_lsp::register_fake_definition_server(&language_registry, language, fs)
+}
+
+fn test_project_1() -> serde_json::Value {
+    let person_rs = indoc! {r#"
+        pub struct Person {
+            first_name: String,
+            last_name: String,
+            email: String,
+            age: u32,
+        }
+
+        impl Person {
+            pub fn get_first_name(&self) -> &str {
+                &self.first_name
+            }
+
+            pub fn get_last_name(&self) -> &str {
+                &self.last_name
+            }
+
+            pub fn get_email(&self) -> &str {
+                &self.email
+            }
+
+            pub fn get_age(&self) -> u32 {
+                self.age
+            }
+        }
+    "#};
+
+    let address_rs = indoc! {r#"
+        pub struct Address {
+            street: String,
+            city: String,
+            state: State,
+            zip: u32,
+        }
+
+        pub enum State {
+            CA,
+            OR,
+            WA,
+            TX,
+            // ...
+        }
+
+        impl Address {
+            pub fn get_street(&self) -> &str {
+                &self.street
+            }
+
+            pub fn get_city(&self) -> &str {
+                &self.city
+            }
+
+            pub fn get_state(&self) -> State {
+                self.state
+            }
+
+            pub fn get_zip(&self) -> u32 {
+                self.zip
+            }
+        }
+    "#};
+
+    let company_rs = indoc! {r#"
+        use super::person::Person;
+        use super::address::Address;
+
+        pub struct Company {
+            owner: Arc<Person>,
+            address: Address,
+        }
+
+        impl Company {
+            pub fn get_owner(&self) -> &Person {
+                &self.owner
+            }
+
+            pub fn get_address(&self) -> &Address {
+                &self.address
+            }
+
+            pub fn to_string(&self) -> String {
+                format!("{} ({})", self.owner.first_name, self.address.city)
+            }
+        }
+    "#};
+
+    let main_rs = indoc! {r#"
+        use std::sync::Arc;
+        use super::person::Person;
+        use super::address::Address;
+        use super::company::Company;
+
+        pub struct Session {
+            company: Arc<Company>,
+        }
+
+        impl Session {
+            pub fn set_company(&mut self, company: Arc<Company>) {
+                self.company = company;
+                if company.owner != self.company.owner {
+                    log("new owner", company.owner.get_first_name()); todo();
+                }
+            }
+        }
+
+        fn main() {
+            let company = Company {
+                owner: Arc::new(Person {
+                    first_name: "John".to_string(),
+                    last_name: "Doe".to_string(),
+                    email: "john@example.com".to_string(),
+                    age: 30,
+                }),
+                address: Address {
+                    street: "123 Main St".to_string(),
+                    city: "Anytown".to_string(),
+                    state: State::CA,
+                    zip: 12345,
+                },
+            };
+
+            println!("Company: {}", company.to_string());
+        }
+    "#};
+
+    json!({
+        "src": {
+            "person.rs": person_rs,
+            "address.rs": address_rs,
+            "company.rs": company_rs,
+            "main.rs": main_rs,
+        },
+    })
+}
+
+fn assert_related_files(actual_files: &[RelatedFile], expected_files: &[(&str, &[&str])]) {
+    let actual_files = actual_files
+        .iter()
+        .map(|file| {
+            let excerpts = file
+                .excerpts
+                .iter()
+                .map(|excerpt| excerpt.text.to_string())
+                .collect::<Vec<_>>();
+            (file.path.to_str().unwrap(), excerpts)
+        })
+        .collect::<Vec<_>>();
+    let expected_excerpts = expected_files
+        .iter()
+        .map(|(path, texts)| {
+            (
+                *path,
+                texts
+                    .iter()
+                    .map(|line| line.to_string())
+                    .collect::<Vec<_>>(),
+            )
+        })
+        .collect::<Vec<_>>();
+    pretty_assertions::assert_eq!(actual_files, expected_excerpts)
+}
+
+fn assert_definitions(definitions: &[LocationLink], first_lines: &[&str], cx: &mut TestAppContext) {
+    let actual_first_lines = definitions
+        .iter()
+        .map(|definition| {
+            definition.target.buffer.read_with(cx, |buffer, _| {
+                let mut start = definition.target.range.start.to_point(&buffer);
+                start.column = 0;
+                let end = Point::new(start.row, buffer.line_len(start.row));
+                buffer
+                    .text_for_range(start..end)
+                    .collect::<String>()
+                    .trim()
+                    .to_string()
+            })
+        })
+        .collect::<Vec<String>>();
+
+    assert_eq!(actual_first_lines, first_lines);
+}
+
+fn format_excerpts(buffer: &Buffer, excerpts: &[RelatedExcerpt]) -> String {
+    let mut output = String::new();
+    let file_line_count = buffer.max_point().row;
+    let mut current_row = 0;
+    for excerpt in excerpts {
+        if excerpt.text.is_empty() {
+            continue;
+        }
+        if current_row < excerpt.row_range.start {
+            writeln!(&mut output, "…").unwrap();
+        }
+        current_row = excerpt.row_range.start;
+
+        for line in excerpt.text.to_string().lines() {
+            output.push_str(line);
+            output.push('\n');
+            current_row += 1;
+        }
+    }
+    if current_row < file_line_count {
+        writeln!(&mut output, "…").unwrap();
+    }
+    output
+}

crates/edit_prediction_context/src/excerpt.rs 🔗

@@ -1,11 +1,9 @@
-use language::{BufferSnapshot, LanguageId};
+use cloud_llm_client::predict_edits_v3::Line;
+use language::{BufferSnapshot, LanguageId, Point, ToOffset as _, ToPoint as _};
 use std::ops::Range;
-use text::{Point, ToOffset as _, ToPoint as _};
 use tree_sitter::{Node, TreeCursor};
 use util::RangeExt;
 
-use crate::{BufferDeclaration, Line, declaration::DeclarationId, syntax_index::SyntaxIndexState};
-
 // TODO:
 //
 // - Test parent signatures
@@ -31,19 +29,16 @@ pub struct EditPredictionExcerptOptions {
     pub target_before_cursor_over_total_bytes: f32,
 }
 
-// TODO: consider merging these
 #[derive(Debug, Clone)]
 pub struct EditPredictionExcerpt {
     pub range: Range<usize>,
     pub line_range: Range<Line>,
-    pub parent_declarations: Vec<(DeclarationId, Range<usize>)>,
     pub size: usize,
 }
 
 #[derive(Debug, Clone)]
 pub struct EditPredictionExcerptText {
     pub body: String,
-    pub parent_signatures: Vec<String>,
     pub language_id: Option<LanguageId>,
 }
 
@@ -52,17 +47,8 @@ impl EditPredictionExcerpt {
         let body = buffer
             .text_for_range(self.range.clone())
             .collect::<String>();
-        let parent_signatures = self
-            .parent_declarations
-            .iter()
-            .map(|(_, range)| buffer.text_for_range(range.clone()).collect::<String>())
-            .collect();
         let language_id = buffer.language().map(|l| l.id());
-        EditPredictionExcerptText {
-            body,
-            parent_signatures,
-            language_id,
-        }
+        EditPredictionExcerptText { body, language_id }
     }
 
     /// Selects an excerpt around a buffer position, attempting to choose logical boundaries based
@@ -79,7 +65,6 @@ impl EditPredictionExcerpt {
         query_point: Point,
         buffer: &BufferSnapshot,
         options: &EditPredictionExcerptOptions,
-        syntax_index: Option<&SyntaxIndexState>,
     ) -> Option<Self> {
         if buffer.len() <= options.max_bytes {
             log::debug!(
@@ -89,11 +74,7 @@ impl EditPredictionExcerpt {
             );
             let offset_range = 0..buffer.len();
             let line_range = Line(0)..Line(buffer.max_point().row);
-            return Some(EditPredictionExcerpt::new(
-                offset_range,
-                line_range,
-                Vec::new(),
-            ));
+            return Some(EditPredictionExcerpt::new(offset_range, line_range));
         }
 
         let query_offset = query_point.to_offset(buffer);
@@ -104,19 +85,10 @@ impl EditPredictionExcerpt {
             return None;
         }
 
-        let parent_declarations = if let Some(syntax_index) = syntax_index {
-            syntax_index
-                .buffer_declarations_containing_range(buffer.remote_id(), query_range.clone())
-                .collect()
-        } else {
-            Vec::new()
-        };
-
         let excerpt_selector = ExcerptSelector {
             query_offset,
             query_range,
             query_line_range: Line(query_line_range.start)..Line(query_line_range.end),
-            parent_declarations: &parent_declarations,
             buffer,
             options,
         };
@@ -139,20 +111,10 @@ impl EditPredictionExcerpt {
         excerpt_selector.select_lines()
     }
 
-    fn new(
-        range: Range<usize>,
-        line_range: Range<Line>,
-        parent_declarations: Vec<(DeclarationId, Range<usize>)>,
-    ) -> Self {
-        let size = range.len()
-            + parent_declarations
-                .iter()
-                .map(|(_, range)| range.len())
-                .sum::<usize>();
+    fn new(range: Range<usize>, line_range: Range<Line>) -> Self {
         Self {
+            size: range.len(),
             range,
-            parent_declarations,
-            size,
             line_range,
         }
     }
@@ -162,14 +124,7 @@ impl EditPredictionExcerpt {
             // this is an issue because parent_signature_ranges may be incorrect
             log::error!("bug: with_expanded_range called with disjoint range");
         }
-        let mut parent_declarations = Vec::with_capacity(self.parent_declarations.len());
-        for (declaration_id, range) in &self.parent_declarations {
-            if !range.contains_inclusive(&new_range) {
-                break;
-            }
-            parent_declarations.push((*declaration_id, range.clone()));
-        }
-        Self::new(new_range, new_line_range, parent_declarations)
+        Self::new(new_range, new_line_range)
     }
 
     fn parent_signatures_size(&self) -> usize {
@@ -181,7 +136,6 @@ struct ExcerptSelector<'a> {
     query_offset: usize,
     query_range: Range<usize>,
     query_line_range: Range<Line>,
-    parent_declarations: &'a [(DeclarationId, &'a BufferDeclaration)],
     buffer: &'a BufferSnapshot,
     options: &'a EditPredictionExcerptOptions,
 }
@@ -409,13 +363,7 @@ impl<'a> ExcerptSelector<'a> {
     }
 
     fn make_excerpt(&self, range: Range<usize>, line_range: Range<Line>) -> EditPredictionExcerpt {
-        let parent_declarations = self
-            .parent_declarations
-            .iter()
-            .filter(|(_, declaration)| declaration.item_range.contains_inclusive(&range))
-            .map(|(id, declaration)| (*id, declaration.signature_range.clone()))
-            .collect();
-        EditPredictionExcerpt::new(range, line_range, parent_declarations)
+        EditPredictionExcerpt::new(range, line_range)
     }
 
     /// Returns `true` if the `forward` excerpt is a better choice than the `backward` excerpt.
@@ -471,30 +419,14 @@ fn node_line_end(node: Node) -> Point {
 mod tests {
     use super::*;
     use gpui::{AppContext, TestAppContext};
-    use language::{Buffer, Language, LanguageConfig, LanguageMatcher, tree_sitter_rust};
+    use language::Buffer;
     use util::test::{generate_marked_text, marked_text_offsets_by};
 
     fn create_buffer(text: &str, cx: &mut TestAppContext) -> BufferSnapshot {
-        let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(rust_lang().into(), cx));
+        let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(language::rust_lang(), cx));
         buffer.read_with(cx, |buffer, _| buffer.snapshot())
     }
 
-    fn rust_lang() -> Language {
-        Language::new(
-            LanguageConfig {
-                name: "Rust".into(),
-                matcher: LanguageMatcher {
-                    path_suffixes: vec!["rs".to_string()],
-                    ..Default::default()
-                },
-                ..Default::default()
-            },
-            Some(tree_sitter_rust::LANGUAGE.into()),
-        )
-        .with_outline_query(include_str!("../../languages/src/rust/outline.scm"))
-        .unwrap()
-    }
-
     fn cursor_and_excerpt_range(text: &str) -> (String, usize, Range<usize>) {
         let (text, offsets) = marked_text_offsets_by(text, vec!['ˇ', '«', '»']);
         (text, offsets[&'ˇ'][0], offsets[&'«'][0]..offsets[&'»'][0])
@@ -506,9 +438,8 @@ mod tests {
         let buffer = create_buffer(&text, cx);
         let cursor_point = cursor.to_point(&buffer);
 
-        let excerpt =
-            EditPredictionExcerpt::select_from_buffer(cursor_point, &buffer, &options, None)
-                .expect("Should select an excerpt");
+        let excerpt = EditPredictionExcerpt::select_from_buffer(cursor_point, &buffer, &options)
+            .expect("Should select an excerpt");
         pretty_assertions::assert_eq!(
             generate_marked_text(&text, std::slice::from_ref(&excerpt.range), false),
             generate_marked_text(&text, &[expected_excerpt], false)

crates/edit_prediction_context/src/fake_definition_lsp.rs 🔗

@@ -0,0 +1,329 @@
+use collections::HashMap;
+use futures::channel::mpsc::UnboundedReceiver;
+use language::{Language, LanguageRegistry};
+use lsp::{
+    FakeLanguageServer, LanguageServerBinary, TextDocumentSyncCapability, TextDocumentSyncKind, Uri,
+};
+use parking_lot::Mutex;
+use project::Fs;
+use std::{ops::Range, path::PathBuf, sync::Arc};
+use tree_sitter::{Parser, QueryCursor, StreamingIterator, Tree};
+
+/// Registers a fake language server that implements go-to-definition using tree-sitter,
+/// making the assumption that all names are unique, and all variables' types are
+/// explicitly declared.
+pub fn register_fake_definition_server(
+    language_registry: &Arc<LanguageRegistry>,
+    language: Arc<Language>,
+    fs: Arc<dyn Fs>,
+) -> UnboundedReceiver<FakeLanguageServer> {
+    let index = Arc::new(Mutex::new(DefinitionIndex::new(language.clone())));
+
+    language_registry.register_fake_lsp(
+        language.name(),
+        language::FakeLspAdapter {
+            name: "fake-definition-lsp",
+            initialization_options: None,
+            prettier_plugins: Vec::new(),
+            disk_based_diagnostics_progress_token: None,
+            disk_based_diagnostics_sources: Vec::new(),
+            language_server_binary: LanguageServerBinary {
+                path: PathBuf::from("fake-definition-lsp"),
+                arguments: Vec::new(),
+                env: None,
+            },
+            capabilities: lsp::ServerCapabilities {
+                definition_provider: Some(lsp::OneOf::Left(true)),
+                text_document_sync: Some(TextDocumentSyncCapability::Kind(
+                    TextDocumentSyncKind::FULL,
+                )),
+                ..Default::default()
+            },
+            label_for_completion: None,
+            initializer: Some(Box::new({
+                move |server| {
+                    server.handle_notification::<lsp::notification::DidOpenTextDocument, _>({
+                        let index = index.clone();
+                        move |params, _cx| {
+                            index
+                                .lock()
+                                .open_buffer(params.text_document.uri, &params.text_document.text);
+                        }
+                    });
+
+                    server.handle_notification::<lsp::notification::DidCloseTextDocument, _>({
+                        let index = index.clone();
+                        let fs = fs.clone();
+                        move |params, cx| {
+                            let uri = params.text_document.uri;
+                            let path = uri.to_file_path().ok();
+                            index.lock().mark_buffer_closed(&uri);
+
+                            if let Some(path) = path {
+                                let index = index.clone();
+                                let fs = fs.clone();
+                                cx.spawn(async move |_cx| {
+                                    if let Ok(content) = fs.load(&path).await {
+                                        index.lock().index_file(uri, &content);
+                                    }
+                                })
+                                .detach();
+                            }
+                        }
+                    });
+
+                    server.handle_notification::<lsp::notification::DidChangeWatchedFiles, _>({
+                        let index = index.clone();
+                        let fs = fs.clone();
+                        move |params, cx| {
+                            let index = index.clone();
+                            let fs = fs.clone();
+                            cx.spawn(async move |_cx| {
+                                for event in params.changes {
+                                    if index.lock().is_buffer_open(&event.uri) {
+                                        continue;
+                                    }
+
+                                    match event.typ {
+                                        lsp::FileChangeType::DELETED => {
+                                            index.lock().remove_definitions_for_file(&event.uri);
+                                        }
+                                        lsp::FileChangeType::CREATED
+                                        | lsp::FileChangeType::CHANGED => {
+                                            if let Some(path) = event.uri.to_file_path().ok() {
+                                                if let Ok(content) = fs.load(&path).await {
+                                                    index.lock().index_file(event.uri, &content);
+                                                }
+                                            }
+                                        }
+                                        _ => {}
+                                    }
+                                }
+                            })
+                            .detach();
+                        }
+                    });
+
+                    server.handle_notification::<lsp::notification::DidChangeTextDocument, _>({
+                        let index = index.clone();
+                        move |params, _cx| {
+                            if let Some(change) = params.content_changes.into_iter().last() {
+                                index
+                                    .lock()
+                                    .index_file(params.text_document.uri, &change.text);
+                            }
+                        }
+                    });
+
+                    server.handle_notification::<lsp::notification::DidChangeWorkspaceFolders, _>(
+                        {
+                            let index = index.clone();
+                            let fs = fs.clone();
+                            move |params, cx| {
+                                let index = index.clone();
+                                let fs = fs.clone();
+                                let files = fs.as_fake().files();
+                                cx.spawn(async move |_cx| {
+                                    for folder in params.event.added {
+                                        let Ok(path) = folder.uri.to_file_path() else {
+                                            continue;
+                                        };
+                                        for file in &files {
+                                            if let Some(uri) = Uri::from_file_path(&file).ok()
+                                                && file.starts_with(&path)
+                                                && let Ok(content) = fs.load(&file).await
+                                            {
+                                                index.lock().index_file(uri, &content);
+                                            }
+                                        }
+                                    }
+                                })
+                                .detach();
+                            }
+                        },
+                    );
+
+                    server.set_request_handler::<lsp::request::GotoDefinition, _, _>({
+                        let index = index.clone();
+                        move |params, _cx| {
+                            let result = index.lock().get_definitions(
+                                params.text_document_position_params.text_document.uri,
+                                params.text_document_position_params.position,
+                            );
+                            async move { Ok(result) }
+                        }
+                    });
+                }
+            })),
+        },
+    )
+}
+
+struct DefinitionIndex {
+    language: Arc<Language>,
+    definitions: HashMap<String, Vec<lsp::Location>>,
+    files: HashMap<Uri, FileEntry>,
+}
+
+#[derive(Debug)]
+struct FileEntry {
+    contents: String,
+    is_open_in_buffer: bool,
+}
+
+impl DefinitionIndex {
+    fn new(language: Arc<Language>) -> Self {
+        Self {
+            language,
+            definitions: HashMap::default(),
+            files: HashMap::default(),
+        }
+    }
+
+    fn remove_definitions_for_file(&mut self, uri: &Uri) {
+        self.definitions.retain(|_, locations| {
+            locations.retain(|loc| &loc.uri != uri);
+            !locations.is_empty()
+        });
+        self.files.remove(uri);
+    }
+
+    fn open_buffer(&mut self, uri: Uri, content: &str) {
+        self.index_file_inner(uri, content, true);
+    }
+
+    fn mark_buffer_closed(&mut self, uri: &Uri) {
+        if let Some(entry) = self.files.get_mut(uri) {
+            entry.is_open_in_buffer = false;
+        }
+    }
+
+    fn is_buffer_open(&self, uri: &Uri) -> bool {
+        self.files
+            .get(uri)
+            .map(|entry| entry.is_open_in_buffer)
+            .unwrap_or(false)
+    }
+
+    fn index_file(&mut self, uri: Uri, content: &str) {
+        self.index_file_inner(uri, content, false);
+    }
+
+    fn index_file_inner(&mut self, uri: Uri, content: &str, is_open_in_buffer: bool) -> Option<()> {
+        self.remove_definitions_for_file(&uri);
+        let grammar = self.language.grammar()?;
+        let outline_config = grammar.outline_config.as_ref()?;
+        let mut parser = Parser::new();
+        parser.set_language(&grammar.ts_language).ok()?;
+        let tree = parser.parse(content, None)?;
+        let declarations = extract_declarations_from_tree(&tree, content, outline_config);
+        for (name, byte_range) in declarations {
+            let range = byte_range_to_lsp_range(content, byte_range);
+            let location = lsp::Location {
+                uri: uri.clone(),
+                range,
+            };
+            self.definitions
+                .entry(name)
+                .or_insert_with(Vec::new)
+                .push(location);
+        }
+        self.files.insert(
+            uri,
+            FileEntry {
+                contents: content.to_string(),
+                is_open_in_buffer,
+            },
+        );
+
+        Some(())
+    }
+
+    fn get_definitions(
+        &mut self,
+        uri: Uri,
+        position: lsp::Position,
+    ) -> Option<lsp::GotoDefinitionResponse> {
+        let entry = self.files.get(&uri)?;
+        let name = word_at_position(&entry.contents, position)?;
+        let locations = self.definitions.get(name).cloned()?;
+        Some(lsp::GotoDefinitionResponse::Array(locations))
+    }
+}
+
+fn extract_declarations_from_tree(
+    tree: &Tree,
+    content: &str,
+    outline_config: &language::OutlineConfig,
+) -> Vec<(String, Range<usize>)> {
+    let mut cursor = QueryCursor::new();
+    let mut declarations = Vec::new();
+    let mut matches = cursor.matches(&outline_config.query, tree.root_node(), content.as_bytes());
+    while let Some(query_match) = matches.next() {
+        let mut name_range: Option<Range<usize>> = None;
+        let mut has_item_range = false;
+
+        for capture in query_match.captures {
+            let range = capture.node.byte_range();
+            if capture.index == outline_config.name_capture_ix {
+                name_range = Some(range);
+            } else if capture.index == outline_config.item_capture_ix {
+                has_item_range = true;
+            }
+        }
+
+        if let Some(name_range) = name_range
+            && has_item_range
+        {
+            let name = content[name_range.clone()].to_string();
+            if declarations.iter().any(|(n, _)| n == &name) {
+                continue;
+            }
+            declarations.push((name, name_range));
+        }
+    }
+    declarations
+}
+
+fn byte_range_to_lsp_range(content: &str, byte_range: Range<usize>) -> lsp::Range {
+    let start = byte_offset_to_position(content, byte_range.start);
+    let end = byte_offset_to_position(content, byte_range.end);
+    lsp::Range { start, end }
+}
+
+fn byte_offset_to_position(content: &str, offset: usize) -> lsp::Position {
+    let mut line = 0;
+    let mut character = 0;
+    let mut current_offset = 0;
+    for ch in content.chars() {
+        if current_offset >= offset {
+            break;
+        }
+        if ch == '\n' {
+            line += 1;
+            character = 0;
+        } else {
+            character += 1;
+        }
+        current_offset += ch.len_utf8();
+    }
+    lsp::Position { line, character }
+}
+
+fn word_at_position(content: &str, position: lsp::Position) -> Option<&str> {
+    let mut lines = content.lines();
+    let line = lines.nth(position.line as usize)?;
+    let column = position.character as usize;
+    if column > line.len() {
+        return None;
+    }
+    let start = line[..column]
+        .rfind(|c: char| !c.is_alphanumeric() && c != '_')
+        .map(|i| i + 1)
+        .unwrap_or(0);
+    let end = line[column..]
+        .find(|c: char| !c.is_alphanumeric() && c != '_')
+        .map(|i| i + column)
+        .unwrap_or(line.len());
+    Some(&line[start..end]).filter(|word| !word.is_empty())
+}

crates/edit_prediction_context/src/imports.rs 🔗

@@ -1,1319 +0,0 @@
-use collections::HashMap;
-use language::BufferSnapshot;
-use language::ImportsConfig;
-use language::Language;
-use std::ops::Deref;
-use std::path::Path;
-use std::sync::Arc;
-use std::{borrow::Cow, ops::Range};
-use text::OffsetRangeExt as _;
-use util::RangeExt;
-use util::paths::PathStyle;
-
-use crate::Identifier;
-use crate::text_similarity::Occurrences;
-
-// TODO: Write documentation for extension authors. The @import capture must match before or in the
-// same pattern as all all captures it contains
-
-// Future improvements to consider:
-//
-// * Distinguish absolute vs relative paths in captures. `#include "maths.h"` is relative whereas
-// `#include <maths.h>` is not.
-//
-// * Provide the name used when importing whole modules (see tests with "named_module" in the name).
-// To be useful, will require parsing of identifier qualification.
-//
-// * Scoping for imports that aren't at the top level
-//
-// * Only scan a prefix of the file, when possible. This could look like having query matches that
-// indicate it reached a declaration that is not allowed in the import section.
-//
-// * Support directly parsing to occurrences instead of storing namespaces / paths. Types should be
-// generic on this, so that tests etc can still use strings. Could do similar in syntax index.
-//
-// * Distinguish different types of namespaces when known. E.g. "name.type" capture. Once capture
-// names are more open-ended like this may make sense to build and cache a jump table (direct
-// dispatch from capture index).
-//
-// * There are a few "Language specific:" comments on behavior that gets applied to all languages.
-// Would be cleaner to be conditional on the language or otherwise configured.
-
-#[derive(Debug, Clone, Default)]
-pub struct Imports {
-    pub identifier_to_imports: HashMap<Identifier, Vec<Import>>,
-    pub wildcard_modules: Vec<Module>,
-}
-
-#[derive(Debug, Clone)]
-pub enum Import {
-    Direct {
-        module: Module,
-    },
-    Alias {
-        module: Module,
-        external_identifier: Identifier,
-    },
-}
-
-#[derive(Debug, Clone)]
-pub enum Module {
-    SourceExact(Arc<Path>),
-    SourceFuzzy(Arc<Path>),
-    Namespace(Namespace),
-}
-
-impl Module {
-    fn empty() -> Self {
-        Module::Namespace(Namespace::default())
-    }
-
-    fn push_range(
-        &mut self,
-        range: &ModuleRange,
-        snapshot: &BufferSnapshot,
-        language: &Language,
-        parent_abs_path: Option<&Path>,
-    ) -> usize {
-        if range.is_empty() {
-            return 0;
-        }
-
-        match range {
-            ModuleRange::Source(range) => {
-                if let Self::Namespace(namespace) = self
-                    && namespace.0.is_empty()
-                {
-                    let path = snapshot.text_for_range(range.clone()).collect::<Cow<str>>();
-
-                    let path = if let Some(strip_regex) =
-                        language.config().import_path_strip_regex.as_ref()
-                    {
-                        strip_regex.replace_all(&path, "")
-                    } else {
-                        path
-                    };
-
-                    let path = Path::new(path.as_ref());
-                    if (path.starts_with(".") || path.starts_with(".."))
-                        && let Some(parent_abs_path) = parent_abs_path
-                        && let Ok(abs_path) =
-                            util::paths::normalize_lexically(&parent_abs_path.join(path))
-                    {
-                        *self = Self::SourceExact(abs_path.into());
-                    } else {
-                        *self = Self::SourceFuzzy(path.into());
-                    };
-                } else if matches!(self, Self::SourceExact(_))
-                    || matches!(self, Self::SourceFuzzy(_))
-                {
-                    log::warn!("bug in imports query: encountered multiple @source matches");
-                } else {
-                    log::warn!(
-                        "bug in imports query: encountered both @namespace and @source match"
-                    );
-                }
-            }
-            ModuleRange::Namespace(range) => {
-                if let Self::Namespace(namespace) = self {
-                    let segment = range_text(snapshot, range);
-                    if language.config().ignored_import_segments.contains(&segment) {
-                        return 0;
-                    } else {
-                        namespace.0.push(segment);
-                        return 1;
-                    }
-                } else {
-                    log::warn!(
-                        "bug in imports query: encountered both @namespace and @source match"
-                    );
-                }
-            }
-        }
-        0
-    }
-}
-
-#[derive(Debug, Clone)]
-enum ModuleRange {
-    Source(Range<usize>),
-    Namespace(Range<usize>),
-}
-
-impl Deref for ModuleRange {
-    type Target = Range<usize>;
-
-    fn deref(&self) -> &Self::Target {
-        match self {
-            ModuleRange::Source(range) => range,
-            ModuleRange::Namespace(range) => range,
-        }
-    }
-}
-
-#[derive(Debug, Clone, PartialEq, Eq, Default)]
-pub struct Namespace(pub Vec<Arc<str>>);
-
-impl Namespace {
-    pub fn occurrences(&self) -> Occurrences {
-        Occurrences::from_identifiers(&self.0)
-    }
-}
-
-impl Imports {
-    pub fn gather(snapshot: &BufferSnapshot, parent_abs_path: Option<&Path>) -> Self {
-        // Query to match different import patterns
-        let mut matches = snapshot
-            .syntax
-            .matches(0..snapshot.len(), &snapshot.text, |grammar| {
-                grammar.imports_config().map(|imports| &imports.query)
-            });
-
-        let mut detached_nodes: Vec<DetachedNode> = Vec::new();
-        let mut identifier_to_imports = HashMap::default();
-        let mut wildcard_modules = Vec::new();
-        let mut import_range = None;
-
-        while let Some(query_match) = matches.peek() {
-            let ImportsConfig {
-                query: _,
-                import_ix,
-                name_ix,
-                namespace_ix,
-                source_ix,
-                list_ix,
-                wildcard_ix,
-                alias_ix,
-            } = matches.grammars()[query_match.grammar_index]
-                .imports_config()
-                .unwrap();
-
-            let mut new_import_range = None;
-            let mut alias_range = None;
-            let mut modules = Vec::new();
-            let mut content: Option<(Range<usize>, ContentKind)> = None;
-            for capture in query_match.captures {
-                let capture_range = capture.node.byte_range();
-
-                if capture.index == *import_ix {
-                    new_import_range = Some(capture_range);
-                } else if Some(capture.index) == *namespace_ix {
-                    modules.push(ModuleRange::Namespace(capture_range));
-                } else if Some(capture.index) == *source_ix {
-                    modules.push(ModuleRange::Source(capture_range));
-                } else if Some(capture.index) == *alias_ix {
-                    alias_range = Some(capture_range);
-                } else {
-                    let mut found_content = None;
-                    if Some(capture.index) == *name_ix {
-                        found_content = Some((capture_range, ContentKind::Name));
-                    } else if Some(capture.index) == *list_ix {
-                        found_content = Some((capture_range, ContentKind::List));
-                    } else if Some(capture.index) == *wildcard_ix {
-                        found_content = Some((capture_range, ContentKind::Wildcard));
-                    }
-                    if let Some((found_content_range, found_kind)) = found_content {
-                        if let Some((_, old_kind)) = content {
-                            let point = found_content_range.to_point(snapshot);
-                            log::warn!(
-                                "bug in {} imports query: unexpected multiple captures of {} and {} ({}:{}:{})",
-                                query_match.language.name(),
-                                old_kind.capture_name(),
-                                found_kind.capture_name(),
-                                snapshot
-                                    .file()
-                                    .map(|p| p.path().display(PathStyle::Posix))
-                                    .unwrap_or_default(),
-                                point.start.row + 1,
-                                point.start.column + 1
-                            );
-                        }
-                        content = Some((found_content_range, found_kind));
-                    }
-                }
-            }
-
-            if let Some(new_import_range) = new_import_range {
-                log::trace!("starting new import {:?}", new_import_range);
-                Self::gather_from_import_statement(
-                    &detached_nodes,
-                    &snapshot,
-                    parent_abs_path,
-                    &mut identifier_to_imports,
-                    &mut wildcard_modules,
-                );
-                detached_nodes.clear();
-                import_range = Some(new_import_range.clone());
-            }
-
-            if let Some((content, content_kind)) = content {
-                if import_range
-                    .as_ref()
-                    .is_some_and(|import_range| import_range.contains_inclusive(&content))
-                {
-                    detached_nodes.push(DetachedNode {
-                        modules,
-                        content: content.clone(),
-                        content_kind,
-                        alias: alias_range.unwrap_or(0..0),
-                        language: query_match.language.clone(),
-                    });
-                } else {
-                    log::trace!(
-                        "filtered out match not inside import range: {content_kind:?} at {content:?}"
-                    );
-                }
-            }
-
-            matches.advance();
-        }
-
-        Self::gather_from_import_statement(
-            &detached_nodes,
-            &snapshot,
-            parent_abs_path,
-            &mut identifier_to_imports,
-            &mut wildcard_modules,
-        );
-
-        Imports {
-            identifier_to_imports,
-            wildcard_modules,
-        }
-    }
-
-    fn gather_from_import_statement(
-        detached_nodes: &[DetachedNode],
-        snapshot: &BufferSnapshot,
-        parent_abs_path: Option<&Path>,
-        identifier_to_imports: &mut HashMap<Identifier, Vec<Import>>,
-        wildcard_modules: &mut Vec<Module>,
-    ) {
-        let mut trees = Vec::new();
-
-        for detached_node in detached_nodes {
-            if let Some(node) = Self::attach_node(detached_node.into(), &mut trees) {
-                trees.push(node);
-            }
-            log::trace!(
-                "Attached node to tree\n{:#?}\nAttach result:\n{:#?}",
-                detached_node,
-                trees
-                    .iter()
-                    .map(|tree| tree.debug(snapshot))
-                    .collect::<Vec<_>>()
-            );
-        }
-
-        for tree in &trees {
-            let mut module = Module::empty();
-            Self::gather_from_tree(
-                tree,
-                snapshot,
-                parent_abs_path,
-                &mut module,
-                identifier_to_imports,
-                wildcard_modules,
-            );
-        }
-    }
-
-    fn attach_node(mut node: ImportTree, trees: &mut Vec<ImportTree>) -> Option<ImportTree> {
-        let mut tree_index = 0;
-        while tree_index < trees.len() {
-            let tree = &mut trees[tree_index];
-            if !node.content.is_empty() && node.content == tree.content {
-                // multiple matches can apply to the same name/list/wildcard. This keeps the queries
-                // simpler by combining info from these matches.
-                if tree.module.is_empty() {
-                    tree.module = node.module;
-                    tree.module_children = node.module_children;
-                }
-                if tree.alias.is_empty() {
-                    tree.alias = node.alias;
-                }
-                return None;
-            } else if !node.module.is_empty() && node.module.contains_inclusive(&tree.range()) {
-                node.module_children.push(trees.remove(tree_index));
-                continue;
-            } else if !node.content.is_empty() && node.content.contains_inclusive(&tree.content) {
-                node.content_children.push(trees.remove(tree_index));
-                continue;
-            } else if !tree.content.is_empty() && tree.content.contains_inclusive(&node.content) {
-                if let Some(node) = Self::attach_node(node, &mut tree.content_children) {
-                    tree.content_children.push(node);
-                }
-                return None;
-            }
-            tree_index += 1;
-        }
-        Some(node)
-    }
-
-    fn gather_from_tree(
-        tree: &ImportTree,
-        snapshot: &BufferSnapshot,
-        parent_abs_path: Option<&Path>,
-        current_module: &mut Module,
-        identifier_to_imports: &mut HashMap<Identifier, Vec<Import>>,
-        wildcard_modules: &mut Vec<Module>,
-    ) {
-        let mut pop_count = 0;
-
-        if tree.module_children.is_empty() {
-            pop_count +=
-                current_module.push_range(&tree.module, snapshot, &tree.language, parent_abs_path);
-        } else {
-            for child in &tree.module_children {
-                pop_count += Self::extend_namespace_from_tree(
-                    child,
-                    snapshot,
-                    parent_abs_path,
-                    current_module,
-                );
-            }
-        };
-
-        if tree.content_children.is_empty() && !tree.content.is_empty() {
-            match tree.content_kind {
-                ContentKind::Name | ContentKind::List => {
-                    if tree.alias.is_empty() {
-                        identifier_to_imports
-                            .entry(Identifier {
-                                language_id: tree.language.id(),
-                                name: range_text(snapshot, &tree.content),
-                            })
-                            .or_default()
-                            .push(Import::Direct {
-                                module: current_module.clone(),
-                            });
-                    } else {
-                        let alias_name: Arc<str> = range_text(snapshot, &tree.alias);
-                        let external_name = range_text(snapshot, &tree.content);
-                        // Language specific: skip "_" aliases for Rust
-                        if alias_name.as_ref() != "_" {
-                            identifier_to_imports
-                                .entry(Identifier {
-                                    language_id: tree.language.id(),
-                                    name: alias_name,
-                                })
-                                .or_default()
-                                .push(Import::Alias {
-                                    module: current_module.clone(),
-                                    external_identifier: Identifier {
-                                        language_id: tree.language.id(),
-                                        name: external_name,
-                                    },
-                                });
-                        }
-                    }
-                }
-                ContentKind::Wildcard => wildcard_modules.push(current_module.clone()),
-            }
-        } else {
-            for child in &tree.content_children {
-                Self::gather_from_tree(
-                    child,
-                    snapshot,
-                    parent_abs_path,
-                    current_module,
-                    identifier_to_imports,
-                    wildcard_modules,
-                );
-            }
-        }
-
-        if pop_count > 0 {
-            match current_module {
-                Module::SourceExact(_) | Module::SourceFuzzy(_) => {
-                    log::warn!(
-                        "bug in imports query: encountered both @namespace and @source match"
-                    );
-                }
-                Module::Namespace(namespace) => {
-                    namespace.0.drain(namespace.0.len() - pop_count..);
-                }
-            }
-        }
-    }
-
-    fn extend_namespace_from_tree(
-        tree: &ImportTree,
-        snapshot: &BufferSnapshot,
-        parent_abs_path: Option<&Path>,
-        module: &mut Module,
-    ) -> usize {
-        let mut pop_count = 0;
-        if tree.module_children.is_empty() {
-            pop_count += module.push_range(&tree.module, snapshot, &tree.language, parent_abs_path);
-        } else {
-            for child in &tree.module_children {
-                pop_count +=
-                    Self::extend_namespace_from_tree(child, snapshot, parent_abs_path, module);
-            }
-        }
-        if tree.content_children.is_empty() {
-            pop_count += module.push_range(
-                &ModuleRange::Namespace(tree.content.clone()),
-                snapshot,
-                &tree.language,
-                parent_abs_path,
-            );
-        } else {
-            for child in &tree.content_children {
-                pop_count +=
-                    Self::extend_namespace_from_tree(child, snapshot, parent_abs_path, module);
-            }
-        }
-        pop_count
-    }
-}
-
-fn range_text(snapshot: &BufferSnapshot, range: &Range<usize>) -> Arc<str> {
-    snapshot
-        .text_for_range(range.clone())
-        .collect::<Cow<str>>()
-        .into()
-}
-
-#[derive(Debug)]
-struct DetachedNode {
-    modules: Vec<ModuleRange>,
-    content: Range<usize>,
-    content_kind: ContentKind,
-    alias: Range<usize>,
-    language: Arc<Language>,
-}
-
-#[derive(Debug, Clone, Copy)]
-enum ContentKind {
-    Name,
-    Wildcard,
-    List,
-}
-
-impl ContentKind {
-    fn capture_name(&self) -> &'static str {
-        match self {
-            ContentKind::Name => "name",
-            ContentKind::Wildcard => "wildcard",
-            ContentKind::List => "list",
-        }
-    }
-}
-
-#[derive(Debug)]
-struct ImportTree {
-    module: ModuleRange,
-    /// When non-empty, provides namespace / source info which should be used instead of `module`.
-    module_children: Vec<ImportTree>,
-    content: Range<usize>,
-    /// When non-empty, provides content which should be used instead of `content`.
-    content_children: Vec<ImportTree>,
-    content_kind: ContentKind,
-    alias: Range<usize>,
-    language: Arc<Language>,
-}
-
-impl ImportTree {
-    fn range(&self) -> Range<usize> {
-        self.module.start.min(self.content.start)..self.module.end.max(self.content.end)
-    }
-
-    #[allow(dead_code)]
-    fn debug<'a>(&'a self, snapshot: &'a BufferSnapshot) -> ImportTreeDebug<'a> {
-        ImportTreeDebug {
-            tree: self,
-            snapshot,
-        }
-    }
-
-    fn from_module_range(module: &ModuleRange, language: Arc<Language>) -> Self {
-        ImportTree {
-            module: module.clone(),
-            module_children: Vec::new(),
-            content: 0..0,
-            content_children: Vec::new(),
-            content_kind: ContentKind::Name,
-            alias: 0..0,
-            language,
-        }
-    }
-}
-
-impl From<&DetachedNode> for ImportTree {
-    fn from(value: &DetachedNode) -> Self {
-        let module;
-        let module_children;
-        match value.modules.len() {
-            0 => {
-                module = ModuleRange::Namespace(0..0);
-                module_children = Vec::new();
-            }
-            1 => {
-                module = value.modules[0].clone();
-                module_children = Vec::new();
-            }
-            _ => {
-                module = ModuleRange::Namespace(
-                    value.modules.first().unwrap().start..value.modules.last().unwrap().end,
-                );
-                module_children = value
-                    .modules
-                    .iter()
-                    .map(|module| ImportTree::from_module_range(module, value.language.clone()))
-                    .collect();
-            }
-        }
-
-        ImportTree {
-            module,
-            module_children,
-            content: value.content.clone(),
-            content_children: Vec::new(),
-            content_kind: value.content_kind,
-            alias: value.alias.clone(),
-            language: value.language.clone(),
-        }
-    }
-}
-
-struct ImportTreeDebug<'a> {
-    tree: &'a ImportTree,
-    snapshot: &'a BufferSnapshot,
-}
-
-impl std::fmt::Debug for ImportTreeDebug<'_> {
-    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
-        f.debug_struct("ImportTree")
-            .field("module_range", &self.tree.module)
-            .field("module_text", &range_text(self.snapshot, &self.tree.module))
-            .field(
-                "module_children",
-                &self
-                    .tree
-                    .module_children
-                    .iter()
-                    .map(|child| child.debug(&self.snapshot))
-                    .collect::<Vec<Self>>(),
-            )
-            .field("content_range", &self.tree.content)
-            .field(
-                "content_text",
-                &range_text(self.snapshot, &self.tree.content),
-            )
-            .field(
-                "content_children",
-                &self
-                    .tree
-                    .content_children
-                    .iter()
-                    .map(|child| child.debug(&self.snapshot))
-                    .collect::<Vec<Self>>(),
-            )
-            .field("content_kind", &self.tree.content_kind)
-            .field("alias_range", &self.tree.alias)
-            .field("alias_text", &range_text(self.snapshot, &self.tree.alias))
-            .finish()
-    }
-}
-
-#[cfg(test)]
-mod test {
-    use std::path::PathBuf;
-    use std::sync::{Arc, LazyLock};
-
-    use super::*;
-    use collections::HashSet;
-    use gpui::{TestAppContext, prelude::*};
-    use indoc::indoc;
-    use language::{
-        Buffer, Language, LanguageConfig, tree_sitter_python, tree_sitter_rust,
-        tree_sitter_typescript,
-    };
-    use regex::Regex;
-
-    #[gpui::test]
-    fn test_rust_simple(cx: &mut TestAppContext) {
-        check_imports(
-            &RUST,
-            "use std::collections::HashMap;",
-            &[&["std", "collections", "HashMap"]],
-            cx,
-        );
-
-        check_imports(
-            &RUST,
-            "pub use std::collections::HashMap;",
-            &[&["std", "collections", "HashMap"]],
-            cx,
-        );
-
-        check_imports(
-            &RUST,
-            "use std::collections::{HashMap, HashSet};",
-            &[
-                &["std", "collections", "HashMap"],
-                &["std", "collections", "HashSet"],
-            ],
-            cx,
-        );
-    }
-
-    #[gpui::test]
-    fn test_rust_nested(cx: &mut TestAppContext) {
-        check_imports(
-            &RUST,
-            "use std::{any::TypeId, collections::{HashMap, HashSet}};",
-            &[
-                &["std", "any", "TypeId"],
-                &["std", "collections", "HashMap"],
-                &["std", "collections", "HashSet"],
-            ],
-            cx,
-        );
-
-        check_imports(
-            &RUST,
-            "use a::b::c::{d::e::F, g::h::I};",
-            &[
-                &["a", "b", "c", "d", "e", "F"],
-                &["a", "b", "c", "g", "h", "I"],
-            ],
-            cx,
-        );
-    }
-
-    #[gpui::test]
-    fn test_rust_multiple_imports(cx: &mut TestAppContext) {
-        check_imports(
-            &RUST,
-            indoc! {"
-                use std::collections::HashMap;
-                use std::any::{TypeId, Any};
-            "},
-            &[
-                &["std", "collections", "HashMap"],
-                &["std", "any", "TypeId"],
-                &["std", "any", "Any"],
-            ],
-            cx,
-        );
-
-        check_imports(
-            &RUST,
-            indoc! {"
-                use std::collections::HashSet;
-
-                fn main() {
-                    let unqualified = HashSet::new();
-                    let qualified = std::collections::HashMap::new();
-                }
-
-                use std::any::TypeId;
-            "},
-            &[
-                &["std", "collections", "HashSet"],
-                &["std", "any", "TypeId"],
-            ],
-            cx,
-        );
-    }
-
-    #[gpui::test]
-    fn test_rust_wildcard(cx: &mut TestAppContext) {
-        check_imports(&RUST, "use prelude::*;", &[&["prelude", "WILDCARD"]], cx);
-
-        check_imports(
-            &RUST,
-            "use zed::prelude::*;",
-            &[&["zed", "prelude", "WILDCARD"]],
-            cx,
-        );
-
-        check_imports(&RUST, "use prelude::{*};", &[&["prelude", "WILDCARD"]], cx);
-
-        check_imports(
-            &RUST,
-            "use prelude::{File, *};",
-            &[&["prelude", "File"], &["prelude", "WILDCARD"]],
-            cx,
-        );
-
-        check_imports(
-            &RUST,
-            "use zed::{App, prelude::*};",
-            &[&["zed", "App"], &["zed", "prelude", "WILDCARD"]],
-            cx,
-        );
-    }
-
-    #[gpui::test]
-    fn test_rust_alias(cx: &mut TestAppContext) {
-        check_imports(
-            &RUST,
-            "use std::io::Result as IoResult;",
-            &[&["std", "io", "Result AS IoResult"]],
-            cx,
-        );
-    }
-
-    #[gpui::test]
-    fn test_rust_crate_and_super(cx: &mut TestAppContext) {
-        check_imports(&RUST, "use crate::a::b::c;", &[&["a", "b", "c"]], cx);
-        check_imports(&RUST, "use super::a::b::c;", &[&["a", "b", "c"]], cx);
-        // TODO: Consider stripping leading "::". Not done for now because for the text similarity matching usecase this
-        // is fine.
-        check_imports(&RUST, "use ::a::b::c;", &[&["::a", "b", "c"]], cx);
-    }
-
-    #[gpui::test]
-    fn test_typescript_imports(cx: &mut TestAppContext) {
-        let parent_abs_path = PathBuf::from("/home/user/project");
-
-        check_imports_with_file_abs_path(
-            Some(&parent_abs_path),
-            &TYPESCRIPT,
-            r#"import "./maths.js";"#,
-            &[&["SOURCE /home/user/project/maths", "WILDCARD"]],
-            cx,
-        );
-
-        check_imports_with_file_abs_path(
-            Some(&parent_abs_path),
-            &TYPESCRIPT,
-            r#"import "../maths.js";"#,
-            &[&["SOURCE /home/user/maths", "WILDCARD"]],
-            cx,
-        );
-
-        check_imports_with_file_abs_path(
-            Some(&parent_abs_path),
-            &TYPESCRIPT,
-            r#"import RandomNumberGenerator, { pi as π } from "./maths.js";"#,
-            &[
-                &["SOURCE /home/user/project/maths", "RandomNumberGenerator"],
-                &["SOURCE /home/user/project/maths", "pi AS π"],
-            ],
-            cx,
-        );
-
-        check_imports_with_file_abs_path(
-            Some(&parent_abs_path),
-            &TYPESCRIPT,
-            r#"import { pi, phi, absolute } from "./maths.js";"#,
-            &[
-                &["SOURCE /home/user/project/maths", "pi"],
-                &["SOURCE /home/user/project/maths", "phi"],
-                &["SOURCE /home/user/project/maths", "absolute"],
-            ],
-            cx,
-        );
-
-        // index.js is removed by import_path_strip_regex
-        check_imports_with_file_abs_path(
-            Some(&parent_abs_path),
-            &TYPESCRIPT,
-            r#"import { pi, phi, absolute } from "./maths/index.js";"#,
-            &[
-                &["SOURCE /home/user/project/maths", "pi"],
-                &["SOURCE /home/user/project/maths", "phi"],
-                &["SOURCE /home/user/project/maths", "absolute"],
-            ],
-            cx,
-        );
-
-        check_imports_with_file_abs_path(
-            Some(&parent_abs_path),
-            &TYPESCRIPT,
-            r#"import type { SomeThing } from "./some-module.js";"#,
-            &[&["SOURCE /home/user/project/some-module", "SomeThing"]],
-            cx,
-        );
-
-        check_imports_with_file_abs_path(
-            Some(&parent_abs_path),
-            &TYPESCRIPT,
-            r#"import { type SomeThing, OtherThing } from "./some-module.js";"#,
-            &[
-                &["SOURCE /home/user/project/some-module", "SomeThing"],
-                &["SOURCE /home/user/project/some-module", "OtherThing"],
-            ],
-            cx,
-        );
-
-        // index.js is removed by import_path_strip_regex
-        check_imports_with_file_abs_path(
-            Some(&parent_abs_path),
-            &TYPESCRIPT,
-            r#"import { type SomeThing, OtherThing } from "./some-module/index.js";"#,
-            &[
-                &["SOURCE /home/user/project/some-module", "SomeThing"],
-                &["SOURCE /home/user/project/some-module", "OtherThing"],
-            ],
-            cx,
-        );
-
-        // fuzzy paths
-        check_imports_with_file_abs_path(
-            Some(&parent_abs_path),
-            &TYPESCRIPT,
-            r#"import { type SomeThing, OtherThing } from "@my-app/some-module.js";"#,
-            &[
-                &["SOURCE FUZZY @my-app/some-module", "SomeThing"],
-                &["SOURCE FUZZY @my-app/some-module", "OtherThing"],
-            ],
-            cx,
-        );
-    }
-
-    #[gpui::test]
-    fn test_typescript_named_module_imports(cx: &mut TestAppContext) {
-        let parent_abs_path = PathBuf::from("/home/user/project");
-
-        // TODO: These should provide the name that the module is bound to.
-        // For now instead these are treated as unqualified wildcard imports.
-        check_imports_with_file_abs_path(
-            Some(&parent_abs_path),
-            &TYPESCRIPT,
-            r#"import * as math from "./maths.js";"#,
-            // &[&["/home/user/project/maths.js", "WILDCARD AS math"]],
-            &[&["SOURCE /home/user/project/maths", "WILDCARD"]],
-            cx,
-        );
-        check_imports_with_file_abs_path(
-            Some(&parent_abs_path),
-            &TYPESCRIPT,
-            r#"import math = require("./maths");"#,
-            // &[&["/home/user/project/maths", "WILDCARD AS math"]],
-            &[&["SOURCE /home/user/project/maths", "WILDCARD"]],
-            cx,
-        );
-    }
-
-    #[gpui::test]
-    fn test_python_imports(cx: &mut TestAppContext) {
-        check_imports(&PYTHON, "from math import pi", &[&["math", "pi"]], cx);
-
-        check_imports(
-            &PYTHON,
-            "from math import pi, sin, cos",
-            &[&["math", "pi"], &["math", "sin"], &["math", "cos"]],
-            cx,
-        );
-
-        check_imports(&PYTHON, "from math import *", &[&["math", "WILDCARD"]], cx);
-
-        check_imports(
-            &PYTHON,
-            "from math import foo.bar.baz",
-            &[&["math", "foo", "bar", "baz"]],
-            cx,
-        );
-
-        check_imports(
-            &PYTHON,
-            "from math import pi as PI",
-            &[&["math", "pi AS PI"]],
-            cx,
-        );
-
-        check_imports(
-            &PYTHON,
-            "from serializers.json import JsonSerializer",
-            &[&["serializers", "json", "JsonSerializer"]],
-            cx,
-        );
-
-        check_imports(
-            &PYTHON,
-            "from custom.serializers import json, xml, yaml",
-            &[
-                &["custom", "serializers", "json"],
-                &["custom", "serializers", "xml"],
-                &["custom", "serializers", "yaml"],
-            ],
-            cx,
-        );
-    }
-
-    #[gpui::test]
-    fn test_python_named_module_imports(cx: &mut TestAppContext) {
-        // TODO: These should provide the name that the module is bound to.
-        // For now instead these are treated as unqualified wildcard imports.
-        //
-        // check_imports(&PYTHON, "import math", &[&["math", "WILDCARD as math"]], cx);
-        // check_imports(&PYTHON, "import math as maths", &[&["math", "WILDCARD AS maths"]], cx);
-        //
-        // Something like:
-        //
-        // (import_statement
-        //     name: [
-        //         (dotted_name
-        //             (identifier)* @namespace
-        //             (identifier) @name.module .)
-        //         (aliased_import
-        //             name: (dotted_name
-        //                 ((identifier) ".")* @namespace
-        //                 (identifier) @name.module .)
-        //             alias: (identifier) @alias)
-        //     ]) @import
-
-        check_imports(&PYTHON, "import math", &[&["math", "WILDCARD"]], cx);
-
-        check_imports(
-            &PYTHON,
-            "import math as maths",
-            &[&["math", "WILDCARD"]],
-            cx,
-        );
-
-        check_imports(&PYTHON, "import a.b.c", &[&["a", "b", "c", "WILDCARD"]], cx);
-
-        check_imports(
-            &PYTHON,
-            "import a.b.c as d",
-            &[&["a", "b", "c", "WILDCARD"]],
-            cx,
-        );
-    }
-
-    #[gpui::test]
-    fn test_python_package_relative_imports(cx: &mut TestAppContext) {
-        // TODO: These should provide info about the dir they are relative to, to provide more
-        // precise resolution. Instead, fuzzy matching is used as usual.
-
-        check_imports(&PYTHON, "from . import math", &[&["math"]], cx);
-
-        check_imports(&PYTHON, "from .a import math", &[&["a", "math"]], cx);
-
-        check_imports(
-            &PYTHON,
-            "from ..a.b import math",
-            &[&["a", "b", "math"]],
-            cx,
-        );
-
-        check_imports(
-            &PYTHON,
-            "from ..a.b import *",
-            &[&["a", "b", "WILDCARD"]],
-            cx,
-        );
-    }
-
-    #[gpui::test]
-    fn test_c_imports(cx: &mut TestAppContext) {
-        let parent_abs_path = PathBuf::from("/home/user/project");
-
-        // TODO: Distinguish that these are not relative to current path
-        check_imports_with_file_abs_path(
-            Some(&parent_abs_path),
-            &C,
-            r#"#include <math.h>"#,
-            &[&["SOURCE FUZZY math.h", "WILDCARD"]],
-            cx,
-        );
-
-        // TODO: These should be treated as relative, but don't start with ./ or ../
-        check_imports_with_file_abs_path(
-            Some(&parent_abs_path),
-            &C,
-            r#"#include "math.h""#,
-            &[&["SOURCE FUZZY math.h", "WILDCARD"]],
-            cx,
-        );
-    }
-
-    #[gpui::test]
-    fn test_cpp_imports(cx: &mut TestAppContext) {
-        let parent_abs_path = PathBuf::from("/home/user/project");
-
-        // TODO: Distinguish that these are not relative to current path
-        check_imports_with_file_abs_path(
-            Some(&parent_abs_path),
-            &CPP,
-            r#"#include <math.h>"#,
-            &[&["SOURCE FUZZY math.h", "WILDCARD"]],
-            cx,
-        );
-
-        // TODO: These should be treated as relative, but don't start with ./ or ../
-        check_imports_with_file_abs_path(
-            Some(&parent_abs_path),
-            &CPP,
-            r#"#include "math.h""#,
-            &[&["SOURCE FUZZY math.h", "WILDCARD"]],
-            cx,
-        );
-    }
-
-    #[gpui::test]
-    fn test_go_imports(cx: &mut TestAppContext) {
-        check_imports(
-            &GO,
-            r#"import . "lib/math""#,
-            &[&["lib/math", "WILDCARD"]],
-            cx,
-        );
-
-        // not included, these are only for side-effects
-        check_imports(&GO, r#"import _ "lib/math""#, &[], cx);
-    }
-
-    #[gpui::test]
-    fn test_go_named_module_imports(cx: &mut TestAppContext) {
-        // TODO: These should provide the name that the module is bound to.
-        // For now instead these are treated as unqualified wildcard imports.
-
-        check_imports(
-            &GO,
-            r#"import "lib/math""#,
-            &[&["lib/math", "WILDCARD"]],
-            cx,
-        );
-        check_imports(
-            &GO,
-            r#"import m "lib/math""#,
-            &[&["lib/math", "WILDCARD"]],
-            cx,
-        );
-    }
-
-    #[track_caller]
-    fn check_imports(
-        language: &Arc<Language>,
-        source: &str,
-        expected: &[&[&str]],
-        cx: &mut TestAppContext,
-    ) {
-        check_imports_with_file_abs_path(None, language, source, expected, cx);
-    }
-
-    #[track_caller]
-    fn check_imports_with_file_abs_path(
-        parent_abs_path: Option<&Path>,
-        language: &Arc<Language>,
-        source: &str,
-        expected: &[&[&str]],
-        cx: &mut TestAppContext,
-    ) {
-        let buffer = cx.new(|cx| {
-            let mut buffer = Buffer::local(source, cx);
-            buffer.set_language(Some(language.clone()), cx);
-            buffer
-        });
-        cx.run_until_parked();
-
-        let snapshot = buffer.read_with(cx, |buffer, _cx| buffer.snapshot());
-
-        let imports = Imports::gather(&snapshot, parent_abs_path);
-        let mut actual_symbols = imports
-            .identifier_to_imports
-            .iter()
-            .flat_map(|(identifier, imports)| {
-                imports
-                    .iter()
-                    .map(|import| import.to_identifier_parts(identifier.name.as_ref()))
-            })
-            .chain(
-                imports
-                    .wildcard_modules
-                    .iter()
-                    .map(|module| module.to_identifier_parts("WILDCARD")),
-            )
-            .collect::<Vec<_>>();
-        let mut expected_symbols = expected
-            .iter()
-            .map(|expected| expected.iter().map(|s| s.to_string()).collect::<Vec<_>>())
-            .collect::<Vec<_>>();
-        actual_symbols.sort();
-        expected_symbols.sort();
-        if actual_symbols != expected_symbols {
-            let top_layer = snapshot.syntax_layers().next().unwrap();
-            panic!(
-                "Expected imports: {:?}\n\
-                Actual imports: {:?}\n\
-                Tree:\n{}",
-                expected_symbols,
-                actual_symbols,
-                tree_to_string(&top_layer.node()),
-            );
-        }
-    }
-
-    fn tree_to_string(node: &tree_sitter::Node) -> String {
-        let mut cursor = node.walk();
-        let mut result = String::new();
-        let mut depth = 0;
-        'outer: loop {
-            result.push_str(&"  ".repeat(depth));
-            if let Some(field_name) = cursor.field_name() {
-                result.push_str(field_name);
-                result.push_str(": ");
-            }
-            if cursor.node().is_named() {
-                result.push_str(cursor.node().kind());
-            } else {
-                result.push('"');
-                result.push_str(cursor.node().kind());
-                result.push('"');
-            }
-            result.push('\n');
-
-            if cursor.goto_first_child() {
-                depth += 1;
-                continue;
-            }
-            if cursor.goto_next_sibling() {
-                continue;
-            }
-            while cursor.goto_parent() {
-                depth -= 1;
-                if cursor.goto_next_sibling() {
-                    continue 'outer;
-                }
-            }
-            break;
-        }
-        result
-    }
-
-    static RUST: LazyLock<Arc<Language>> = LazyLock::new(|| {
-        Arc::new(
-            Language::new(
-                LanguageConfig {
-                    name: "Rust".into(),
-                    ignored_import_segments: HashSet::from_iter(["crate".into(), "super".into()]),
-                    import_path_strip_regex: Some(Regex::new("/(lib|mod)\\.rs$").unwrap()),
-                    ..Default::default()
-                },
-                Some(tree_sitter_rust::LANGUAGE.into()),
-            )
-            .with_imports_query(include_str!("../../languages/src/rust/imports.scm"))
-            .unwrap(),
-        )
-    });
-
-    static TYPESCRIPT: LazyLock<Arc<Language>> = LazyLock::new(|| {
-        Arc::new(
-            Language::new(
-                LanguageConfig {
-                    name: "TypeScript".into(),
-                    import_path_strip_regex: Some(Regex::new("(?:/index)?\\.[jt]s$").unwrap()),
-                    ..Default::default()
-                },
-                Some(tree_sitter_typescript::LANGUAGE_TYPESCRIPT.into()),
-            )
-            .with_imports_query(include_str!("../../languages/src/typescript/imports.scm"))
-            .unwrap(),
-        )
-    });
-
-    static PYTHON: LazyLock<Arc<Language>> = LazyLock::new(|| {
-        Arc::new(
-            Language::new(
-                LanguageConfig {
-                    name: "Python".into(),
-                    import_path_strip_regex: Some(Regex::new("/__init__\\.py$").unwrap()),
-                    ..Default::default()
-                },
-                Some(tree_sitter_python::LANGUAGE.into()),
-            )
-            .with_imports_query(include_str!("../../languages/src/python/imports.scm"))
-            .unwrap(),
-        )
-    });
-
-    // TODO: Ideally should use actual language configurations
-    static C: LazyLock<Arc<Language>> = LazyLock::new(|| {
-        Arc::new(
-            Language::new(
-                LanguageConfig {
-                    name: "C".into(),
-                    import_path_strip_regex: Some(Regex::new("^<|>$").unwrap()),
-                    ..Default::default()
-                },
-                Some(tree_sitter_c::LANGUAGE.into()),
-            )
-            .with_imports_query(include_str!("../../languages/src/c/imports.scm"))
-            .unwrap(),
-        )
-    });
-
-    static CPP: LazyLock<Arc<Language>> = LazyLock::new(|| {
-        Arc::new(
-            Language::new(
-                LanguageConfig {
-                    name: "C++".into(),
-                    import_path_strip_regex: Some(Regex::new("^<|>$").unwrap()),
-                    ..Default::default()
-                },
-                Some(tree_sitter_cpp::LANGUAGE.into()),
-            )
-            .with_imports_query(include_str!("../../languages/src/cpp/imports.scm"))
-            .unwrap(),
-        )
-    });
-
-    static GO: LazyLock<Arc<Language>> = LazyLock::new(|| {
-        Arc::new(
-            Language::new(
-                LanguageConfig {
-                    name: "Go".into(),
-                    ..Default::default()
-                },
-                Some(tree_sitter_go::LANGUAGE.into()),
-            )
-            .with_imports_query(include_str!("../../languages/src/go/imports.scm"))
-            .unwrap(),
-        )
-    });
-
-    impl Import {
-        fn to_identifier_parts(&self, identifier: &str) -> Vec<String> {
-            match self {
-                Import::Direct { module } => module.to_identifier_parts(identifier),
-                Import::Alias {
-                    module,
-                    external_identifier: external_name,
-                } => {
-                    module.to_identifier_parts(&format!("{} AS {}", external_name.name, identifier))
-                }
-            }
-        }
-    }
-
-    impl Module {
-        fn to_identifier_parts(&self, identifier: &str) -> Vec<String> {
-            match self {
-                Self::Namespace(namespace) => namespace.to_identifier_parts(identifier),
-                Self::SourceExact(path) => {
-                    vec![
-                        format!("SOURCE {}", path.display().to_string().replace("\\", "/")),
-                        identifier.to_string(),
-                    ]
-                }
-                Self::SourceFuzzy(path) => {
-                    vec![
-                        format!(
-                            "SOURCE FUZZY {}",
-                            path.display().to_string().replace("\\", "/")
-                        ),
-                        identifier.to_string(),
-                    ]
-                }
-            }
-        }
-    }
-
-    impl Namespace {
-        fn to_identifier_parts(&self, identifier: &str) -> Vec<String> {
-            self.0
-                .iter()
-                .map(|chunk| chunk.to_string())
-                .chain(std::iter::once(identifier.to_string()))
-                .collect::<Vec<_>>()
-        }
-    }
-}

crates/edit_prediction_context/src/outline.rs 🔗

@@ -1,126 +0,0 @@
-use language::{BufferSnapshot, SyntaxMapMatches};
-use std::{cmp::Reverse, ops::Range};
-
-use crate::declaration::Identifier;
-
-// TODO:
-//
-// * how to handle multiple name captures? for now last one wins
-//
-// * annotation ranges
-//
-// * new "signature" capture for outline queries
-//
-// * Check parent behavior of "int x, y = 0" declarations in a test
-
-pub struct OutlineDeclaration {
-    pub parent_index: Option<usize>,
-    pub identifier: Identifier,
-    pub item_range: Range<usize>,
-    pub signature_range: Range<usize>,
-}
-
-pub fn declarations_in_buffer(buffer: &BufferSnapshot) -> Vec<OutlineDeclaration> {
-    declarations_overlapping_range(0..buffer.len(), buffer)
-}
-
-pub fn declarations_overlapping_range(
-    range: Range<usize>,
-    buffer: &BufferSnapshot,
-) -> Vec<OutlineDeclaration> {
-    let mut declarations = OutlineIterator::new(range, buffer).collect::<Vec<_>>();
-    declarations.sort_unstable_by_key(|item| (item.item_range.start, Reverse(item.item_range.end)));
-
-    let mut parent_stack: Vec<(usize, Range<usize>)> = Vec::new();
-    for (index, declaration) in declarations.iter_mut().enumerate() {
-        while let Some((top_parent_index, top_parent_range)) = parent_stack.last() {
-            if declaration.item_range.start >= top_parent_range.end {
-                parent_stack.pop();
-            } else {
-                declaration.parent_index = Some(*top_parent_index);
-                break;
-            }
-        }
-        parent_stack.push((index, declaration.item_range.clone()));
-    }
-    declarations
-}
-
-/// Iterates outline items without being ordered w.r.t. nested items and without populating
-/// `parent`.
-pub struct OutlineIterator<'a> {
-    buffer: &'a BufferSnapshot,
-    matches: SyntaxMapMatches<'a>,
-}
-
-impl<'a> OutlineIterator<'a> {
-    pub fn new(range: Range<usize>, buffer: &'a BufferSnapshot) -> Self {
-        let matches = buffer.syntax.matches(range, &buffer.text, |grammar| {
-            grammar.outline_config.as_ref().map(|c| &c.query)
-        });
-
-        Self { buffer, matches }
-    }
-}
-
-impl<'a> Iterator for OutlineIterator<'a> {
-    type Item = OutlineDeclaration;
-
-    fn next(&mut self) -> Option<Self::Item> {
-        while let Some(mat) = self.matches.peek() {
-            let config = self.matches.grammars()[mat.grammar_index]
-                .outline_config
-                .as_ref()
-                .unwrap();
-
-            let mut name_range = None;
-            let mut item_range = None;
-            let mut signature_start = None;
-            let mut signature_end = None;
-
-            let mut add_to_signature = |range: Range<usize>| {
-                if signature_start.is_none() {
-                    signature_start = Some(range.start);
-                }
-                signature_end = Some(range.end);
-            };
-
-            for capture in mat.captures {
-                let range = capture.node.byte_range();
-                if capture.index == config.name_capture_ix {
-                    name_range = Some(range.clone());
-                    add_to_signature(range);
-                } else if Some(capture.index) == config.context_capture_ix
-                    || Some(capture.index) == config.extra_context_capture_ix
-                {
-                    add_to_signature(range);
-                } else if capture.index == config.item_capture_ix {
-                    item_range = Some(range.clone());
-                }
-            }
-
-            let language_id = mat.language.id();
-            self.matches.advance();
-
-            if let Some(name_range) = name_range
-                && let Some(item_range) = item_range
-                && let Some(signature_start) = signature_start
-                && let Some(signature_end) = signature_end
-            {
-                let name = self
-                    .buffer
-                    .text_for_range(name_range)
-                    .collect::<String>()
-                    .into();
-
-                return Some(OutlineDeclaration {
-                    identifier: Identifier { name, language_id },
-                    item_range: item_range,
-                    signature_range: signature_start..signature_end,
-                    parent_index: None,
-                });
-            }
-        }
-        None
-    }
-}

crates/edit_prediction_context/src/reference.rs 🔗

@@ -1,173 +0,0 @@
-use collections::HashMap;
-use language::BufferSnapshot;
-use std::ops::Range;
-use util::RangeExt;
-
-use crate::{
-    declaration::Identifier,
-    excerpt::{EditPredictionExcerpt, EditPredictionExcerptText},
-};
-
-#[derive(Debug, Clone)]
-pub struct Reference {
-    pub identifier: Identifier,
-    pub range: Range<usize>,
-    pub region: ReferenceRegion,
-}
-
-#[derive(Copy, Clone, Debug, Eq, PartialEq)]
-pub enum ReferenceRegion {
-    Breadcrumb,
-    Nearby,
-}
-
-pub fn references_in_excerpt(
-    excerpt: &EditPredictionExcerpt,
-    excerpt_text: &EditPredictionExcerptText,
-    snapshot: &BufferSnapshot,
-) -> HashMap<Identifier, Vec<Reference>> {
-    let mut references = references_in_range(
-        excerpt.range.clone(),
-        excerpt_text.body.as_str(),
-        ReferenceRegion::Nearby,
-        snapshot,
-    );
-
-    for ((_, range), text) in excerpt
-        .parent_declarations
-        .iter()
-        .zip(excerpt_text.parent_signatures.iter())
-    {
-        references.extend(references_in_range(
-            range.clone(),
-            text.as_str(),
-            ReferenceRegion::Breadcrumb,
-            snapshot,
-        ));
-    }
-
-    let mut identifier_to_references: HashMap<Identifier, Vec<Reference>> = HashMap::default();
-    for reference in references {
-        identifier_to_references
-            .entry(reference.identifier.clone())
-            .or_insert_with(Vec::new)
-            .push(reference);
-    }
-    identifier_to_references
-}
-
-/// Finds all nodes which have a "variable" match from the highlights query within the offset range.
-pub fn references_in_range(
-    range: Range<usize>,
-    range_text: &str,
-    reference_region: ReferenceRegion,
-    buffer: &BufferSnapshot,
-) -> Vec<Reference> {
-    let mut matches = buffer
-        .syntax
-        .matches(range.clone(), &buffer.text, |grammar| {
-            grammar
-                .highlights_config
-                .as_ref()
-                .map(|config| &config.query)
-        });
-
-    let mut references = Vec::new();
-    let mut last_added_range = None;
-    while let Some(mat) = matches.peek() {
-        let config = matches.grammars()[mat.grammar_index]
-            .highlights_config
-            .as_ref();
-
-        if let Some(config) = config {
-            for capture in mat.captures {
-                if config.identifier_capture_indices.contains(&capture.index) {
-                    let node_range = capture.node.byte_range();
-
-                    // sometimes multiple highlight queries match - this deduplicates them
-                    if Some(node_range.clone()) == last_added_range {
-                        continue;
-                    }
-
-                    if !range.contains_inclusive(&node_range) {
-                        continue;
-                    }
-
-                    let identifier_text =
-                        &range_text[node_range.start - range.start..node_range.end - range.start];
-
-                    references.push(Reference {
-                        identifier: Identifier {
-                            name: identifier_text.into(),
-                            language_id: mat.language.id(),
-                        },
-                        range: node_range.clone(),
-                        region: reference_region,
-                    });
-                    last_added_range = Some(node_range);
-                }
-            }
-        }
-
-        matches.advance();
-    }
-    references
-}
-
-#[cfg(test)]
-mod test {
-    use gpui::{TestAppContext, prelude::*};
-    use indoc::indoc;
-    use language::{BufferSnapshot, Language, LanguageConfig, LanguageMatcher, tree_sitter_rust};
-
-    use crate::reference::{ReferenceRegion, references_in_range};
-
-    #[gpui::test]
-    fn test_identifier_node_truncated(cx: &mut TestAppContext) {
-        let code = indoc! { r#"
-            fn main() {
-                add(1, 2);
-            }
-
-            fn add(a: i32, b: i32) -> i32 {
-                a + b
-            }
-        "# };
-        let buffer = create_buffer(code, cx);
-
-        let range = 0..35;
-        let references = references_in_range(
-            range.clone(),
-            &code[range],
-            ReferenceRegion::Breadcrumb,
-            &buffer,
-        );
-        assert_eq!(references.len(), 2);
-        assert_eq!(references[0].identifier.name.as_ref(), "main");
-        assert_eq!(references[1].identifier.name.as_ref(), "add");
-    }
-
-    fn create_buffer(text: &str, cx: &mut TestAppContext) -> BufferSnapshot {
-        let buffer =
-            cx.new(|cx| language::Buffer::local(text, cx).with_language(rust_lang().into(), cx));
-        buffer.read_with(cx, |buffer, _| buffer.snapshot())
-    }
-
-    fn rust_lang() -> Language {
-        Language::new(
-            LanguageConfig {
-                name: "Rust".into(),
-                matcher: LanguageMatcher {
-                    path_suffixes: vec!["rs".to_string()],
-                    ..Default::default()
-                },
-                ..Default::default()
-            },
-            Some(tree_sitter_rust::LANGUAGE.into()),
-        )
-        .with_highlights_query(include_str!("../../languages/src/rust/highlights.scm"))
-        .unwrap()
-        .with_outline_query(include_str!("../../languages/src/rust/outline.scm"))
-        .unwrap()
-    }
-}

crates/edit_prediction_context/src/syntax_index.rs 🔗

@@ -1,1069 +0,0 @@
-use anyhow::{Result, anyhow};
-use collections::{HashMap, HashSet};
-use futures::channel::mpsc;
-use futures::lock::Mutex;
-use futures::{FutureExt as _, StreamExt, future};
-use gpui::{App, AppContext as _, AsyncApp, Context, Entity, Task, WeakEntity};
-use itertools::Itertools;
-
-use language::{Buffer, BufferEvent};
-use postage::stream::Stream as _;
-use project::buffer_store::{BufferStore, BufferStoreEvent};
-use project::worktree_store::{WorktreeStore, WorktreeStoreEvent};
-use project::{PathChange, Project, ProjectEntryId, ProjectPath};
-use slotmap::SlotMap;
-use std::iter;
-use std::ops::{DerefMut, Range};
-use std::sync::Arc;
-use text::BufferId;
-use util::{RangeExt as _, debug_panic, some_or_debug_panic};
-
-use crate::CachedDeclarationPath;
-use crate::declaration::{
-    BufferDeclaration, Declaration, DeclarationId, FileDeclaration, Identifier,
-};
-use crate::outline::declarations_in_buffer;
-
-// TODO
-//
-// * Also queue / debounce buffer changes. A challenge for this is that use of
-// `buffer_declarations_containing_range` assumes that the index is always immediately up to date.
-//
-// * Add a per language configuration for skipping indexing.
-//
-// * Handle tsx / ts / js referencing each-other
-
-// Potential future improvements:
-//
-// * Prevent indexing of a large file from blocking the queue.
-//
-// * Send multiple selected excerpt ranges. Challenge is that excerpt ranges influence which
-// references are present and their scores.
-//
-// * Include single-file worktrees / non visible worktrees? E.g. go to definition that resolves to a
-// file in a build dependency. Should not be editable in that case - but how to distinguish the case
-// where it should be editable?
-
-// Potential future optimizations:
-//
-// * Index files on multiple threads in Zed (currently only parallel for the CLI). Adding some kind
-// of priority system to the background executor could help - it's single threaded for now to avoid
-// interfering with other work.
-//
-// * Parse files directly instead of loading into a Rope.
-//
-//   - This would allow the task handling dirty_files to be done entirely on the background executor.
-//
-//   - Make SyntaxMap generic to handle embedded languages? Will also need to find line boundaries,
-//   but that can be done by scanning characters in the flat representation.
-//
-// * Use something similar to slotmap without key versions.
-//
-// * Concurrent slotmap
-
-pub struct SyntaxIndex {
-    state: Arc<Mutex<SyntaxIndexState>>,
-    project: WeakEntity<Project>,
-    initial_file_indexing_done_rx: postage::watch::Receiver<bool>,
-    _file_indexing_task: Option<Task<()>>,
-}
-
-pub struct SyntaxIndexState {
-    declarations: SlotMap<DeclarationId, Declaration>,
-    identifiers: HashMap<Identifier, HashSet<DeclarationId>>,
-    files: HashMap<ProjectEntryId, FileState>,
-    buffers: HashMap<BufferId, BufferState>,
-    dirty_files: HashMap<ProjectEntryId, ProjectPath>,
-    dirty_files_tx: mpsc::Sender<()>,
-}
-
-#[derive(Debug, Default)]
-struct FileState {
-    declarations: Vec<DeclarationId>,
-}
-
-#[derive(Default)]
-struct BufferState {
-    declarations: Vec<DeclarationId>,
-    task: Option<Task<()>>,
-}
-
-impl SyntaxIndex {
-    pub fn new(
-        project: &Entity<Project>,
-        file_indexing_parallelism: usize,
-        cx: &mut Context<Self>,
-    ) -> Self {
-        assert!(file_indexing_parallelism > 0);
-        let (dirty_files_tx, mut dirty_files_rx) = mpsc::channel::<()>(1);
-        let (mut initial_file_indexing_done_tx, initial_file_indexing_done_rx) =
-            postage::watch::channel();
-
-        let initial_state = SyntaxIndexState {
-            declarations: SlotMap::default(),
-            identifiers: HashMap::default(),
-            files: HashMap::default(),
-            buffers: HashMap::default(),
-            dirty_files: HashMap::default(),
-            dirty_files_tx,
-        };
-        let mut this = Self {
-            project: project.downgrade(),
-            state: Arc::new(Mutex::new(initial_state)),
-            initial_file_indexing_done_rx,
-            _file_indexing_task: None,
-        };
-
-        let worktree_store = project.read(cx).worktree_store();
-        let initial_worktree_snapshots = worktree_store
-            .read(cx)
-            .worktrees()
-            .map(|w| w.read(cx).snapshot())
-            .collect::<Vec<_>>();
-        this._file_indexing_task = Some(cx.spawn(async move |this, cx| {
-            let snapshots_file_count = initial_worktree_snapshots
-                .iter()
-                .map(|worktree| worktree.file_count())
-                .sum::<usize>();
-            if snapshots_file_count > 0 {
-                let chunk_size = snapshots_file_count.div_ceil(file_indexing_parallelism);
-                let chunk_count = snapshots_file_count.div_ceil(chunk_size);
-                let file_chunks = initial_worktree_snapshots
-                    .iter()
-                    .flat_map(|worktree| {
-                        let worktree_id = worktree.id();
-                        worktree.files(false, 0).map(move |entry| {
-                            (
-                                entry.id,
-                                ProjectPath {
-                                    worktree_id,
-                                    path: entry.path.clone(),
-                                },
-                            )
-                        })
-                    })
-                    .chunks(chunk_size);
-
-                let mut tasks = Vec::with_capacity(chunk_count);
-                for chunk in file_chunks.into_iter() {
-                    tasks.push(Self::update_dirty_files(
-                        &this,
-                        chunk.into_iter().collect(),
-                        cx.clone(),
-                    ));
-                }
-                futures::future::join_all(tasks).await;
-                log::info!("Finished initial file indexing");
-            }
-
-            *initial_file_indexing_done_tx.borrow_mut() = true;
-
-            let Ok(state) = this.read_with(cx, |this, _cx| Arc::downgrade(&this.state)) else {
-                return;
-            };
-            while dirty_files_rx.next().await.is_some() {
-                let Some(state) = state.upgrade() else {
-                    return;
-                };
-                let mut state = state.lock().await;
-                let was_underused = state.dirty_files.capacity() > 255
-                    && state.dirty_files.len() * 8 < state.dirty_files.capacity();
-                let dirty_files = state.dirty_files.drain().collect::<Vec<_>>();
-                if was_underused {
-                    state.dirty_files.shrink_to_fit();
-                }
-                drop(state);
-                if dirty_files.is_empty() {
-                    continue;
-                }
-
-                let chunk_size = dirty_files.len().div_ceil(file_indexing_parallelism);
-                let chunk_count = dirty_files.len().div_ceil(chunk_size);
-                let mut tasks = Vec::with_capacity(chunk_count);
-                let chunks = dirty_files.into_iter().chunks(chunk_size);
-                for chunk in chunks.into_iter() {
-                    tasks.push(Self::update_dirty_files(
-                        &this,
-                        chunk.into_iter().collect(),
-                        cx.clone(),
-                    ));
-                }
-                futures::future::join_all(tasks).await;
-            }
-        }));
-
-        cx.subscribe(&worktree_store, Self::handle_worktree_store_event)
-            .detach();
-
-        let buffer_store = project.read(cx).buffer_store().clone();
-        for buffer in buffer_store.read(cx).buffers().collect::<Vec<_>>() {
-            this.register_buffer(&buffer, cx);
-        }
-        cx.subscribe(&buffer_store, Self::handle_buffer_store_event)
-            .detach();
-
-        this
-    }
-
-    async fn update_dirty_files(
-        this: &WeakEntity<Self>,
-        dirty_files: Vec<(ProjectEntryId, ProjectPath)>,
-        mut cx: AsyncApp,
-    ) {
-        for (entry_id, project_path) in dirty_files {
-            let Ok(task) = this.update(&mut cx, |this, cx| {
-                this.update_file(entry_id, project_path, cx)
-            }) else {
-                return;
-            };
-            task.await;
-        }
-    }
-
-    pub fn wait_for_initial_file_indexing(&self, cx: &App) -> Task<Result<()>> {
-        if *self.initial_file_indexing_done_rx.borrow() {
-            Task::ready(Ok(()))
-        } else {
-            let mut rx = self.initial_file_indexing_done_rx.clone();
-            cx.background_spawn(async move {
-                loop {
-                    match rx.recv().await {
-                        Some(true) => return Ok(()),
-                        Some(false) => {}
-                        None => {
-                            return Err(anyhow!(
-                                "SyntaxIndex dropped while waiting for initial file indexing"
-                            ));
-                        }
-                    }
-                }
-            })
-        }
-    }
-
-    pub fn indexed_file_paths(&self, cx: &App) -> Task<Vec<ProjectPath>> {
-        let state = self.state.clone();
-        let project = self.project.clone();
-
-        cx.spawn(async move |cx| {
-            let state = state.lock().await;
-            let Some(project) = project.upgrade() else {
-                return vec![];
-            };
-            project
-                .read_with(cx, |project, cx| {
-                    state
-                        .files
-                        .keys()
-                        .filter_map(|entry_id| project.path_for_entry(*entry_id, cx))
-                        .collect()
-                })
-                .unwrap_or_default()
-        })
-    }
-
-    fn handle_worktree_store_event(
-        &mut self,
-        _worktree_store: Entity<WorktreeStore>,
-        event: &WorktreeStoreEvent,
-        cx: &mut Context<Self>,
-    ) {
-        use WorktreeStoreEvent::*;
-        match event {
-            WorktreeUpdatedEntries(worktree_id, updated_entries_set) => {
-                let state = Arc::downgrade(&self.state);
-                let worktree_id = *worktree_id;
-                let updated_entries_set = updated_entries_set.clone();
-                cx.background_spawn(async move {
-                    let Some(state) = state.upgrade() else { return };
-                    let mut state = state.lock().await;
-                    for (path, entry_id, path_change) in updated_entries_set.iter() {
-                        if let PathChange::Removed = path_change {
-                            state.files.remove(entry_id);
-                            state.dirty_files.remove(entry_id);
-                        } else {
-                            let project_path = ProjectPath {
-                                worktree_id,
-                                path: path.clone(),
-                            };
-                            state.dirty_files.insert(*entry_id, project_path);
-                        }
-                    }
-                    match state.dirty_files_tx.try_send(()) {
-                        Err(err) if err.is_disconnected() => {
-                            log::error!("bug: syntax indexing queue is disconnected");
-                        }
-                        _ => {}
-                    }
-                })
-                .detach();
-            }
-            WorktreeDeletedEntry(_worktree_id, project_entry_id) => {
-                let project_entry_id = *project_entry_id;
-                self.with_state(cx, move |state| {
-                    state.files.remove(&project_entry_id);
-                })
-            }
-            _ => {}
-        }
-    }
-
-    fn handle_buffer_store_event(
-        &mut self,
-        _buffer_store: Entity<BufferStore>,
-        event: &BufferStoreEvent,
-        cx: &mut Context<Self>,
-    ) {
-        use BufferStoreEvent::*;
-        match event {
-            BufferAdded(buffer) => self.register_buffer(buffer, cx),
-            BufferOpened { .. }
-            | BufferChangedFilePath { .. }
-            | BufferDropped { .. }
-            | SharedBufferClosed { .. } => {}
-        }
-    }
-
-    pub fn state(&self) -> &Arc<Mutex<SyntaxIndexState>> {
-        &self.state
-    }
-
-    fn with_state(&self, cx: &mut App, f: impl FnOnce(&mut SyntaxIndexState) + Send + 'static) {
-        if let Some(mut state) = self.state.try_lock() {
-            f(&mut state);
-            return;
-        }
-        let state = Arc::downgrade(&self.state);
-        cx.background_spawn(async move {
-            let Some(state) = state.upgrade() else {
-                return;
-            };
-            let mut state = state.lock().await;
-            f(&mut state)
-        })
-        .detach();
-    }
-
-    fn register_buffer(&self, buffer: &Entity<Buffer>, cx: &mut Context<Self>) {
-        let buffer_id = buffer.read(cx).remote_id();
-        cx.observe_release(buffer, move |this, _buffer, cx| {
-            this.with_state(cx, move |state| {
-                if let Some(buffer_state) = state.buffers.remove(&buffer_id) {
-                    SyntaxIndexState::remove_buffer_declarations(
-                        &buffer_state.declarations,
-                        &mut state.declarations,
-                        &mut state.identifiers,
-                    );
-                }
-            })
-        })
-        .detach();
-        cx.subscribe(buffer, Self::handle_buffer_event).detach();
-
-        self.update_buffer(buffer.clone(), cx);
-    }
-
-    fn handle_buffer_event(
-        &mut self,
-        buffer: Entity<Buffer>,
-        event: &BufferEvent,
-        cx: &mut Context<Self>,
-    ) {
-        match event {
-            BufferEvent::Edited |
-            // paths are cached and so should be updated
-            BufferEvent::FileHandleChanged => self.update_buffer(buffer, cx),
-            _ => {}
-        }
-    }
-
-    fn update_buffer(&self, buffer_entity: Entity<Buffer>, cx: &mut Context<Self>) {
-        let buffer = buffer_entity.read(cx);
-        if buffer.language().is_none() {
-            return;
-        }
-
-        let Some((project_entry_id, cached_path)) = project::File::from_dyn(buffer.file())
-            .and_then(|f| {
-                let project_entry_id = f.project_entry_id()?;
-                let cached_path = CachedDeclarationPath::new(
-                    f.worktree.read(cx).abs_path(),
-                    &f.path,
-                    buffer.language(),
-                );
-                Some((project_entry_id, cached_path))
-            })
-        else {
-            return;
-        };
-        let buffer_id = buffer.remote_id();
-
-        let mut parse_status = buffer.parse_status();
-        let snapshot_task = cx.spawn({
-            let weak_buffer = buffer_entity.downgrade();
-            async move |_, cx| {
-                while *parse_status.borrow() != language::ParseStatus::Idle {
-                    parse_status.changed().await?;
-                }
-                weak_buffer.read_with(cx, |buffer, _cx| buffer.snapshot())
-            }
-        });
-
-        let state = Arc::downgrade(&self.state);
-        let task = cx.background_spawn(async move {
-            // TODO: How to handle errors?
-            let Ok(snapshot) = snapshot_task.await else {
-                return;
-            };
-            let rope = snapshot.text.as_rope();
-
-            let declarations = declarations_in_buffer(&snapshot)
-                .into_iter()
-                .map(|item| {
-                    (
-                        item.parent_index,
-                        BufferDeclaration::from_outline(item, &rope),
-                    )
-                })
-                .collect::<Vec<_>>();
-
-            let Some(state) = state.upgrade() else {
-                return;
-            };
-            let mut state = state.lock().await;
-            let state = state.deref_mut();
-
-            let buffer_state = state
-                .buffers
-                .entry(buffer_id)
-                .or_insert_with(Default::default);
-
-            SyntaxIndexState::remove_buffer_declarations(
-                &buffer_state.declarations,
-                &mut state.declarations,
-                &mut state.identifiers,
-            );
-
-            let mut new_ids = Vec::with_capacity(declarations.len());
-            state.declarations.reserve(declarations.len());
-            for (parent_index, mut declaration) in declarations {
-                declaration.parent =
-                    parent_index.and_then(|ix| some_or_debug_panic(new_ids.get(ix).copied()));
-
-                let identifier = declaration.identifier.clone();
-                let declaration_id = state.declarations.insert(Declaration::Buffer {
-                    rope: rope.clone(),
-                    buffer_id,
-                    declaration,
-                    project_entry_id,
-                    cached_path: cached_path.clone(),
-                });
-                new_ids.push(declaration_id);
-
-                state
-                    .identifiers
-                    .entry(identifier)
-                    .or_default()
-                    .insert(declaration_id);
-            }
-
-            buffer_state.declarations = new_ids;
-        });
-
-        self.with_state(cx, move |state| {
-            state
-                .buffers
-                .entry(buffer_id)
-                .or_insert_with(Default::default)
-                .task = Some(task)
-        });
-    }
-
-    fn update_file(
-        &mut self,
-        entry_id: ProjectEntryId,
-        project_path: ProjectPath,
-        cx: &mut Context<Self>,
-    ) -> Task<()> {
-        let Some(project) = self.project.upgrade() else {
-            return Task::ready(());
-        };
-        let project = project.read(cx);
-
-        let language_registry = project.languages();
-        let Some(available_language) =
-            language_registry.language_for_file_path(project_path.path.as_std_path())
-        else {
-            return Task::ready(());
-        };
-        let language = if let Some(Ok(Ok(language))) = language_registry
-            .load_language(&available_language)
-            .now_or_never()
-        {
-            if language
-                .grammar()
-                .is_none_or(|grammar| grammar.outline_config.is_none())
-            {
-                return Task::ready(());
-            }
-            future::Either::Left(async { Ok(language) })
-        } else {
-            let language_registry = language_registry.clone();
-            future::Either::Right(async move {
-                anyhow::Ok(
-                    language_registry
-                        .load_language(&available_language)
-                        .await??,
-                )
-            })
-        };
-
-        let Some(worktree) = project.worktree_for_id(project_path.worktree_id, cx) else {
-            return Task::ready(());
-        };
-
-        let snapshot_task = worktree.update(cx, |worktree, cx| {
-            let load_task = worktree.load_file(&project_path.path, cx);
-            let worktree_abs_path = worktree.abs_path();
-            cx.spawn(async move |_this, cx| {
-                let loaded_file = load_task.await?;
-                let language = language.await?;
-
-                let buffer = cx.new(|cx| {
-                    let mut buffer = Buffer::local(loaded_file.text, cx);
-                    buffer.set_language(Some(language.clone()), cx);
-                    buffer
-                })?;
-
-                let mut parse_status = buffer.read_with(cx, |buffer, _| buffer.parse_status())?;
-                while *parse_status.borrow() != language::ParseStatus::Idle {
-                    parse_status.changed().await?;
-                }
-
-                let cached_path = CachedDeclarationPath::new(
-                    worktree_abs_path,
-                    &project_path.path,
-                    Some(&language),
-                );
-
-                let snapshot = buffer.read_with(cx, |buffer, _cx| buffer.snapshot())?;
-
-                anyhow::Ok((snapshot, cached_path))
-            })
-        });
-
-        let state = Arc::downgrade(&self.state);
-        cx.background_spawn(async move {
-            // TODO: How to handle errors?
-            let Ok((snapshot, cached_path)) = snapshot_task.await else {
-                return;
-            };
-            let rope = snapshot.as_rope();
-            let declarations = declarations_in_buffer(&snapshot)
-                .into_iter()
-                .map(|item| (item.parent_index, FileDeclaration::from_outline(item, rope)))
-                .collect::<Vec<_>>();
-
-            let Some(state) = state.upgrade() else {
-                return;
-            };
-            let mut state = state.lock().await;
-            let state = state.deref_mut();
-
-            let file_state = state.files.entry(entry_id).or_insert_with(Default::default);
-            for old_declaration_id in &file_state.declarations {
-                let Some(declaration) = state.declarations.remove(*old_declaration_id) else {
-                    debug_panic!("declaration not found");
-                    continue;
-                };
-                if let Some(identifier_declarations) =
-                    state.identifiers.get_mut(declaration.identifier())
-                {
-                    identifier_declarations.remove(old_declaration_id);
-                }
-            }
-
-            let mut new_ids = Vec::with_capacity(declarations.len());
-            state.declarations.reserve(declarations.len());
-            for (parent_index, mut declaration) in declarations {
-                declaration.parent =
-                    parent_index.and_then(|ix| some_or_debug_panic(new_ids.get(ix).copied()));
-
-                let identifier = declaration.identifier.clone();
-                let declaration_id = state.declarations.insert(Declaration::File {
-                    project_entry_id: entry_id,
-                    declaration,
-                    cached_path: cached_path.clone(),
-                });
-                new_ids.push(declaration_id);
-
-                state
-                    .identifiers
-                    .entry(identifier)
-                    .or_default()
-                    .insert(declaration_id);
-            }
-            file_state.declarations = new_ids;
-        })
-    }
-}
-
-impl SyntaxIndexState {
-    pub fn declaration(&self, id: DeclarationId) -> Option<&Declaration> {
-        self.declarations.get(id)
-    }
-
-    /// Returns declarations for the identifier. If the limit is exceeded, returns an empty vector.
-    ///
-    /// TODO: Consider doing some pre-ranking and instead truncating when N is exceeded.
-    pub fn declarations_for_identifier<const N: usize>(
-        &self,
-        identifier: &Identifier,
-    ) -> Vec<(DeclarationId, &Declaration)> {
-        // make sure to not have a large stack allocation
-        assert!(N < 32);
-
-        let Some(declaration_ids) = self.identifiers.get(&identifier) else {
-            return vec![];
-        };
-
-        let mut result = Vec::with_capacity(N);
-        let mut included_buffer_entry_ids = arrayvec::ArrayVec::<_, N>::new();
-        let mut file_declarations = Vec::new();
-
-        for declaration_id in declaration_ids {
-            let declaration = self.declarations.get(*declaration_id);
-            let Some(declaration) = some_or_debug_panic(declaration) else {
-                continue;
-            };
-            match declaration {
-                Declaration::Buffer {
-                    project_entry_id, ..
-                } => {
-                    included_buffer_entry_ids.push(*project_entry_id);
-                    result.push((*declaration_id, declaration));
-                    if result.len() == N {
-                        return Vec::new();
-                    }
-                }
-                Declaration::File {
-                    project_entry_id, ..
-                } => {
-                    if !included_buffer_entry_ids.contains(&project_entry_id) {
-                        file_declarations.push((*declaration_id, declaration));
-                    }
-                }
-            }
-        }
-
-        for (declaration_id, declaration) in file_declarations {
-            match declaration {
-                Declaration::File {
-                    project_entry_id, ..
-                } => {
-                    if !included_buffer_entry_ids.contains(&project_entry_id) {
-                        result.push((declaration_id, declaration));
-
-                        if result.len() == N {
-                            return Vec::new();
-                        }
-                    }
-                }
-                Declaration::Buffer { .. } => {}
-            }
-        }
-
-        result
-    }
-
-    pub fn buffer_declarations_containing_range(
-        &self,
-        buffer_id: BufferId,
-        range: Range<usize>,
-    ) -> impl Iterator<Item = (DeclarationId, &BufferDeclaration)> {
-        let Some(buffer_state) = self.buffers.get(&buffer_id) else {
-            return itertools::Either::Left(iter::empty());
-        };
-
-        let iter = buffer_state
-            .declarations
-            .iter()
-            .filter_map(move |declaration_id| {
-                let Some(declaration) = self
-                    .declarations
-                    .get(*declaration_id)
-                    .and_then(|d| d.as_buffer())
-                else {
-                    log::error!("bug: missing buffer outline declaration");
-                    return None;
-                };
-                if declaration.item_range.contains_inclusive(&range) {
-                    return Some((*declaration_id, declaration));
-                }
-                return None;
-            });
-        itertools::Either::Right(iter)
-    }
-
-    pub fn file_declaration_count(&self, declaration: &Declaration) -> usize {
-        match declaration {
-            Declaration::File {
-                project_entry_id, ..
-            } => self
-                .files
-                .get(project_entry_id)
-                .map(|file_state| file_state.declarations.len())
-                .unwrap_or_default(),
-            Declaration::Buffer { buffer_id, .. } => self
-                .buffers
-                .get(buffer_id)
-                .map(|buffer_state| buffer_state.declarations.len())
-                .unwrap_or_default(),
-        }
-    }
-
-    fn remove_buffer_declarations(
-        old_declaration_ids: &[DeclarationId],
-        declarations: &mut SlotMap<DeclarationId, Declaration>,
-        identifiers: &mut HashMap<Identifier, HashSet<DeclarationId>>,
-    ) {
-        for old_declaration_id in old_declaration_ids {
-            let Some(declaration) = declarations.remove(*old_declaration_id) else {
-                debug_panic!("declaration not found");
-                continue;
-            };
-            if let Some(identifier_declarations) = identifiers.get_mut(declaration.identifier()) {
-                identifier_declarations.remove(old_declaration_id);
-            }
-        }
-    }
-}
-
-#[cfg(test)]
-mod tests {
-    use super::*;
-    use std::sync::Arc;
-
-    use gpui::TestAppContext;
-    use indoc::indoc;
-    use language::{Language, LanguageConfig, LanguageId, LanguageMatcher, tree_sitter_rust};
-    use project::{FakeFs, Project};
-    use serde_json::json;
-    use settings::SettingsStore;
-    use text::OffsetRangeExt as _;
-    use util::{path, rel_path::rel_path};
-
-    use crate::syntax_index::SyntaxIndex;
-
-    #[gpui::test]
-    async fn test_unopen_indexed_files(cx: &mut TestAppContext) {
-        let (project, index, rust_lang_id) = init_test(cx).await;
-        let main = Identifier {
-            name: "main".into(),
-            language_id: rust_lang_id,
-        };
-
-        let index_state = index.read_with(cx, |index, _cx| index.state().clone());
-        let index_state = index_state.lock().await;
-        cx.update(|cx| {
-            let decls = index_state.declarations_for_identifier::<8>(&main);
-            assert_eq!(decls.len(), 2);
-
-            let decl = expect_file_decl("a.rs", &decls[0].1, &project, cx);
-            assert_eq!(decl.identifier, main);
-            assert_eq!(decl.item_range, 0..98);
-
-            let decl = expect_file_decl("c.rs", &decls[1].1, &project, cx);
-            assert_eq!(decl.identifier, main.clone());
-            assert_eq!(decl.item_range, 32..280);
-        });
-    }
-
-    #[gpui::test]
-    async fn test_parents_in_file(cx: &mut TestAppContext) {
-        let (project, index, rust_lang_id) = init_test(cx).await;
-        let test_process_data = Identifier {
-            name: "test_process_data".into(),
-            language_id: rust_lang_id,
-        };
-
-        let index_state = index.read_with(cx, |index, _cx| index.state().clone());
-        let index_state = index_state.lock().await;
-        cx.update(|cx| {
-            let decls = index_state.declarations_for_identifier::<8>(&test_process_data);
-            assert_eq!(decls.len(), 1);
-
-            let decl = expect_file_decl("c.rs", &decls[0].1, &project, cx);
-            assert_eq!(decl.identifier, test_process_data);
-
-            let parent_id = decl.parent.unwrap();
-            let parent = index_state.declaration(parent_id).unwrap();
-            let parent_decl = expect_file_decl("c.rs", &parent, &project, cx);
-            assert_eq!(
-                parent_decl.identifier,
-                Identifier {
-                    name: "tests".into(),
-                    language_id: rust_lang_id
-                }
-            );
-            assert_eq!(parent_decl.parent, None);
-        });
-    }
-
-    #[gpui::test]
-    async fn test_parents_in_buffer(cx: &mut TestAppContext) {
-        let (project, index, rust_lang_id) = init_test(cx).await;
-        let test_process_data = Identifier {
-            name: "test_process_data".into(),
-            language_id: rust_lang_id,
-        };
-
-        let buffer = project
-            .update(cx, |project, cx| {
-                let project_path = project.find_project_path("c.rs", cx).unwrap();
-                project.open_buffer(project_path, cx)
-            })
-            .await
-            .unwrap();
-
-        cx.run_until_parked();
-
-        let index_state = index.read_with(cx, |index, _cx| index.state().clone());
-        let index_state = index_state.lock().await;
-        cx.update(|cx| {
-            let decls = index_state.declarations_for_identifier::<8>(&test_process_data);
-            assert_eq!(decls.len(), 1);
-
-            let decl = expect_buffer_decl("c.rs", &decls[0].1, &project, cx);
-            assert_eq!(decl.identifier, test_process_data);
-
-            let parent_id = decl.parent.unwrap();
-            let parent = index_state.declaration(parent_id).unwrap();
-            let parent_decl = expect_buffer_decl("c.rs", &parent, &project, cx);
-            assert_eq!(
-                parent_decl.identifier,
-                Identifier {
-                    name: "tests".into(),
-                    language_id: rust_lang_id
-                }
-            );
-            assert_eq!(parent_decl.parent, None);
-        });
-
-        drop(buffer);
-    }
-
-    #[gpui::test]
-    async fn test_declarations_limit(cx: &mut TestAppContext) {
-        let (_, index, rust_lang_id) = init_test(cx).await;
-
-        let index_state = index.read_with(cx, |index, _cx| index.state().clone());
-        let index_state = index_state.lock().await;
-        let decls = index_state.declarations_for_identifier::<1>(&Identifier {
-            name: "main".into(),
-            language_id: rust_lang_id,
-        });
-        assert_eq!(decls.len(), 0);
-    }
-
-    #[gpui::test]
-    async fn test_buffer_shadow(cx: &mut TestAppContext) {
-        let (project, index, rust_lang_id) = init_test(cx).await;
-
-        let main = Identifier {
-            name: "main".into(),
-            language_id: rust_lang_id,
-        };
-
-        let buffer = project
-            .update(cx, |project, cx| {
-                let project_path = project.find_project_path("c.rs", cx).unwrap();
-                project.open_buffer(project_path, cx)
-            })
-            .await
-            .unwrap();
-
-        cx.run_until_parked();
-
-        let index_state_arc = index.read_with(cx, |index, _cx| index.state().clone());
-        {
-            let index_state = index_state_arc.lock().await;
-
-            cx.update(|cx| {
-                let decls = index_state.declarations_for_identifier::<8>(&main);
-                assert_eq!(decls.len(), 2);
-                let decl = expect_buffer_decl("c.rs", &decls[0].1, &project, cx);
-                assert_eq!(decl.identifier, main);
-                assert_eq!(decl.item_range.to_offset(&buffer.read(cx)), 32..280);
-
-                expect_file_decl("a.rs", &decls[1].1, &project, cx);
-            });
-        }
-
-        // Drop the buffer and wait for release
-        cx.update(|_| {
-            drop(buffer);
-        });
-        cx.run_until_parked();
-
-        let index_state = index_state_arc.lock().await;
-
-        cx.update(|cx| {
-            let decls = index_state.declarations_for_identifier::<8>(&main);
-            assert_eq!(decls.len(), 2);
-            expect_file_decl("a.rs", &decls[0].1, &project, cx);
-            expect_file_decl("c.rs", &decls[1].1, &project, cx);
-        });
-    }
-
-    fn expect_buffer_decl<'a>(
-        path: &str,
-        declaration: &'a Declaration,
-        project: &Entity<Project>,
-        cx: &App,
-    ) -> &'a BufferDeclaration {
-        if let Declaration::Buffer {
-            declaration,
-            project_entry_id,
-            ..
-        } = declaration
-        {
-            let project_path = project
-                .read(cx)
-                .path_for_entry(*project_entry_id, cx)
-                .unwrap();
-            assert_eq!(project_path.path.as_ref(), rel_path(path),);
-            declaration
-        } else {
-            panic!("Expected a buffer declaration, found {:?}", declaration);
-        }
-    }
-
-    fn expect_file_decl<'a>(
-        path: &str,
-        declaration: &'a Declaration,
-        project: &Entity<Project>,
-        cx: &App,
-    ) -> &'a FileDeclaration {
-        if let Declaration::File {
-            declaration,
-            project_entry_id: file,
-            ..
-        } = declaration
-        {
-            assert_eq!(
-                project
-                    .read(cx)
-                    .path_for_entry(*file, cx)
-                    .unwrap()
-                    .path
-                    .as_ref(),
-                rel_path(path),
-            );
-            declaration
-        } else {
-            panic!("Expected a file declaration, found {:?}", declaration);
-        }
-    }
-
-    async fn init_test(
-        cx: &mut TestAppContext,
-    ) -> (Entity<Project>, Entity<SyntaxIndex>, LanguageId) {
-        cx.update(|cx| {
-            let settings_store = SettingsStore::test(cx);
-            cx.set_global(settings_store);
-        });
-
-        let fs = FakeFs::new(cx.executor());
-        fs.insert_tree(
-            path!("/root"),
-            json!({
-                "a.rs": indoc! {r#"
-                    fn main() {
-                        let x = 1;
-                        let y = 2;
-                        let z = add(x, y);
-                        println!("Result: {}", z);
-                    }
-
-                    fn add(a: i32, b: i32) -> i32 {
-                        a + b
-                    }
-                "#},
-                "b.rs": indoc! {"
-                    pub struct Config {
-                        pub name: String,
-                        pub value: i32,
-                    }
-
-                    impl Config {
-                        pub fn new(name: String, value: i32) -> Self {
-                            Config { name, value }
-                        }
-                    }
-                "},
-                "c.rs": indoc! {r#"
-                    use std::collections::HashMap;
-
-                    fn main() {
-                        let args: Vec<String> = std::env::args().collect();
-                        let data: Vec<i32> = args[1..]
-                            .iter()
-                            .filter_map(|s| s.parse().ok())
-                            .collect();
-                        let result = process_data(data);
-                        println!("{:?}", result);
-                    }
-
-                    fn process_data(data: Vec<i32>) -> HashMap<i32, usize> {
-                        let mut counts = HashMap::new();
-                        for value in data {
-                            *counts.entry(value).or_insert(0) += 1;
-                        }
-                        counts
-                    }
-
-                    #[cfg(test)]
-                    mod tests {
-                        use super::*;
-
-                        #[test]
-                        fn test_process_data() {
-                            let data = vec![1, 2, 2, 3];
-                            let result = process_data(data);
-                            assert_eq!(result.get(&2), Some(&2));
-                        }
-                    }
-                "#}
-            }),
-        )
-        .await;
-        let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
-        let language_registry = project.read_with(cx, |project, _| project.languages().clone());
-        let lang = rust_lang();
-        let lang_id = lang.id();
-        language_registry.add(Arc::new(lang));
-
-        let file_indexing_parallelism = 2;
-        let index = cx.new(|cx| SyntaxIndex::new(&project, file_indexing_parallelism, cx));
-        cx.run_until_parked();
-
-        (project, index, lang_id)
-    }
-
-    fn rust_lang() -> Language {
-        Language::new(
-            LanguageConfig {
-                name: "Rust".into(),
-                matcher: LanguageMatcher {
-                    path_suffixes: vec!["rs".to_string()],
-                    ..Default::default()
-                },
-                ..Default::default()
-            },
-            Some(tree_sitter_rust::LANGUAGE.into()),
-        )
-        .with_outline_query(include_str!("../../languages/src/rust/outline.scm"))
-        .unwrap()
-    }
-}

crates/edit_prediction_context/src/text_similarity.rs 🔗

@@ -1,314 +0,0 @@
-use hashbrown::HashTable;
-use regex::Regex;
-use std::{
-    borrow::Cow,
-    hash::{Hash, Hasher as _},
-    path::Path,
-    sync::LazyLock,
-};
-use util::rel_path::RelPath;
-
-use crate::reference::Reference;
-
-// TODO: Consider implementing sliding window similarity matching like
-// https://github.com/sourcegraph/cody-public-snapshot/blob/8e20ac6c1460c08b0db581c0204658112a246eda/vscode/src/completions/context/retrievers/jaccard-similarity/bestJaccardMatch.ts
-//
-// That implementation could actually be more efficient - no need to track words in the window that
-// are not in the query.
-
-// TODO: Consider a flat sorted Vec<(String, usize)> representation. Intersection can just walk the
-// two in parallel.
-
-static IDENTIFIER_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\b\w+\b").unwrap());
-
-/// Multiset of text occurrences for text similarity that only stores hashes and counts.
-#[derive(Debug, Default)]
-pub struct Occurrences {
-    table: HashTable<OccurrenceEntry>,
-    total_count: usize,
-}
-
-#[derive(Debug)]
-struct OccurrenceEntry {
-    hash: u64,
-    count: usize,
-}
-
-impl Occurrences {
-    pub fn within_string(text: &str) -> Self {
-        Self::from_identifiers(IDENTIFIER_REGEX.find_iter(text).map(|mat| mat.as_str()))
-    }
-
-    #[allow(dead_code)]
-    pub fn within_references(references: &[Reference]) -> Self {
-        Self::from_identifiers(
-            references
-                .iter()
-                .map(|reference| reference.identifier.name.as_ref()),
-        )
-    }
-
-    pub fn from_identifiers(identifiers: impl IntoIterator<Item = impl AsRef<str>>) -> Self {
-        let mut this = Self::default();
-        // TODO: Score matches that match case higher?
-        //
-        // TODO: Also include unsplit identifier?
-        for identifier in identifiers {
-            for identifier_part in split_identifier(identifier.as_ref()) {
-                this.add_hash(fx_hash(&identifier_part.to_lowercase()));
-            }
-        }
-        this
-    }
-
-    pub fn from_worktree_path(worktree_name: Option<Cow<'_, str>>, rel_path: &RelPath) -> Self {
-        if let Some(worktree_name) = worktree_name {
-            Self::from_identifiers(
-                std::iter::once(worktree_name)
-                    .chain(iter_path_without_extension(rel_path.as_std_path())),
-            )
-        } else {
-            Self::from_path(rel_path.as_std_path())
-        }
-    }
-
-    pub fn from_path(path: &Path) -> Self {
-        Self::from_identifiers(iter_path_without_extension(path))
-    }
-
-    fn add_hash(&mut self, hash: u64) {
-        self.table
-            .entry(
-                hash,
-                |entry: &OccurrenceEntry| entry.hash == hash,
-                |entry| entry.hash,
-            )
-            .and_modify(|entry| entry.count += 1)
-            .or_insert(OccurrenceEntry { hash, count: 1 });
-        self.total_count += 1;
-    }
-
-    fn contains_hash(&self, hash: u64) -> bool {
-        self.get_count(hash) != 0
-    }
-
-    fn get_count(&self, hash: u64) -> usize {
-        self.table
-            .find(hash, |entry| entry.hash == hash)
-            .map(|entry| entry.count)
-            .unwrap_or(0)
-    }
-}
-
-fn iter_path_without_extension(path: &Path) -> impl Iterator<Item = Cow<'_, str>> {
-    let last_component: Option<Cow<'_, str>> = path.file_stem().map(|stem| stem.to_string_lossy());
-    let mut path_components = path.components();
-    path_components.next_back();
-    path_components
-        .map(|component| component.as_os_str().to_string_lossy())
-        .chain(last_component)
-}
-
-pub fn fx_hash<T: Hash + ?Sized>(data: &T) -> u64 {
-    let mut hasher = collections::FxHasher::default();
-    data.hash(&mut hasher);
-    hasher.finish()
-}
-
-// Splits camelcase / snakecase / kebabcase / pascalcase
-//
-// TODO: Make this more efficient / elegant.
-fn split_identifier(identifier: &str) -> Vec<&str> {
-    let mut parts = Vec::new();
-    let mut start = 0;
-    let chars: Vec<char> = identifier.chars().collect();
-
-    if chars.is_empty() {
-        return parts;
-    }
-
-    let mut i = 0;
-    while i < chars.len() {
-        let ch = chars[i];
-
-        // Handle explicit delimiters (underscore and hyphen)
-        if ch == '_' || ch == '-' {
-            if i > start {
-                parts.push(&identifier[start..i]);
-            }
-            start = i + 1;
-            i += 1;
-            continue;
-        }
-
-        // Handle camelCase and PascalCase transitions
-        if i > 0 && i < chars.len() {
-            let prev_char = chars[i - 1];
-
-            // Transition from lowercase/digit to uppercase
-            if (prev_char.is_lowercase() || prev_char.is_ascii_digit()) && ch.is_uppercase() {
-                parts.push(&identifier[start..i]);
-                start = i;
-            }
-            // Handle sequences like "XMLParser" -> ["XML", "Parser"]
-            else if i + 1 < chars.len()
-                && ch.is_uppercase()
-                && chars[i + 1].is_lowercase()
-                && prev_char.is_uppercase()
-            {
-                parts.push(&identifier[start..i]);
-                start = i;
-            }
-        }
-
-        i += 1;
-    }
-
-    // Add the last part if there's any remaining
-    if start < identifier.len() {
-        parts.push(&identifier[start..]);
-    }
-
-    // Filter out empty strings
-    parts.into_iter().filter(|s| !s.is_empty()).collect()
-}
-
-pub fn jaccard_similarity<'a>(mut set_a: &'a Occurrences, mut set_b: &'a Occurrences) -> f32 {
-    if set_a.table.len() > set_b.table.len() {
-        std::mem::swap(&mut set_a, &mut set_b);
-    }
-    let intersection = set_a
-        .table
-        .iter()
-        .filter(|entry| set_b.contains_hash(entry.hash))
-        .count();
-    let union = set_a.table.len() + set_b.table.len() - intersection;
-    intersection as f32 / union as f32
-}
-
-// TODO
-#[allow(dead_code)]
-pub fn overlap_coefficient<'a>(mut set_a: &'a Occurrences, mut set_b: &'a Occurrences) -> f32 {
-    if set_a.table.len() > set_b.table.len() {
-        std::mem::swap(&mut set_a, &mut set_b);
-    }
-    let intersection = set_a
-        .table
-        .iter()
-        .filter(|entry| set_b.contains_hash(entry.hash))
-        .count();
-    intersection as f32 / set_a.table.len() as f32
-}
-
-// TODO
-#[allow(dead_code)]
-pub fn weighted_jaccard_similarity<'a>(
-    mut set_a: &'a Occurrences,
-    mut set_b: &'a Occurrences,
-) -> f32 {
-    if set_a.table.len() > set_b.table.len() {
-        std::mem::swap(&mut set_a, &mut set_b);
-    }
-
-    let mut numerator = 0;
-    let mut denominator_a = 0;
-    let mut used_count_b = 0;
-    for entry_a in set_a.table.iter() {
-        let count_a = entry_a.count;
-        let count_b = set_b.get_count(entry_a.hash);
-        numerator += count_a.min(count_b);
-        denominator_a += count_a.max(count_b);
-        used_count_b += count_b;
-    }
-
-    let denominator = denominator_a + (set_b.total_count - used_count_b);
-    if denominator == 0 {
-        0.0
-    } else {
-        numerator as f32 / denominator as f32
-    }
-}
-
-pub fn weighted_overlap_coefficient<'a>(
-    mut set_a: &'a Occurrences,
-    mut set_b: &'a Occurrences,
-) -> f32 {
-    if set_a.table.len() > set_b.table.len() {
-        std::mem::swap(&mut set_a, &mut set_b);
-    }
-
-    let mut numerator = 0;
-    for entry_a in set_a.table.iter() {
-        let count_a = entry_a.count;
-        let count_b = set_b.get_count(entry_a.hash);
-        numerator += count_a.min(count_b);
-    }
-
-    let denominator = set_a.total_count.min(set_b.total_count);
-    if denominator == 0 {
-        0.0
-    } else {
-        numerator as f32 / denominator as f32
-    }
-}
-
-#[cfg(test)]
-mod test {
-    use super::*;
-
-    #[test]
-    fn test_split_identifier() {
-        assert_eq!(split_identifier("snake_case"), vec!["snake", "case"]);
-        assert_eq!(split_identifier("kebab-case"), vec!["kebab", "case"]);
-        assert_eq!(split_identifier("PascalCase"), vec!["Pascal", "Case"]);
-        assert_eq!(split_identifier("camelCase"), vec!["camel", "Case"]);
-        assert_eq!(split_identifier("XMLParser"), vec!["XML", "Parser"]);
-    }
-
-    #[test]
-    fn test_similarity_functions() {
-        // 10 identifier parts, 8 unique
-        // Repeats: 2 "outline", 2 "items"
-        let set_a = Occurrences::within_string(
-            "let mut outline_items = query_outline_items(&language, &tree, &source);",
-        );
-        // 14 identifier parts, 11 unique
-        // Repeats: 2 "outline", 2 "language", 2 "tree"
-        let set_b = Occurrences::within_string(
-            "pub fn query_outline_items(language: &Language, tree: &Tree, source: &str) -> Vec<OutlineItem> {",
-        );
-
-        // 6 overlaps: "outline", "items", "query", "language", "tree", "source"
-        // 7 non-overlaps: "let", "mut", "pub", "fn", "vec", "item", "str"
-        assert_eq!(jaccard_similarity(&set_a, &set_b), 6.0 / (6.0 + 7.0));
-
-        // Numerator is one more than before due to both having 2 "outline".
-        // Denominator is the same except for 3 more due to the non-overlapping duplicates
-        assert_eq!(
-            weighted_jaccard_similarity(&set_a, &set_b),
-            7.0 / (7.0 + 7.0 + 3.0)
-        );
-
-        // Numerator is the same as jaccard_similarity. Denominator is the size of the smaller set, 8.
-        assert_eq!(overlap_coefficient(&set_a, &set_b), 6.0 / 8.0);
-
-        // Numerator is the same as weighted_jaccard_similarity. Denominator is the total weight of
-        // the smaller set, 10.
-        assert_eq!(weighted_overlap_coefficient(&set_a, &set_b), 7.0 / 10.0);
-    }
-
-    #[test]
-    fn test_iter_path_without_extension() {
-        let mut iter = iter_path_without_extension(Path::new(""));
-        assert_eq!(iter.next(), None);
-
-        let iter = iter_path_without_extension(Path::new("foo"));
-        assert_eq!(iter.collect::<Vec<_>>(), ["foo"]);
-
-        let iter = iter_path_without_extension(Path::new("foo/bar.txt"));
-        assert_eq!(iter.collect::<Vec<_>>(), ["foo", "bar"]);
-
-        let iter = iter_path_without_extension(Path::new("foo/bar/baz.txt"));
-        assert_eq!(iter.collect::<Vec<_>>(), ["foo", "bar", "baz"]);
-    }
-}

crates/edit_prediction_types/Cargo.toml 🔗

@@ -0,0 +1,18 @@
+[package]
+name = "edit_prediction_types"
+version = "0.1.0"
+edition.workspace = true
+publish.workspace = true
+license = "GPL-3.0-or-later"
+
+[lints]
+workspace = true
+
+[lib]
+path = "src/edit_prediction_types.rs"
+
+[dependencies]
+client.workspace = true
+gpui.workspace = true
+language.workspace = true
+text.workspace = true

crates/edit_prediction_types/src/edit_prediction_types.rs 🔗

@@ -0,0 +1,278 @@
+use std::{ops::Range, sync::Arc};
+
+use client::EditPredictionUsage;
+use gpui::{App, Context, Entity, SharedString};
+use language::{Anchor, Buffer, OffsetRangeExt};
+
+// TODO: Find a better home for `Direction`.
+//
+// This should live in an ancestor crate of `editor` and `edit_prediction`,
+// but at time of writing there isn't an obvious spot.
+#[derive(Copy, Clone, PartialEq, Eq)]
+pub enum Direction {
+    Prev,
+    Next,
+}
+
+#[derive(Clone)]
+pub enum EditPrediction {
+    /// Edits within the buffer that requested the prediction
+    Local {
+        id: Option<SharedString>,
+        edits: Vec<(Range<language::Anchor>, Arc<str>)>,
+        edit_preview: Option<language::EditPreview>,
+    },
+    /// Jump to a different file from the one that requested the prediction
+    Jump {
+        id: Option<SharedString>,
+        snapshot: language::BufferSnapshot,
+        target: language::Anchor,
+    },
+}
+
+pub enum DataCollectionState {
+    /// The provider doesn't support data collection.
+    Unsupported,
+    /// Data collection is enabled.
+    Enabled { is_project_open_source: bool },
+    /// Data collection is disabled or unanswered.
+    Disabled { is_project_open_source: bool },
+}
+
+impl DataCollectionState {
+    pub fn is_supported(&self) -> bool {
+        !matches!(self, DataCollectionState::Unsupported)
+    }
+
+    pub fn is_enabled(&self) -> bool {
+        matches!(self, DataCollectionState::Enabled { .. })
+    }
+
+    pub fn is_project_open_source(&self) -> bool {
+        match self {
+            Self::Enabled {
+                is_project_open_source,
+            }
+            | Self::Disabled {
+                is_project_open_source,
+            } => *is_project_open_source,
+            _ => false,
+        }
+    }
+}
+
+pub trait EditPredictionDelegate: 'static + Sized {
+    fn name() -> &'static str;
+    fn display_name() -> &'static str;
+    fn show_predictions_in_menu() -> bool;
+    fn show_tab_accept_marker() -> bool {
+        false
+    }
+    fn supports_jump_to_edit() -> bool {
+        true
+    }
+
+    fn data_collection_state(&self, _cx: &App) -> DataCollectionState {
+        DataCollectionState::Unsupported
+    }
+
+    fn usage(&self, _cx: &App) -> Option<EditPredictionUsage> {
+        None
+    }
+
+    fn toggle_data_collection(&mut self, _cx: &mut App) {}
+    fn is_enabled(
+        &self,
+        buffer: &Entity<Buffer>,
+        cursor_position: language::Anchor,
+        cx: &App,
+    ) -> bool;
+    fn is_refreshing(&self, cx: &App) -> bool;
+    fn refresh(
+        &mut self,
+        buffer: Entity<Buffer>,
+        cursor_position: language::Anchor,
+        debounce: bool,
+        cx: &mut Context<Self>,
+    );
+    fn accept(&mut self, cx: &mut Context<Self>);
+    fn discard(&mut self, cx: &mut Context<Self>);
+    fn did_show(&mut self, _cx: &mut Context<Self>) {}
+    fn suggest(
+        &mut self,
+        buffer: &Entity<Buffer>,
+        cursor_position: language::Anchor,
+        cx: &mut Context<Self>,
+    ) -> Option<EditPrediction>;
+}
+
+pub trait EditPredictionDelegateHandle {
+    fn name(&self) -> &'static str;
+    fn display_name(&self) -> &'static str;
+    fn is_enabled(
+        &self,
+        buffer: &Entity<Buffer>,
+        cursor_position: language::Anchor,
+        cx: &App,
+    ) -> bool;
+    fn show_predictions_in_menu(&self) -> bool;
+    fn show_tab_accept_marker(&self) -> bool;
+    fn supports_jump_to_edit(&self) -> bool;
+    fn data_collection_state(&self, cx: &App) -> DataCollectionState;
+    fn usage(&self, cx: &App) -> Option<EditPredictionUsage>;
+    fn toggle_data_collection(&self, cx: &mut App);
+    fn is_refreshing(&self, cx: &App) -> bool;
+    fn refresh(
+        &self,
+        buffer: Entity<Buffer>,
+        cursor_position: language::Anchor,
+        debounce: bool,
+        cx: &mut App,
+    );
+    fn did_show(&self, cx: &mut App);
+    fn accept(&self, cx: &mut App);
+    fn discard(&self, cx: &mut App);
+    fn suggest(
+        &self,
+        buffer: &Entity<Buffer>,
+        cursor_position: language::Anchor,
+        cx: &mut App,
+    ) -> Option<EditPrediction>;
+}
+
+impl<T> EditPredictionDelegateHandle for Entity<T>
+where
+    T: EditPredictionDelegate,
+{
+    fn name(&self) -> &'static str {
+        T::name()
+    }
+
+    fn display_name(&self) -> &'static str {
+        T::display_name()
+    }
+
+    fn show_predictions_in_menu(&self) -> bool {
+        T::show_predictions_in_menu()
+    }
+
+    fn show_tab_accept_marker(&self) -> bool {
+        T::show_tab_accept_marker()
+    }
+
+    fn supports_jump_to_edit(&self) -> bool {
+        T::supports_jump_to_edit()
+    }
+
+    fn data_collection_state(&self, cx: &App) -> DataCollectionState {
+        self.read(cx).data_collection_state(cx)
+    }
+
+    fn usage(&self, cx: &App) -> Option<EditPredictionUsage> {
+        self.read(cx).usage(cx)
+    }
+
+    fn toggle_data_collection(&self, cx: &mut App) {
+        self.update(cx, |this, cx| this.toggle_data_collection(cx))
+    }
+
+    fn is_enabled(
+        &self,
+        buffer: &Entity<Buffer>,
+        cursor_position: language::Anchor,
+        cx: &App,
+    ) -> bool {
+        self.read(cx).is_enabled(buffer, cursor_position, cx)
+    }
+
+    fn is_refreshing(&self, cx: &App) -> bool {
+        self.read(cx).is_refreshing(cx)
+    }
+
+    fn refresh(
+        &self,
+        buffer: Entity<Buffer>,
+        cursor_position: language::Anchor,
+        debounce: bool,
+        cx: &mut App,
+    ) {
+        self.update(cx, |this, cx| {
+            this.refresh(buffer, cursor_position, debounce, cx)
+        })
+    }
+
+    fn accept(&self, cx: &mut App) {
+        self.update(cx, |this, cx| this.accept(cx))
+    }
+
+    fn discard(&self, cx: &mut App) {
+        self.update(cx, |this, cx| this.discard(cx))
+    }
+
+    fn did_show(&self, cx: &mut App) {
+        self.update(cx, |this, cx| this.did_show(cx))
+    }
+
+    fn suggest(
+        &self,
+        buffer: &Entity<Buffer>,
+        cursor_position: language::Anchor,
+        cx: &mut App,
+    ) -> Option<EditPrediction> {
+        self.update(cx, |this, cx| this.suggest(buffer, cursor_position, cx))
+    }
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum EditPredictionGranularity {
+    Word,
+    Line,
+    Full,
+}
+/// Returns edits updated based on user edits since the old snapshot. None is returned if any user
+/// edit is not a prefix of a predicted insertion.
+pub fn interpolate_edits(
+    old_snapshot: &text::BufferSnapshot,
+    new_snapshot: &text::BufferSnapshot,
+    current_edits: &[(Range<Anchor>, Arc<str>)],
+) -> Option<Vec<(Range<Anchor>, Arc<str>)>> {
+    let mut edits = Vec::new();
+
+    let mut model_edits = current_edits.iter().peekable();
+    for user_edit in new_snapshot.edits_since::<usize>(&old_snapshot.version) {
+        while let Some((model_old_range, _)) = model_edits.peek() {
+            let model_old_range = model_old_range.to_offset(old_snapshot);
+            if model_old_range.end < user_edit.old.start {
+                let (model_old_range, model_new_text) = model_edits.next().unwrap();
+                edits.push((model_old_range.clone(), model_new_text.clone()));
+            } else {
+                break;
+            }
+        }
+
+        if let Some((model_old_range, model_new_text)) = model_edits.peek() {
+            let model_old_offset_range = model_old_range.to_offset(old_snapshot);
+            if user_edit.old == model_old_offset_range {
+                let user_new_text = new_snapshot
+                    .text_for_range(user_edit.new.clone())
+                    .collect::<String>();
+
+                if let Some(model_suffix) = model_new_text.strip_prefix(&user_new_text) {
+                    if !model_suffix.is_empty() {
+                        let anchor = old_snapshot.anchor_after(user_edit.old.end);
+                        edits.push((anchor..anchor, model_suffix.into()));
+                    }
+
+                    model_edits.next();
+                    continue;
+                }
+            }
+        }
+
+        return None;
+    }
+
+    edits.extend(model_edits.cloned());
+
+    if edits.is_empty() { None } else { Some(edits) }
+}

crates/edit_prediction_button/Cargo.toml → crates/edit_prediction_ui/Cargo.toml 🔗

@@ -1,5 +1,5 @@
 [package]
-name = "edit_prediction_button"
+name = "edit_prediction_ui"
 version = "0.1.0"
 edition.workspace = true
 publish.workspace = true
@@ -9,42 +9,58 @@ license = "GPL-3.0-or-later"
 workspace = true
 
 [lib]
-path = "src/edit_prediction_button.rs"
+path = "src/edit_prediction_ui.rs"
 doctest = false
 
 [dependencies]
 anyhow.workspace = true
+buffer_diff.workspace = true
+collections.workspace = true
+time.workspace = true
 client.workspace = true
 cloud_llm_client.workspace = true
 codestral.workspace = true
+command_palette_hooks.workspace = true
 copilot.workspace = true
+edit_prediction_types.workspace = true
 edit_prediction.workspace = true
 editor.workspace = true
 feature_flags.workspace = true
 fs.workspace = true
+futures.workspace = true
 gpui.workspace = true
 indoc.workspace = true
 language.workspace = true
+markdown.workspace = true
+menu.workspace = true
+multi_buffer.workspace = true
 paths.workspace = true
 project.workspace = true
 regex.workspace = true
 settings.workspace = true
 supermaven.workspace = true
 telemetry.workspace = true
+text.workspace = true
+theme.workspace = true
 ui.workspace = true
-ui_input.workspace = true
-menu.workspace = true
 util.workspace = true
 workspace.workspace = true
 zed_actions.workspace = true
-zeta.workspace = true
+zeta_prompt.workspace = true
 
 [dev-dependencies]
+clock.workspace = true
 copilot = { workspace = true, features = ["test-support"] }
 editor = { workspace = true, features = ["test-support"] }
 futures.workspace = true
 indoc.workspace = true
+language_model.workspace = true
 lsp = { workspace = true, features = ["test-support"] }
+pretty_assertions.workspace = true
 project = { workspace = true, features = ["test-support"] }
+release_channel.workspace = true
+semver.workspace = true
 serde_json.workspace = true
 theme = { workspace = true, features = ["test-support"] }
+workspace = { workspace = true, features = ["test-support"] }
+zlog.workspace = true

crates/edit_prediction_button/src/edit_prediction_button.rs → crates/edit_prediction_ui/src/edit_prediction_button.rs 🔗

@@ -1,16 +1,16 @@
-mod sweep_api_token_modal;
-
-pub use sweep_api_token_modal::SweepApiKeyModal;
-
 use anyhow::Result;
 use client::{Client, UserStore, zed_urls};
 use cloud_llm_client::UsageLimit;
-use codestral::CodestralCompletionProvider;
+use codestral::CodestralEditPredictionDelegate;
 use copilot::{Copilot, Status};
+use edit_prediction::{
+    EditPredictionStore, MercuryFeatureFlag, SweepFeatureFlag, Zeta2FeatureFlag,
+};
+use edit_prediction_types::EditPredictionDelegateHandle;
 use editor::{
     Editor, MultiBufferOffset, SelectionEffects, actions::ShowEditPrediction, scroll::Autoscroll,
 };
-use feature_flags::{FeatureFlagAppExt, PredictEditsRateCompletionsFeatureFlag};
+use feature_flags::FeatureFlagAppExt;
 use fs::Fs;
 use gpui::{
     Action, Animation, AnimationExt, App, AsyncWindowContext, Corner, Entity, FocusHandle,
@@ -25,6 +25,7 @@ use language::{
 use project::DisableAiSettings;
 use regex::Regex;
 use settings::{
+    EXPERIMENTAL_MERCURY_EDIT_PREDICTION_PROVIDER_NAME,
     EXPERIMENTAL_SWEEP_EDIT_PREDICTION_PROVIDER_NAME,
     EXPERIMENTAL_ZETA2_EDIT_PREDICTION_PROVIDER_NAME, Settings, SettingsStore,
     update_settings_file,
@@ -43,8 +44,11 @@ use workspace::{
     StatusItemView, Toast, Workspace, create_and_open_local_file, item::ItemHandle,
     notifications::NotificationId,
 };
-use zed_actions::OpenBrowser;
-use zeta::{RateCompletions, SweepFeatureFlag, Zeta2FeatureFlag};
+use zed_actions::{OpenBrowser, OpenSettingsAt};
+
+use crate::{
+    CaptureExample, RatePredictions, rate_prediction_modal::PredictEditsRatePredictionsFeatureFlag,
+};
 
 actions!(
     edit_prediction,
@@ -67,7 +71,7 @@ pub struct EditPredictionButton {
     editor_focus_handle: Option<FocusHandle>,
     language: Option<Arc<Language>>,
     file: Option<Arc<dyn File>>,
-    edit_prediction_provider: Option<Arc<dyn edit_prediction::EditPredictionProviderHandle>>,
+    edit_prediction_provider: Option<Arc<dyn EditPredictionDelegateHandle>>,
     fs: Arc<dyn Fs>,
     user_store: Entity<UserStore>,
     popover_menu_handle: PopoverMenuHandle<ContextMenu>,
@@ -244,46 +248,22 @@ impl Render for EditPredictionButton {
 
             EditPredictionProvider::Codestral => {
                 let enabled = self.editor_enabled.unwrap_or(true);
-                let has_api_key = CodestralCompletionProvider::has_api_key(cx);
-                let fs = self.fs.clone();
+                let has_api_key = CodestralEditPredictionDelegate::has_api_key(cx);
                 let this = cx.weak_entity();
 
+                let tooltip_meta = if has_api_key {
+                    "Powered by Codestral"
+                } else {
+                    "Missing API key for Codestral"
+                };
+
                 div().child(
                     PopoverMenu::new("codestral")
                         .menu(move |window, cx| {
-                            if has_api_key {
-                                this.update(cx, |this, cx| {
-                                    this.build_codestral_context_menu(window, cx)
-                                })
-                                .ok()
-                            } else {
-                                Some(ContextMenu::build(window, cx, |menu, _, _| {
-                                    let fs = fs.clone();
-
-                                    menu.entry(
-                                        "Configure Codestral API Key",
-                                        None,
-                                        move |window, cx| {
-                                            window.dispatch_action(
-                                                zed_actions::agent::OpenSettings.boxed_clone(),
-                                                cx,
-                                            );
-                                        },
-                                    )
-                                    .separator()
-                                    .entry(
-                                        "Use Zed AI instead",
-                                        None,
-                                        move |_, cx| {
-                                            set_completion_provider(
-                                                fs.clone(),
-                                                cx,
-                                                EditPredictionProvider::Zed,
-                                            )
-                                        },
-                                    )
-                                }))
-                            }
+                            this.update(cx, |this, cx| {
+                                this.build_codestral_context_menu(window, cx)
+                            })
+                            .ok()
                         })
                         .anchor(Corner::BottomRight)
                         .trigger_with_tooltip(
@@ -301,7 +281,14 @@ impl Render for EditPredictionButton {
                                             cx.theme().colors().status_bar_background,
                                         ))
                                 }),
-                            move |_window, cx| Tooltip::for_action("Codestral", &ToggleMenu, cx),
+                            move |_window, cx| {
+                                Tooltip::with_meta(
+                                    "Edit Prediction",
+                                    Some(&ToggleMenu),
+                                    tooltip_meta,
+                                    cx,
+                                )
+                            },
                         )
                         .with_handle(self.popover_menu_handle.clone()),
                 )
@@ -309,24 +296,46 @@ impl Render for EditPredictionButton {
             provider @ (EditPredictionProvider::Experimental(_) | EditPredictionProvider::Zed) => {
                 let enabled = self.editor_enabled.unwrap_or(true);
 
-                let is_sweep = matches!(
-                    provider,
-                    EditPredictionProvider::Experimental(
-                        EXPERIMENTAL_SWEEP_EDIT_PREDICTION_PROVIDER_NAME
-                    )
-                );
-
-                let sweep_missing_token = is_sweep
-                    && !zeta::Zeta::try_global(cx)
-                        .map_or(false, |zeta| zeta.read(cx).has_sweep_api_token());
+                let ep_icon;
+                let tooltip_meta;
+                let mut missing_token = false;
 
-                let zeta_icon = match (is_sweep, enabled) {
-                    (true, _) => IconName::SweepAi,
-                    (false, true) => IconName::ZedPredict,
-                    (false, false) => IconName::ZedPredictDisabled,
+                match provider {
+                    EditPredictionProvider::Experimental(
+                        EXPERIMENTAL_SWEEP_EDIT_PREDICTION_PROVIDER_NAME,
+                    ) => {
+                        ep_icon = IconName::SweepAi;
+                        tooltip_meta = if missing_token {
+                            "Missing API key for Sweep"
+                        } else {
+                            "Powered by Sweep"
+                        };
+                        missing_token = edit_prediction::EditPredictionStore::try_global(cx)
+                            .is_some_and(|ep_store| !ep_store.read(cx).has_sweep_api_token(cx));
+                    }
+                    EditPredictionProvider::Experimental(
+                        EXPERIMENTAL_MERCURY_EDIT_PREDICTION_PROVIDER_NAME,
+                    ) => {
+                        ep_icon = IconName::Inception;
+                        missing_token = edit_prediction::EditPredictionStore::try_global(cx)
+                            .is_some_and(|ep_store| !ep_store.read(cx).has_mercury_api_token(cx));
+                        tooltip_meta = if missing_token {
+                            "Missing API key for Mercury"
+                        } else {
+                            "Powered by Mercury"
+                        };
+                    }
+                    _ => {
+                        ep_icon = if enabled {
+                            IconName::ZedPredict
+                        } else {
+                            IconName::ZedPredictDisabled
+                        };
+                        tooltip_meta = "Powered by Zeta"
+                    }
                 };
 
-                if zeta::should_show_upsell_modal() {
+                if edit_prediction::should_show_upsell_modal() {
                     let tooltip_meta = if self.user_store.read(cx).current_user().is_some() {
                         "Choose a Plan"
                     } else {
@@ -334,7 +343,7 @@ impl Render for EditPredictionButton {
                     };
 
                     return div().child(
-                        IconButton::new("zed-predict-pending-button", zeta_icon)
+                        IconButton::new("zed-predict-pending-button", ep_icon)
                             .shape(IconButtonShape::Square)
                             .indicator(Indicator::dot().color(Color::Muted))
                             .indicator_border_color(Some(cx.theme().colors().status_bar_background))
@@ -367,7 +376,7 @@ impl Render for EditPredictionButton {
                 let show_editor_predictions = self.editor_show_predictions;
                 let user = self.user_store.read(cx).current_user();
 
-                let indicator_color = if sweep_missing_token {
+                let indicator_color = if missing_token {
                     Some(Color::Error)
                 } else if enabled && (!show_editor_predictions || over_limit) {
                     Some(if over_limit {
@@ -379,7 +388,7 @@ impl Render for EditPredictionButton {
                     None
                 };
 
-                let icon_button = IconButton::new("zed-predict-pending-button", zeta_icon)
+                let icon_button = IconButton::new("zed-predict-pending-button", ep_icon)
                     .shape(IconButtonShape::Square)
                     .when_some(indicator_color, |this, color| {
                         this.indicator(Indicator::dot().color(color))
@@ -387,45 +396,38 @@ impl Render for EditPredictionButton {
                     })
                     .when(!self.popover_menu_handle.is_deployed(), |element| {
                         let user = user.clone();
+
                         element.tooltip(move |_window, cx| {
-                            if enabled {
+                            let description = if enabled {
                                 if show_editor_predictions {
-                                    Tooltip::for_action("Edit Prediction", &ToggleMenu, cx)
+                                    tooltip_meta
                                 } else if user.is_none() {
-                                    Tooltip::with_meta(
-                                        "Edit Prediction",
-                                        Some(&ToggleMenu),
-                                        "Sign In To Use",
-                                        cx,
-                                    )
+                                    "Sign In To Use"
                                 } else {
-                                    Tooltip::with_meta(
-                                        "Edit Prediction",
-                                        Some(&ToggleMenu),
-                                        "Hidden For This File",
-                                        cx,
-                                    )
+                                    "Hidden For This File"
                                 }
                             } else {
-                                Tooltip::with_meta(
-                                    "Edit Prediction",
-                                    Some(&ToggleMenu),
-                                    "Disabled For This File",
-                                    cx,
-                                )
-                            }
+                                "Disabled For This File"
+                            };
+
+                            Tooltip::with_meta(
+                                "Edit Prediction",
+                                Some(&ToggleMenu),
+                                description,
+                                cx,
+                            )
                         })
                     });
 
                 let this = cx.weak_entity();
 
-                let mut popover_menu = PopoverMenu::new("zeta")
+                let mut popover_menu = PopoverMenu::new("edit-prediction")
                     .when(user.is_some(), |popover_menu| {
                         let this = this.clone();
 
                         popover_menu.menu(move |window, cx| {
                             this.update(cx, |this, cx| {
-                                this.build_zeta_context_menu(provider, window, cx)
+                                this.build_edit_prediction_context_menu(provider, window, cx)
                             })
                             .ok()
                         })
@@ -485,7 +487,22 @@ impl EditPredictionButton {
         cx.observe_global::<SettingsStore>(move |_, cx| cx.notify())
             .detach();
 
-        CodestralCompletionProvider::ensure_api_key_loaded(client.http_client(), cx);
+        cx.observe_global::<EditPredictionStore>(move |_, cx| cx.notify())
+            .detach();
+
+        let sweep_api_token_task = edit_prediction::sweep_ai::load_sweep_api_token(cx);
+        let mercury_api_token_task = edit_prediction::mercury::load_mercury_api_token(cx);
+
+        cx.spawn(async move |this, cx| {
+            _ = futures::join!(sweep_api_token_task, mercury_api_token_task);
+            this.update(cx, |_, cx| {
+                cx.notify();
+            })
+            .ok();
+        })
+        .detach();
+
+        CodestralEditPredictionDelegate::ensure_api_key_loaded(client.http_client(), cx);
 
         Self {
             editor_subscription: None,
@@ -501,11 +518,17 @@ impl EditPredictionButton {
         }
     }
 
-    fn get_available_providers(&self, cx: &App) -> Vec<EditPredictionProvider> {
+    fn get_available_providers(&self, cx: &mut App) -> Vec<EditPredictionProvider> {
         let mut providers = Vec::new();
 
         providers.push(EditPredictionProvider::Zed);
 
+        if cx.has_flag::<Zeta2FeatureFlag>() {
+            providers.push(EditPredictionProvider::Experimental(
+                EXPERIMENTAL_ZETA2_EDIT_PREDICTION_PROVIDER_NAME,
+            ));
+        }
+
         if let Some(copilot) = Copilot::global(cx) {
             if matches!(copilot.read(cx).status(), Status::Authorized) {
                 providers.push(EditPredictionProvider::Copilot);
@@ -520,19 +543,27 @@ impl EditPredictionButton {
             }
         }
 
-        if CodestralCompletionProvider::has_api_key(cx) {
+        if CodestralEditPredictionDelegate::has_api_key(cx) {
             providers.push(EditPredictionProvider::Codestral);
         }
 
-        if cx.has_flag::<SweepFeatureFlag>() {
+        if cx.has_flag::<SweepFeatureFlag>()
+            && edit_prediction::sweep_ai::sweep_api_token(cx)
+                .read(cx)
+                .has_key()
+        {
             providers.push(EditPredictionProvider::Experimental(
                 EXPERIMENTAL_SWEEP_EDIT_PREDICTION_PROVIDER_NAME,
             ));
         }
 
-        if cx.has_flag::<Zeta2FeatureFlag>() {
+        if cx.has_flag::<MercuryFeatureFlag>()
+            && edit_prediction::mercury::mercury_api_token(cx)
+                .read(cx)
+                .has_key()
+        {
             providers.push(EditPredictionProvider::Experimental(
-                EXPERIMENTAL_ZETA2_EDIT_PREDICTION_PROVIDER_NAME,
+                EXPERIMENTAL_MERCURY_EDIT_PREDICTION_PROVIDER_NAME,
             ));
         }
 
@@ -543,13 +574,10 @@ impl EditPredictionButton {
         &self,
         mut menu: ContextMenu,
         current_provider: EditPredictionProvider,
-        cx: &App,
+        cx: &mut App,
     ) -> ContextMenu {
         let available_providers = self.get_available_providers(cx);
 
-        const ZED_AI_CALLOUT: &str =
-            "Zed's edit prediction is powered by Zeta, an open-source, dataset mode.";
-
         let providers: Vec<_> = available_providers
             .into_iter()
             .filter(|p| *p != EditPredictionProvider::None)
@@ -562,94 +590,32 @@ impl EditPredictionButton {
                 let is_current = provider == current_provider;
                 let fs = self.fs.clone();
 
-                menu = match provider {
-                    EditPredictionProvider::Zed => menu.item(
-                        ContextMenuEntry::new("Zed AI")
-                            .toggleable(IconPosition::Start, is_current)
-                            .documentation_aside(
-                                DocumentationSide::Left,
-                                DocumentationEdge::Bottom,
-                                |_| Label::new(ZED_AI_CALLOUT).into_any_element(),
-                            )
-                            .handler(move |_, cx| {
-                                set_completion_provider(fs.clone(), cx, provider);
-                            }),
-                    ),
-                    EditPredictionProvider::Copilot => menu.item(
-                        ContextMenuEntry::new("GitHub Copilot")
-                            .toggleable(IconPosition::Start, is_current)
-                            .handler(move |_, cx| {
-                                set_completion_provider(fs.clone(), cx, provider);
-                            }),
-                    ),
-                    EditPredictionProvider::Supermaven => menu.item(
-                        ContextMenuEntry::new("Supermaven")
-                            .toggleable(IconPosition::Start, is_current)
-                            .handler(move |_, cx| {
-                                set_completion_provider(fs.clone(), cx, provider);
-                            }),
-                    ),
-                    EditPredictionProvider::Codestral => menu.item(
-                        ContextMenuEntry::new("Codestral")
-                            .toggleable(IconPosition::Start, is_current)
-                            .handler(move |_, cx| {
-                                set_completion_provider(fs.clone(), cx, provider);
-                            }),
-                    ),
+                let name = match provider {
+                    EditPredictionProvider::Zed => "Zed AI",
+                    EditPredictionProvider::Copilot => "GitHub Copilot",
+                    EditPredictionProvider::Supermaven => "Supermaven",
+                    EditPredictionProvider::Codestral => "Codestral",
                     EditPredictionProvider::Experimental(
                         EXPERIMENTAL_SWEEP_EDIT_PREDICTION_PROVIDER_NAME,
-                    ) => {
-                        let has_api_token = zeta::Zeta::try_global(cx)
-                            .map_or(false, |zeta| zeta.read(cx).has_sweep_api_token());
-
-                        let should_open_modal = !has_api_token || is_current;
-
-                        let entry = if has_api_token {
-                            ContextMenuEntry::new("Sweep")
-                                .toggleable(IconPosition::Start, is_current)
-                        } else {
-                            ContextMenuEntry::new("Sweep")
-                                .icon(IconName::XCircle)
-                                .icon_color(Color::Error)
-                                .documentation_aside(
-                                    DocumentationSide::Left,
-                                    DocumentationEdge::Bottom,
-                                    |_| {
-                                        Label::new("Click to configure your Sweep API token")
-                                            .into_any_element()
-                                    },
-                                )
-                        };
-
-                        let entry = entry.handler(move |window, cx| {
-                            if should_open_modal {
-                                if let Some(workspace) = window.root::<Workspace>().flatten() {
-                                    workspace.update(cx, |workspace, cx| {
-                                        workspace.toggle_modal(window, cx, |window, cx| {
-                                            SweepApiKeyModal::new(window, cx)
-                                        });
-                                    });
-                                };
-                            } else {
-                                set_completion_provider(fs.clone(), cx, provider);
-                            }
-                        });
-
-                        menu.item(entry)
-                    }
+                    ) => "Sweep",
+                    EditPredictionProvider::Experimental(
+                        EXPERIMENTAL_MERCURY_EDIT_PREDICTION_PROVIDER_NAME,
+                    ) => "Mercury",
                     EditPredictionProvider::Experimental(
                         EXPERIMENTAL_ZETA2_EDIT_PREDICTION_PROVIDER_NAME,
-                    ) => menu.item(
-                        ContextMenuEntry::new("Zeta2")
-                            .toggleable(IconPosition::Start, is_current)
-                            .handler(move |_, cx| {
-                                set_completion_provider(fs.clone(), cx, provider);
-                            }),
-                    ),
+                    ) => "Zeta2",
                     EditPredictionProvider::None | EditPredictionProvider::Experimental(_) => {
                         continue;
                     }
                 };
+
+                menu = menu.item(
+                    ContextMenuEntry::new(name)
+                        .toggleable(IconPosition::Start, is_current)
+                        .handler(move |_, cx| {
+                            set_completion_provider(fs.clone(), cx, provider);
+                        }),
+                )
             }
         }
 
@@ -754,14 +720,7 @@ impl EditPredictionButton {
         let subtle_mode = matches!(current_mode, EditPredictionsMode::Subtle);
         let eager_mode = matches!(current_mode, EditPredictionsMode::Eager);
 
-        if matches!(
-            provider,
-            EditPredictionProvider::Zed
-                | EditPredictionProvider::Copilot
-                | EditPredictionProvider::Supermaven
-                | EditPredictionProvider::Codestral
-        ) {
-            menu = menu
+        menu = menu
                 .separator()
                 .header("Display Modes")
                 .item(
@@ -790,104 +749,111 @@ impl EditPredictionButton {
                             }
                         }),
                 );
-        }
 
         menu = menu.separator().header("Privacy");
 
-        if let Some(provider) = &self.edit_prediction_provider {
-            let data_collection = provider.data_collection_state(cx);
-
-            if data_collection.is_supported() {
-                let provider = provider.clone();
-                let enabled = data_collection.is_enabled();
-                let is_open_source = data_collection.is_project_open_source();
-                let is_collecting = data_collection.is_enabled();
-                let (icon_name, icon_color) = if is_open_source && is_collecting {
-                    (IconName::Check, Color::Success)
-                } else {
-                    (IconName::Check, Color::Accent)
-                };
-
-                menu = menu.item(
-                    ContextMenuEntry::new("Training Data Collection")
-                        .toggleable(IconPosition::Start, data_collection.is_enabled())
-                        .icon(icon_name)
-                        .icon_color(icon_color)
-                        .documentation_aside(DocumentationSide::Left, DocumentationEdge::Top, move |cx| {
-                            let (msg, label_color, icon_name, icon_color) = match (is_open_source, is_collecting) {
-                                (true, true) => (
-                                    "Project identified as open source, and you're sharing data.",
-                                    Color::Default,
-                                    IconName::Check,
-                                    Color::Success,
-                                ),
-                                (true, false) => (
-                                    "Project identified as open source, but you're not sharing data.",
-                                    Color::Muted,
-                                    IconName::Close,
-                                    Color::Muted,
-                                ),
-                                (false, true) => (
-                                    "Project not identified as open source. No data captured.",
-                                    Color::Muted,
-                                    IconName::Close,
-                                    Color::Muted,
-                                ),
-                                (false, false) => (
-                                    "Project not identified as open source, and setting turned off.",
-                                    Color::Muted,
-                                    IconName::Close,
-                                    Color::Muted,
-                                ),
-                            };
-                            v_flex()
-                                .gap_2()
-                                .child(
-                                    Label::new(indoc!{
-                                        "Help us improve our open dataset model by sharing data from open source repositories. \
-                                        Zed must detect a license file in your repo for this setting to take effect. \
-                                        Files with sensitive data and secrets are excluded by default."
-                                    })
-                                )
-                                .child(
-                                    h_flex()
-                                        .items_start()
-                                        .pt_2()
-                                        .pr_1()
-                                        .flex_1()
-                                        .gap_1p5()
-                                        .border_t_1()
-                                        .border_color(cx.theme().colors().border_variant)
-                                        .child(h_flex().flex_shrink_0().h(line_height).child(Icon::new(icon_name).size(IconSize::XSmall).color(icon_color)))
-                                        .child(div().child(msg).w_full().text_sm().text_color(label_color.color(cx)))
-                                )
-                                .into_any_element()
-                        })
-                        .handler(move |_, cx| {
-                            provider.toggle_data_collection(cx);
-
-                            if !enabled {
-                                telemetry::event!(
-                                    "Data Collection Enabled",
-                                    source = "Edit Prediction Status Menu"
-                                );
-                            } else {
-                                telemetry::event!(
-                                    "Data Collection Disabled",
-                                    source = "Edit Prediction Status Menu"
-                                );
-                            }
-                        })
-                );
+        if matches!(
+            provider,
+            EditPredictionProvider::Zed
+                | EditPredictionProvider::Experimental(
+                    EXPERIMENTAL_ZETA2_EDIT_PREDICTION_PROVIDER_NAME,
+                )
+        ) {
+            if let Some(provider) = &self.edit_prediction_provider {
+                let data_collection = provider.data_collection_state(cx);
+
+                if data_collection.is_supported() {
+                    let provider = provider.clone();
+                    let enabled = data_collection.is_enabled();
+                    let is_open_source = data_collection.is_project_open_source();
+                    let is_collecting = data_collection.is_enabled();
+                    let (icon_name, icon_color) = if is_open_source && is_collecting {
+                        (IconName::Check, Color::Success)
+                    } else {
+                        (IconName::Check, Color::Accent)
+                    };
 
-                if is_collecting && !is_open_source {
                     menu = menu.item(
-                        ContextMenuEntry::new("No data captured.")
-                            .disabled(true)
-                            .icon(IconName::Close)
-                            .icon_color(Color::Error)
-                            .icon_size(IconSize::Small),
+                        ContextMenuEntry::new("Training Data Collection")
+                            .toggleable(IconPosition::Start, data_collection.is_enabled())
+                            .icon(icon_name)
+                            .icon_color(icon_color)
+                            .documentation_aside(DocumentationSide::Left, DocumentationEdge::Top, move |cx| {
+                                let (msg, label_color, icon_name, icon_color) = match (is_open_source, is_collecting) {
+                                    (true, true) => (
+                                        "Project identified as open source, and you're sharing data.",
+                                        Color::Default,
+                                        IconName::Check,
+                                        Color::Success,
+                                    ),
+                                    (true, false) => (
+                                        "Project identified as open source, but you're not sharing data.",
+                                        Color::Muted,
+                                        IconName::Close,
+                                        Color::Muted,
+                                    ),
+                                    (false, true) => (
+                                        "Project not identified as open source. No data captured.",
+                                        Color::Muted,
+                                        IconName::Close,
+                                        Color::Muted,
+                                    ),
+                                    (false, false) => (
+                                        "Project not identified as open source, and setting turned off.",
+                                        Color::Muted,
+                                        IconName::Close,
+                                        Color::Muted,
+                                    ),
+                                };
+                                v_flex()
+                                    .gap_2()
+                                    .child(
+                                        Label::new(indoc!{
+                                            "Help us improve our open dataset model by sharing data from open source repositories. \
+                                            Zed must detect a license file in your repo for this setting to take effect. \
+                                            Files with sensitive data and secrets are excluded by default."
+                                        })
+                                    )
+                                    .child(
+                                        h_flex()
+                                            .items_start()
+                                            .pt_2()
+                                            .pr_1()
+                                            .flex_1()
+                                            .gap_1p5()
+                                            .border_t_1()
+                                            .border_color(cx.theme().colors().border_variant)
+                                            .child(h_flex().flex_shrink_0().h(line_height).child(Icon::new(icon_name).size(IconSize::XSmall).color(icon_color)))
+                                            .child(div().child(msg).w_full().text_sm().text_color(label_color.color(cx)))
+                                    )
+                                    .into_any_element()
+                            })
+                            .handler(move |_, cx| {
+                                provider.toggle_data_collection(cx);
+
+                                if !enabled {
+                                    telemetry::event!(
+                                        "Data Collection Enabled",
+                                        source = "Edit Prediction Status Menu"
+                                    );
+                                } else {
+                                    telemetry::event!(
+                                        "Data Collection Disabled",
+                                        source = "Edit Prediction Status Menu"
+                                    );
+                                }
+                            })
                     );
+
+                    if is_collecting && !is_open_source {
+                        menu = menu.item(
+                            ContextMenuEntry::new("No data captured.")
+                                .disabled(true)
+                                .icon(IconName::Close)
+                                .icon_color(Color::Error)
+                                .icon_size(IconSize::Small),
+                        );
+                    }
                 }
             }
         }
@@ -947,8 +913,11 @@ impl EditPredictionButton {
                 )
                 .context(editor_focus_handle)
                 .when(
-                    cx.has_flag::<PredictEditsRateCompletionsFeatureFlag>(),
-                    |this| this.action("Rate Completions", RateCompletions.boxed_clone()),
+                    cx.has_flag::<PredictEditsRatePredictionsFeatureFlag>(),
+                    |this| {
+                        this.action("Capture Prediction Example", CaptureExample.boxed_clone())
+                            .action("Rate Predictions", RatePredictions.boxed_clone())
+                    },
                 );
         }
 
@@ -1009,14 +978,11 @@ impl EditPredictionButton {
             let menu =
                 self.add_provider_switching_section(menu, EditPredictionProvider::Codestral, cx);
 
-            menu.separator()
-                .entry("Configure Codestral API Key", None, move |window, cx| {
-                    window.dispatch_action(zed_actions::agent::OpenSettings.boxed_clone(), cx);
-                })
+            menu
         })
     }
 
-    fn build_zeta_context_menu(
+    fn build_edit_prediction_context_menu(
         &self,
         provider: EditPredictionProvider,
         window: &mut Window,
@@ -1105,8 +1071,48 @@ impl EditPredictionButton {
                     .separator();
             }
 
-            let menu = self.build_language_settings_menu(menu, window, cx);
-            let menu = self.add_provider_switching_section(menu, provider, cx);
+            menu = self.build_language_settings_menu(menu, window, cx);
+
+            if cx.has_flag::<Zeta2FeatureFlag>() {
+                let settings = all_language_settings(None, cx);
+                let context_retrieval = settings.edit_predictions.use_context;
+                menu = menu.separator().header("Context Retrieval").item(
+                    ContextMenuEntry::new("Enable Context Retrieval")
+                        .toggleable(IconPosition::Start, context_retrieval)
+                        .action(workspace::ToggleEditPrediction.boxed_clone())
+                        .handler({
+                            let fs = self.fs.clone();
+                            move |_, cx| {
+                                update_settings_file(fs.clone(), cx, move |settings, _| {
+                                    settings
+                                        .project
+                                        .all_languages
+                                        .features
+                                        .get_or_insert_default()
+                                        .experimental_edit_prediction_context_retrieval =
+                                        Some(!context_retrieval)
+                                });
+                            }
+                        }),
+                );
+            }
+
+            menu = self.add_provider_switching_section(menu, provider, cx);
+            menu = menu.separator().item(
+                ContextMenuEntry::new("Configure Providers")
+                    .icon(IconName::Settings)
+                    .icon_position(IconPosition::Start)
+                    .icon_color(Color::Muted)
+                    .handler(move |window, cx| {
+                        window.dispatch_action(
+                            OpenSettingsAt {
+                                path: "edit_predictions.providers".to_string(),
+                            }
+                            .boxed_clone(),
+                            cx,
+                        );
+                    }),
+            );
 
             menu
         })

crates/edit_prediction_ui/src/edit_prediction_context_view.rs 🔗

@@ -0,0 +1,370 @@
+use std::{
+    any::TypeId,
+    collections::VecDeque,
+    ops::Add,
+    sync::Arc,
+    time::{Duration, Instant},
+};
+
+use anyhow::Result;
+use client::{Client, UserStore};
+use editor::{Editor, PathKey};
+use futures::StreamExt as _;
+use gpui::{
+    Animation, AnimationExt, App, AppContext as _, Context, Entity, EventEmitter, FocusHandle,
+    Focusable, InteractiveElement as _, IntoElement as _, ParentElement as _, SharedString,
+    Styled as _, Task, TextAlign, Window, actions, div, pulsating_between,
+};
+use multi_buffer::MultiBuffer;
+use project::Project;
+use text::Point;
+use ui::{
+    ButtonCommon, Clickable, Disableable, FluentBuilder as _, IconButton, IconName,
+    StyledTypography as _, h_flex, v_flex,
+};
+
+use edit_prediction::{
+    ContextRetrievalFinishedDebugEvent, ContextRetrievalStartedDebugEvent, DebugEvent,
+    EditPredictionStore,
+};
+use workspace::Item;
+
+pub struct EditPredictionContextView {
+    empty_focus_handle: FocusHandle,
+    project: Entity<Project>,
+    store: Entity<EditPredictionStore>,
+    runs: VecDeque<RetrievalRun>,
+    current_ix: usize,
+    _update_task: Task<Result<()>>,
+}
+
+#[derive(Debug)]
+struct RetrievalRun {
+    editor: Entity<Editor>,
+    started_at: Instant,
+    metadata: Vec<(&'static str, SharedString)>,
+    finished_at: Option<Instant>,
+}
+
+actions!(
+    dev,
+    [
+        /// Go to the previous context retrieval run
+        EditPredictionContextGoBack,
+        /// Go to the next context retrieval run
+        EditPredictionContextGoForward
+    ]
+);
+
+impl EditPredictionContextView {
+    pub fn new(
+        project: Entity<Project>,
+        client: &Arc<Client>,
+        user_store: &Entity<UserStore>,
+        window: &mut gpui::Window,
+        cx: &mut Context<Self>,
+    ) -> Self {
+        let store = EditPredictionStore::global(client, user_store, cx);
+
+        let mut debug_rx = store.update(cx, |store, cx| store.debug_info(&project, cx));
+        let _update_task = cx.spawn_in(window, async move |this, cx| {
+            while let Some(event) = debug_rx.next().await {
+                this.update_in(cx, |this, window, cx| {
+                    this.handle_store_event(event, window, cx)
+                })?;
+            }
+            Ok(())
+        });
+
+        Self {
+            empty_focus_handle: cx.focus_handle(),
+            project,
+            runs: VecDeque::new(),
+            current_ix: 0,
+            store,
+            _update_task,
+        }
+    }
+
+    fn handle_store_event(
+        &mut self,
+        event: DebugEvent,
+        window: &mut gpui::Window,
+        cx: &mut Context<Self>,
+    ) {
+        match event {
+            DebugEvent::ContextRetrievalStarted(info) => {
+                if info.project_entity_id == self.project.entity_id() {
+                    self.handle_context_retrieval_started(info, window, cx);
+                }
+            }
+            DebugEvent::ContextRetrievalFinished(info) => {
+                if info.project_entity_id == self.project.entity_id() {
+                    self.handle_context_retrieval_finished(info, window, cx);
+                }
+            }
+            DebugEvent::EditPredictionStarted(_) => {}
+            DebugEvent::EditPredictionFinished(_) => {}
+        }
+    }
+
+    fn handle_context_retrieval_started(
+        &mut self,
+        info: ContextRetrievalStartedDebugEvent,
+        window: &mut Window,
+        cx: &mut Context<Self>,
+    ) {
+        if self
+            .runs
+            .back()
+            .is_some_and(|run| run.finished_at.is_none())
+        {
+            self.runs.pop_back();
+        }
+
+        let multibuffer = cx.new(|_| MultiBuffer::new(language::Capability::ReadOnly));
+        let editor = cx
+            .new(|cx| Editor::for_multibuffer(multibuffer, Some(self.project.clone()), window, cx));
+
+        if self.runs.len() == 32 {
+            self.runs.pop_front();
+        }
+
+        self.runs.push_back(RetrievalRun {
+            editor,
+            started_at: info.timestamp,
+            finished_at: None,
+            metadata: Vec::new(),
+        });
+
+        cx.notify();
+    }
+
+    fn handle_context_retrieval_finished(
+        &mut self,
+        info: ContextRetrievalFinishedDebugEvent,
+        window: &mut Window,
+        cx: &mut Context<Self>,
+    ) {
+        let Some(run) = self.runs.back_mut() else {
+            return;
+        };
+
+        run.finished_at = Some(info.timestamp);
+        run.metadata = info.metadata;
+
+        let related_files = self
+            .store
+            .read(cx)
+            .context_for_project_with_buffers(&self.project, cx)
+            .map_or(Vec::new(), |files| files.collect());
+
+        let editor = run.editor.clone();
+        let multibuffer = run.editor.read(cx).buffer().clone();
+
+        if self.current_ix + 2 == self.runs.len() {
+            self.current_ix += 1;
+        }
+
+        cx.spawn_in(window, async move |this, cx| {
+            let mut paths = Vec::new();
+            for (related_file, buffer) in related_files {
+                let point_ranges = related_file
+                    .excerpts
+                    .iter()
+                    .map(|excerpt| {
+                        Point::new(excerpt.row_range.start, 0)..Point::new(excerpt.row_range.end, 0)
+                    })
+                    .collect::<Vec<_>>();
+                cx.update(|_, cx| {
+                    let path = PathKey::for_buffer(&buffer, cx);
+                    paths.push((path, buffer, point_ranges));
+                })?;
+            }
+
+            multibuffer.update(cx, |multibuffer, cx| {
+                multibuffer.clear(cx);
+
+                for (path, buffer, ranges) in paths {
+                    multibuffer.set_excerpts_for_path(path, buffer, ranges, 0, cx);
+                }
+            })?;
+
+            editor.update_in(cx, |editor, window, cx| {
+                editor.move_to_beginning(&Default::default(), window, cx);
+            })?;
+
+            this.update(cx, |_, cx| cx.notify())
+        })
+        .detach();
+    }
+
+    fn handle_go_back(
+        &mut self,
+        _: &EditPredictionContextGoBack,
+        window: &mut Window,
+        cx: &mut Context<Self>,
+    ) {
+        self.current_ix = self.current_ix.saturating_sub(1);
+        cx.focus_self(window);
+        cx.notify();
+    }
+
+    fn handle_go_forward(
+        &mut self,
+        _: &EditPredictionContextGoForward,
+        window: &mut Window,
+        cx: &mut Context<Self>,
+    ) {
+        self.current_ix = self
+            .current_ix
+            .add(1)
+            .min(self.runs.len().saturating_sub(1));
+        cx.focus_self(window);
+        cx.notify();
+    }
+
+    fn render_informational_footer(
+        &self,
+        cx: &mut Context<'_, EditPredictionContextView>,
+    ) -> ui::Div {
+        let run = &self.runs[self.current_ix];
+        let new_run_started = self
+            .runs
+            .back()
+            .map_or(false, |latest_run| latest_run.finished_at.is_none());
+
+        h_flex()
+            .p_2()
+            .w_full()
+            .font_buffer(cx)
+            .text_xs()
+            .border_t_1()
+            .gap_2()
+            .child(v_flex().h_full().flex_1().child({
+                let t0 = run.started_at;
+                let mut table = ui::Table::<2>::new().width(ui::px(300.)).no_ui_font();
+                for (key, value) in &run.metadata {
+                    table = table.row([key.into_any_element(), value.clone().into_any_element()])
+                }
+                table = table.row([
+                    "Total Time".into_any_element(),
+                    format!("{} ms", (run.finished_at.unwrap_or(t0) - t0).as_millis())
+                        .into_any_element(),
+                ]);
+                table
+            }))
+            .child(
+                v_flex().h_full().text_align(TextAlign::Right).child(
+                    h_flex()
+                        .justify_end()
+                        .child(
+                            IconButton::new("go-back", IconName::ChevronLeft)
+                                .disabled(self.current_ix == 0 || self.runs.len() < 2)
+                                .tooltip(ui::Tooltip::for_action_title(
+                                    "Go to previous run",
+                                    &EditPredictionContextGoBack,
+                                ))
+                                .on_click(cx.listener(|this, _, window, cx| {
+                                    this.handle_go_back(&EditPredictionContextGoBack, window, cx);
+                                })),
+                        )
+                        .child(
+                            div()
+                                .child(format!("{}/{}", self.current_ix + 1, self.runs.len()))
+                                .map(|this| {
+                                    if new_run_started {
+                                        this.with_animation(
+                                            "pulsating-count",
+                                            Animation::new(Duration::from_secs(2))
+                                                .repeat()
+                                                .with_easing(pulsating_between(0.4, 0.8)),
+                                            |label, delta| label.opacity(delta),
+                                        )
+                                        .into_any_element()
+                                    } else {
+                                        this.into_any_element()
+                                    }
+                                }),
+                        )
+                        .child(
+                            IconButton::new("go-forward", IconName::ChevronRight)
+                                .disabled(self.current_ix + 1 == self.runs.len())
+                                .tooltip(ui::Tooltip::for_action_title(
+                                    "Go to next run",
+                                    &EditPredictionContextGoBack,
+                                ))
+                                .on_click(cx.listener(|this, _, window, cx| {
+                                    this.handle_go_forward(
+                                        &EditPredictionContextGoForward,
+                                        window,
+                                        cx,
+                                    );
+                                })),
+                        ),
+                ),
+            )
+    }
+}
+
+impl Focusable for EditPredictionContextView {
+    fn focus_handle(&self, cx: &App) -> FocusHandle {
+        self.runs
+            .get(self.current_ix)
+            .map(|run| run.editor.read(cx).focus_handle(cx))
+            .unwrap_or_else(|| self.empty_focus_handle.clone())
+    }
+}
+
+impl EventEmitter<()> for EditPredictionContextView {}
+
+impl Item for EditPredictionContextView {
+    type Event = ();
+
+    fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
+        "Edit Prediction Context".into()
+    }
+
+    fn buffer_kind(&self, _cx: &App) -> workspace::item::ItemBufferKind {
+        workspace::item::ItemBufferKind::Multibuffer
+    }
+
+    fn act_as_type<'a>(
+        &'a self,
+        type_id: TypeId,
+        self_handle: &'a Entity<Self>,
+        _: &'a App,
+    ) -> Option<gpui::AnyEntity> {
+        if type_id == TypeId::of::<Self>() {
+            Some(self_handle.clone().into())
+        } else if type_id == TypeId::of::<Editor>() {
+            Some(self.runs.get(self.current_ix)?.editor.clone().into())
+        } else {
+            None
+        }
+    }
+}
+
+impl gpui::Render for EditPredictionContextView {
+    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl ui::IntoElement {
+        v_flex()
+            .key_context("EditPredictionContext")
+            .on_action(cx.listener(Self::handle_go_back))
+            .on_action(cx.listener(Self::handle_go_forward))
+            .size_full()
+            .map(|this| {
+                if self.runs.is_empty() {
+                    this.child(
+                        v_flex()
+                            .size_full()
+                            .justify_center()
+                            .items_center()
+                            .child("No retrieval runs yet"),
+                    )
+                } else {
+                    this.child(self.runs[self.current_ix].editor.clone())
+                        .child(self.render_informational_footer(cx))
+                }
+            })
+    }
+}

crates/edit_prediction_ui/src/edit_prediction_ui.rs 🔗

@@ -0,0 +1,191 @@
+mod edit_prediction_button;
+mod edit_prediction_context_view;
+mod rate_prediction_modal;
+
+use command_palette_hooks::CommandPaletteFilter;
+use edit_prediction::{ResetOnboarding, Zeta2FeatureFlag, capture_example};
+use edit_prediction_context_view::EditPredictionContextView;
+use editor::Editor;
+use feature_flags::FeatureFlagAppExt as _;
+use gpui::actions;
+use language::language_settings::AllLanguageSettings;
+use project::DisableAiSettings;
+use rate_prediction_modal::RatePredictionsModal;
+use settings::{Settings as _, SettingsStore};
+use std::any::{Any as _, TypeId};
+use ui::{App, prelude::*};
+use workspace::{SplitDirection, Workspace};
+
+pub use edit_prediction_button::{EditPredictionButton, ToggleMenu};
+
+use crate::rate_prediction_modal::PredictEditsRatePredictionsFeatureFlag;
+
+actions!(
+    dev,
+    [
+        /// Opens the edit prediction context view.
+        OpenEditPredictionContextView,
+    ]
+);
+
+actions!(
+    edit_prediction,
+    [
+        /// Opens the rate completions modal.
+        RatePredictions,
+        /// Captures an ExampleSpec from the current editing session and opens it as Markdown.
+        CaptureExample,
+    ]
+);
+
+pub fn init(cx: &mut App) {
+    feature_gate_predict_edits_actions(cx);
+
+    cx.observe_new(move |workspace: &mut Workspace, _, _cx| {
+        workspace.register_action(|workspace, _: &RatePredictions, window, cx| {
+            if cx.has_flag::<PredictEditsRatePredictionsFeatureFlag>() {
+                RatePredictionsModal::toggle(workspace, window, cx);
+            }
+        });
+
+        workspace.register_action(|workspace, _: &CaptureExample, window, cx| {
+            capture_example_as_markdown(workspace, window, cx);
+        });
+        workspace.register_action_renderer(|div, _, _, cx| {
+            let has_flag = cx.has_flag::<Zeta2FeatureFlag>();
+            div.when(has_flag, |div| {
+                div.on_action(cx.listener(
+                    move |workspace, _: &OpenEditPredictionContextView, window, cx| {
+                        let project = workspace.project();
+                        workspace.split_item(
+                            SplitDirection::Right,
+                            Box::new(cx.new(|cx| {
+                                EditPredictionContextView::new(
+                                    project.clone(),
+                                    workspace.client(),
+                                    workspace.user_store(),
+                                    window,
+                                    cx,
+                                )
+                            })),
+                            window,
+                            cx,
+                        );
+                    },
+                ))
+            })
+        });
+    })
+    .detach();
+}
+
+fn feature_gate_predict_edits_actions(cx: &mut App) {
+    let rate_completion_action_types = [TypeId::of::<RatePredictions>()];
+    let reset_onboarding_action_types = [TypeId::of::<ResetOnboarding>()];
+    let all_action_types = [
+        TypeId::of::<RatePredictions>(),
+        TypeId::of::<CaptureExample>(),
+        TypeId::of::<edit_prediction::ResetOnboarding>(),
+        zed_actions::OpenZedPredictOnboarding.type_id(),
+        TypeId::of::<edit_prediction::ClearHistory>(),
+        TypeId::of::<rate_prediction_modal::ThumbsUpActivePrediction>(),
+        TypeId::of::<rate_prediction_modal::ThumbsDownActivePrediction>(),
+        TypeId::of::<rate_prediction_modal::NextEdit>(),
+        TypeId::of::<rate_prediction_modal::PreviousEdit>(),
+    ];
+
+    CommandPaletteFilter::update_global(cx, |filter, _cx| {
+        filter.hide_action_types(&rate_completion_action_types);
+        filter.hide_action_types(&reset_onboarding_action_types);
+        filter.hide_action_types(&[zed_actions::OpenZedPredictOnboarding.type_id()]);
+    });
+
+    cx.observe_global::<SettingsStore>(move |cx| {
+        let is_ai_disabled = DisableAiSettings::get_global(cx).disable_ai;
+        let has_feature_flag = cx.has_flag::<PredictEditsRatePredictionsFeatureFlag>();
+
+        CommandPaletteFilter::update_global(cx, |filter, _cx| {
+            if is_ai_disabled {
+                filter.hide_action_types(&all_action_types);
+            } else if has_feature_flag {
+                filter.show_action_types(&rate_completion_action_types);
+            } else {
+                filter.hide_action_types(&rate_completion_action_types);
+            }
+        });
+    })
+    .detach();
+
+    cx.observe_flag::<PredictEditsRatePredictionsFeatureFlag, _>(move |is_enabled, cx| {
+        if !DisableAiSettings::get_global(cx).disable_ai {
+            if is_enabled {
+                CommandPaletteFilter::update_global(cx, |filter, _cx| {
+                    filter.show_action_types(&rate_completion_action_types);
+                });
+            } else {
+                CommandPaletteFilter::update_global(cx, |filter, _cx| {
+                    filter.hide_action_types(&rate_completion_action_types);
+                });
+            }
+        }
+    })
+    .detach();
+}
+
+fn capture_example_as_markdown(
+    workspace: &mut Workspace,
+    window: &mut Window,
+    cx: &mut Context<Workspace>,
+) -> Option<()> {
+    let markdown_language = workspace
+        .app_state()
+        .languages
+        .language_for_name("Markdown");
+
+    let fs = workspace.app_state().fs.clone();
+    let project = workspace.project().clone();
+    let editor = workspace.active_item_as::<Editor>(cx)?;
+    let editor = editor.read(cx);
+    let (buffer, cursor_anchor) = editor
+        .buffer()
+        .read(cx)
+        .text_anchor_for_position(editor.selections.newest_anchor().head(), cx)?;
+    let example = capture_example(project.clone(), buffer, cursor_anchor, true, cx)?;
+
+    let examples_dir = AllLanguageSettings::get_global(cx)
+        .edit_predictions
+        .examples_dir
+        .clone();
+
+    cx.spawn_in(window, async move |workspace_entity, cx| {
+        let markdown_language = markdown_language.await?;
+        let example_spec = example.await?;
+        let buffer = if let Some(dir) = examples_dir {
+            fs.create_dir(&dir).await.ok();
+            let mut path = dir.join(&example_spec.name.replace(' ', "--").replace(':', "-"));
+            path.set_extension("md");
+            project.update(cx, |project, cx| project.open_local_buffer(&path, cx))
+        } else {
+            project.update(cx, |project, cx| project.create_buffer(false, cx))
+        }?
+        .await?;
+
+        buffer.update(cx, |buffer, cx| {
+            buffer.set_text(example_spec.to_markdown(), cx);
+            buffer.set_language(Some(markdown_language), cx);
+        })?;
+        workspace_entity.update_in(cx, |workspace, window, cx| {
+            workspace.add_item_to_active_pane(
+                Box::new(
+                    cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
+                ),
+                None,
+                true,
+                window,
+                cx,
+            );
+        })
+    })
+    .detach_and_log_err(cx);
+    None
+}

crates/zeta/src/rate_prediction_modal.rs → crates/edit_prediction_ui/src/rate_prediction_modal.rs 🔗

@@ -1,7 +1,7 @@
-use crate::{EditPrediction, EditPredictionRating, Zeta};
 use buffer_diff::BufferDiff;
-use cloud_zeta2_prompt::write_codeblock;
+use edit_prediction::{EditPrediction, EditPredictionRating, EditPredictionStore};
 use editor::{Editor, ExcerptRange, MultiBuffer};
+use feature_flags::FeatureFlag;
 use gpui::{
     App, BorderStyle, DismissEvent, EdgesRefinement, Entity, EventEmitter, FocusHandle, Focusable,
     Length, StyleRefinement, TextStyleRefinement, Window, actions, prelude::*,
@@ -9,9 +9,7 @@ use gpui::{
 use language::{LanguageRegistry, Point, language_settings};
 use markdown::{Markdown, MarkdownStyle};
 use settings::Settings as _;
-use std::fmt::Write;
-use std::sync::Arc;
-use std::time::Duration;
+use std::{fmt::Write, sync::Arc, time::Duration};
 use theme::ThemeSettings;
 use ui::{KeyBinding, List, ListItem, ListItemSpacing, Tooltip, prelude::*};
 use workspace::{ModalView, Workspace};
@@ -34,8 +32,14 @@ actions!(
     ]
 );
 
+pub struct PredictEditsRatePredictionsFeatureFlag;
+
+impl FeatureFlag for PredictEditsRatePredictionsFeatureFlag {
+    const NAME: &'static str = "predict-edits-rate-completions";
+}
+
 pub struct RatePredictionsModal {
-    zeta: Entity<Zeta>,
+    ep_store: Entity<EditPredictionStore>,
     language_registry: Arc<LanguageRegistry>,
     active_prediction: Option<ActivePrediction>,
     selected_index: usize,
@@ -68,10 +72,10 @@ impl RatePredictionView {
 
 impl RatePredictionsModal {
     pub fn toggle(workspace: &mut Workspace, window: &mut Window, cx: &mut Context<Workspace>) {
-        if let Some(zeta) = Zeta::try_global(cx) {
+        if let Some(ep_store) = EditPredictionStore::try_global(cx) {
             let language_registry = workspace.app_state().languages.clone();
             workspace.toggle_modal(window, cx, |window, cx| {
-                RatePredictionsModal::new(zeta, language_registry, window, cx)
+                RatePredictionsModal::new(ep_store, language_registry, window, cx)
             });
 
             telemetry::event!("Rate Prediction Modal Open", source = "Edit Prediction");
@@ -79,15 +83,15 @@ impl RatePredictionsModal {
     }
 
     pub fn new(
-        zeta: Entity<Zeta>,
+        ep_store: Entity<EditPredictionStore>,
         language_registry: Arc<LanguageRegistry>,
         window: &mut Window,
         cx: &mut Context<Self>,
     ) -> Self {
-        let subscription = cx.observe(&zeta, |_, _, cx| cx.notify());
+        let subscription = cx.observe(&ep_store, |_, _, cx| cx.notify());
 
         Self {
-            zeta,
+            ep_store,
             language_registry,
             selected_index: 0,
             focus_handle: cx.focus_handle(),
@@ -113,7 +117,7 @@ impl RatePredictionsModal {
         self.selected_index += 1;
         self.selected_index = usize::min(
             self.selected_index,
-            self.zeta.read(cx).shown_predictions().count(),
+            self.ep_store.read(cx).shown_predictions().count(),
         );
         cx.notify();
     }
@@ -130,7 +134,7 @@ impl RatePredictionsModal {
 
     fn select_next_edit(&mut self, _: &NextEdit, _: &mut Window, cx: &mut Context<Self>) {
         let next_index = self
-            .zeta
+            .ep_store
             .read(cx)
             .shown_predictions()
             .skip(self.selected_index)
@@ -146,11 +150,11 @@ impl RatePredictionsModal {
     }
 
     fn select_prev_edit(&mut self, _: &PreviousEdit, _: &mut Window, cx: &mut Context<Self>) {
-        let zeta = self.zeta.read(cx);
-        let completions_len = zeta.shown_completions_len();
+        let ep_store = self.ep_store.read(cx);
+        let completions_len = ep_store.shown_completions_len();
 
         let prev_index = self
-            .zeta
+            .ep_store
             .read(cx)
             .shown_predictions()
             .rev()
@@ -173,7 +177,7 @@ impl RatePredictionsModal {
     }
 
     fn select_last(&mut self, _: &menu::SelectLast, _window: &mut Window, cx: &mut Context<Self>) {
-        self.selected_index = self.zeta.read(cx).shown_completions_len() - 1;
+        self.selected_index = self.ep_store.read(cx).shown_completions_len() - 1;
         cx.notify();
     }
 
@@ -183,9 +187,9 @@ impl RatePredictionsModal {
         window: &mut Window,
         cx: &mut Context<Self>,
     ) {
-        self.zeta.update(cx, |zeta, cx| {
+        self.ep_store.update(cx, |ep_store, cx| {
             if let Some(active) = &self.active_prediction {
-                zeta.rate_prediction(
+                ep_store.rate_prediction(
                     &active.prediction,
                     EditPredictionRating::Positive,
                     active.feedback_editor.read(cx).text(cx),
@@ -216,8 +220,8 @@ impl RatePredictionsModal {
                 return;
             }
 
-            self.zeta.update(cx, |zeta, cx| {
-                zeta.rate_prediction(
+            self.ep_store.update(cx, |ep_store, cx| {
+                ep_store.rate_prediction(
                     &active.prediction,
                     EditPredictionRating::Negative,
                     active.feedback_editor.read(cx).text(cx),
@@ -254,7 +258,7 @@ impl RatePredictionsModal {
         cx: &mut Context<Self>,
     ) {
         let completion = self
-            .zeta
+            .ep_store
             .read(cx)
             .shown_predictions()
             .skip(self.selected_index)
@@ -267,7 +271,7 @@ impl RatePredictionsModal {
 
     fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
         let completion = self
-            .zeta
+            .ep_store
             .read(cx)
             .shown_predictions()
             .skip(self.selected_index)
@@ -288,7 +292,7 @@ impl RatePredictionsModal {
         // Avoid resetting completion rating if it's already selected.
         if let Some(prediction) = prediction {
             self.selected_index = self
-                .zeta
+                .ep_store
                 .read(cx)
                 .shown_predictions()
                 .enumerate()
@@ -301,7 +305,7 @@ impl RatePredictionsModal {
                 && prediction.id == prev_prediction.prediction.id
             {
                 if focus {
-                    window.focus(&prev_prediction.feedback_editor.focus_handle(cx));
+                    window.focus(&prev_prediction.feedback_editor.focus_handle(cx), cx);
                 }
                 return;
             }
@@ -358,14 +362,14 @@ impl RatePredictionsModal {
             write!(&mut formatted_inputs, "## Events\n\n").unwrap();
 
             for event in &prediction.inputs.events {
-                write!(&mut formatted_inputs, "```diff\n{event}```\n\n").unwrap();
+                formatted_inputs.push_str("```diff\n");
+                zeta_prompt::write_event(&mut formatted_inputs, event.as_ref());
+                formatted_inputs.push_str("```\n\n");
             }
 
-            write!(&mut formatted_inputs, "## Included files\n\n").unwrap();
-
-            for included_file in &prediction.inputs.included_files {
-                let cursor_insertions = &[(prediction.inputs.cursor_point, "<|CURSOR|>")];
+            write!(&mut formatted_inputs, "## Related files\n\n").unwrap();
 
+            for included_file in prediction.inputs.related_files.as_ref() {
                 write!(
                     &mut formatted_inputs,
                     "### {}\n\n",
@@ -373,20 +377,28 @@ impl RatePredictionsModal {
                 )
                 .unwrap();
 
-                write_codeblock(
-                    &included_file.path,
-                    &included_file.excerpts,
-                    if included_file.path == prediction.inputs.cursor_path {
-                        cursor_insertions
-                    } else {
-                        &[]
-                    },
-                    included_file.max_row,
-                    false,
-                    &mut formatted_inputs,
-                );
+                for excerpt in included_file.excerpts.iter() {
+                    write!(
+                        &mut formatted_inputs,
+                        "```{}\n{}\n```\n",
+                        included_file.path.display(),
+                        excerpt.text
+                    )
+                    .unwrap();
+                }
             }
 
+            write!(&mut formatted_inputs, "## Cursor Excerpt\n\n").unwrap();
+
+            writeln!(
+                &mut formatted_inputs,
+                "```{}\n{}<CURSOR>{}\n```\n",
+                prediction.inputs.cursor_path.display(),
+                &prediction.inputs.cursor_excerpt[..prediction.inputs.cursor_offset_in_excerpt],
+                &prediction.inputs.cursor_excerpt[prediction.inputs.cursor_offset_in_excerpt..],
+            )
+            .unwrap();
+
             self.active_prediction = Some(ActivePrediction {
                 prediction,
                 feedback_editor: cx.new(|cx| {
@@ -499,13 +511,13 @@ impl RatePredictionsModal {
                                     base_text_style: window.text_style(),
                                     syntax: cx.theme().syntax().clone(),
                                     code_block: StyleRefinement {
-                                        text: Some(TextStyleRefinement {
+                                        text: TextStyleRefinement {
                                             font_family: Some(
                                                 theme_settings.buffer_font.family.clone(),
                                             ),
                                             font_size: Some(buffer_font_size.into()),
                                             ..Default::default()
-                                        }),
+                                        },
                                         padding: EdgesRefinement {
                                             top: Some(DefiniteLength::Absolute(
                                                 AbsoluteLength::Pixels(px(8.)),
@@ -565,7 +577,7 @@ impl RatePredictionsModal {
         let border_color = cx.theme().colors().border;
         let bg_color = cx.theme().colors().editor_background;
 
-        let rated = self.zeta.read(cx).is_prediction_rated(&completion_id);
+        let rated = self.ep_store.read(cx).is_prediction_rated(&completion_id);
         let feedback_empty = active_prediction
             .feedback_editor
             .read(cx)
@@ -716,7 +728,7 @@ impl RatePredictionsModal {
     }
 
     fn render_shown_completions(&self, cx: &Context<Self>) -> impl Iterator<Item = ListItem> {
-        self.zeta
+        self.ep_store
             .read(cx)
             .shown_predictions()
             .cloned()
@@ -726,7 +738,7 @@ impl RatePredictionsModal {
                     .active_prediction
                     .as_ref()
                     .is_some_and(|selected| selected.prediction.id == completion.id);
-                let rated = self.zeta.read(cx).is_prediction_rated(&completion.id);
+                let rated = self.ep_store.read(cx).is_prediction_rated(&completion.id);
 
                 let (icon_name, icon_color, tooltip_text) =
                     match (rated, completion.edits.is_empty()) {

crates/editor/Cargo.toml 🔗

@@ -49,7 +49,7 @@ fs.workspace = true
 git.workspace = true
 gpui.workspace = true
 indoc.workspace = true
-edit_prediction.workspace = true
+edit_prediction_types.workspace = true
 itertools.workspace = true
 language.workspace = true
 linkify.workspace = true
@@ -84,6 +84,8 @@ tree-sitter-html = { workspace = true, optional = true }
 tree-sitter-rust = { workspace = true, optional = true }
 tree-sitter-typescript = { workspace = true, optional = true }
 tree-sitter-python = { workspace = true, optional = true }
+ztracing.workspace = true
+tracing.workspace = true
 unicode-segmentation.workspace = true
 unicode-script.workspace = true
 unindent = { workspace = true, optional = true }
@@ -94,6 +96,7 @@ uuid.workspace = true
 vim_mode_setting.workspace = true
 workspace.workspace = true
 zed_actions.workspace = true
+zlog.workspace = true
 
 [dev-dependencies]
 criterion.workspace = true
@@ -118,6 +121,7 @@ tree-sitter-rust.workspace = true
 tree-sitter-typescript.workspace = true
 tree-sitter-yaml.workspace = true
 tree-sitter-bash.workspace = true
+tree-sitter-md.workspace = true
 unindent.workspace = true
 util = { workspace = true, features = ["test-support"] }
 workspace = { workspace = true, features = ["test-support"] }

crates/editor/benches/editor_render.rs 🔗

@@ -29,7 +29,7 @@ fn editor_input_with_1000_cursors(bencher: &mut Bencher<'_>, cx: &TestAppContext
             );
             editor
         });
-        window.focus(&editor.focus_handle(cx));
+        window.focus(&editor.focus_handle(cx), cx);
         editor
     });
 
@@ -72,7 +72,7 @@ fn open_editor_with_one_long_line(bencher: &mut Bencher<'_>, args: &(String, Tes
                 editor.set_style(editor::EditorStyle::default(), window, cx);
                 editor
             });
-            window.focus(&editor.focus_handle(cx));
+            window.focus(&editor.focus_handle(cx), cx);
             editor
         });
     });
@@ -100,7 +100,7 @@ fn editor_render(bencher: &mut Bencher<'_>, cx: &TestAppContext) {
             editor.set_style(editor::EditorStyle::default(), window, cx);
             editor
         });
-        window.focus(&editor.focus_handle(cx));
+        window.focus(&editor.focus_handle(cx), cx);
         editor
     });
 

crates/editor/src/actions.rs 🔗

@@ -327,6 +327,23 @@ pub struct AddSelectionBelow {
     pub skip_soft_wrap: bool,
 }
 
+/// Inserts a snippet at the cursor.
+#[derive(PartialEq, Clone, Default, Debug, Deserialize, JsonSchema, Action)]
+#[action(namespace = editor)]
+#[serde(deny_unknown_fields)]
+pub struct InsertSnippet {
+    /// Language name if using a named snippet, or `None` for a global snippet
+    ///
+    /// This is typically lowercase and matches the filename containing the snippet, without the `.json` extension.
+    pub language: Option<String>,
+    /// Name if using a named snippet
+    pub name: Option<String>,
+
+    /// Snippet body, if not using a named snippet
+    // todo(andrew): use `ListOrDirect` or similar for multiline snippet body
+    pub snippet: Option<String>,
+}
+
 actions!(
     debugger,
     [
@@ -353,7 +370,8 @@ actions!(
         AcceptEditPrediction,
         /// Accepts a partial edit prediction.
         #[action(deprecated_aliases = ["editor::AcceptPartialCopilotSuggestion"])]
-        AcceptPartialEditPrediction,
+        AcceptNextWordEditPrediction,
+        AcceptNextLineEditPrediction,
         /// Applies all diff hunks in the editor.
         ApplyAllDiffHunks,
         /// Applies the diff hunk at the current position.
@@ -453,8 +471,6 @@ actions!(
         CollapseAllDiffHunks,
         /// Expands macros recursively at cursor position.
         ExpandMacroRecursively,
-        /// Finds all references to the symbol at cursor.
-        FindAllReferences,
         /// Finds the next match in the search.
         FindNextMatch,
         /// Finds the previous match in the search.
@@ -665,6 +681,10 @@ actions!(
         ReloadFile,
         /// Rewraps text to fit within the preferred line length.
         Rewrap,
+        /// Rotates selections or lines backward.
+        RotateSelectionsBackward,
+        /// Rotates selections or lines forward.
+        RotateSelectionsForward,
         /// Runs flycheck diagnostics.
         RunFlycheck,
         /// Scrolls the cursor to the bottom of the viewport.
@@ -827,3 +847,20 @@ actions!(
         WrapSelectionsInTag
     ]
 );
+
+/// Finds all references to the symbol at cursor.
+#[derive(PartialEq, Clone, Deserialize, JsonSchema, Action)]
+#[action(namespace = editor)]
+#[serde(deny_unknown_fields)]
+pub struct FindAllReferences {
+    #[serde(default = "default_true")]
+    pub always_open_multibuffer: bool,
+}
+
+impl Default for FindAllReferences {
+    fn default() -> Self {
+        Self {
+            always_open_multibuffer: true,
+        }
+    }
+}

crates/editor/src/bracket_colorization.rs 🔗

@@ -45,7 +45,7 @@ impl Editor {
 
         let bracket_matches_by_accent = self.visible_excerpts(false, cx).into_iter().fold(
             HashMap::default(),
-            |mut acc, (excerpt_id, (buffer, buffer_version, buffer_range))| {
+            |mut acc, (excerpt_id, (buffer, _, buffer_range))| {
                 let buffer_snapshot = buffer.read(cx).snapshot();
                 if language_settings::language_settings(
                     buffer_snapshot.language().map(|language| language.name()),
@@ -62,7 +62,7 @@ impl Editor {
                     let brackets_by_accent = buffer_snapshot
                         .fetch_bracket_ranges(
                             buffer_range.start..buffer_range.end,
-                            Some((&buffer_version, fetched_chunks)),
+                            Some(fetched_chunks),
                         )
                         .into_iter()
                         .flat_map(|(chunk_range, pairs)| {
@@ -333,6 +333,74 @@ where
             &bracket_colors_markup(&mut cx),
             "All markdown brackets should be colored based on their depth"
         );
+
+        cx.set_state(indoc! {r#"ˇ{{}}"#});
+        cx.executor().advance_clock(Duration::from_millis(100));
+        cx.executor().run_until_parked();
+
+        assert_eq!(
+            r#"«1{«2{}2»}1»
+1 hsla(207.80, 16.20%, 69.19%, 1.00)
+2 hsla(29.00, 54.00%, 65.88%, 1.00)
+"#,
+            &bracket_colors_markup(&mut cx),
+            "All markdown brackets should be colored based on their depth, again"
+        );
+    }
+
+    #[gpui::test]
+    async fn test_bracket_colorization_after_language_swap(cx: &mut gpui::TestAppContext) {
+        init_test(cx, |language_settings| {
+            language_settings.defaults.colorize_brackets = Some(true);
+        });
+
+        let language_registry = Arc::new(language::LanguageRegistry::test(cx.executor()));
+        language_registry.add(markdown_lang());
+        language_registry.add(rust_lang());
+
+        let mut cx = EditorTestContext::new(cx).await;
+        cx.update_buffer(|buffer, cx| {
+            buffer.set_language_registry(language_registry.clone());
+            buffer.set_language(Some(markdown_lang()), cx);
+        });
+
+        cx.set_state(indoc! {r#"
+            fn main() {
+                let v: Vec<Stringˇ> = vec![];
+            }
+        "#});
+        cx.executor().advance_clock(Duration::from_millis(100));
+        cx.executor().run_until_parked();
+
+        assert_eq!(
+            r#"fn main«1()1» «1{
+    let v: Vec<String> = vec!«2[]2»;
+}1»
+
+1 hsla(207.80, 16.20%, 69.19%, 1.00)
+2 hsla(29.00, 54.00%, 65.88%, 1.00)
+"#,
+            &bracket_colors_markup(&mut cx),
+            "Markdown does not colorize <> brackets"
+        );
+
+        cx.update_buffer(|buffer, cx| {
+            buffer.set_language(Some(rust_lang()), cx);
+        });
+        cx.executor().advance_clock(Duration::from_millis(100));
+        cx.executor().run_until_parked();
+
+        assert_eq!(
+            r#"fn main«1()1» «1{
+    let v: Vec«2<String>2» = vec!«2[]2»;
+}1»
+
+1 hsla(207.80, 16.20%, 69.19%, 1.00)
+2 hsla(29.00, 54.00%, 65.88%, 1.00)
+"#,
+            &bracket_colors_markup(&mut cx),
+            "After switching to Rust, <> brackets are now colorized"
+        );
     }
 
     #[gpui::test]

crates/editor/src/code_context_menus.rs 🔗

@@ -51,6 +51,8 @@ pub const MENU_ASIDE_MIN_WIDTH: Pixels = px(260.);
 pub const MENU_ASIDE_MAX_WIDTH: Pixels = px(500.);
 pub const COMPLETION_MENU_MIN_WIDTH: Pixels = px(280.);
 pub const COMPLETION_MENU_MAX_WIDTH: Pixels = px(540.);
+pub const CODE_ACTION_MENU_MIN_WIDTH: Pixels = px(220.);
+pub const CODE_ACTION_MENU_MAX_WIDTH: Pixels = px(540.);
 
 // Constants for the markdown cache. The purpose of this cache is to reduce flickering due to
 // documentation not yet being parsed.
@@ -179,7 +181,7 @@ impl CodeContextMenu {
     ) -> Option<AnyElement> {
         match self {
             CodeContextMenu::Completions(menu) => menu.render_aside(max_size, window, cx),
-            CodeContextMenu::CodeActions(_) => None,
+            CodeContextMenu::CodeActions(menu) => menu.render_aside(max_size, window, cx),
         }
     }
 
@@ -206,6 +208,13 @@ impl CodeContextMenu {
             CodeContextMenu::CodeActions(_) => (),
         }
     }
+
+    pub fn primary_scroll_handle(&self) -> UniformListScrollHandle {
+        match self {
+            CodeContextMenu::Completions(menu) => menu.scroll_handle.clone(),
+            CodeContextMenu::CodeActions(menu) => menu.scroll_handle.clone(),
+        }
+    }
 }
 
 pub enum ContextMenuOrigin {
@@ -303,6 +312,7 @@ impl CompletionsMenu {
         is_incomplete: bool,
         buffer: Entity<Buffer>,
         completions: Box<[Completion]>,
+        scroll_handle: Option<UniformListScrollHandle>,
         display_options: CompletionDisplayOptions,
         snippet_sort_order: SnippetSortOrder,
         language_registry: Option<Arc<LanguageRegistry>>,
@@ -332,7 +342,7 @@ impl CompletionsMenu {
             selected_item: 0,
             filter_task: Task::ready(()),
             cancel_filter: Arc::new(AtomicBool::new(false)),
-            scroll_handle: UniformListScrollHandle::new(),
+            scroll_handle: scroll_handle.unwrap_or_else(UniformListScrollHandle::new),
             scroll_handle_aside: ScrollHandle::new(),
             resolve_completions: true,
             last_rendered_range: RefCell::new(None).into(),
@@ -354,6 +364,7 @@ impl CompletionsMenu {
         choices: &Vec<String>,
         selection: Range<Anchor>,
         buffer: Entity<Buffer>,
+        scroll_handle: Option<UniformListScrollHandle>,
         snippet_sort_order: SnippetSortOrder,
     ) -> Self {
         let completions = choices
@@ -404,7 +415,7 @@ impl CompletionsMenu {
             selected_item: 0,
             filter_task: Task::ready(()),
             cancel_filter: Arc::new(AtomicBool::new(false)),
-            scroll_handle: UniformListScrollHandle::new(),
+            scroll_handle: scroll_handle.unwrap_or_else(UniformListScrollHandle::new),
             scroll_handle_aside: ScrollHandle::new(),
             resolve_completions: false,
             show_completion_documentation: false,
@@ -882,7 +893,7 @@ impl CompletionsMenu {
                                     None
                                 } else {
                                     Some(
-                                        Label::new(text.clone())
+                                        Label::new(text.trim().to_string())
                                             .ml_4()
                                             .size(LabelSize::Small)
                                             .color(Color::Muted),
@@ -1410,26 +1421,6 @@ pub enum CodeActionsItem {
 }
 
 impl CodeActionsItem {
-    fn as_task(&self) -> Option<&ResolvedTask> {
-        let Self::Task(_, task) = self else {
-            return None;
-        };
-        Some(task)
-    }
-
-    fn as_code_action(&self) -> Option<&CodeAction> {
-        let Self::CodeAction { action, .. } = self else {
-            return None;
-        };
-        Some(action)
-    }
-    fn as_debug_scenario(&self) -> Option<&DebugScenario> {
-        let Self::DebugScenario(scenario) = self else {
-            return None;
-        };
-        Some(scenario)
-    }
-
     pub fn label(&self) -> String {
         match self {
             Self::CodeAction { action, .. } => action.lsp_action.title().to_owned(),
@@ -1437,6 +1428,14 @@ impl CodeActionsItem {
             Self::DebugScenario(scenario) => scenario.label.to_string(),
         }
     }
+
+    pub fn menu_label(&self) -> String {
+        match self {
+            Self::CodeAction { action, .. } => action.lsp_action.title().replace("\n", ""),
+            Self::Task(_, task) => task.resolved_label.replace("\n", ""),
+            Self::DebugScenario(scenario) => format!("debug: {}", scenario.label),
+        }
+    }
 }
 
 pub struct CodeActionsMenu {
@@ -1546,60 +1545,33 @@ impl CodeActionsMenu {
                         let item_ix = range.start + ix;
                         let selected = item_ix == selected_item;
                         let colors = cx.theme().colors();
-                        div().min_w(px(220.)).max_w(px(540.)).child(
-                            ListItem::new(item_ix)
-                                .inset(true)
-                                .toggle_state(selected)
-                                .when_some(action.as_code_action(), |this, action| {
-                                    this.child(
-                                        h_flex()
-                                            .overflow_hidden()
-                                            .when(is_quick_action_bar, |this| this.text_ui(cx))
-                                            .child(
-                                                // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
-                                                action.lsp_action.title().replace("\n", ""),
-                                            )
-                                            .when(selected, |this| {
-                                                this.text_color(colors.text_accent)
-                                            }),
-                                    )
-                                })
-                                .when_some(action.as_task(), |this, task| {
-                                    this.child(
-                                        h_flex()
-                                            .overflow_hidden()
-                                            .when(is_quick_action_bar, |this| this.text_ui(cx))
-                                            .child(task.resolved_label.replace("\n", ""))
-                                            .when(selected, |this| {
-                                                this.text_color(colors.text_accent)
-                                            }),
-                                    )
-                                })
-                                .when_some(action.as_debug_scenario(), |this, scenario| {
-                                    this.child(
-                                        h_flex()
-                                            .overflow_hidden()
-                                            .when(is_quick_action_bar, |this| this.text_ui(cx))
-                                            .child("debug: ")
-                                            .child(scenario.label.clone())
-                                            .when(selected, |this| {
-                                                this.text_color(colors.text_accent)
-                                            }),
-                                    )
-                                })
-                                .on_click(cx.listener(move |editor, _, window, cx| {
-                                    cx.stop_propagation();
-                                    if let Some(task) = editor.confirm_code_action(
-                                        &ConfirmCodeAction {
-                                            item_ix: Some(item_ix),
-                                        },
-                                        window,
-                                        cx,
-                                    ) {
-                                        task.detach_and_log_err(cx)
-                                    }
-                                })),
-                        )
+
+                        ListItem::new(item_ix)
+                            .inset(true)
+                            .toggle_state(selected)
+                            .overflow_x()
+                            .child(
+                                div()
+                                    .min_w(CODE_ACTION_MENU_MIN_WIDTH)
+                                    .max_w(CODE_ACTION_MENU_MAX_WIDTH)
+                                    .overflow_hidden()
+                                    .text_ellipsis()
+                                    .when(is_quick_action_bar, |this| this.text_ui(cx))
+                                    .when(selected, |this| this.text_color(colors.text_accent))
+                                    .child(action.menu_label()),
+                            )
+                            .on_click(cx.listener(move |editor, _, window, cx| {
+                                cx.stop_propagation();
+                                if let Some(task) = editor.confirm_code_action(
+                                    &ConfirmCodeAction {
+                                        item_ix: Some(item_ix),
+                                    },
+                                    window,
+                                    cx,
+                                ) {
+                                    task.detach_and_log_err(cx)
+                                }
+                            }))
                     })
                     .collect()
             }),
@@ -1626,4 +1598,46 @@ impl CodeActionsMenu {
 
         Popover::new().child(list).into_any_element()
     }
+
+    fn render_aside(
+        &mut self,
+        max_size: Size<Pixels>,
+        window: &mut Window,
+        _cx: &mut Context<Editor>,
+    ) -> Option<AnyElement> {
+        let Some(action) = self.actions.get(self.selected_item) else {
+            return None;
+        };
+
+        let label = action.menu_label();
+        let text_system = window.text_system();
+        let mut line_wrapper = text_system.line_wrapper(
+            window.text_style().font(),
+            window.text_style().font_size.to_pixels(window.rem_size()),
+        );
+        let is_truncated = line_wrapper.should_truncate_line(
+            &label,
+            CODE_ACTION_MENU_MAX_WIDTH,
+            "…",
+            gpui::TruncateFrom::End,
+        );
+
+        if is_truncated.is_none() {
+            return None;
+        }
+
+        Some(
+            Popover::new()
+                .child(
+                    div()
+                        .child(label)
+                        .id("code_actions_menu_extended")
+                        .px(MENU_ASIDE_X_PADDING / 2.)
+                        .max_w(max_size.width)
+                        .max_h(max_size.height)
+                        .occlude(),
+                )
+                .into_any_element(),
+        )
+    }
 }

crates/editor/src/display_map.rs 🔗

@@ -14,8 +14,57 @@
 //! - [`DisplayMap`] that adds background highlights to the regions of text.
 //!   Each one of those builds on top of preceding map.
 //!
+//! ## Structure of the display map layers
+//!
+//! Each layer in the map (and the multibuffer itself to some extent) has a few
+//! structures that are used to implement the public API available to the layer
+//! above:
+//! - a `Transform` type - this represents a region of text that the layer in
+//!   question is "managing", that it transforms into a more "processed" text
+//!   for the layer above. For example, the inlay map has an `enum Transform`
+//!   that has two variants:
+//!     - `Isomorphic`, representing a region of text that has no inlay hints (i.e.
+//!       is passed through the map transparently)
+//!     - `Inlay`, representing a location where an inlay hint is to be inserted.
+//! - a `TransformSummary` type, which is usually a struct with two fields:
+//!   [`input: TextSummary`][`TextSummary`] and [`output: TextSummary`][`TextSummary`]. Here,
+//!   `input` corresponds to "text in the layer below", and `output` corresponds to the text
+//!   exposed to the layer above. So in the inlay map case, a `Transform::Isomorphic`'s summary is
+//!   just `input = output = summary`, where `summary` is the [`TextSummary`] stored in that
+//!   variant. Conversely, a `Transform::Inlay` always has an empty `input` summary, because it's
+//!   not "replacing" any text that exists on disk. The `output` is the summary of the inlay text
+//!   to be injected. - Various newtype wrappers for co-ordinate spaces (e.g. [`WrapRow`]
+//!   represents a row index, after soft-wrapping (and all lower layers)).
+//! - A `Snapshot` type (e.g. [`InlaySnapshot`]) that captures the state of a layer at a specific
+//!   point in time.
+//! - various APIs which drill through the layers below to work with the underlying text. Notably:
+//!   - `fn text_summary_for_offset()` returns a [`TextSummary`] for the range in the co-ordinate
+//!     space that the map in question is responsible for.
+//!   - `fn <A>_point_to_<B>_point()` converts a point in co-ordinate space `A` into co-ordinate
+//!     space `B`.
+//!   - A [`RowInfo`] iterator (e.g. [`InlayBufferRows`]) and a [`Chunk`] iterator
+//!     (e.g. [`InlayChunks`])
+//!   - A `sync` function (e.g. [`InlayMap::sync`]) that takes a snapshot and list of [`Edit<T>`]s,
+//!     and returns a new snapshot and a list of transformed [`Edit<S>`]s. Note that the generic
+//!     parameter on `Edit` changes, since these methods take in edits in the co-ordinate space of
+//!     the lower layer, and return edits in their own co-ordinate space. The term "edit" is
+//!     slightly misleading, since an [`Edit<T>`] doesn't tell you what changed - rather it can be
+//!     thought of as a "region to invalidate". In theory, it would be correct to always use a
+//!     single edit that covers the entire range. However, this would lead to lots of unnecessary
+//!     recalculation.
+//!
+//! See the docs for the [`inlay_map`] module for a more in-depth explanation of how a single layer
+//! works.
+//!
 //! [Editor]: crate::Editor
 //! [EditorElement]: crate::element::EditorElement
+//! [`TextSummary`]: multi_buffer::MBTextSummary
+//! [`WrapRow`]: wrap_map::WrapRow
+//! [`InlayBufferRows`]: inlay_map::InlayBufferRows
+//! [`InlayChunks`]: inlay_map::InlayChunks
+//! [`Edit<T>`]: text::Edit
+//! [`Edit<S>`]: text::Edit
+//! [`Chunk`]: language::Chunk
 
 #[macro_use]
 mod dimensions;
@@ -56,6 +105,7 @@ use sum_tree::{Bias, TreeMap};
 use text::{BufferId, LineIndent};
 use ui::{SharedString, px};
 use unicode_segmentation::UnicodeSegmentation;
+use ztracing::instrument;
 
 use std::{
     any::TypeId,
@@ -168,6 +218,7 @@ impl DisplayMap {
         }
     }
 
+    #[instrument(skip_all)]
     pub fn snapshot(&mut self, cx: &mut Context<Self>) -> DisplaySnapshot {
         let tab_size = Self::tab_size(&self.buffer, cx);
 
@@ -193,6 +244,7 @@ impl DisplayMap {
         }
     }
 
+    #[instrument(skip_all)]
     pub fn set_state(&mut self, other: &DisplaySnapshot, cx: &mut Context<Self>) {
         self.fold(
             other
@@ -209,6 +261,7 @@ impl DisplayMap {
     }
 
     /// Creates folds for the given creases.
+    #[instrument(skip_all)]
     pub fn fold<T: Clone + ToOffset>(&mut self, creases: Vec<Crease<T>>, cx: &mut Context<Self>) {
         let buffer_snapshot = self.buffer.read(cx).snapshot(cx);
         let edits = self.buffer_subscription.consume().into_inner();
@@ -277,6 +330,7 @@ impl DisplayMap {
     }
 
     /// Removes any folds with the given ranges.
+    #[instrument(skip_all)]
     pub fn remove_folds_with_type<T: ToOffset>(
         &mut self,
         ranges: impl IntoIterator<Item = Range<T>>,
@@ -302,6 +356,7 @@ impl DisplayMap {
     }
 
     /// Removes any folds whose ranges intersect any of the given ranges.
+    #[instrument(skip_all)]
     pub fn unfold_intersecting<T: ToOffset>(
         &mut self,
         ranges: impl IntoIterator<Item = Range<T>>,
@@ -333,6 +388,7 @@ impl DisplayMap {
         block_map.remove_intersecting_replace_blocks(offset_ranges, inclusive);
     }
 
+    #[instrument(skip_all)]
     pub fn disable_header_for_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
         let snapshot = self.buffer.read(cx).snapshot(cx);
         let edits = self.buffer_subscription.consume().into_inner();
@@ -347,6 +403,7 @@ impl DisplayMap {
         block_map.disable_header_for_buffer(buffer_id)
     }
 
+    #[instrument(skip_all)]
     pub fn fold_buffers(
         &mut self,
         buffer_ids: impl IntoIterator<Item = language::BufferId>,
@@ -365,6 +422,7 @@ impl DisplayMap {
         block_map.fold_buffers(buffer_ids, self.buffer.read(cx), cx)
     }
 
+    #[instrument(skip_all)]
     pub fn unfold_buffers(
         &mut self,
         buffer_ids: impl IntoIterator<Item = language::BufferId>,
@@ -383,14 +441,17 @@ impl DisplayMap {
         block_map.unfold_buffers(buffer_ids, self.buffer.read(cx), cx)
     }
 
+    #[instrument(skip_all)]
     pub(crate) fn is_buffer_folded(&self, buffer_id: language::BufferId) -> bool {
         self.block_map.folded_buffers.contains(&buffer_id)
     }
 
+    #[instrument(skip_all)]
     pub(crate) fn folded_buffers(&self) -> &HashSet<BufferId> {
         &self.block_map.folded_buffers
     }
 
+    #[instrument(skip_all)]
     pub fn insert_creases(
         &mut self,
         creases: impl IntoIterator<Item = Crease<Anchor>>,
@@ -400,6 +461,7 @@ impl DisplayMap {
         self.crease_map.insert(creases, &snapshot)
     }
 
+    #[instrument(skip_all)]
     pub fn remove_creases(
         &mut self,
         crease_ids: impl IntoIterator<Item = CreaseId>,
@@ -409,6 +471,7 @@ impl DisplayMap {
         self.crease_map.remove(crease_ids, &snapshot)
     }
 
+    #[instrument(skip_all)]
     pub fn insert_blocks(
         &mut self,
         blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
@@ -427,6 +490,7 @@ impl DisplayMap {
         block_map.insert(blocks)
     }
 
+    #[instrument(skip_all)]
     pub fn resize_blocks(&mut self, heights: HashMap<CustomBlockId, u32>, cx: &mut Context<Self>) {
         let snapshot = self.buffer.read(cx).snapshot(cx);
         let edits = self.buffer_subscription.consume().into_inner();
@@ -441,10 +505,12 @@ impl DisplayMap {
         block_map.resize(heights);
     }
 
+    #[instrument(skip_all)]
     pub fn replace_blocks(&mut self, renderers: HashMap<CustomBlockId, RenderBlock>) {
         self.block_map.replace_blocks(renderers);
     }
 
+    #[instrument(skip_all)]
     pub fn remove_blocks(&mut self, ids: HashSet<CustomBlockId>, cx: &mut Context<Self>) {
         let snapshot = self.buffer.read(cx).snapshot(cx);
         let edits = self.buffer_subscription.consume().into_inner();
@@ -459,6 +525,7 @@ impl DisplayMap {
         block_map.remove(ids);
     }
 
+    #[instrument(skip_all)]
     pub fn row_for_block(
         &mut self,
         block_id: CustomBlockId,
@@ -478,6 +545,7 @@ impl DisplayMap {
         Some(DisplayRow(block_row.0))
     }
 
+    #[instrument(skip_all)]
     pub fn highlight_text(
         &mut self,
         key: HighlightKey,
@@ -505,6 +573,7 @@ impl DisplayMap {
         self.text_highlights.insert(key, to_insert);
     }
 
+    #[instrument(skip_all)]
     pub(crate) fn highlight_inlays(
         &mut self,
         type_id: TypeId,
@@ -524,6 +593,7 @@ impl DisplayMap {
         }
     }
 
+    #[instrument(skip_all)]
     pub fn text_highlights(&self, type_id: TypeId) -> Option<(HighlightStyle, &[Range<Anchor>])> {
         let highlights = self.text_highlights.get(&HighlightKey::Type(type_id))?;
         Some((highlights.0, &highlights.1))
@@ -536,6 +606,7 @@ impl DisplayMap {
         self.text_highlights.values()
     }
 
+    #[instrument(skip_all)]
     pub fn clear_highlights(&mut self, type_id: TypeId) -> bool {
         let mut cleared = self
             .text_highlights
@@ -564,6 +635,7 @@ impl DisplayMap {
             .update(cx, |map, cx| map.set_wrap_width(width, cx))
     }
 
+    #[instrument(skip_all)]
     pub fn update_fold_widths(
         &mut self,
         widths: impl IntoIterator<Item = (ChunkRendererId, Pixels)>,
@@ -595,6 +667,7 @@ impl DisplayMap {
         self.inlay_map.current_inlays()
     }
 
+    #[instrument(skip_all)]
     pub(crate) fn splice_inlays(
         &mut self,
         to_remove: &[InlayId],
@@ -624,6 +697,7 @@ impl DisplayMap {
         self.block_map.read(snapshot, edits);
     }
 
+    #[instrument(skip_all)]
     fn tab_size(buffer: &Entity<MultiBuffer>, cx: &App) -> NonZeroU32 {
         let buffer = buffer.read(cx).as_singleton().map(|buffer| buffer.read(cx));
         let language = buffer
@@ -673,6 +747,7 @@ pub struct HighlightedChunk<'a> {
 }
 
 impl<'a> HighlightedChunk<'a> {
+    #[instrument(skip_all)]
     fn highlight_invisibles(
         self,
         editor_style: &'a EditorStyle,
@@ -830,6 +905,7 @@ impl DisplaySnapshot {
         self.buffer_snapshot().widest_line_number()
     }
 
+    #[instrument(skip_all)]
     pub fn prev_line_boundary(&self, mut point: MultiBufferPoint) -> (Point, DisplayPoint) {
         loop {
             let mut inlay_point = self.inlay_snapshot().to_inlay_point(point);
@@ -848,6 +924,7 @@ impl DisplaySnapshot {
         }
     }
 
+    #[instrument(skip_all)]
     pub fn next_line_boundary(
         &self,
         mut point: MultiBufferPoint,
@@ -886,6 +963,7 @@ impl DisplaySnapshot {
         new_start..new_end
     }
 
+    #[instrument(skip_all)]
     pub fn point_to_display_point(&self, point: MultiBufferPoint, bias: Bias) -> DisplayPoint {
         let inlay_point = self.inlay_snapshot().to_inlay_point(point);
         let fold_point = self.fold_snapshot().to_fold_point(inlay_point, bias);
@@ -915,6 +993,7 @@ impl DisplaySnapshot {
             .anchor_at(point.to_offset(self, bias), bias)
     }
 
+    #[instrument(skip_all)]
     fn display_point_to_inlay_point(&self, point: DisplayPoint, bias: Bias) -> InlayPoint {
         let block_point = point.0;
         let wrap_point = self.block_snapshot.to_wrap_point(block_point, bias);
@@ -926,6 +1005,7 @@ impl DisplaySnapshot {
         fold_point.to_inlay_point(self.fold_snapshot())
     }
 
+    #[instrument(skip_all)]
     pub fn display_point_to_fold_point(&self, point: DisplayPoint, bias: Bias) -> FoldPoint {
         let block_point = point.0;
         let wrap_point = self.block_snapshot.to_wrap_point(block_point, bias);
@@ -935,6 +1015,7 @@ impl DisplaySnapshot {
             .0
     }
 
+    #[instrument(skip_all)]
     pub fn fold_point_to_display_point(&self, fold_point: FoldPoint) -> DisplayPoint {
         let tab_point = self.tab_snapshot().fold_point_to_tab_point(fold_point);
         let wrap_point = self.wrap_snapshot().tab_point_to_wrap_point(tab_point);
@@ -947,6 +1028,7 @@ impl DisplaySnapshot {
     }
 
     /// Returns text chunks starting at the given display row until the end of the file
+    #[instrument(skip_all)]
     pub fn text_chunks(&self, display_row: DisplayRow) -> impl Iterator<Item = &str> {
         self.block_snapshot
             .chunks(
@@ -959,6 +1041,7 @@ impl DisplaySnapshot {
     }
 
     /// Returns text chunks starting at the end of the given display row in reverse until the start of the file
+    #[instrument(skip_all)]
     pub fn reverse_text_chunks(&self, display_row: DisplayRow) -> impl Iterator<Item = &str> {
         (0..=display_row.0).rev().flat_map(move |row| {
             self.block_snapshot
@@ -975,6 +1058,7 @@ impl DisplaySnapshot {
         })
     }
 
+    #[instrument(skip_all)]
     pub fn chunks(
         &self,
         display_rows: Range<DisplayRow>,
@@ -993,6 +1077,7 @@ impl DisplaySnapshot {
         )
     }
 
+    #[instrument(skip_all)]
     pub fn highlighted_chunks<'a>(
         &'a self,
         display_rows: Range<DisplayRow>,
@@ -1069,6 +1154,7 @@ impl DisplaySnapshot {
         })
     }
 
+    #[instrument(skip_all)]
     pub fn layout_row(
         &self,
         display_row: DisplayRow,
@@ -1130,6 +1216,7 @@ impl DisplaySnapshot {
         layout_line.closest_index_for_x(x) as u32
     }
 
+    #[instrument(skip_all)]
     pub fn grapheme_at(&self, mut point: DisplayPoint) -> Option<SharedString> {
         point = DisplayPoint(self.block_snapshot.clip_point(point.0, Bias::Left));
         let chars = self
@@ -1319,6 +1406,7 @@ impl DisplaySnapshot {
             .unwrap_or(false)
     }
 
+    #[instrument(skip_all)]
     pub fn crease_for_buffer_row(&self, buffer_row: MultiBufferRow) -> Option<Crease<Point>> {
         let start =
             MultiBufferPoint::new(buffer_row.0, self.buffer_snapshot().line_len(buffer_row));
@@ -1405,6 +1493,7 @@ impl DisplaySnapshot {
     }
 
     #[cfg(any(test, feature = "test-support"))]
+    #[instrument(skip_all)]
     pub fn text_highlight_ranges<Tag: ?Sized + 'static>(
         &self,
     ) -> Option<Arc<(HighlightStyle, Vec<Range<Anchor>>)>> {
@@ -1415,6 +1504,7 @@ impl DisplaySnapshot {
     }
 
     #[cfg(any(test, feature = "test-support"))]
+    #[instrument(skip_all)]
     pub fn all_text_highlight_ranges<Tag: ?Sized + 'static>(
         &self,
     ) -> Vec<(gpui::Hsla, Range<Point>)> {
@@ -1464,6 +1554,7 @@ impl DisplaySnapshot {
     ///
     /// This moves by buffer rows instead of display rows, a distinction that is
     /// important when soft wrapping is enabled.
+    #[instrument(skip_all)]
     pub fn start_of_relative_buffer_row(&self, point: DisplayPoint, times: isize) -> DisplayPoint {
         let start = self.display_point_to_fold_point(point, Bias::Left);
         let target = start.row() as isize + times;

crates/editor/src/display_map/block_map.rs 🔗

@@ -164,6 +164,7 @@ impl<T> BlockPlacement<T> {
 }
 
 impl BlockPlacement<Anchor> {
+    #[ztracing::instrument(skip_all)]
     fn cmp(&self, other: &Self, buffer: &MultiBufferSnapshot) -> Ordering {
         self.start()
             .cmp(other.start(), buffer)
@@ -171,6 +172,7 @@ impl BlockPlacement<Anchor> {
             .then_with(|| self.tie_break().cmp(&other.tie_break()))
     }
 
+    #[ztracing::instrument(skip_all)]
     fn to_wrap_row(&self, wrap_snapshot: &WrapSnapshot) -> Option<BlockPlacement<WrapRow>> {
         let buffer_snapshot = wrap_snapshot.buffer_snapshot();
         match self {
@@ -474,6 +476,7 @@ pub struct BlockRows<'a> {
 }
 
 impl BlockMap {
+    #[ztracing::instrument(skip_all)]
     pub fn new(
         wrap_snapshot: WrapSnapshot,
         buffer_header_height: u32,
@@ -503,6 +506,7 @@ impl BlockMap {
         map
     }
 
+    #[ztracing::instrument(skip_all)]
     pub fn read(&self, wrap_snapshot: WrapSnapshot, edits: WrapPatch) -> BlockMapReader<'_> {
         self.sync(&wrap_snapshot, edits);
         *self.wrap_snapshot.borrow_mut() = wrap_snapshot.clone();
@@ -518,13 +522,17 @@ impl BlockMap {
         }
     }
 
+    #[ztracing::instrument(skip_all)]
     pub fn write(&mut self, wrap_snapshot: WrapSnapshot, edits: WrapPatch) -> BlockMapWriter<'_> {
         self.sync(&wrap_snapshot, edits);
         *self.wrap_snapshot.borrow_mut() = wrap_snapshot;
         BlockMapWriter(self)
     }
 
+    #[ztracing::instrument(skip_all, fields(edits = ?edits))]
     fn sync(&self, wrap_snapshot: &WrapSnapshot, mut edits: WrapPatch) {
+        let _timer = zlog::time!("BlockMap::sync").warn_if_gt(std::time::Duration::from_millis(50));
+
         let buffer = wrap_snapshot.buffer_snapshot();
 
         // Handle changing the last excerpt if it is empty.
@@ -537,7 +545,7 @@ impl BlockMap {
         {
             let max_point = wrap_snapshot.max_point();
             let edit_start = wrap_snapshot.prev_row_boundary(max_point);
-            let edit_end = max_point.row() + WrapRow(1);
+            let edit_end = max_point.row() + WrapRow(1); // this is end of file
             edits = edits.compose([WrapEdit {
                 old: edit_start..edit_end,
                 new: edit_start..edit_end,
@@ -562,6 +570,9 @@ impl BlockMap {
         let mut wrap_point_cursor = wrap_snapshot.wrap_point_cursor();
 
         while let Some(edit) = edits.next() {
+            let span = ztracing::debug_span!("while edits", edit = ?edit);
+            let _enter = span.enter();
+
             let mut old_start = edit.old.start;
             let mut new_start = edit.new.start;
 
@@ -620,6 +631,8 @@ impl BlockMap {
             let mut old_end = edit.old.end;
             let mut new_end = edit.new.end;
             loop {
+                let span = ztracing::debug_span!("decide where edit ends loop");
+                let _enter = span.enter();
                 // Seek to the transform starting at or after the end of the edit
                 cursor.seek(&old_end, Bias::Left);
                 cursor.next();
@@ -702,6 +715,7 @@ impl BlockMap {
                         let placement = block.placement.to_wrap_row(wrap_snapshot)?;
                         if let BlockPlacement::Above(row) = placement
                             && row < new_start
+                        // this will be true more often now
                         {
                             return None;
                         }
@@ -728,6 +742,10 @@ impl BlockMap {
             // and then insert the block itself.
             let mut just_processed_folded_buffer = false;
             for (block_placement, block) in blocks_in_edit.drain(..) {
+                let span =
+                    ztracing::debug_span!("for block in edits", block_height = block.height());
+                let _enter = span.enter();
+
                 let mut summary = TransformSummary {
                     input_rows: WrapRow(0),
                     output_rows: BlockRow(block.height()),
@@ -784,6 +802,7 @@ impl BlockMap {
         *transforms = new_transforms;
     }
 
+    #[ztracing::instrument(skip_all)]
     pub fn replace_blocks(&mut self, mut renderers: HashMap<CustomBlockId, RenderBlock>) {
         for block in &mut self.custom_blocks {
             if let Some(render) = renderers.remove(&block.id) {
@@ -793,6 +812,7 @@ impl BlockMap {
     }
 
     /// Guarantees that `wrap_row_for` is called with points in increasing order.
+    #[ztracing::instrument(skip_all)]
     fn header_and_footer_blocks<'a, R, T>(
         &'a self,
         buffer: &'a multi_buffer::MultiBufferSnapshot,
@@ -880,6 +900,7 @@ impl BlockMap {
         })
     }
 
+    #[ztracing::instrument(skip_all)]
     fn sort_blocks(blocks: &mut Vec<(BlockPlacement<WrapRow>, Block)>) {
         blocks.sort_unstable_by(|(placement_a, block_a), (placement_b, block_b)| {
             placement_a
@@ -946,6 +967,7 @@ impl BlockMap {
     }
 }
 
+#[ztracing::instrument(skip(tree, wrap_snapshot))]
 fn push_isomorphic(tree: &mut SumTree<Transform>, rows: RowDelta, wrap_snapshot: &WrapSnapshot) {
     if rows == RowDelta(0) {
         return;
@@ -1016,6 +1038,7 @@ impl DerefMut for BlockMapReader<'_> {
 }
 
 impl BlockMapReader<'_> {
+    #[ztracing::instrument(skip_all)]
     pub fn row_for_block(&self, block_id: CustomBlockId) -> Option<BlockRow> {
         let block = self.blocks.iter().find(|block| block.id == block_id)?;
         let buffer_row = block
@@ -1054,6 +1077,7 @@ impl BlockMapReader<'_> {
 }
 
 impl BlockMapWriter<'_> {
+    #[ztracing::instrument(skip_all)]
     pub fn insert(
         &mut self,
         blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
@@ -1120,6 +1144,7 @@ impl BlockMapWriter<'_> {
         ids
     }
 
+    #[ztracing::instrument(skip_all)]
     pub fn resize(&mut self, mut heights: HashMap<CustomBlockId, u32>) {
         let wrap_snapshot = &*self.0.wrap_snapshot.borrow();
         let buffer = wrap_snapshot.buffer_snapshot();
@@ -1172,6 +1197,7 @@ impl BlockMapWriter<'_> {
         self.0.sync(wrap_snapshot, edits);
     }
 
+    #[ztracing::instrument(skip_all)]
     pub fn remove(&mut self, block_ids: HashSet<CustomBlockId>) {
         let wrap_snapshot = &*self.0.wrap_snapshot.borrow();
         let buffer = wrap_snapshot.buffer_snapshot();
@@ -1217,6 +1243,7 @@ impl BlockMapWriter<'_> {
         self.0.sync(wrap_snapshot, edits);
     }
 
+    #[ztracing::instrument(skip_all)]
     pub fn remove_intersecting_replace_blocks(
         &mut self,
         ranges: impl IntoIterator<Item = Range<MultiBufferOffset>>,
@@ -1239,6 +1266,7 @@ impl BlockMapWriter<'_> {
         self.0.buffers_with_disabled_headers.insert(buffer_id);
     }
 
+    #[ztracing::instrument(skip_all)]
     pub fn fold_buffers(
         &mut self,
         buffer_ids: impl IntoIterator<Item = BufferId>,
@@ -1248,6 +1276,7 @@ impl BlockMapWriter<'_> {
         self.fold_or_unfold_buffers(true, buffer_ids, multi_buffer, cx);
     }
 
+    #[ztracing::instrument(skip_all)]
     pub fn unfold_buffers(
         &mut self,
         buffer_ids: impl IntoIterator<Item = BufferId>,
@@ -1257,6 +1286,7 @@ impl BlockMapWriter<'_> {
         self.fold_or_unfold_buffers(false, buffer_ids, multi_buffer, cx);
     }
 
+    #[ztracing::instrument(skip_all)]
     fn fold_or_unfold_buffers(
         &mut self,
         fold: bool,
@@ -1292,6 +1322,7 @@ impl BlockMapWriter<'_> {
         self.0.sync(&wrap_snapshot, edits);
     }
 
+    #[ztracing::instrument(skip_all)]
     fn blocks_intersecting_buffer_range(
         &self,
         range: Range<MultiBufferOffset>,
@@ -1326,6 +1357,7 @@ impl BlockMapWriter<'_> {
 
 impl BlockSnapshot {
     #[cfg(test)]
+    #[ztracing::instrument(skip_all)]
     pub fn text(&self) -> String {
         self.chunks(
             BlockRow(0)..self.transforms.summary().output_rows,
@@ -1337,6 +1369,7 @@ impl BlockSnapshot {
         .collect()
     }
 
+    #[ztracing::instrument(skip_all)]
     pub(crate) fn chunks<'a>(
         &'a self,
         rows: Range<BlockRow>,
@@ -1378,6 +1411,7 @@ impl BlockSnapshot {
         }
     }
 
+    #[ztracing::instrument(skip_all)]
     pub(super) fn row_infos(&self, start_row: BlockRow) -> BlockRows<'_> {
         let mut cursor = self.transforms.cursor::<Dimensions<BlockRow, WrapRow>>(());
         cursor.seek(&start_row, Bias::Right);
@@ -1399,6 +1433,7 @@ impl BlockSnapshot {
         }
     }
 
+    #[ztracing::instrument(skip_all)]
     pub fn blocks_in_range(
         &self,
         rows: Range<BlockRow>,
@@ -1432,6 +1467,7 @@ impl BlockSnapshot {
         })
     }
 
+    #[ztracing::instrument(skip_all)]
     pub(crate) fn sticky_header_excerpt(&self, position: f64) -> Option<StickyHeaderExcerpt<'_>> {
         let top_row = position as u32;
         let mut cursor = self.transforms.cursor::<BlockRow>(());
@@ -1455,6 +1491,7 @@ impl BlockSnapshot {
         None
     }
 
+    #[ztracing::instrument(skip_all)]
     pub fn block_for_id(&self, block_id: BlockId) -> Option<Block> {
         let buffer = self.wrap_snapshot.buffer_snapshot();
         let wrap_point = match block_id {
@@ -1491,6 +1528,7 @@ impl BlockSnapshot {
         None
     }
 
+    #[ztracing::instrument(skip_all)]
     pub fn max_point(&self) -> BlockPoint {
         let row = self
             .transforms
@@ -1500,10 +1538,12 @@ impl BlockSnapshot {
         BlockPoint::new(row, self.line_len(row))
     }
 
+    #[ztracing::instrument(skip_all)]
     pub fn longest_row(&self) -> BlockRow {
         self.transforms.summary().longest_row
     }
 
+    #[ztracing::instrument(skip_all)]
     pub fn longest_row_in_range(&self, range: Range<BlockRow>) -> BlockRow {
         let mut cursor = self.transforms.cursor::<Dimensions<BlockRow, WrapRow>>(());
         cursor.seek(&range.start, Bias::Right);
@@ -1555,6 +1595,7 @@ impl BlockSnapshot {
         longest_row
     }
 
+    #[ztracing::instrument(skip_all)]
     pub(super) fn line_len(&self, row: BlockRow) -> u32 {
         let (start, _, item) =
             self.transforms
@@ -1574,11 +1615,13 @@ impl BlockSnapshot {
         }
     }
 
+    #[ztracing::instrument(skip_all)]
     pub(super) fn is_block_line(&self, row: BlockRow) -> bool {
         let (_, _, item) = self.transforms.find::<BlockRow, _>((), &row, Bias::Right);
         item.is_some_and(|t| t.block.is_some())
     }
 
+    #[ztracing::instrument(skip_all)]
     pub(super) fn is_folded_buffer_header(&self, row: BlockRow) -> bool {
         let (_, _, item) = self.transforms.find::<BlockRow, _>((), &row, Bias::Right);
         let Some(transform) = item else {
@@ -1587,6 +1630,7 @@ impl BlockSnapshot {
         matches!(transform.block, Some(Block::FoldedBuffer { .. }))
     }
 
+    #[ztracing::instrument(skip_all)]
     pub(super) fn is_line_replaced(&self, row: MultiBufferRow) -> bool {
         let wrap_point = self
             .wrap_snapshot
@@ -1602,6 +1646,7 @@ impl BlockSnapshot {
         })
     }
 
+    #[ztracing::instrument(skip_all)]
     pub fn clip_point(&self, point: BlockPoint, bias: Bias) -> BlockPoint {
         let mut cursor = self.transforms.cursor::<Dimensions<BlockRow, WrapRow>>(());
         cursor.seek(&BlockRow(point.row), Bias::Right);
@@ -1663,6 +1708,7 @@ impl BlockSnapshot {
         }
     }
 
+    #[ztracing::instrument(skip_all)]
     pub fn to_block_point(&self, wrap_point: WrapPoint) -> BlockPoint {
         let (start, _, item) = self.transforms.find::<Dimensions<WrapRow, BlockRow>, _>(
             (),
@@ -1684,6 +1730,7 @@ impl BlockSnapshot {
         }
     }
 
+    #[ztracing::instrument(skip_all)]
     pub fn to_wrap_point(&self, block_point: BlockPoint, bias: Bias) -> WrapPoint {
         let (start, end, item) = self.transforms.find::<Dimensions<BlockRow, WrapRow>, _>(
             (),
@@ -1719,6 +1766,7 @@ impl BlockSnapshot {
 
 impl BlockChunks<'_> {
     /// Go to the next transform
+    #[ztracing::instrument(skip_all)]
     fn advance(&mut self) {
         self.input_chunk = Chunk::default();
         self.transforms.next();
@@ -1759,6 +1807,7 @@ pub struct StickyHeaderExcerpt<'a> {
 impl<'a> Iterator for BlockChunks<'a> {
     type Item = Chunk<'a>;
 
+    #[ztracing::instrument(skip_all)]
     fn next(&mut self) -> Option<Self::Item> {
         if self.output_row >= self.max_output_row {
             return None;
@@ -1858,6 +1907,7 @@ impl<'a> Iterator for BlockChunks<'a> {
 impl Iterator for BlockRows<'_> {
     type Item = RowInfo;
 
+    #[ztracing::instrument(skip_all)]
     fn next(&mut self) -> Option<Self::Item> {
         if self.started {
             self.output_row.0 += 1;
@@ -1960,14 +2010,17 @@ impl DerefMut for BlockContext<'_, '_> {
 }
 
 impl CustomBlock {
+    #[ztracing::instrument(skip_all)]
     pub fn render(&self, cx: &mut BlockContext) -> AnyElement {
         self.render.lock()(cx)
     }
 
+    #[ztracing::instrument(skip_all)]
     pub fn start(&self) -> Anchor {
         *self.placement.start()
     }
 
+    #[ztracing::instrument(skip_all)]
     pub fn end(&self) -> Anchor {
         *self.placement.end()
     }

crates/editor/src/display_map/crease_map.rs 🔗

@@ -19,6 +19,7 @@ pub struct CreaseMap {
 }
 
 impl CreaseMap {
+    #[ztracing::instrument(skip_all)]
     pub fn new(snapshot: &MultiBufferSnapshot) -> Self {
         CreaseMap {
             snapshot: CreaseSnapshot::new(snapshot),
@@ -40,11 +41,13 @@ impl CreaseSnapshot {
         }
     }
 
+    #[ztracing::instrument(skip_all)]
     pub fn creases(&self) -> impl Iterator<Item = (CreaseId, &Crease<Anchor>)> {
         self.creases.iter().map(|item| (item.id, &item.crease))
     }
 
     /// Returns the first Crease starting on the specified buffer row.
+    #[ztracing::instrument(skip_all)]
     pub fn query_row<'a>(
         &'a self,
         row: MultiBufferRow,
@@ -69,6 +72,7 @@ impl CreaseSnapshot {
         None
     }
 
+    #[ztracing::instrument(skip_all)]
     pub fn creases_in_range<'a>(
         &'a self,
         range: Range<MultiBufferRow>,
@@ -95,6 +99,7 @@ impl CreaseSnapshot {
         })
     }
 
+    #[ztracing::instrument(skip_all)]
     pub fn crease_items_with_offsets(
         &self,
         snapshot: &MultiBufferSnapshot,
@@ -156,6 +161,7 @@ pub struct CreaseMetadata {
 }
 
 impl<T> Crease<T> {
+    #[ztracing::instrument(skip_all)]
     pub fn simple(range: Range<T>, placeholder: FoldPlaceholder) -> Self {
         Crease::Inline {
             range,
@@ -166,6 +172,7 @@ impl<T> Crease<T> {
         }
     }
 
+    #[ztracing::instrument(skip_all)]
     pub fn block(range: Range<T>, height: u32, style: BlockStyle, render: RenderBlock) -> Self {
         Self::Block {
             range,
@@ -177,6 +184,7 @@ impl<T> Crease<T> {
         }
     }
 
+    #[ztracing::instrument(skip_all)]
     pub fn inline<RenderToggle, ToggleElement, RenderTrailer, TrailerElement>(
         range: Range<T>,
         placeholder: FoldPlaceholder,
@@ -216,6 +224,7 @@ impl<T> Crease<T> {
         }
     }
 
+    #[ztracing::instrument(skip_all)]
     pub fn with_metadata(self, metadata: CreaseMetadata) -> Self {
         match self {
             Crease::Inline {
@@ -235,6 +244,7 @@ impl<T> Crease<T> {
         }
     }
 
+    #[ztracing::instrument(skip_all)]
     pub fn range(&self) -> &Range<T> {
         match self {
             Crease::Inline { range, .. } => range,
@@ -242,6 +252,7 @@ impl<T> Crease<T> {
         }
     }
 
+    #[ztracing::instrument(skip_all)]
     pub fn metadata(&self) -> Option<&CreaseMetadata> {
         match self {
             Self::Inline { metadata, .. } => metadata.as_ref(),
@@ -287,6 +298,7 @@ impl CreaseMap {
         self.snapshot.clone()
     }
 
+    #[ztracing::instrument(skip_all)]
     pub fn insert(
         &mut self,
         creases: impl IntoIterator<Item = Crease<Anchor>>,
@@ -312,6 +324,7 @@ impl CreaseMap {
         new_ids
     }
 
+    #[ztracing::instrument(skip_all)]
     pub fn remove(
         &mut self,
         ids: impl IntoIterator<Item = CreaseId>,
@@ -379,6 +392,7 @@ impl sum_tree::Summary for ItemSummary {
 impl sum_tree::Item for CreaseItem {
     type Summary = ItemSummary;
 
+    #[ztracing::instrument(skip_all)]
     fn summary(&self, _cx: &MultiBufferSnapshot) -> Self::Summary {
         ItemSummary {
             range: self.crease.range().clone(),
@@ -388,12 +402,14 @@ impl sum_tree::Item for CreaseItem {
 
 /// Implements `SeekTarget` for `Range<Anchor>` to enable seeking within a `SumTree` of `CreaseItem`s.
 impl SeekTarget<'_, ItemSummary, ItemSummary> for Range<Anchor> {
+    #[ztracing::instrument(skip_all)]
     fn cmp(&self, cursor_location: &ItemSummary, snapshot: &MultiBufferSnapshot) -> Ordering {
         AnchorRangeExt::cmp(self, &cursor_location.range, snapshot)
     }
 }
 
 impl SeekTarget<'_, ItemSummary, ItemSummary> for Anchor {
+    #[ztracing::instrument(skip_all)]
     fn cmp(&self, other: &ItemSummary, snapshot: &MultiBufferSnapshot) -> Ordering {
         self.cmp(&other.range.start, snapshot)
     }
@@ -461,6 +477,7 @@ mod test {
     }
 
     #[gpui::test]
+    #[ztracing::instrument(skip_all)]
     fn test_creases_in_range(cx: &mut App) {
         let text = "line1\nline2\nline3\nline4\nline5\nline6\nline7";
         let buffer = MultiBuffer::build_simple(text, cx);

crates/editor/src/display_map/custom_highlights.rs 🔗

@@ -30,6 +30,7 @@ struct HighlightEndpoint {
 }
 
 impl<'a> CustomHighlightsChunks<'a> {
+    #[ztracing::instrument(skip_all)]
     pub fn new(
         range: Range<MultiBufferOffset>,
         language_aware: bool,
@@ -51,6 +52,7 @@ impl<'a> CustomHighlightsChunks<'a> {
         }
     }
 
+    #[ztracing::instrument(skip_all)]
     pub fn seek(&mut self, new_range: Range<MultiBufferOffset>) {
         self.highlight_endpoints =
             create_highlight_endpoints(&new_range, self.text_highlights, self.multibuffer_snapshot);
@@ -77,12 +79,15 @@ fn create_highlight_endpoints(
             let start_ix = ranges
                 .binary_search_by(|probe| probe.end.cmp(&start, buffer).then(cmp::Ordering::Less))
                 .unwrap_or_else(|i| i);
+            let end_ix = ranges[start_ix..]
+                .binary_search_by(|probe| {
+                    probe.start.cmp(&end, buffer).then(cmp::Ordering::Greater)
+                })
+                .unwrap_or_else(|i| i);
 
-            for range in &ranges[start_ix..] {
-                if range.start.cmp(&end, buffer).is_ge() {
-                    break;
-                }
+            highlight_endpoints.reserve(2 * end_ix);
 
+            for range in &ranges[start_ix..][..end_ix] {
                 let start = range.start.to_offset(buffer);
                 let end = range.end.to_offset(buffer);
                 if start == end {
@@ -108,6 +113,7 @@ fn create_highlight_endpoints(
 impl<'a> Iterator for CustomHighlightsChunks<'a> {
     type Item = Chunk<'a>;
 
+    #[ztracing::instrument(skip_all)]
     fn next(&mut self) -> Option<Self::Item> {
         let mut next_highlight_endpoint = MultiBufferOffset(usize::MAX);
         while let Some(endpoint) = self.highlight_endpoints.peek().copied() {

crates/editor/src/display_map/fold_map.rs 🔗

@@ -99,6 +99,7 @@ impl FoldPoint {
         &mut self.0.column
     }
 
+    #[ztracing::instrument(skip_all)]
     pub fn to_inlay_point(self, snapshot: &FoldSnapshot) -> InlayPoint {
         let (start, _, _) = snapshot
             .transforms
@@ -107,6 +108,7 @@ impl FoldPoint {
         InlayPoint(start.1.0 + overshoot)
     }
 
+    #[ztracing::instrument(skip_all)]
     pub fn to_offset(self, snapshot: &FoldSnapshot) -> FoldOffset {
         let (start, _, item) = snapshot
             .transforms
@@ -138,6 +140,7 @@ impl<'a> sum_tree::Dimension<'a, TransformSummary> for FoldPoint {
 pub(crate) struct FoldMapWriter<'a>(&'a mut FoldMap);
 
 impl FoldMapWriter<'_> {
+    #[ztracing::instrument(skip_all)]
     pub(crate) fn fold<T: ToOffset>(
         &mut self,
         ranges: impl IntoIterator<Item = (Range<T>, FoldPlaceholder)>,
@@ -202,6 +205,7 @@ impl FoldMapWriter<'_> {
     }
 
     /// Removes any folds with the given ranges.
+    #[ztracing::instrument(skip_all)]
     pub(crate) fn remove_folds<T: ToOffset>(
         &mut self,
         ranges: impl IntoIterator<Item = Range<T>>,
@@ -215,6 +219,7 @@ impl FoldMapWriter<'_> {
     }
 
     /// Removes any folds whose ranges intersect the given ranges.
+    #[ztracing::instrument(skip_all)]
     pub(crate) fn unfold_intersecting<T: ToOffset>(
         &mut self,
         ranges: impl IntoIterator<Item = Range<T>>,
@@ -225,6 +230,7 @@ impl FoldMapWriter<'_> {
 
     /// Removes any folds that intersect the given ranges and for which the given predicate
     /// returns true.
+    #[ztracing::instrument(skip_all)]
     fn remove_folds_with<T: ToOffset>(
         &mut self,
         ranges: impl IntoIterator<Item = Range<T>>,
@@ -277,6 +283,7 @@ impl FoldMapWriter<'_> {
         (self.0.snapshot.clone(), edits)
     }
 
+    #[ztracing::instrument(skip_all)]
     pub(crate) fn update_fold_widths(
         &mut self,
         new_widths: impl IntoIterator<Item = (ChunkRendererId, Pixels)>,
@@ -326,6 +333,7 @@ pub struct FoldMap {
 }
 
 impl FoldMap {
+    #[ztracing::instrument(skip_all)]
     pub fn new(inlay_snapshot: InlaySnapshot) -> (Self, FoldSnapshot) {
         let this = Self {
             snapshot: FoldSnapshot {
@@ -350,6 +358,7 @@ impl FoldMap {
         (this, snapshot)
     }
 
+    #[ztracing::instrument(skip_all)]
     pub fn read(
         &mut self,
         inlay_snapshot: InlaySnapshot,
@@ -360,6 +369,7 @@ impl FoldMap {
         (self.snapshot.clone(), edits)
     }
 
+    #[ztracing::instrument(skip_all)]
     pub(crate) fn write(
         &mut self,
         inlay_snapshot: InlaySnapshot,
@@ -369,6 +379,7 @@ impl FoldMap {
         (FoldMapWriter(self), snapshot, edits)
     }
 
+    #[ztracing::instrument(skip_all)]
     fn check_invariants(&self) {
         if cfg!(test) {
             assert_eq!(
@@ -398,6 +409,7 @@ impl FoldMap {
         }
     }
 
+    #[ztracing::instrument(skip_all)]
     fn sync(
         &mut self,
         inlay_snapshot: InlaySnapshot,
@@ -645,6 +657,7 @@ impl FoldSnapshot {
         &self.inlay_snapshot.buffer
     }
 
+    #[ztracing::instrument(skip_all)]
     fn fold_width(&self, fold_id: &FoldId) -> Option<Pixels> {
         self.fold_metadata_by_id.get(fold_id)?.width
     }
@@ -665,6 +678,7 @@ impl FoldSnapshot {
         self.folds.items(&self.inlay_snapshot.buffer).len()
     }
 
+    #[ztracing::instrument(skip_all)]
     pub fn text_summary_for_range(&self, range: Range<FoldPoint>) -> MBTextSummary {
         let mut summary = MBTextSummary::default();
 
@@ -718,6 +732,7 @@ impl FoldSnapshot {
         summary
     }
 
+    #[ztracing::instrument(skip_all)]
     pub fn to_fold_point(&self, point: InlayPoint, bias: Bias) -> FoldPoint {
         let (start, end, item) = self
             .transforms
@@ -734,6 +749,7 @@ impl FoldSnapshot {
         }
     }
 
+    #[ztracing::instrument(skip_all)]
     pub fn fold_point_cursor(&self) -> FoldPointCursor<'_> {
         let cursor = self
             .transforms
@@ -741,10 +757,12 @@ impl FoldSnapshot {
         FoldPointCursor { cursor }
     }
 
+    #[ztracing::instrument(skip_all)]
     pub fn len(&self) -> FoldOffset {
         FoldOffset(self.transforms.summary().output.len)
     }
 
+    #[ztracing::instrument(skip_all)]
     pub fn line_len(&self, row: u32) -> u32 {
         let line_start = FoldPoint::new(row, 0).to_offset(self).0;
         let line_end = if row >= self.max_point().row() {
@@ -755,6 +773,7 @@ impl FoldSnapshot {
         (line_end - line_start) as u32
     }
 
+    #[ztracing::instrument(skip_all)]
     pub fn row_infos(&self, start_row: u32) -> FoldRows<'_> {
         if start_row > self.transforms.summary().output.lines.row {
             panic!("invalid display row {}", start_row);
@@ -777,6 +796,7 @@ impl FoldSnapshot {
         }
     }
 
+    #[ztracing::instrument(skip_all)]
     pub fn max_point(&self) -> FoldPoint {
         FoldPoint(self.transforms.summary().output.lines)
     }
@@ -786,6 +806,7 @@ impl FoldSnapshot {
         self.transforms.summary().output.longest_row
     }
 
+    #[ztracing::instrument(skip_all)]
     pub fn folds_in_range<T>(&self, range: Range<T>) -> impl Iterator<Item = &Fold>
     where
         T: ToOffset,
@@ -800,6 +821,7 @@ impl FoldSnapshot {
         })
     }
 
+    #[ztracing::instrument(skip_all)]
     pub fn intersects_fold<T>(&self, offset: T) -> bool
     where
         T: ToOffset,
@@ -812,6 +834,7 @@ impl FoldSnapshot {
         item.is_some_and(|t| t.placeholder.is_some())
     }
 
+    #[ztracing::instrument(skip_all)]
     pub fn is_line_folded(&self, buffer_row: MultiBufferRow) -> bool {
         let mut inlay_point = self
             .inlay_snapshot
@@ -840,6 +863,7 @@ impl FoldSnapshot {
         }
     }
 
+    #[ztracing::instrument(skip_all)]
     pub(crate) fn chunks<'a>(
         &'a self,
         range: Range<FoldOffset>,
@@ -884,6 +908,7 @@ impl FoldSnapshot {
         }
     }
 
+    #[ztracing::instrument(skip_all)]
     pub fn chars_at(&self, start: FoldPoint) -> impl '_ + Iterator<Item = char> {
         self.chunks(
             start.to_offset(self)..self.len(),
@@ -893,6 +918,7 @@ impl FoldSnapshot {
         .flat_map(|chunk| chunk.text.chars())
     }
 
+    #[ztracing::instrument(skip_all)]
     pub fn chunks_at(&self, start: FoldPoint) -> FoldChunks<'_> {
         self.chunks(
             start.to_offset(self)..self.len(),
@@ -902,6 +928,7 @@ impl FoldSnapshot {
     }
 
     #[cfg(test)]
+    #[ztracing::instrument(skip_all)]
     pub fn clip_offset(&self, offset: FoldOffset, bias: Bias) -> FoldOffset {
         if offset > self.len() {
             self.len()
@@ -910,6 +937,7 @@ impl FoldSnapshot {
         }
     }
 
+    #[ztracing::instrument(skip_all)]
     pub fn clip_point(&self, point: FoldPoint, bias: Bias) -> FoldPoint {
         let (start, end, item) = self
             .transforms
@@ -939,6 +967,7 @@ pub struct FoldPointCursor<'transforms> {
 }
 
 impl FoldPointCursor<'_> {
+    #[ztracing::instrument(skip_all)]
     pub fn map(&mut self, point: InlayPoint, bias: Bias) -> FoldPoint {
         let cursor = &mut self.cursor;
         if cursor.did_seek() {
@@ -1267,6 +1296,7 @@ pub struct FoldRows<'a> {
 }
 
 impl FoldRows<'_> {
+    #[ztracing::instrument(skip_all)]
     pub(crate) fn seek(&mut self, row: u32) {
         let fold_point = FoldPoint::new(row, 0);
         self.cursor.seek(&fold_point, Bias::Left);
@@ -1280,6 +1310,7 @@ impl FoldRows<'_> {
 impl Iterator for FoldRows<'_> {
     type Item = RowInfo;
 
+    #[ztracing::instrument(skip_all)]
     fn next(&mut self) -> Option<Self::Item> {
         let mut traversed_fold = false;
         while self.fold_point > self.cursor.end().0 {
@@ -1391,6 +1422,7 @@ pub struct FoldChunks<'a> {
 }
 
 impl FoldChunks<'_> {
+    #[ztracing::instrument(skip_all)]
     pub(crate) fn seek(&mut self, range: Range<FoldOffset>) {
         self.transform_cursor.seek(&range.start, Bias::Right);
 
@@ -1425,6 +1457,7 @@ impl FoldChunks<'_> {
 impl<'a> Iterator for FoldChunks<'a> {
     type Item = Chunk<'a>;
 
+    #[ztracing::instrument(skip_all)]
     fn next(&mut self) -> Option<Self::Item> {
         if self.output_offset >= self.max_output_offset {
             return None;
@@ -1524,6 +1557,7 @@ impl<'a> Iterator for FoldChunks<'a> {
 pub struct FoldOffset(pub MultiBufferOffset);
 
 impl FoldOffset {
+    #[ztracing::instrument(skip_all)]
     pub fn to_point(self, snapshot: &FoldSnapshot) -> FoldPoint {
         let (start, _, item) = snapshot
             .transforms
@@ -1539,6 +1573,7 @@ impl FoldOffset {
     }
 
     #[cfg(test)]
+    #[ztracing::instrument(skip_all)]
     pub fn to_inlay_offset(self, snapshot: &FoldSnapshot) -> InlayOffset {
         let (start, _, _) = snapshot
             .transforms

crates/editor/src/display_map/inlay_map.rs 🔗

@@ -1,3 +1,10 @@
+//! The inlay map. See the [`display_map`][super] docs for an overview of how the inlay map fits
+//! into the rest of the [`DisplayMap`][super::DisplayMap]. Much of the documentation for this
+//! module generalizes to other layers.
+//!
+//! The core of this module is the [`InlayMap`] struct, which maintains a vec of [`Inlay`]s, and
+//! [`InlaySnapshot`], which holds a sum tree of [`Transform`]s.
+
 use crate::{
     ChunkRenderer, HighlightStyles,
     inlays::{Inlay, InlayContent},
@@ -52,6 +59,7 @@ enum Transform {
 impl sum_tree::Item for Transform {
     type Summary = TransformSummary;
 
+    #[ztracing::instrument(skip_all)]
     fn summary(&self, _: ()) -> Self::Summary {
         match self {
             Transform::Isomorphic(summary) => TransformSummary {
@@ -68,7 +76,9 @@ impl sum_tree::Item for Transform {
 
 #[derive(Clone, Debug, Default)]
 struct TransformSummary {
+    /// Summary of the text before inlays have been applied.
     input: MBTextSummary,
+    /// Summary of the text after inlays have been applied.
     output: MBTextSummary,
 }
 
@@ -228,6 +238,7 @@ pub struct InlayChunk<'a> {
 }
 
 impl InlayChunks<'_> {
+    #[ztracing::instrument(skip_all)]
     pub fn seek(&mut self, new_range: Range<InlayOffset>) {
         self.transforms.seek(&new_range.start, Bias::Right);
 
@@ -248,6 +259,7 @@ impl InlayChunks<'_> {
 impl<'a> Iterator for InlayChunks<'a> {
     type Item = InlayChunk<'a>;
 
+    #[ztracing::instrument(skip_all)]
     fn next(&mut self) -> Option<Self::Item> {
         if self.output_offset == self.max_output_offset {
             return None;
@@ -441,6 +453,7 @@ impl<'a> Iterator for InlayChunks<'a> {
 }
 
 impl InlayBufferRows<'_> {
+    #[ztracing::instrument(skip_all)]
     pub fn seek(&mut self, row: u32) {
         let inlay_point = InlayPoint::new(row, 0);
         self.transforms.seek(&inlay_point, Bias::Left);
@@ -465,6 +478,7 @@ impl InlayBufferRows<'_> {
 impl Iterator for InlayBufferRows<'_> {
     type Item = RowInfo;
 
+    #[ztracing::instrument(skip_all)]
     fn next(&mut self) -> Option<Self::Item> {
         let buffer_row = if self.inlay_row == 0 {
             self.buffer_rows.next().unwrap()
@@ -494,6 +508,7 @@ impl InlayPoint {
 }
 
 impl InlayMap {
+    #[ztracing::instrument(skip_all)]
     pub fn new(buffer: MultiBufferSnapshot) -> (Self, InlaySnapshot) {
         let version = 0;
         let snapshot = InlaySnapshot {
@@ -511,6 +526,7 @@ impl InlayMap {
         )
     }
 
+    #[ztracing::instrument(skip_all)]
     pub fn sync(
         &mut self,
         buffer_snapshot: MultiBufferSnapshot,
@@ -643,6 +659,7 @@ impl InlayMap {
         }
     }
 
+    #[ztracing::instrument(skip_all)]
     pub fn splice(
         &mut self,
         to_remove: &[InlayId],
@@ -693,11 +710,13 @@ impl InlayMap {
         (snapshot, edits)
     }
 
+    #[ztracing::instrument(skip_all)]
     pub fn current_inlays(&self) -> impl Iterator<Item = &Inlay> {
         self.inlays.iter()
     }
 
     #[cfg(test)]
+    #[ztracing::instrument(skip_all)]
     pub(crate) fn randomly_mutate(
         &mut self,
         next_inlay_id: &mut usize,
@@ -766,6 +785,7 @@ impl InlayMap {
 }
 
 impl InlaySnapshot {
+    #[ztracing::instrument(skip_all)]
     pub fn to_point(&self, offset: InlayOffset) -> InlayPoint {
         let (start, _, item) = self.transforms.find::<Dimensions<
             InlayOffset,
@@ -789,14 +809,17 @@ impl InlaySnapshot {
         }
     }
 
+    #[ztracing::instrument(skip_all)]
     pub fn len(&self) -> InlayOffset {
         InlayOffset(self.transforms.summary().output.len)
     }
 
+    #[ztracing::instrument(skip_all)]
     pub fn max_point(&self) -> InlayPoint {
         InlayPoint(self.transforms.summary().output.lines)
     }
 
+    #[ztracing::instrument(skip_all, fields(point))]
     pub fn to_offset(&self, point: InlayPoint) -> InlayOffset {
         let (start, _, item) = self
             .transforms
@@ -817,6 +840,7 @@ impl InlaySnapshot {
             None => self.len(),
         }
     }
+    #[ztracing::instrument(skip_all)]
     pub fn to_buffer_point(&self, point: InlayPoint) -> Point {
         let (start, _, item) =
             self.transforms
@@ -830,6 +854,7 @@ impl InlaySnapshot {
             None => self.buffer.max_point(),
         }
     }
+    #[ztracing::instrument(skip_all)]
     pub fn to_buffer_offset(&self, offset: InlayOffset) -> MultiBufferOffset {
         let (start, _, item) = self
             .transforms
@@ -844,6 +869,7 @@ impl InlaySnapshot {
         }
     }
 
+    #[ztracing::instrument(skip_all)]
     pub fn to_inlay_offset(&self, offset: MultiBufferOffset) -> InlayOffset {
         let mut cursor = self
             .transforms
@@ -880,10 +906,12 @@ impl InlaySnapshot {
         }
     }
 
+    #[ztracing::instrument(skip_all)]
     pub fn to_inlay_point(&self, point: Point) -> InlayPoint {
         self.inlay_point_cursor().map(point)
     }
 
+    #[ztracing::instrument(skip_all)]
     pub fn inlay_point_cursor(&self) -> InlayPointCursor<'_> {
         let cursor = self.transforms.cursor::<Dimensions<Point, InlayPoint>>(());
         InlayPointCursor {
@@ -892,6 +920,7 @@ impl InlaySnapshot {
         }
     }
 
+    #[ztracing::instrument(skip_all)]
     pub fn clip_point(&self, mut point: InlayPoint, mut bias: Bias) -> InlayPoint {
         let mut cursor = self.transforms.cursor::<Dimensions<InlayPoint, Point>>(());
         cursor.seek(&point, Bias::Left);
@@ -983,10 +1012,12 @@ impl InlaySnapshot {
         }
     }
 
+    #[ztracing::instrument(skip_all)]
     pub fn text_summary(&self) -> MBTextSummary {
         self.transforms.summary().output
     }
 
+    #[ztracing::instrument(skip_all)]
     pub fn text_summary_for_range(&self, range: Range<InlayOffset>) -> MBTextSummary {
         let mut summary = MBTextSummary::default();
 
@@ -1044,6 +1075,7 @@ impl InlaySnapshot {
         summary
     }
 
+    #[ztracing::instrument(skip_all)]
     pub fn row_infos(&self, row: u32) -> InlayBufferRows<'_> {
         let mut cursor = self.transforms.cursor::<Dimensions<InlayPoint, Point>>(());
         let inlay_point = InlayPoint::new(row, 0);
@@ -1071,6 +1103,7 @@ impl InlaySnapshot {
         }
     }
 
+    #[ztracing::instrument(skip_all)]
     pub fn line_len(&self, row: u32) -> u32 {
         let line_start = self.to_offset(InlayPoint::new(row, 0)).0;
         let line_end = if row >= self.max_point().row() {
@@ -1081,6 +1114,7 @@ impl InlaySnapshot {
         (line_end - line_start) as u32
     }
 
+    #[ztracing::instrument(skip_all)]
     pub(crate) fn chunks<'a>(
         &'a self,
         range: Range<InlayOffset>,
@@ -1115,12 +1149,14 @@ impl InlaySnapshot {
     }
 
     #[cfg(test)]
+    #[ztracing::instrument(skip_all)]
     pub fn text(&self) -> String {
         self.chunks(Default::default()..self.len(), false, Highlights::default())
             .map(|chunk| chunk.chunk.text)
             .collect()
     }
 
+    #[ztracing::instrument(skip_all)]
     fn check_invariants(&self) {
         #[cfg(any(debug_assertions, feature = "test-support"))]
         {
@@ -1147,6 +1183,7 @@ pub struct InlayPointCursor<'transforms> {
 }
 
 impl InlayPointCursor<'_> {
+    #[ztracing::instrument(skip_all)]
     pub fn map(&mut self, point: Point) -> InlayPoint {
         let cursor = &mut self.cursor;
         if cursor.did_seek() {

crates/editor/src/display_map/invisibles.rs 🔗

@@ -30,6 +30,7 @@
 // ref: https://gist.github.com/ConradIrwin/f759e1fc29267143c4c7895aa495dca5?h=1
 // ref: https://unicode.org/Public/emoji/13.0/emoji-test.txt
 // https://github.com/bits/UTF-8-Unicode-Test-Documents/blob/master/UTF-8_sequence_separated/utf8_sequence_0-0x10ffff_assigned_including-unprintable-asis.txt
+#[ztracing::instrument(skip_all)]
 pub fn is_invisible(c: char) -> bool {
     if c <= '\u{1f}' {
         c != '\t' && c != '\n' && c != '\r'

crates/editor/src/display_map/tab_map.rs 🔗

@@ -20,6 +20,7 @@ const MAX_TABS: NonZeroU32 = NonZeroU32::new(SPACES.len() as u32).unwrap();
 pub struct TabMap(TabSnapshot);
 
 impl TabMap {
+    #[ztracing::instrument(skip_all)]
     pub fn new(fold_snapshot: FoldSnapshot, tab_size: NonZeroU32) -> (Self, TabSnapshot) {
         let snapshot = TabSnapshot {
             fold_snapshot,
@@ -36,6 +37,7 @@ impl TabMap {
         self.0.clone()
     }
 
+    #[ztracing::instrument(skip_all)]
     pub fn sync(
         &mut self,
         fold_snapshot: FoldSnapshot,
@@ -176,10 +178,12 @@ impl std::ops::Deref for TabSnapshot {
 }
 
 impl TabSnapshot {
+    #[ztracing::instrument(skip_all)]
     pub fn buffer_snapshot(&self) -> &MultiBufferSnapshot {
         &self.fold_snapshot.inlay_snapshot.buffer
     }
 
+    #[ztracing::instrument(skip_all)]
     pub fn line_len(&self, row: u32) -> u32 {
         let max_point = self.max_point();
         if row < max_point.row() {
@@ -191,10 +195,12 @@ impl TabSnapshot {
         }
     }
 
+    #[ztracing::instrument(skip_all)]
     pub fn text_summary(&self) -> TextSummary {
         self.text_summary_for_range(TabPoint::zero()..self.max_point())
     }
 
+    #[ztracing::instrument(skip_all, fields(rows))]
     pub fn text_summary_for_range(&self, range: Range<TabPoint>) -> TextSummary {
         let input_start = self.tab_point_to_fold_point(range.start, Bias::Left).0;
         let input_end = self.tab_point_to_fold_point(range.end, Bias::Right).0;
@@ -234,6 +240,7 @@ impl TabSnapshot {
         }
     }
 
+    #[ztracing::instrument(skip_all)]
     pub(crate) fn chunks<'a>(
         &'a self,
         range: Range<TabPoint>,
@@ -276,11 +283,13 @@ impl TabSnapshot {
         }
     }
 
+    #[ztracing::instrument(skip_all)]
     pub fn rows(&self, row: u32) -> fold_map::FoldRows<'_> {
         self.fold_snapshot.row_infos(row)
     }
 
     #[cfg(test)]
+    #[ztracing::instrument(skip_all)]
     pub fn text(&self) -> String {
         self.chunks(
             TabPoint::zero()..self.max_point(),
@@ -291,10 +300,12 @@ impl TabSnapshot {
         .collect()
     }
 
+    #[ztracing::instrument(skip_all)]
     pub fn max_point(&self) -> TabPoint {
         self.fold_point_to_tab_point(self.fold_snapshot.max_point())
     }
 
+    #[ztracing::instrument(skip_all)]
     pub fn clip_point(&self, point: TabPoint, bias: Bias) -> TabPoint {
         self.fold_point_to_tab_point(
             self.fold_snapshot
@@ -302,6 +313,7 @@ impl TabSnapshot {
         )
     }
 
+    #[ztracing::instrument(skip_all)]
     pub fn fold_point_to_tab_point(&self, input: FoldPoint) -> TabPoint {
         let chunks = self.fold_snapshot.chunks_at(FoldPoint::new(input.row(), 0));
         let tab_cursor = TabStopCursor::new(chunks);
@@ -309,10 +321,12 @@ impl TabSnapshot {
         TabPoint::new(input.row(), expanded)
     }
 
+    #[ztracing::instrument(skip_all)]
     pub fn tab_point_cursor(&self) -> TabPointCursor<'_> {
         TabPointCursor { this: self }
     }
 
+    #[ztracing::instrument(skip_all)]
     pub fn tab_point_to_fold_point(&self, output: TabPoint, bias: Bias) -> (FoldPoint, u32, u32) {
         let chunks = self
             .fold_snapshot
@@ -330,12 +344,14 @@ impl TabSnapshot {
         )
     }
 
+    #[ztracing::instrument(skip_all)]
     pub fn point_to_tab_point(&self, point: Point, bias: Bias) -> TabPoint {
         let inlay_point = self.fold_snapshot.inlay_snapshot.to_inlay_point(point);
         let fold_point = self.fold_snapshot.to_fold_point(inlay_point, bias);
         self.fold_point_to_tab_point(fold_point)
     }
 
+    #[ztracing::instrument(skip_all)]
     pub fn tab_point_to_point(&self, point: TabPoint, bias: Bias) -> Point {
         let fold_point = self.tab_point_to_fold_point(point, bias).0;
         let inlay_point = fold_point.to_inlay_point(&self.fold_snapshot);
@@ -344,6 +360,7 @@ impl TabSnapshot {
             .to_buffer_point(inlay_point)
     }
 
+    #[ztracing::instrument(skip_all)]
     fn expand_tabs<'a, I>(&self, mut cursor: TabStopCursor<'a, I>, column: u32) -> u32
     where
         I: Iterator<Item = Chunk<'a>>,
@@ -377,6 +394,7 @@ impl TabSnapshot {
         expanded_bytes + column.saturating_sub(collapsed_bytes)
     }
 
+    #[ztracing::instrument(skip_all)]
     fn collapse_tabs<'a, I>(
         &self,
         mut cursor: TabStopCursor<'a, I>,
@@ -442,6 +460,7 @@ pub struct TabPointCursor<'this> {
 }
 
 impl TabPointCursor<'_> {
+    #[ztracing::instrument(skip_all)]
     pub fn map(&mut self, point: FoldPoint) -> TabPoint {
         self.this.fold_point_to_tab_point(point)
     }
@@ -486,6 +505,7 @@ pub struct TextSummary {
 }
 
 impl<'a> From<&'a str> for TextSummary {
+    #[ztracing::instrument(skip_all)]
     fn from(text: &'a str) -> Self {
         let sum = text::TextSummary::from(text);
 
@@ -500,6 +520,7 @@ impl<'a> From<&'a str> for TextSummary {
 }
 
 impl<'a> std::ops::AddAssign<&'a Self> for TextSummary {
+    #[ztracing::instrument(skip_all)]
     fn add_assign(&mut self, other: &'a Self) {
         let joined_chars = self.last_line_chars + other.first_line_chars;
         if joined_chars > self.longest_row_chars {
@@ -541,6 +562,7 @@ pub struct TabChunks<'a> {
 }
 
 impl TabChunks<'_> {
+    #[ztracing::instrument(skip_all)]
     pub(crate) fn seek(&mut self, range: Range<TabPoint>) {
         let (input_start, expanded_char_column, to_next_stop) = self
             .snapshot
@@ -576,6 +598,7 @@ impl TabChunks<'_> {
 impl<'a> Iterator for TabChunks<'a> {
     type Item = Chunk<'a>;
 
+    #[ztracing::instrument(skip_all)]
     fn next(&mut self) -> Option<Self::Item> {
         if self.chunk.text.is_empty() {
             if let Some(chunk) = self.fold_chunks.next() {
@@ -1452,6 +1475,7 @@ impl<'a, I> TabStopCursor<'a, I>
 where
     I: Iterator<Item = Chunk<'a>>,
 {
+    #[ztracing::instrument(skip_all)]
     fn new(chunks: impl IntoIterator<Item = Chunk<'a>, IntoIter = I>) -> Self {
         Self {
             chunks: chunks.into_iter(),
@@ -1461,6 +1485,7 @@ where
         }
     }
 
+    #[ztracing::instrument(skip_all)]
     fn bytes_until_next_char(&self) -> Option<usize> {
         self.current_chunk.as_ref().and_then(|(chunk, idx)| {
             let mut idx = *idx;
@@ -1482,6 +1507,7 @@ where
         })
     }
 
+    #[ztracing::instrument(skip_all)]
     fn is_char_boundary(&self) -> bool {
         self.current_chunk
             .as_ref()
@@ -1489,6 +1515,7 @@ where
     }
 
     /// distance: length to move forward while searching for the next tab stop
+    #[ztracing::instrument(skip_all)]
     fn seek(&mut self, distance: u32) -> Option<TabStop> {
         if distance == 0 {
             return None;

crates/editor/src/display_map/wrap_map.rs 🔗

@@ -86,6 +86,7 @@ pub struct WrapRows<'a> {
 }
 
 impl WrapRows<'_> {
+    #[ztracing::instrument(skip_all)]
     pub(crate) fn seek(&mut self, start_row: WrapRow) {
         self.transforms
             .seek(&WrapPoint::new(start_row, 0), Bias::Left);
@@ -101,6 +102,7 @@ impl WrapRows<'_> {
 }
 
 impl WrapMap {
+    #[ztracing::instrument(skip_all)]
     pub fn new(
         tab_snapshot: TabSnapshot,
         font: Font,
@@ -131,6 +133,7 @@ impl WrapMap {
         self.background_task.is_some()
     }
 
+    #[ztracing::instrument(skip_all)]
     pub fn sync(
         &mut self,
         tab_snapshot: TabSnapshot,
@@ -150,6 +153,7 @@ impl WrapMap {
         (self.snapshot.clone(), mem::take(&mut self.edits_since_sync))
     }
 
+    #[ztracing::instrument(skip_all)]
     pub fn set_font_with_size(
         &mut self,
         font: Font,
@@ -167,6 +171,7 @@ impl WrapMap {
         }
     }
 
+    #[ztracing::instrument(skip_all)]
     pub fn set_wrap_width(&mut self, wrap_width: Option<Pixels>, cx: &mut Context<Self>) -> bool {
         if wrap_width == self.wrap_width {
             return false;
@@ -177,6 +182,7 @@ impl WrapMap {
         true
     }
 
+    #[ztracing::instrument(skip_all)]
     fn rewrap(&mut self, cx: &mut Context<Self>) {
         self.background_task.take();
         self.interpolated_edits.clear();
@@ -248,6 +254,7 @@ impl WrapMap {
         }
     }
 
+    #[ztracing::instrument(skip_all)]
     fn flush_edits(&mut self, cx: &mut Context<Self>) {
         if !self.snapshot.interpolated {
             let mut to_remove_len = 0;
@@ -330,6 +337,7 @@ impl WrapMap {
 }
 
 impl WrapSnapshot {
+    #[ztracing::instrument(skip_all)]
     fn new(tab_snapshot: TabSnapshot) -> Self {
         let mut transforms = SumTree::default();
         let extent = tab_snapshot.text_summary();
@@ -343,10 +351,12 @@ impl WrapSnapshot {
         }
     }
 
+    #[ztracing::instrument(skip_all)]
     pub fn buffer_snapshot(&self) -> &MultiBufferSnapshot {
         self.tab_snapshot.buffer_snapshot()
     }
 
+    #[ztracing::instrument(skip_all)]
     fn interpolate(&mut self, new_tab_snapshot: TabSnapshot, tab_edits: &[TabEdit]) -> WrapPatch {
         let mut new_transforms;
         if tab_edits.is_empty() {
@@ -411,6 +421,7 @@ impl WrapSnapshot {
         old_snapshot.compute_edits(tab_edits, self)
     }
 
+    #[ztracing::instrument(skip_all)]
     async fn update(
         &mut self,
         new_tab_snapshot: TabSnapshot,
@@ -570,6 +581,7 @@ impl WrapSnapshot {
         old_snapshot.compute_edits(tab_edits, self)
     }
 
+    #[ztracing::instrument(skip_all)]
     fn compute_edits(&self, tab_edits: &[TabEdit], new_snapshot: &WrapSnapshot) -> WrapPatch {
         let mut wrap_edits = Vec::with_capacity(tab_edits.len());
         let mut old_cursor = self.transforms.cursor::<TransformSummary>(());
@@ -606,6 +618,7 @@ impl WrapSnapshot {
         Patch::new(wrap_edits)
     }
 
+    #[ztracing::instrument(skip_all)]
     pub(crate) fn chunks<'a>(
         &'a self,
         rows: Range<WrapRow>,
@@ -640,10 +653,12 @@ impl WrapSnapshot {
         }
     }
 
+    #[ztracing::instrument(skip_all)]
     pub fn max_point(&self) -> WrapPoint {
         WrapPoint(self.transforms.summary().output.lines)
     }
 
+    #[ztracing::instrument(skip_all)]
     pub fn line_len(&self, row: WrapRow) -> u32 {
         let (start, _, item) = self.transforms.find::<Dimensions<WrapPoint, TabPoint>, _>(
             (),
@@ -664,6 +679,7 @@ impl WrapSnapshot {
         }
     }
 
+    #[ztracing::instrument(skip_all, fields(rows))]
     pub fn text_summary_for_range(&self, rows: Range<WrapRow>) -> TextSummary {
         let mut summary = TextSummary::default();
 
@@ -725,6 +741,7 @@ impl WrapSnapshot {
         summary
     }
 
+    #[ztracing::instrument(skip_all)]
     pub fn soft_wrap_indent(&self, row: WrapRow) -> Option<u32> {
         let (.., item) = self.transforms.find::<WrapPoint, _>(
             (),
@@ -740,10 +757,12 @@ impl WrapSnapshot {
         })
     }
 
+    #[ztracing::instrument(skip_all)]
     pub fn longest_row(&self) -> u32 {
         self.transforms.summary().output.longest_row
     }
 
+    #[ztracing::instrument(skip_all)]
     pub fn row_infos(&self, start_row: WrapRow) -> WrapRows<'_> {
         let mut transforms = self
             .transforms
@@ -766,6 +785,7 @@ impl WrapSnapshot {
         }
     }
 
+    #[ztracing::instrument(skip_all)]
     pub fn to_tab_point(&self, point: WrapPoint) -> TabPoint {
         let (start, _, item) =
             self.transforms
@@ -777,15 +797,18 @@ impl WrapSnapshot {
         TabPoint(tab_point)
     }
 
+    #[ztracing::instrument(skip_all)]
     pub fn to_point(&self, point: WrapPoint, bias: Bias) -> Point {
         self.tab_snapshot
             .tab_point_to_point(self.to_tab_point(point), bias)
     }
 
+    #[ztracing::instrument(skip_all)]
     pub fn make_wrap_point(&self, point: Point, bias: Bias) -> WrapPoint {
         self.tab_point_to_wrap_point(self.tab_snapshot.point_to_tab_point(point, bias))
     }
 
+    #[ztracing::instrument(skip_all)]
     pub fn tab_point_to_wrap_point(&self, point: TabPoint) -> WrapPoint {
         let (start, ..) =
             self.transforms
@@ -793,6 +816,7 @@ impl WrapSnapshot {
         WrapPoint(start.1.0 + (point.0 - start.0.0))
     }
 
+    #[ztracing::instrument(skip_all)]
     pub fn wrap_point_cursor(&self) -> WrapPointCursor<'_> {
         WrapPointCursor {
             cursor: self
@@ -801,6 +825,7 @@ impl WrapSnapshot {
         }
     }
 
+    #[ztracing::instrument(skip_all)]
     pub fn clip_point(&self, mut point: WrapPoint, bias: Bias) -> WrapPoint {
         if bias == Bias::Left {
             let (start, _, item) = self
@@ -815,32 +840,65 @@ impl WrapSnapshot {
         self.tab_point_to_wrap_point(self.tab_snapshot.clip_point(self.to_tab_point(point), bias))
     }
 
-    pub fn prev_row_boundary(&self, mut point: WrapPoint) -> WrapRow {
+    /// Try to find a TabRow start that is also a WrapRow start
+    /// Every TabRow start is a WrapRow start
+    #[ztracing::instrument(skip_all, fields(point=?point))]
+    pub fn prev_row_boundary(&self, point: WrapPoint) -> WrapRow {
         if self.transforms.is_empty() {
             return WrapRow(0);
         }
 
-        *point.column_mut() = 0;
+        let point = WrapPoint::new(point.row(), 0);
 
         let mut cursor = self
             .transforms
             .cursor::<Dimensions<WrapPoint, TabPoint>>(());
+
         cursor.seek(&point, Bias::Right);
         if cursor.item().is_none() {
             cursor.prev();
         }
 
+        //                          real newline     fake          fake
+        // text:      helloworldasldlfjasd\njdlasfalsk\naskdjfasdkfj\n
+        // dimensions v       v           v            v            v
+        // transforms |-------|-----NW----|-----W------|-----W------|
+        // cursor    ^        ^^^^^^^^^^^^^                          ^
+        //                               (^)           ^^^^^^^^^^^^^^
+        // point:                                            ^
+        // point(col_zero):                           (^)
+
         while let Some(transform) = cursor.item() {
-            if transform.is_isomorphic() && cursor.start().1.column() == 0 {
-                return cmp::min(cursor.end().0.row(), point.row());
-            } else {
-                cursor.prev();
+            if transform.is_isomorphic() {
+                // this transform only has real linefeeds
+                let tab_summary = &transform.summary.input;
+                // is the wrap just before the end of the transform a tab row?
+                // thats only if this transform has at least one newline
+                //
+                // "this wrap row is a tab row" <=> self.to_tab_point(WrapPoint::new(wrap_row, 0)).column() == 0
+
+                // Note on comparison:
+                // We have code that relies on this to be row > 1
+                // It should work with row >= 1 but it does not :(
+                //
+                // That means that if every line is wrapped we walk back all the
+                // way to the start. Which invalidates the entire state triggering
+                // a full re-render.
+                if tab_summary.lines.row > 1 {
+                    let wrap_point_at_end = cursor.end().0.row();
+                    return cmp::min(wrap_point_at_end - RowDelta(1), point.row());
+                } else if cursor.start().1.column() == 0 {
+                    return cmp::min(cursor.end().0.row(), point.row());
+                }
             }
+
+            cursor.prev();
         }
 
-        unreachable!()
+        WrapRow(0)
     }
 
+    #[ztracing::instrument(skip_all)]
     pub fn next_row_boundary(&self, mut point: WrapPoint) -> Option<WrapRow> {
         point.0 += Point::new(1, 0);
 
@@ -874,6 +932,7 @@ impl WrapSnapshot {
         .map(|h| h.text)
     }
 
+    #[ztracing::instrument(skip_all)]
     fn check_invariants(&self) {
         #[cfg(test)]
         {
@@ -927,6 +986,7 @@ pub struct WrapPointCursor<'transforms> {
 }
 
 impl WrapPointCursor<'_> {
+    #[ztracing::instrument(skip_all)]
     pub fn map(&mut self, point: TabPoint) -> WrapPoint {
         let cursor = &mut self.cursor;
         if cursor.did_seek() {
@@ -939,6 +999,7 @@ impl WrapPointCursor<'_> {
 }
 
 impl WrapChunks<'_> {
+    #[ztracing::instrument(skip_all)]
     pub(crate) fn seek(&mut self, rows: Range<WrapRow>) {
         let output_start = WrapPoint::new(rows.start, 0);
         let output_end = WrapPoint::new(rows.end, 0);
@@ -961,6 +1022,7 @@ impl WrapChunks<'_> {
 impl<'a> Iterator for WrapChunks<'a> {
     type Item = Chunk<'a>;
 
+    #[ztracing::instrument(skip_all)]
     fn next(&mut self) -> Option<Self::Item> {
         if self.output_position.row() >= self.max_output_row {
             return None;
@@ -1033,6 +1095,7 @@ impl<'a> Iterator for WrapChunks<'a> {
 impl Iterator for WrapRows<'_> {
     type Item = RowInfo;
 
+    #[ztracing::instrument(skip_all)]
     fn next(&mut self) -> Option<Self::Item> {
         if self.output_row > self.max_output_row {
             return None;
@@ -1068,6 +1131,7 @@ impl Iterator for WrapRows<'_> {
 }
 
 impl Transform {
+    #[ztracing::instrument(skip_all)]
     fn isomorphic(summary: TextSummary) -> Self {
         #[cfg(test)]
         assert!(!summary.lines.is_zero());
@@ -1081,6 +1145,7 @@ impl Transform {
         }
     }
 
+    #[ztracing::instrument(skip_all)]
     fn wrap(indent: u32) -> Self {
         static WRAP_TEXT: LazyLock<String> = LazyLock::new(|| {
             let mut wrap_text = String::new();
@@ -1133,6 +1198,7 @@ trait SumTreeExt {
 }
 
 impl SumTreeExt for SumTree<Transform> {
+    #[ztracing::instrument(skip_all)]
     fn push_or_extend(&mut self, transform: Transform) {
         let mut transform = Some(transform);
         self.update_last(
@@ -1196,6 +1262,7 @@ impl<'a> sum_tree::Dimension<'a, TransformSummary> for TabPoint {
 }
 
 impl sum_tree::SeekTarget<'_, TransformSummary, TransformSummary> for TabPoint {
+    #[ztracing::instrument(skip_all)]
     fn cmp(&self, cursor_location: &TransformSummary, _: ()) -> std::cmp::Ordering {
         Ord::cmp(&self.0, &cursor_location.input.lines)
     }
@@ -1255,6 +1322,71 @@ mod tests {
     use text::Rope;
     use theme::LoadThemes;
 
+    #[gpui::test]
+    async fn test_prev_row_boundary(cx: &mut gpui::TestAppContext) {
+        init_test(cx);
+
+        fn test_wrap_snapshot(
+            text: &str,
+            soft_wrap_every: usize, // font size multiple
+            cx: &mut gpui::TestAppContext,
+        ) -> WrapSnapshot {
+            let text_system = cx.read(|cx| cx.text_system().clone());
+            let tab_size = 4.try_into().unwrap();
+            let font = test_font();
+            let _font_id = text_system.resolve_font(&font);
+            let font_size = px(14.0);
+            // this is very much an estimate to try and get the wrapping to
+            // occur at `soft_wrap_every` we check that it pans out for every test case
+            let soft_wrapping = Some(font_size * soft_wrap_every * 0.6);
+
+            let buffer = cx.new(|cx| language::Buffer::local(text, cx));
+            let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
+            let buffer_snapshot = buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx));
+            let (_inlay_map, inlay_snapshot) = InlayMap::new(buffer_snapshot);
+            let (_fold_map, fold_snapshot) = FoldMap::new(inlay_snapshot);
+            let (mut tab_map, _) = TabMap::new(fold_snapshot, tab_size);
+            let tabs_snapshot = tab_map.set_max_expansion_column(32);
+            let (_wrap_map, wrap_snapshot) =
+                cx.update(|cx| WrapMap::new(tabs_snapshot, font, font_size, soft_wrapping, cx));
+
+            wrap_snapshot
+        }
+
+        // These two should pass but dont, see the comparison note in
+        // prev_row_boundary about why.
+        //
+        // //                                      0123  4567  wrap_rows
+        // let wrap_snapshot = test_wrap_snapshot("1234\n5678", 1, cx);
+        // assert_eq!(wrap_snapshot.text(), "1\n2\n3\n4\n5\n6\n7\n8");
+        // let row = wrap_snapshot.prev_row_boundary(wrap_snapshot.max_point());
+        // assert_eq!(row.0, 3);
+
+        // //                                      012  345  678  wrap_rows
+        // let wrap_snapshot = test_wrap_snapshot("123\n456\n789", 1, cx);
+        // assert_eq!(wrap_snapshot.text(), "1\n2\n3\n4\n5\n6\n7\n8\n9");
+        // let row = wrap_snapshot.prev_row_boundary(wrap_snapshot.max_point());
+        // assert_eq!(row.0, 5);
+
+        //                                      012345678  wrap_rows
+        let wrap_snapshot = test_wrap_snapshot("123456789", 1, cx);
+        assert_eq!(wrap_snapshot.text(), "1\n2\n3\n4\n5\n6\n7\n8\n9");
+        let row = wrap_snapshot.prev_row_boundary(wrap_snapshot.max_point());
+        assert_eq!(row.0, 0);
+
+        //                                      111  2222    44  wrap_rows
+        let wrap_snapshot = test_wrap_snapshot("123\n4567\n\n89", 4, cx);
+        assert_eq!(wrap_snapshot.text(), "123\n4567\n\n89");
+        let row = wrap_snapshot.prev_row_boundary(wrap_snapshot.max_point());
+        assert_eq!(row.0, 2);
+
+        //                                      11  2223   wrap_rows
+        let wrap_snapshot = test_wrap_snapshot("12\n3456\n\n", 3, cx);
+        assert_eq!(wrap_snapshot.text(), "12\n345\n6\n\n");
+        let row = wrap_snapshot.prev_row_boundary(wrap_snapshot.max_point());
+        assert_eq!(row.0, 3);
+    }
+
     #[gpui::test(iterations = 100)]
     async fn test_random_wraps(cx: &mut gpui::TestAppContext, mut rng: StdRng) {
         // todo this test is flaky

crates/editor/src/edit_prediction_tests.rs 🔗

@@ -1,4 +1,4 @@
-use edit_prediction::EditPredictionProvider;
+use edit_prediction_types::EditPredictionDelegate;
 use gpui::{Entity, KeyBinding, Modifiers, prelude::*};
 use indoc::indoc;
 use multi_buffer::{Anchor, MultiBufferSnapshot, ToPoint};
@@ -15,7 +15,7 @@ async fn test_edit_prediction_insert(cx: &mut gpui::TestAppContext) {
     init_test(cx, |_| {});
 
     let mut cx = EditorTestContext::new(cx).await;
-    let provider = cx.new(|_| FakeEditPredictionProvider::default());
+    let provider = cx.new(|_| FakeEditPredictionDelegate::default());
     assign_editor_completion_provider(provider.clone(), &mut cx);
     cx.set_state("let absolute_zero_celsius = ˇ;");
 
@@ -37,7 +37,7 @@ async fn test_edit_prediction_modification(cx: &mut gpui::TestAppContext) {
     init_test(cx, |_| {});
 
     let mut cx = EditorTestContext::new(cx).await;
-    let provider = cx.new(|_| FakeEditPredictionProvider::default());
+    let provider = cx.new(|_| FakeEditPredictionDelegate::default());
     assign_editor_completion_provider(provider.clone(), &mut cx);
     cx.set_state("let pi = ˇ\"foo\";");
 
@@ -59,7 +59,7 @@ async fn test_edit_prediction_jump_button(cx: &mut gpui::TestAppContext) {
     init_test(cx, |_| {});
 
     let mut cx = EditorTestContext::new(cx).await;
-    let provider = cx.new(|_| FakeEditPredictionProvider::default());
+    let provider = cx.new(|_| FakeEditPredictionDelegate::default());
     assign_editor_completion_provider(provider.clone(), &mut cx);
 
     // Cursor is 2+ lines above the proposed edit
@@ -128,7 +128,7 @@ async fn test_edit_prediction_invalidation_range(cx: &mut gpui::TestAppContext)
     init_test(cx, |_| {});
 
     let mut cx = EditorTestContext::new(cx).await;
-    let provider = cx.new(|_| FakeEditPredictionProvider::default());
+    let provider = cx.new(|_| FakeEditPredictionDelegate::default());
     assign_editor_completion_provider(provider.clone(), &mut cx);
 
     // Cursor is 3+ lines above the proposed edit
@@ -233,7 +233,7 @@ async fn test_edit_prediction_jump_disabled_for_non_zed_providers(cx: &mut gpui:
     init_test(cx, |_| {});
 
     let mut cx = EditorTestContext::new(cx).await;
-    let provider = cx.new(|_| FakeNonZedEditPredictionProvider::default());
+    let provider = cx.new(|_| FakeNonZedEditPredictionDelegate::default());
     assign_editor_completion_provider_non_zed(provider.clone(), &mut cx);
 
     // Cursor is 2+ lines above the proposed edit
@@ -281,7 +281,7 @@ async fn test_edit_prediction_preview_cleanup_on_toggle_off(cx: &mut gpui::TestA
     cx.update(|cx| cx.bind_keys([KeyBinding::new("ctrl-shift-a", AcceptEditPrediction, None)]));
 
     let mut cx = EditorTestContext::new(cx).await;
-    let provider = cx.new(|_| FakeEditPredictionProvider::default());
+    let provider = cx.new(|_| FakeEditPredictionDelegate::default());
     assign_editor_completion_provider(provider.clone(), &mut cx);
     cx.set_state("let x = ˇ;");
 
@@ -371,7 +371,7 @@ fn accept_completion(cx: &mut EditorTestContext) {
 }
 
 fn propose_edits<T: ToOffset>(
-    provider: &Entity<FakeEditPredictionProvider>,
+    provider: &Entity<FakeEditPredictionDelegate>,
     edits: Vec<(Range<T>, &str)>,
     cx: &mut EditorTestContext,
 ) {
@@ -383,7 +383,7 @@ fn propose_edits<T: ToOffset>(
 
     cx.update(|_, cx| {
         provider.update(cx, |provider, _| {
-            provider.set_edit_prediction(Some(edit_prediction::EditPrediction::Local {
+            provider.set_edit_prediction(Some(edit_prediction_types::EditPrediction::Local {
                 id: None,
                 edits: edits.collect(),
                 edit_preview: None,
@@ -393,7 +393,7 @@ fn propose_edits<T: ToOffset>(
 }
 
 fn assign_editor_completion_provider(
-    provider: Entity<FakeEditPredictionProvider>,
+    provider: Entity<FakeEditPredictionDelegate>,
     cx: &mut EditorTestContext,
 ) {
     cx.update_editor(|editor, window, cx| {
@@ -402,7 +402,7 @@ fn assign_editor_completion_provider(
 }
 
 fn propose_edits_non_zed<T: ToOffset>(
-    provider: &Entity<FakeNonZedEditPredictionProvider>,
+    provider: &Entity<FakeNonZedEditPredictionDelegate>,
     edits: Vec<(Range<T>, &str)>,
     cx: &mut EditorTestContext,
 ) {
@@ -414,7 +414,7 @@ fn propose_edits_non_zed<T: ToOffset>(
 
     cx.update(|_, cx| {
         provider.update(cx, |provider, _| {
-            provider.set_edit_prediction(Some(edit_prediction::EditPrediction::Local {
+            provider.set_edit_prediction(Some(edit_prediction_types::EditPrediction::Local {
                 id: None,
                 edits: edits.collect(),
                 edit_preview: None,
@@ -424,7 +424,7 @@ fn propose_edits_non_zed<T: ToOffset>(
 }
 
 fn assign_editor_completion_provider_non_zed(
-    provider: Entity<FakeNonZedEditPredictionProvider>,
+    provider: Entity<FakeNonZedEditPredictionDelegate>,
     cx: &mut EditorTestContext,
 ) {
     cx.update_editor(|editor, window, cx| {
@@ -433,17 +433,20 @@ fn assign_editor_completion_provider_non_zed(
 }
 
 #[derive(Default, Clone)]
-pub struct FakeEditPredictionProvider {
-    pub completion: Option<edit_prediction::EditPrediction>,
+pub struct FakeEditPredictionDelegate {
+    pub completion: Option<edit_prediction_types::EditPrediction>,
 }
 
-impl FakeEditPredictionProvider {
-    pub fn set_edit_prediction(&mut self, completion: Option<edit_prediction::EditPrediction>) {
+impl FakeEditPredictionDelegate {
+    pub fn set_edit_prediction(
+        &mut self,
+        completion: Option<edit_prediction_types::EditPrediction>,
+    ) {
         self.completion = completion;
     }
 }
 
-impl EditPredictionProvider for FakeEditPredictionProvider {
+impl EditPredictionDelegate for FakeEditPredictionDelegate {
     fn name() -> &'static str {
         "fake-completion-provider"
     }
@@ -452,7 +455,7 @@ impl EditPredictionProvider for FakeEditPredictionProvider {
         "Fake Completion Provider"
     }
 
-    fn show_completions_in_menu() -> bool {
+    fn show_predictions_in_menu() -> bool {
         true
     }
 
@@ -482,15 +485,6 @@ impl EditPredictionProvider for FakeEditPredictionProvider {
     ) {
     }
 
-    fn cycle(
-        &mut self,
-        _buffer: gpui::Entity<language::Buffer>,
-        _cursor_position: language::Anchor,
-        _direction: edit_prediction::Direction,
-        _cx: &mut gpui::Context<Self>,
-    ) {
-    }
-
     fn accept(&mut self, _cx: &mut gpui::Context<Self>) {}
 
     fn discard(&mut self, _cx: &mut gpui::Context<Self>) {}
@@ -500,23 +494,26 @@ impl EditPredictionProvider for FakeEditPredictionProvider {
         _buffer: &gpui::Entity<language::Buffer>,
         _cursor_position: language::Anchor,
         _cx: &mut gpui::Context<Self>,
-    ) -> Option<edit_prediction::EditPrediction> {
+    ) -> Option<edit_prediction_types::EditPrediction> {
         self.completion.clone()
     }
 }
 
 #[derive(Default, Clone)]
-pub struct FakeNonZedEditPredictionProvider {
-    pub completion: Option<edit_prediction::EditPrediction>,
+pub struct FakeNonZedEditPredictionDelegate {
+    pub completion: Option<edit_prediction_types::EditPrediction>,
 }
 
-impl FakeNonZedEditPredictionProvider {
-    pub fn set_edit_prediction(&mut self, completion: Option<edit_prediction::EditPrediction>) {
+impl FakeNonZedEditPredictionDelegate {
+    pub fn set_edit_prediction(
+        &mut self,
+        completion: Option<edit_prediction_types::EditPrediction>,
+    ) {
         self.completion = completion;
     }
 }
 
-impl EditPredictionProvider for FakeNonZedEditPredictionProvider {
+impl EditPredictionDelegate for FakeNonZedEditPredictionDelegate {
     fn name() -> &'static str {
         "fake-non-zed-provider"
     }
@@ -525,7 +522,7 @@ impl EditPredictionProvider for FakeNonZedEditPredictionProvider {
         "Fake Non-Zed Provider"
     }
 
-    fn show_completions_in_menu() -> bool {
+    fn show_predictions_in_menu() -> bool {
         false
     }
 
@@ -555,15 +552,6 @@ impl EditPredictionProvider for FakeNonZedEditPredictionProvider {
     ) {
     }
 
-    fn cycle(
-        &mut self,
-        _buffer: gpui::Entity<language::Buffer>,
-        _cursor_position: language::Anchor,
-        _direction: edit_prediction::Direction,
-        _cx: &mut gpui::Context<Self>,
-    ) {
-    }
-
     fn accept(&mut self, _cx: &mut gpui::Context<Self>) {}
 
     fn discard(&mut self, _cx: &mut gpui::Context<Self>) {}
@@ -573,7 +561,7 @@ impl EditPredictionProvider for FakeNonZedEditPredictionProvider {
         _buffer: &gpui::Entity<language::Buffer>,
         _cursor_position: language::Anchor,
         _cx: &mut gpui::Context<Self>,
-    ) -> Option<edit_prediction::EditPrediction> {
+    ) -> Option<edit_prediction_types::EditPrediction> {
         self.completion.clone()
     }
 }

crates/editor/src/editor.rs 🔗

@@ -51,7 +51,7 @@ pub mod test;
 
 pub(crate) use actions::*;
 pub use display_map::{ChunkRenderer, ChunkRendererContext, DisplayPoint, FoldPlaceholder};
-pub use edit_prediction::Direction;
+pub use edit_prediction_types::Direction;
 pub use editor_settings::{
     CurrentLineHighlight, DocumentColorsRenderMode, EditorSettings, HideMouseMode,
     ScrollBeyondLastLine, ScrollbarAxes, SearchSettings, ShowMinimap,
@@ -73,13 +73,9 @@ pub use multi_buffer::{
 pub use split::SplittableEditor;
 pub use text::Bias;
 
-use ::git::{
-    Restore,
-    blame::{BlameEntry, ParsedCommitMessage},
-    status::FileStatus,
-};
+use ::git::{Restore, blame::BlameEntry, commit::ParsedCommitMessage, status::FileStatus};
 use aho_corasick::{AhoCorasick, AhoCorasickBuilder, BuildError};
-use anyhow::{Context as _, Result, anyhow};
+use anyhow::{Context as _, Result, anyhow, bail};
 use blink_manager::BlinkManager;
 use buffer_diff::DiffHunkStatus;
 use client::{Collaborator, ParticipantIndex, parse_zed_link};
@@ -92,7 +88,9 @@ use collections::{BTreeMap, HashMap, HashSet, VecDeque};
 use convert_case::{Case, Casing};
 use dap::TelemetrySpawnLocation;
 use display_map::*;
-use edit_prediction::{EditPredictionProvider, EditPredictionProviderHandle};
+use edit_prediction_types::{
+    EditPredictionDelegate, EditPredictionDelegateHandle, EditPredictionGranularity,
+};
 use editor_settings::{GoToDefinitionFallback, Minimap as MinimapSettings};
 use element::{AcceptEditPredictionBinding, LineWithInvisibles, PositionMap, layout_line};
 use futures::{
@@ -107,10 +105,11 @@ use gpui::{
     AvailableSpace, Background, Bounds, ClickEvent, ClipboardEntry, ClipboardItem, Context,
     DispatchPhase, Edges, Entity, EntityInputHandler, EventEmitter, FocusHandle, FocusOutEvent,
     Focusable, FontId, FontWeight, Global, HighlightStyle, Hsla, KeyContext, Modifiers,
-    MouseButton, MouseDownEvent, MouseMoveEvent, PaintQuad, ParentElement, Pixels, Render,
-    ScrollHandle, SharedString, Size, Stateful, Styled, Subscription, Task, TextStyle,
-    TextStyleRefinement, UTF16Selection, UnderlineStyle, UniformListScrollHandle, WeakEntity,
-    WeakFocusHandle, Window, div, point, prelude::*, pulsating_between, px, relative, size,
+    MouseButton, MouseDownEvent, MouseMoveEvent, PaintQuad, ParentElement, Pixels, PressureStage,
+    Render, ScrollHandle, SharedString, Size, Stateful, Styled, Subscription, Task, TextRun,
+    TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle, UniformListScrollHandle,
+    WeakEntity, WeakFocusHandle, Window, div, point, prelude::*, pulsating_between, px, relative,
+    size,
 };
 use hover_links::{HoverLink, HoveredLinkState, find_file};
 use hover_popover::{HoverState, hide_hover};
@@ -121,8 +120,9 @@ use language::{
     AutoindentMode, BlockCommentConfig, BracketMatch, BracketPair, Buffer, BufferRow,
     BufferSnapshot, Capability, CharClassifier, CharKind, CharScopeContext, CodeLabel, CursorShape,
     DiagnosticEntryRef, DiffOptions, EditPredictionsMode, EditPreview, HighlightedText, IndentKind,
-    IndentSize, Language, LanguageName, LanguageRegistry, OffsetRangeExt, OutlineItem, Point,
-    Runnable, Selection, SelectionGoal, TextObject, TransactionId, TreeSitterOptions, WordsQuery,
+    IndentSize, Language, LanguageName, LanguageRegistry, LanguageScope, OffsetRangeExt,
+    OutlineItem, Point, Runnable, Selection, SelectionGoal, TextObject, TransactionId,
+    TreeSitterOptions, WordsQuery,
     language_settings::{
         self, LanguageSettings, LspInsertMode, RewrapBehavior, WordsCompletionMode,
         all_language_settings, language_settings,
@@ -163,6 +163,7 @@ use project::{
     project_settings::{DiagnosticSeverity, GoToDiagnosticSeverityFilter, ProjectSettings},
 };
 use rand::seq::SliceRandom;
+use regex::Regex;
 use rpc::{ErrorCode, ErrorExt, proto::PeerId};
 use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager};
 use selections_collection::{MutableSelectionsCollection, SelectionsCollection};
@@ -182,7 +183,7 @@ use std::{
     iter::{self, Peekable},
     mem,
     num::NonZeroU32,
-    ops::{Deref, DerefMut, Not, Range, RangeInclusive},
+    ops::{ControlFlow, Deref, DerefMut, Not, Range, RangeInclusive},
     path::{Path, PathBuf},
     rc::Rc,
     sync::Arc,
@@ -191,7 +192,7 @@ use std::{
 use task::{ResolvedTask, RunnableTag, TaskTemplate, TaskVariables};
 use text::{BufferId, FromAnchor, OffsetUtf16, Rope, ToOffset as _};
 use theme::{
-    ActiveTheme, PlayerColor, StatusColors, SyntaxTheme, Theme, ThemeSettings,
+    AccentColors, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme, Theme, ThemeSettings,
     observe_buffer_font_size_adjustment,
 };
 use ui::{
@@ -351,8 +352,8 @@ pub fn init(cx: &mut App) {
             )
             .detach();
         }
-    });
-    cx.on_action(move |_: &workspace::NewWindow, cx| {
+    })
+    .on_action(move |_: &workspace::NewWindow, cx| {
         let app_state = workspace::AppState::global(cx);
         if let Some(app_state) = app_state.upgrade() {
             workspace::open_new(
@@ -575,7 +576,7 @@ impl Default for EditorStyle {
     }
 }
 
-pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
+pub fn make_inlay_hints_style(cx: &App) -> HighlightStyle {
     let show_background = language_settings::language_settings(None, None, cx)
         .inlay_hints
         .show_background;
@@ -598,7 +599,7 @@ pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
     style
 }
 
-pub fn make_suggestion_styles(cx: &mut App) -> EditPredictionStyles {
+pub fn make_suggestion_styles(cx: &App) -> EditPredictionStyles {
     EditPredictionStyles {
         insertion: HighlightStyle {
             color: Some(cx.theme().status().predictive),
@@ -726,7 +727,10 @@ impl EditorActionId {
 // type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
 // type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
 
-type BackgroundHighlight = (fn(&Theme) -> Hsla, Arc<[Range<Anchor>]>);
+type BackgroundHighlight = (
+    Arc<dyn Fn(&usize, &Theme) -> Hsla + Send + Sync>,
+    Arc<[Range<Anchor>]>,
+);
 type GutterHighlight = (fn(&App) -> Hsla, Vec<Range<Anchor>>);
 
 #[derive(Default)]
@@ -1076,6 +1080,7 @@ pub struct Editor {
     show_breakpoints: Option<bool>,
     show_wrap_guides: Option<bool>,
     show_indent_guides: Option<bool>,
+    buffers_with_disabled_indent_guides: HashSet<BufferId>,
     highlight_order: usize,
     highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
     background_highlights: HashMap<HighlightKey, BackgroundHighlight>,
@@ -1103,6 +1108,9 @@ pub struct Editor {
     pending_rename: Option<RenameState>,
     searchable: bool,
     cursor_shape: CursorShape,
+    /// Whether the cursor is offset one character to the left when something is
+    /// selected (needed for vim visual mode)
+    cursor_offset_on_selection: bool,
     current_line_highlight: Option<CurrentLineHighlight>,
     pub collapse_matches: bool,
     autoindent_mode: Option<AutoindentMode>,
@@ -1114,9 +1122,10 @@ pub struct Editor {
     remote_id: Option<ViewId>,
     pub hover_state: HoverState,
     pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
+    prev_pressure_stage: Option<PressureStage>,
     gutter_hovered: bool,
     hovered_link_state: Option<HoveredLinkState>,
-    edit_prediction_provider: Option<RegisteredEditPredictionProvider>,
+    edit_prediction_provider: Option<RegisteredEditPredictionDelegate>,
     code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
     active_edit_prediction: Option<EditPredictionState>,
     /// Used to prevent flickering as the user types while the menu is open
@@ -1124,6 +1133,7 @@ pub struct Editor {
     edit_prediction_settings: EditPredictionSettings,
     edit_predictions_hidden_for_vim_mode: bool,
     show_edit_predictions_override: Option<bool>,
+    show_completions_on_input_override: Option<bool>,
     menu_edit_predictions_policy: MenuEditPredictionsPolicy,
     edit_prediction_preview: EditPredictionPreview,
     edit_prediction_indent_conflict: bool,
@@ -1172,6 +1182,7 @@ pub struct Editor {
     gutter_breakpoint_indicator: (Option<PhantomBreakpointIndicator>, Option<Task<()>>),
     hovered_diff_hunk_row: Option<DisplayRow>,
     pull_diagnostics_task: Task<()>,
+    pull_diagnostics_background_task: Task<()>,
     in_project_search: bool,
     previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
     breadcrumb_header: Option<String>,
@@ -1203,10 +1214,16 @@ pub struct Editor {
     select_next_is_case_sensitive: Option<bool>,
     pub lookup_key: Option<Box<dyn Any + Send + Sync>>,
     applicable_language_settings: HashMap<Option<LanguageName>, LanguageSettings>,
-    accent_overrides: Vec<SharedString>,
+    accent_data: Option<AccentData>,
     fetched_tree_sitter_chunks: HashMap<ExcerptId, HashSet<Range<BufferRow>>>,
 }
 
+#[derive(Debug, PartialEq)]
+struct AccentData {
+    colors: AccentColors,
+    overrides: Vec<SharedString>,
+}
+
 fn debounce_value(debounce_ms: u64) -> Option<Duration> {
     if debounce_ms > 0 {
         Some(Duration::from_millis(debounce_ms))
@@ -1237,6 +1254,7 @@ impl NextScrollCursorCenterTopBottom {
 pub struct EditorSnapshot {
     pub mode: EditorMode,
     show_gutter: bool,
+    offset_content: bool,
     show_line_numbers: Option<bool>,
     number_deleted_lines: bool,
     show_git_diff_gutter: Option<bool>,
@@ -1552,8 +1570,8 @@ pub struct RenameState {
 
 struct InvalidationStack<T>(Vec<T>);
 
-struct RegisteredEditPredictionProvider {
-    provider: Arc<dyn EditPredictionProviderHandle>,
+struct RegisteredEditPredictionDelegate {
+    provider: Arc<dyn EditPredictionDelegateHandle>,
     _subscription: Subscription,
 }
 
@@ -1581,6 +1599,45 @@ pub struct ClipboardSelection {
     pub is_entire_line: bool,
     /// The indentation of the first line when this content was originally copied.
     pub first_line_indent: u32,
+    #[serde(default)]
+    pub file_path: Option<PathBuf>,
+    #[serde(default)]
+    pub line_range: Option<RangeInclusive<u32>>,
+}
+
+impl ClipboardSelection {
+    pub fn for_buffer(
+        len: usize,
+        is_entire_line: bool,
+        range: Range<Point>,
+        buffer: &MultiBufferSnapshot,
+        project: Option<&Entity<Project>>,
+        cx: &App,
+    ) -> Self {
+        let first_line_indent = buffer
+            .indent_size_for_line(MultiBufferRow(range.start.row))
+            .len;
+
+        let file_path = util::maybe!({
+            let project = project?.read(cx);
+            let file = buffer.file_at(range.start)?;
+            let project_path = ProjectPath {
+                worktree_id: file.worktree_id(cx),
+                path: file.path().clone(),
+            };
+            project.absolute_path(&project_path, cx)
+        });
+
+        let line_range = file_path.as_ref().map(|_| range.start.row..=range.end.row);
+
+        Self {
+            len,
+            is_entire_line,
+            first_line_indent,
+            file_path,
+            line_range,
+        }
+    }
 }
 
 // selections, scroll behavior, was newest selection reversed
@@ -1775,7 +1832,11 @@ impl Editor {
         Editor::new_internal(mode, buffer, project, None, window, cx)
     }
 
-    pub fn sticky_headers(&self, cx: &App) -> Option<Vec<OutlineItem<Anchor>>> {
+    pub fn sticky_headers(
+        &self,
+        style: &EditorStyle,
+        cx: &App,
+    ) -> Option<Vec<OutlineItem<Anchor>>> {
         let multi_buffer = self.buffer().read(cx);
         let multi_buffer_snapshot = multi_buffer.snapshot(cx);
         let multi_buffer_visible_start = self
@@ -1793,7 +1854,7 @@ impl Editor {
                 .outline_items_containing(
                     Point::new(start_row, 0)..Point::new(end_row, 0),
                     true,
-                    self.style().map(|style| style.syntax.as_ref()),
+                    Some(style.syntax.as_ref()),
                 )
                 .into_iter()
                 .map(|outline_item| OutlineItem {
@@ -2001,46 +2062,34 @@ impl Editor {
                                         })
                                     });
                             });
-                            let edited_buffers_already_open = {
-                                let other_editors: Vec<Entity<Editor>> = workspace
-                                    .read(cx)
-                                    .panes()
-                                    .iter()
-                                    .flat_map(|pane| pane.read(cx).items_of_type::<Editor>())
-                                    .filter(|editor| editor.entity_id() != cx.entity_id())
-                                    .collect();
-
-                                transaction.0.keys().all(|buffer| {
-                                    other_editors.iter().any(|editor| {
-                                        let multi_buffer = editor.read(cx).buffer();
-                                        multi_buffer.read(cx).is_singleton()
-                                            && multi_buffer.read(cx).as_singleton().map_or(
-                                                false,
-                                                |singleton| {
-                                                    singleton.entity_id() == buffer.entity_id()
-                                                },
-                                            )
-                                    })
-                                })
-                            };
-                            if !edited_buffers_already_open {
-                                let workspace = workspace.downgrade();
-                                let transaction = transaction.clone();
-                                cx.defer_in(window, move |_, window, cx| {
-                                    cx.spawn_in(window, async move |editor, cx| {
-                                        Self::open_project_transaction(
-                                            &editor,
-                                            workspace,
-                                            transaction,
-                                            "Rename".to_string(),
-                                            cx,
-                                        )
-                                        .await
-                                        .ok()
-                                    })
-                                    .detach();
-                                });
-                            }
+
+                            Self::open_transaction_for_hidden_buffers(
+                                workspace,
+                                transaction.clone(),
+                                "Rename".to_string(),
+                                window,
+                                cx,
+                            );
+                        }
+                    }
+
+                    project::Event::WorkspaceEditApplied(transaction) => {
+                        let Some(workspace) = editor.workspace() else {
+                            return;
+                        };
+                        let Some(active_editor) = workspace.read(cx).active_item_as::<Self>(cx)
+                        else {
+                            return;
+                        };
+
+                        if active_editor.entity_id() == cx.entity_id() {
+                            Self::open_transaction_for_hidden_buffers(
+                                workspace,
+                                transaction.clone(),
+                                "LSP Edit".to_string(),
+                                window,
+                                cx,
+                            );
                         }
                     }
 
@@ -2195,6 +2244,7 @@ impl Editor {
             show_breakpoints: None,
             show_wrap_guides: None,
             show_indent_guides,
+            buffers_with_disabled_indent_guides: HashSet::default(),
             highlight_order: 0,
             highlighted_rows: HashMap::default(),
             background_highlights: HashMap::default(),
@@ -2225,6 +2275,7 @@ impl Editor {
             cursor_shape: EditorSettings::get_global(cx)
                 .cursor_shape
                 .unwrap_or_default(),
+            cursor_offset_on_selection: false,
             current_line_highlight: None,
             autoindent_mode: Some(AutoindentMode::EachLine),
             collapse_matches: false,
@@ -2240,6 +2291,7 @@ impl Editor {
             remote_id: None,
             hover_state: HoverState::default(),
             pending_mouse_down: None,
+            prev_pressure_stage: None,
             hovered_link_state: None,
             edit_prediction_provider: None,
             active_edit_prediction: None,
@@ -2264,6 +2316,7 @@ impl Editor {
             editor_actions: Rc::default(),
             edit_predictions_hidden_for_vim_mode: false,
             show_edit_predictions_override: None,
+            show_completions_on_input_override: None,
             menu_edit_predictions_policy: MenuEditPredictionsPolicy::ByProvider,
             edit_prediction_settings: EditPredictionSettings::Disabled,
             edit_prediction_indent_conflict: false,
@@ -2317,6 +2370,7 @@ impl Editor {
                 .unwrap_or_default(),
             tasks_update_task: None,
             pull_diagnostics_task: Task::ready(()),
+            pull_diagnostics_background_task: Task::ready(()),
             colors: None,
             refresh_colors_task: Task::ready(()),
             inlay_hints: None,
@@ -2350,7 +2404,7 @@ impl Editor {
             lookup_key: None,
             select_next_is_case_sensitive: None,
             applicable_language_settings: HashMap::default(),
-            accent_overrides: Vec::new(),
+            accent_data: None,
             fetched_tree_sitter_chunks: HashMap::default(),
             number_deleted_lines: false,
         };
@@ -2360,7 +2414,7 @@ impl Editor {
         }
 
         editor.applicable_language_settings = editor.fetch_applicable_language_settings(cx);
-        editor.accent_overrides = editor.fetch_accent_overrides(cx);
+        editor.accent_data = editor.fetch_accent_data(cx);
 
         if let Some(breakpoints) = editor.breakpoint_store.as_ref() {
             editor
@@ -2493,7 +2547,6 @@ impl Editor {
             if let Some(buffer) = multi_buffer.read(cx).as_singleton() {
                 editor.register_buffer(buffer.read(cx).remote_id(), cx);
             }
-            editor.update_lsp_data(None, window, cx);
             editor.report_editor_event(ReportEditorEvent::EditorOpened, None, cx);
         }
 
@@ -2714,21 +2767,24 @@ impl Editor {
 
     pub fn accept_edit_prediction_keybind(
         &self,
-        accept_partial: bool,
+        granularity: EditPredictionGranularity,
         window: &mut Window,
         cx: &mut App,
     ) -> AcceptEditPredictionBinding {
         let key_context = self.key_context_internal(true, window, cx);
         let in_conflict = self.edit_prediction_in_conflict();
 
-        let bindings = if accept_partial {
-            window.bindings_for_action_in_context(&AcceptPartialEditPrediction, key_context)
-        } else {
-            window.bindings_for_action_in_context(&AcceptEditPrediction, key_context)
-        };
+        let bindings =
+            match granularity {
+                EditPredictionGranularity::Word => window
+                    .bindings_for_action_in_context(&AcceptNextWordEditPrediction, key_context),
+                EditPredictionGranularity::Line => window
+                    .bindings_for_action_in_context(&AcceptNextLineEditPrediction, key_context),
+                EditPredictionGranularity::Full => {
+                    window.bindings_for_action_in_context(&AcceptEditPrediction, key_context)
+                }
+            };
 
-        // TODO: if the binding contains multiple keystrokes, display all of them, not
-        // just the first one.
         AcceptEditPredictionBinding(bindings.into_iter().rev().find(|binding| {
             !in_conflict
                 || binding
@@ -2883,6 +2939,7 @@ impl Editor {
         EditorSnapshot {
             mode: self.mode.clone(),
             show_gutter: self.show_gutter,
+            offset_content: self.offset_content,
             show_line_numbers: self.show_line_numbers,
             number_deleted_lines: self.number_deleted_lines,
             show_git_diff_gutter: self.show_git_diff_gutter,
@@ -2978,9 +3035,9 @@ impl Editor {
         window: &mut Window,
         cx: &mut Context<Self>,
     ) where
-        T: EditPredictionProvider,
+        T: EditPredictionDelegate,
     {
-        self.edit_prediction_provider = provider.map(|provider| RegisteredEditPredictionProvider {
+        self.edit_prediction_provider = provider.map(|provider| RegisteredEditPredictionDelegate {
             _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
                 if this.focus_handle.is_focused(window) {
                     this.update_visible_edit_prediction(window, cx);
@@ -3038,6 +3095,10 @@ impl Editor {
         self.cursor_shape
     }
 
+    pub fn set_cursor_offset_on_selection(&mut self, set_cursor_offset_on_selection: bool) {
+        self.cursor_offset_on_selection = set_cursor_offset_on_selection;
+    }
+
     pub fn set_current_line_highlight(
         &mut self,
         current_line_highlight: Option<CurrentLineHighlight>,
@@ -3147,6 +3208,10 @@ impl Editor {
         }
     }
 
+    pub fn set_show_completions_on_input(&mut self, show_completions_on_input: Option<bool>) {
+        self.show_completions_on_input_override = show_completions_on_input;
+    }
+
     pub fn set_show_edit_predictions(
         &mut self,
         show_edit_predictions: Option<bool>,
@@ -3350,7 +3415,8 @@ impl Editor {
                 data.selections = inmemory_selections;
             });
 
-            if WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
+            if WorkspaceSettings::get(None, cx).restore_on_startup
+                != RestoreOnStartupBehavior::EmptyTab
                 && let Some(workspace_id) = self.workspace_serialization_id(cx)
             {
                 let snapshot = self.buffer().read(cx).snapshot(cx);
@@ -3390,7 +3456,8 @@ impl Editor {
         use text::ToPoint as _;
 
         if self.mode.is_minimap()
-            || WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None
+            || WorkspaceSettings::get(None, cx).restore_on_startup
+                == RestoreOnStartupBehavior::EmptyTab
         {
             return;
         }
@@ -3748,7 +3815,7 @@ impl Editor {
     ) {
         if !self.focus_handle.is_focused(window) {
             self.last_focused_descendant = None;
-            window.focus(&self.focus_handle);
+            window.focus(&self.focus_handle, cx);
         }
 
         let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
@@ -3853,7 +3920,7 @@ impl Editor {
     ) {
         if !self.focus_handle.is_focused(window) {
             self.last_focused_descendant = None;
-            window.focus(&self.focus_handle);
+            window.focus(&self.focus_handle, cx);
         }
 
         let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
@@ -4327,10 +4394,50 @@ impl Editor {
                                 && bracket_pair.start.len() == 1
                             {
                                 let target = bracket_pair.start.chars().next().unwrap();
+                                let mut byte_offset = 0u32;
                                 let current_line_count = snapshot
                                     .reversed_chars_at(selection.start)
                                     .take_while(|&c| c != '\n')
-                                    .filter(|&c| c == target)
+                                    .filter(|c| {
+                                        byte_offset += c.len_utf8() as u32;
+                                        if *c != target {
+                                            return false;
+                                        }
+
+                                        let point = Point::new(
+                                            selection.start.row,
+                                            selection.start.column.saturating_sub(byte_offset),
+                                        );
+
+                                        let is_enabled = snapshot
+                                            .language_scope_at(point)
+                                            .and_then(|scope| {
+                                                scope
+                                                    .brackets()
+                                                    .find(|(pair, _)| {
+                                                        pair.start == bracket_pair.start
+                                                    })
+                                                    .map(|(_, enabled)| enabled)
+                                            })
+                                            .unwrap_or(true);
+
+                                        let is_delimiter = snapshot
+                                            .language_scope_at(Point::new(
+                                                point.row,
+                                                point.column + 1,
+                                            ))
+                                            .and_then(|scope| {
+                                                scope
+                                                    .brackets()
+                                                    .find(|(pair, _)| {
+                                                        pair.start == bracket_pair.start
+                                                    })
+                                                    .map(|(_, enabled)| !enabled)
+                                            })
+                                            .unwrap_or(false);
+
+                                        is_enabled && !is_delimiter
+                                    })
                                     .count();
                                 current_line_count % 2 == 1
                             } else {
@@ -4683,18 +4790,27 @@ impl Editor {
                         let end = selection.end;
                         let selection_is_empty = start == end;
                         let language_scope = buffer.language_scope_at(start);
-                        let (
-                            comment_delimiter,
-                            doc_delimiter,
-                            insert_extra_newline,
-                            indent_on_newline,
-                            indent_on_extra_newline,
-                        ) = if let Some(language) = &language_scope {
-                            let mut insert_extra_newline =
-                                insert_extra_newline_brackets(&buffer, start..end, language)
-                                    || insert_extra_newline_tree_sitter(&buffer, start..end);
-
-                            // Comment extension on newline is allowed only for cursor selections
+                        let (delimiter, newline_config) = if let Some(language) = &language_scope {
+                            let needs_extra_newline = NewlineConfig::insert_extra_newline_brackets(
+                                &buffer,
+                                start..end,
+                                language,
+                            )
+                                || NewlineConfig::insert_extra_newline_tree_sitter(
+                                    &buffer,
+                                    start..end,
+                                );
+
+                            let mut newline_config = NewlineConfig::Newline {
+                                additional_indent: IndentSize::spaces(0),
+                                extra_line_additional_indent: if needs_extra_newline {
+                                    Some(IndentSize::spaces(0))
+                                } else {
+                                    None
+                                },
+                                prevent_auto_indent: false,
+                            };
+
                             let comment_delimiter = maybe!({
                                 if !selection_is_empty {
                                     return None;
@@ -4704,63 +4820,13 @@ impl Editor {
                                     return None;
                                 }
 
-                                let delimiters = language.line_comment_prefixes();
-                                let max_len_of_delimiter =
-                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
-                                let (snapshot, range) =
-                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
-
-                                let num_of_whitespaces = snapshot
-                                    .chars_for_range(range.clone())
-                                    .take_while(|c| c.is_whitespace())
-                                    .count();
-                                let comment_candidate = snapshot
-                                    .chars_for_range(range.clone())
-                                    .skip(num_of_whitespaces)
-                                    .take(max_len_of_delimiter)
-                                    .collect::<String>();
-                                let (delimiter, trimmed_len) = delimiters
-                                    .iter()
-                                    .filter_map(|delimiter| {
-                                        let prefix = delimiter.trim_end();
-                                        if comment_candidate.starts_with(prefix) {
-                                            Some((delimiter, prefix.len()))
-                                        } else {
-                                            None
-                                        }
-                                    })
-                                    .max_by_key(|(_, len)| *len)?;
-
-                                if let Some(BlockCommentConfig {
-                                    start: block_start, ..
-                                }) = language.block_comment()
-                                {
-                                    let block_start_trimmed = block_start.trim_end();
-                                    if block_start_trimmed.starts_with(delimiter.trim_end()) {
-                                        let line_content = snapshot
-                                            .chars_for_range(range)
-                                            .skip(num_of_whitespaces)
-                                            .take(block_start_trimmed.len())
-                                            .collect::<String>();
-
-                                        if line_content.starts_with(block_start_trimmed) {
-                                            return None;
-                                        }
-                                    }
-                                }
-
-                                let cursor_is_placed_after_comment_marker =
-                                    num_of_whitespaces + trimmed_len <= start_point.column as usize;
-                                if cursor_is_placed_after_comment_marker {
-                                    Some(delimiter.clone())
-                                } else {
-                                    None
-                                }
+                                return comment_delimiter_for_newline(
+                                    &start_point,
+                                    &buffer,
+                                    language,
+                                );
                             });
 
-                            let mut indent_on_newline = IndentSize::spaces(0);
-                            let mut indent_on_extra_newline = IndentSize::spaces(0);
-
                             let doc_delimiter = maybe!({
                                 if !selection_is_empty {
                                     return None;
@@ -4770,149 +4836,100 @@ impl Editor {
                                     return None;
                                 }
 
-                                let BlockCommentConfig {
-                                    start: start_tag,
-                                    end: end_tag,
-                                    prefix: delimiter,
-                                    tab_size: len,
-                                } = language.documentation_comment()?;
-                                let is_within_block_comment = buffer
-                                    .language_scope_at(start_point)
-                                    .is_some_and(|scope| scope.override_name() == Some("comment"));
-                                if !is_within_block_comment {
+                                return documentation_delimiter_for_newline(
+                                    &start_point,
+                                    &buffer,
+                                    language,
+                                    &mut newline_config,
+                                );
+                            });
+
+                            let list_delimiter = maybe!({
+                                if !selection_is_empty {
                                     return None;
                                 }
 
-                                let (snapshot, range) =
-                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
-
-                                let num_of_whitespaces = snapshot
-                                    .chars_for_range(range.clone())
-                                    .take_while(|c| c.is_whitespace())
-                                    .count();
-
-                                // It is safe to use a column from MultiBufferPoint in context of a single buffer ranges, because we're only ever looking at a single line at a time.
-                                let column = start_point.column;
-                                let cursor_is_after_start_tag = {
-                                    let start_tag_len = start_tag.len();
-                                    let start_tag_line = snapshot
-                                        .chars_for_range(range.clone())
-                                        .skip(num_of_whitespaces)
-                                        .take(start_tag_len)
-                                        .collect::<String>();
-                                    if start_tag_line.starts_with(start_tag.as_ref()) {
-                                        num_of_whitespaces + start_tag_len <= column as usize
-                                    } else {
-                                        false
-                                    }
-                                };
-
-                                let cursor_is_after_delimiter = {
-                                    let delimiter_trim = delimiter.trim_end();
-                                    let delimiter_line = snapshot
-                                        .chars_for_range(range.clone())
-                                        .skip(num_of_whitespaces)
-                                        .take(delimiter_trim.len())
-                                        .collect::<String>();
-                                    if delimiter_line.starts_with(delimiter_trim) {
-                                        num_of_whitespaces + delimiter_trim.len() <= column as usize
-                                    } else {
-                                        false
-                                    }
-                                };
-
-                                let cursor_is_before_end_tag_if_exists = {
-                                    let mut char_position = 0u32;
-                                    let mut end_tag_offset = None;
-
-                                    'outer: for chunk in snapshot.text_for_range(range) {
-                                        if let Some(byte_pos) = chunk.find(&**end_tag) {
-                                            let chars_before_match =
-                                                chunk[..byte_pos].chars().count() as u32;
-                                            end_tag_offset =
-                                                Some(char_position + chars_before_match);
-                                            break 'outer;
-                                        }
-                                        char_position += chunk.chars().count() as u32;
-                                    }
-
-                                    if let Some(end_tag_offset) = end_tag_offset {
-                                        let cursor_is_before_end_tag = column <= end_tag_offset;
-                                        if cursor_is_after_start_tag {
-                                            if cursor_is_before_end_tag {
-                                                insert_extra_newline = true;
-                                            }
-                                            let cursor_is_at_start_of_end_tag =
-                                                column == end_tag_offset;
-                                            if cursor_is_at_start_of_end_tag {
-                                                indent_on_extra_newline.len = *len;
-                                            }
-                                        }
-                                        cursor_is_before_end_tag
-                                    } else {
-                                        true
-                                    }
-                                };
-
-                                if (cursor_is_after_start_tag || cursor_is_after_delimiter)
-                                    && cursor_is_before_end_tag_if_exists
-                                {
-                                    if cursor_is_after_start_tag {
-                                        indent_on_newline.len = *len;
-                                    }
-                                    Some(delimiter.clone())
-                                } else {
-                                    None
+                                if !multi_buffer.language_settings(cx).extend_list_on_newline {
+                                    return None;
                                 }
+
+                                return list_delimiter_for_newline(
+                                    &start_point,
+                                    &buffer,
+                                    language,
+                                    &mut newline_config,
+                                );
                             });
 
                             (
-                                comment_delimiter,
-                                doc_delimiter,
-                                insert_extra_newline,
-                                indent_on_newline,
-                                indent_on_extra_newline,
+                                comment_delimiter.or(doc_delimiter).or(list_delimiter),
+                                newline_config,
                             )
                         } else {
                             (
                                 None,
-                                None,
-                                false,
-                                IndentSize::default(),
-                                IndentSize::default(),
+                                NewlineConfig::Newline {
+                                    additional_indent: IndentSize::spaces(0),
+                                    extra_line_additional_indent: None,
+                                    prevent_auto_indent: false,
+                                },
                             )
                         };
 
-                        let prevent_auto_indent = doc_delimiter.is_some();
-                        let delimiter = comment_delimiter.or(doc_delimiter);
-
-                        let capacity_for_delimiter =
-                            delimiter.as_deref().map(str::len).unwrap_or_default();
-                        let mut new_text = String::with_capacity(
-                            1 + capacity_for_delimiter
-                                + existing_indent.len as usize
-                                + indent_on_newline.len as usize
-                                + indent_on_extra_newline.len as usize,
-                        );
-                        new_text.push('\n');
-                        new_text.extend(existing_indent.chars());
-                        new_text.extend(indent_on_newline.chars());
-
-                        if let Some(delimiter) = &delimiter {
-                            new_text.push_str(delimiter);
-                        }
-
-                        if insert_extra_newline {
-                            new_text.push('\n');
-                            new_text.extend(existing_indent.chars());
-                            new_text.extend(indent_on_extra_newline.chars());
-                        }
+                        let (edit_start, new_text, prevent_auto_indent) = match &newline_config {
+                            NewlineConfig::ClearCurrentLine => {
+                                let row_start =
+                                    buffer.point_to_offset(Point::new(start_point.row, 0));
+                                (row_start, String::new(), false)
+                            }
+                            NewlineConfig::UnindentCurrentLine { continuation } => {
+                                let row_start =
+                                    buffer.point_to_offset(Point::new(start_point.row, 0));
+                                let tab_size = buffer.language_settings_at(start, cx).tab_size;
+                                let tab_size_indent = IndentSize::spaces(tab_size.get());
+                                let reduced_indent =
+                                    existing_indent.with_delta(Ordering::Less, tab_size_indent);
+                                let mut new_text = String::new();
+                                new_text.extend(reduced_indent.chars());
+                                new_text.push_str(continuation);
+                                (row_start, new_text, true)
+                            }
+                            NewlineConfig::Newline {
+                                additional_indent,
+                                extra_line_additional_indent,
+                                prevent_auto_indent,
+                            } => {
+                                let capacity_for_delimiter =
+                                    delimiter.as_deref().map(str::len).unwrap_or_default();
+                                let extra_line_len = extra_line_additional_indent
+                                    .map(|i| 1 + existing_indent.len as usize + i.len as usize)
+                                    .unwrap_or(0);
+                                let mut new_text = String::with_capacity(
+                                    1 + capacity_for_delimiter
+                                        + existing_indent.len as usize
+                                        + additional_indent.len as usize
+                                        + extra_line_len,
+                                );
+                                new_text.push('\n');
+                                new_text.extend(existing_indent.chars());
+                                new_text.extend(additional_indent.chars());
+                                if let Some(delimiter) = &delimiter {
+                                    new_text.push_str(delimiter);
+                                }
+                                if let Some(extra_indent) = extra_line_additional_indent {
+                                    new_text.push('\n');
+                                    new_text.extend(existing_indent.chars());
+                                    new_text.extend(extra_indent.chars());
+                                }
+                                (start, new_text, *prevent_auto_indent)
+                            }
+                        };
 
                         let anchor = buffer.anchor_after(end);
                         let new_selection = selection.map(|_| anchor);
                         (
-                            ((start..end, new_text), prevent_auto_indent),
-                            (insert_extra_newline, new_selection),
+                            ((edit_start..end, new_text), prevent_auto_indent),
+                            (newline_config.has_extra_line(), new_selection),
                         )
                     })
                     .unzip()
@@ -4949,6 +4966,9 @@ impl Editor {
 
             this.change_selections(Default::default(), window, cx, |s| s.select(new_selections));
             this.refresh_edit_prediction(true, false, window, cx);
+            if let Some(task) = this.trigger_on_type_formatting("\n".to_owned(), window, cx) {
+                task.detach_and_log_err(cx);
+            }
         });
     }
 
@@ -5013,6 +5033,9 @@ impl Editor {
                 }
             }
             editor.edit(indent_edits, cx);
+            if let Some(format) = editor.trigger_on_type_formatting("\n".to_owned(), window, cx) {
+                format.detach_and_log_err(cx);
+            }
         });
     }
 
@@ -5075,6 +5098,9 @@ impl Editor {
                 }
             }
             editor.edit(indent_edits, cx);
+            if let Some(format) = editor.trigger_on_type_formatting("\n".to_owned(), window, cx) {
+                format.detach_and_log_err(cx);
+            }
         });
     }
 
@@ -5385,7 +5411,7 @@ impl Editor {
         window: &mut Window,
         cx: &mut Context<Self>,
     ) -> Option<Task<Result<()>>> {
-        if input.len() != 1 {
+        if input.chars().count() != 1 {
             return None;
         }
 
@@ -5511,6 +5537,25 @@ impl Editor {
         };
         let buffer_snapshot = buffer.read(cx).snapshot();
 
+        let menu_is_open = matches!(
+            self.context_menu.borrow().as_ref(),
+            Some(CodeContextMenu::Completions(_))
+        );
+
+        let language = buffer_snapshot
+            .language_at(buffer_position.text_anchor)
+            .map(|language| language.name());
+
+        let language_settings = language_settings(language.clone(), buffer_snapshot.file(), cx);
+        let completion_settings = language_settings.completions.clone();
+
+        let show_completions_on_input = self
+            .show_completions_on_input_override
+            .unwrap_or(language_settings.show_completions_on_input);
+        if !menu_is_open && trigger.is_some() && !show_completions_on_input {
+            return;
+        }
+
         let query: Option<Arc<String>> =
             Self::completion_query(&multibuffer_snapshot, buffer_position)
                 .map(|query| query.into());
@@ -5519,14 +5564,8 @@ impl Editor {
 
         // Hide the current completions menu when query is empty. Without this, cached
         // completions from before the trigger char may be reused (#32774).
-        if query.is_none() {
-            let menu_is_open = matches!(
-                self.context_menu.borrow().as_ref(),
-                Some(CodeContextMenu::Completions(_))
-            );
-            if menu_is_open {
-                self.hide_context_menu(window, cx);
-            }
+        if query.is_none() && menu_is_open {
+            self.hide_context_menu(window, cx);
         }
 
         let mut ignore_word_threshold = false;

crates/editor/src/editor_settings.rs 🔗

@@ -215,7 +215,8 @@ impl Settings for EditorSettings {
             },
             scrollbar: Scrollbar {
                 show: scrollbar.show.map(Into::into).unwrap(),
-                git_diff: scrollbar.git_diff.unwrap(),
+                git_diff: scrollbar.git_diff.unwrap()
+                    && content.git.unwrap().enabled.unwrap().is_git_diff_enabled(),
                 selected_text: scrollbar.selected_text.unwrap(),
                 selected_symbol: scrollbar.selected_symbol.unwrap(),
                 search_results: scrollbar.search_results.unwrap(),

crates/editor/src/editor_tests.rs 🔗

@@ -2,7 +2,7 @@ use super::*;
 use crate::{
     JoinLines,
     code_context_menus::CodeContextMenu,
-    edit_prediction_tests::FakeEditPredictionProvider,
+    edit_prediction_tests::FakeEditPredictionDelegate,
     element::StickyHeader,
     linked_editing_ranges::LinkedEditingRanges,
     scroll::scroll_amount::ScrollAmount,
@@ -35,18 +35,22 @@ use language_settings::Formatter;
 use languages::markdown_lang;
 use languages::rust_lang;
 use lsp::CompletionParams;
-use multi_buffer::{IndentGuide, MultiBufferOffset, MultiBufferOffsetUtf16, PathKey};
+use multi_buffer::{
+    ExcerptRange, IndentGuide, MultiBuffer, MultiBufferOffset, MultiBufferOffsetUtf16, PathKey,
+};
 use parking_lot::Mutex;
 use pretty_assertions::{assert_eq, assert_ne};
 use project::{
-    FakeFs,
+    FakeFs, Project,
     debugger::breakpoint_store::{BreakpointState, SourceBreakpoint},
     project_settings::LspSettings,
+    trusted_worktrees::{PathTrust, TrustedWorktrees},
 };
 use serde_json::{self, json};
 use settings::{
     AllLanguageSettingsContent, EditorSettingsContent, IndentGuideBackgroundColoring,
-    IndentGuideColoring, ProjectSettingsContent, SearchSettingsContent,
+    IndentGuideColoring, InlayHintSettingsContent, ProjectSettingsContent, SearchSettingsContent,
+    SettingsStore,
 };
 use std::{cell::RefCell, future::Future, rc::Rc, sync::atomic::AtomicBool, time::Instant};
 use std::{
@@ -65,7 +69,6 @@ use util::{
 use workspace::{
     CloseActiveItem, CloseAllItems, CloseOtherItems, MoveItemToPaneInDirection, NavigationEntry,
     OpenOptions, ViewId,
-    invalid_item_view::InvalidItemView,
     item::{FollowEvent, FollowableItem, Item, ItemHandle, SaveOptions},
     register_project_item,
 };
@@ -2216,10 +2219,9 @@ async fn test_move_start_of_paragraph_end_of_paragraph(cx: &mut TestAppContext)
     init_test(cx, |_| {});
     let mut cx = EditorTestContext::new(cx).await;
 
-    let line_height = cx.editor(|editor, window, _| {
+    let line_height = cx.update_editor(|editor, window, cx| {
         editor
-            .style()
-            .unwrap()
+            .style(cx)
             .text
             .line_height_in_pixels(window.rem_size())
     });
@@ -2332,10 +2334,9 @@ async fn test_move_start_of_paragraph_end_of_paragraph(cx: &mut TestAppContext)
 async fn test_scroll_page_up_page_down(cx: &mut TestAppContext) {
     init_test(cx, |_| {});
     let mut cx = EditorTestContext::new(cx).await;
-    let line_height = cx.editor(|editor, window, _| {
+    let line_height = cx.update_editor(|editor, window, cx| {
         editor
-            .style()
-            .unwrap()
+            .style(cx)
             .text
             .line_height_in_pixels(window.rem_size())
     });
@@ -2398,8 +2399,7 @@ async fn test_autoscroll(cx: &mut TestAppContext) {
     let line_height = cx.update_editor(|editor, window, cx| {
         editor.set_vertical_scroll_margin(2, cx);
         editor
-            .style()
-            .unwrap()
+            .style(cx)
             .text
             .line_height_in_pixels(window.rem_size())
     });
@@ -2478,10 +2478,9 @@ async fn test_move_page_up_page_down(cx: &mut TestAppContext) {
     init_test(cx, |_| {});
     let mut cx = EditorTestContext::new(cx).await;
 
-    let line_height = cx.editor(|editor, window, _cx| {
+    let line_height = cx.update_editor(|editor, window, cx| {
         editor
-            .style()
-            .unwrap()
+            .style(cx)
             .text
             .line_height_in_pixels(window.rem_size())
     });
@@ -5775,6 +5774,116 @@ fn test_duplicate_line(cx: &mut TestAppContext) {
     });
 }
 
+#[gpui::test]
+async fn test_rotate_selections(cx: &mut TestAppContext) {
+    init_test(cx, |_| {});
+
+    let mut cx = EditorTestContext::new(cx).await;
+
+    // Rotate text selections (horizontal)
+    cx.set_state("x=«1ˇ», y=«2ˇ», z=«3ˇ»");
+    cx.update_editor(|e, window, cx| {
+        e.rotate_selections_forward(&RotateSelectionsForward, window, cx)
+    });
+    cx.assert_editor_state("x=«3ˇ», y=«1ˇ», z=«2ˇ»");
+    cx.update_editor(|e, window, cx| {
+        e.rotate_selections_backward(&RotateSelectionsBackward, window, cx)
+    });
+    cx.assert_editor_state("x=«1ˇ», y=«2ˇ», z=«3ˇ»");
+
+    // Rotate text selections (vertical)
+    cx.set_state(indoc! {"
+        x=«1ˇ»
+        y=«2ˇ»
+        z=«3ˇ»
+    "});
+    cx.update_editor(|e, window, cx| {
+        e.rotate_selections_forward(&RotateSelectionsForward, window, cx)
+    });
+    cx.assert_editor_state(indoc! {"
+        x=«3ˇ»
+        y=«1ˇ»
+        z=«2ˇ»
+    "});
+    cx.update_editor(|e, window, cx| {
+        e.rotate_selections_backward(&RotateSelectionsBackward, window, cx)
+    });
+    cx.assert_editor_state(indoc! {"
+        x=«1ˇ»
+        y=«2ˇ»
+        z=«3ˇ»
+    "});
+
+    // Rotate text selections (vertical, different lengths)
+    cx.set_state(indoc! {"
+        x=\"«ˇ»\"
+        y=\"«aˇ»\"
+        z=\"«aaˇ»\"
+    "});
+    cx.update_editor(|e, window, cx| {
+        e.rotate_selections_forward(&RotateSelectionsForward, window, cx)
+    });
+    cx.assert_editor_state(indoc! {"
+        x=\"«aaˇ»\"
+        y=\"«ˇ»\"
+        z=\"«aˇ»\"
+    "});
+    cx.update_editor(|e, window, cx| {
+        e.rotate_selections_backward(&RotateSelectionsBackward, window, cx)
+    });
+    cx.assert_editor_state(indoc! {"
+        x=\"«ˇ»\"
+        y=\"«aˇ»\"
+        z=\"«aaˇ»\"
+    "});
+
+    // Rotate whole lines (cursor positions preserved)
+    cx.set_state(indoc! {"
+        ˇline123
+        liˇne23
+        line3ˇ
+    "});
+    cx.update_editor(|e, window, cx| {
+        e.rotate_selections_forward(&RotateSelectionsForward, window, cx)
+    });
+    cx.assert_editor_state(indoc! {"
+        line3ˇ
+        ˇline123
+        liˇne23
+    "});
+    cx.update_editor(|e, window, cx| {
+        e.rotate_selections_backward(&RotateSelectionsBackward, window, cx)
+    });
+    cx.assert_editor_state(indoc! {"
+        ˇline123
+        liˇne23
+        line3ˇ
+    "});
+
+    // Rotate whole lines, multiple cursors per line (positions preserved)
+    cx.set_state(indoc! {"
+        ˇliˇne123
+        ˇline23
+        ˇline3
+    "});
+    cx.update_editor(|e, window, cx| {
+        e.rotate_selections_forward(&RotateSelectionsForward, window, cx)
+    });
+    cx.assert_editor_state(indoc! {"
+        ˇline3
+        ˇliˇne123
+        ˇline23
+    "});
+    cx.update_editor(|e, window, cx| {
+        e.rotate_selections_backward(&RotateSelectionsBackward, window, cx)
+    });
+    cx.assert_editor_state(indoc! {"
+        ˇliˇne123
+        ˇline23
+        ˇline3
+    "});
+}
+
 #[gpui::test]
 fn test_move_line_up_down(cx: &mut TestAppContext) {
     init_test(cx, |_| {});
@@ -7642,10 +7751,12 @@ fn test_select_line(cx: &mut TestAppContext) {
             ])
         });
         editor.select_line(&SelectLine, window, cx);
+        // Adjacent line selections should NOT merge (only overlapping ones do)
         assert_eq!(
             display_ranges(editor, cx),
             vec![
-                DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(2), 0),
+                DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(1), 0),
+                DisplayPoint::new(DisplayRow(1), 0)..DisplayPoint::new(DisplayRow(2), 0),
                 DisplayPoint::new(DisplayRow(4), 0)..DisplayPoint::new(DisplayRow(5), 0),
             ]
         );
@@ -7664,9 +7775,13 @@ fn test_select_line(cx: &mut TestAppContext) {
 
     _ = editor.update(cx, |editor, window, cx| {
         editor.select_line(&SelectLine, window, cx);
+        // Adjacent but not overlapping, so they stay separate
         assert_eq!(
             display_ranges(editor, cx),
-            vec![DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(5), 5)]
+            vec![
+                DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(4), 0),
+                DisplayPoint::new(DisplayRow(4), 0)..DisplayPoint::new(DisplayRow(5), 5),
+            ]
         );
     });
 }
@@ -8634,7 +8749,7 @@ async fn test_undo_edit_prediction_scrolls_to_edit_pos(cx: &mut TestAppContext)
 
     let mut cx = EditorTestContext::new(cx).await;
 
-    let provider = cx.new(|_| FakeEditPredictionProvider::default());
+    let provider = cx.new(|_| FakeEditPredictionDelegate::default());
     cx.update_editor(|editor, window, cx| {
         editor.set_edit_prediction_provider(Some(provider.clone()), window, cx);
     });
@@ -8657,7 +8772,7 @@ async fn test_undo_edit_prediction_scrolls_to_edit_pos(cx: &mut TestAppContext)
 
     cx.update(|_, cx| {
         provider.update(cx, |provider, _| {
-            provider.set_edit_prediction(Some(edit_prediction::EditPrediction::Local {
+            provider.set_edit_prediction(Some(edit_prediction_types::EditPrediction::Local {
                 id: None,
                 edits: vec![(edit_position..edit_position, "X".into())],
                 edit_preview: None,
@@ -9968,7 +10083,7 @@ async fn test_autoindent_disabled_with_nested_language(cx: &mut TestAppContext)
                     ],
                     ..Default::default()
                 },
-                name: LanguageName::new("rust"),
+                name: LanguageName::new_static("rust"),
                 ..Default::default()
             },
             Some(tree_sitter_rust::LANGUAGE.into()),
@@ -10755,6 +10870,115 @@ async fn test_autoclose_with_overrides(cx: &mut TestAppContext) {
     );
 }
 
+#[gpui::test]
+async fn test_autoclose_quotes_with_scope_awareness(cx: &mut TestAppContext) {
+    init_test(cx, |_| {});
+
+    let mut cx = EditorTestContext::new(cx).await;
+    let language = languages::language("python", tree_sitter_python::LANGUAGE.into());
+
+    cx.update_buffer(|buffer, cx| buffer.set_language(Some(language), cx));
+
+    // Double quote inside single-quoted string
+    cx.set_state(indoc! {r#"
+        def main():
+            items = ['"', ˇ]
+    "#});
+    cx.update_editor(|editor, window, cx| {
+        editor.handle_input("\"", window, cx);
+    });
+    cx.assert_editor_state(indoc! {r#"
+        def main():
+            items = ['"', "ˇ"]
+    "#});
+
+    // Two double quotes inside single-quoted string
+    cx.set_state(indoc! {r#"
+        def main():
+            items = ['""', ˇ]
+    "#});
+    cx.update_editor(|editor, window, cx| {
+        editor.handle_input("\"", window, cx);
+    });
+    cx.assert_editor_state(indoc! {r#"
+        def main():
+            items = ['""', "ˇ"]
+    "#});
+
+    // Single quote inside double-quoted string
+    cx.set_state(indoc! {r#"
+        def main():
+            items = ["'", ˇ]
+    "#});
+    cx.update_editor(|editor, window, cx| {
+        editor.handle_input("'", window, cx);
+    });
+    cx.assert_editor_state(indoc! {r#"
+        def main():
+            items = ["'", 'ˇ']
+    "#});
+
+    // Two single quotes inside double-quoted string
+    cx.set_state(indoc! {r#"
+        def main():
+            items = ["''", ˇ]
+    "#});
+    cx.update_editor(|editor, window, cx| {
+        editor.handle_input("'", window, cx);
+    });
+    cx.assert_editor_state(indoc! {r#"
+        def main():
+            items = ["''", 'ˇ']
+    "#});
+
+    // Mixed quotes on same line
+    cx.set_state(indoc! {r#"
+        def main():
+            items = ['"""', "'''''", ˇ]
+    "#});
+    cx.update_editor(|editor, window, cx| {
+        editor.handle_input("\"", window, cx);
+    });
+    cx.assert_editor_state(indoc! {r#"
+        def main():
+            items = ['"""', "'''''", "ˇ"]
+    "#});
+    cx.update_editor(|editor, window, cx| {
+        editor.move_right(&MoveRight, window, cx);
+    });
+    cx.update_editor(|editor, window, cx| {
+        editor.handle_input(", ", window, cx);
+    });
+    cx.update_editor(|editor, window, cx| {
+        editor.handle_input("'", window, cx);
+    });
+    cx.assert_editor_state(indoc! {r#"
+        def main():
+            items = ['"""', "'''''", "", 'ˇ']
+    "#});
+}
+
+#[gpui::test]
+async fn test_autoclose_quotes_with_multibyte_characters(cx: &mut TestAppContext) {
+    init_test(cx, |_| {});
+
+    let mut cx = EditorTestContext::new(cx).await;
+    let language = languages::language("python", tree_sitter_python::LANGUAGE.into());
+    cx.update_buffer(|buffer, cx| buffer.set_language(Some(language), cx));
+
+    cx.set_state(indoc! {r#"
+        def main():
+            items = ["🎉", ˇ]
+    "#});
+    cx.update_editor(|editor, window, cx| {
+        editor.handle_input("\"", window, cx);
+    });
+    cx.assert_editor_state(indoc! {r#"
+        def main():
+            items = ["🎉", "ˇ"]
+    "#});
+}
+
 #[gpui::test]
 async fn test_surround_with_pair(cx: &mut TestAppContext) {
     init_test(cx, |_| {});
@@ -16087,7 +16311,7 @@ async fn test_toggle_comment(cx: &mut TestAppContext) {
     cx.assert_editor_state(indoc! {"
         fn a() {
             «b();
-            c();
+            ˇ»«c();
             ˇ» d();
         }
     "});
@@ -16099,8 +16323,8 @@ async fn test_toggle_comment(cx: &mut TestAppContext) {
     cx.assert_editor_state(indoc! {"
         fn a() {
             // «b();
-            // c();
-            ˇ»//  d();
+            ˇ»// «c();
+            ˇ» // d();
         }
     "});
 
@@ -16109,7 +16333,7 @@ async fn test_toggle_comment(cx: &mut TestAppContext) {
         fn a() {
             // b();
             «// c();
-        ˇ»    //  d();
+        ˇ»     // d();
         }
     "});
 
@@ -16119,7 +16343,7 @@ async fn test_toggle_comment(cx: &mut TestAppContext) {
         fn a() {
             // b();
             «c();
-        ˇ»    //  d();
+        ˇ»     // d();
         }
     "});
 
@@ -16975,7 +17199,7 @@ fn test_highlighted_ranges(cx: &mut TestAppContext) {
                 anchor_range(Point::new(6, 3)..Point::new(6, 5)),
                 anchor_range(Point::new(8, 4)..Point::new(8, 6)),
             ],
-            |_| Hsla::red(),
+            |_, _| Hsla::red(),
             cx,
         );
         editor.highlight_background::<Type2>(
@@ -16985,7 +17209,7 @@ fn test_highlighted_ranges(cx: &mut TestAppContext) {
                 anchor_range(Point::new(7, 4)..Point::new(7, 7)),
                 anchor_range(Point::new(9, 5)..Point::new(9, 8)),
             ],
-            |_| Hsla::green(),
+            |_, _| Hsla::green(),
             cx,
         );
 
@@ -17975,7 +18199,7 @@ async fn test_on_type_formatting_not_triggered(cx: &mut TestAppContext) {
     );
 
     editor_handle.update_in(cx, |editor, window, cx| {
-        window.focus(&editor.focus_handle(cx));
+        window.focus(&editor.focus_handle(cx), cx);
         editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
             s.select_ranges([Point::new(0, 21)..Point::new(0, 20)])
         });
@@ -18120,7 +18344,7 @@ async fn test_language_server_restart_due_to_settings_change(cx: &mut TestAppCon
     );
 
     update_test_project_settings(cx, |project_settings| {
-        project_settings.lsp.insert(
+        project_settings.lsp.0.insert(
             "Some other server name".into(),
             LspSettings {
                 binary: None,
@@ -18141,7 +18365,7 @@ async fn test_language_server_restart_due_to_settings_change(cx: &mut TestAppCon
     );
 
     update_test_project_settings(cx, |project_settings| {
-        project_settings.lsp.insert(
+        project_settings.lsp.0.insert(
             language_server_name.into(),
             LspSettings {
                 binary: None,
@@ -18162,7 +18386,7 @@ async fn test_language_server_restart_due_to_settings_change(cx: &mut TestAppCon
     );
 
     update_test_project_settings(cx, |project_settings| {
-        project_settings.lsp.insert(
+        project_settings.lsp.0.insert(
             language_server_name.into(),
             LspSettings {
                 binary: None,
@@ -18183,7 +18407,7 @@ async fn test_language_server_restart_due_to_settings_change(cx: &mut TestAppCon
     );
 
     update_test_project_settings(cx, |project_settings| {
-        project_settings.lsp.insert(
+        project_settings.lsp.0.insert(
             language_server_name.into(),
             LspSettings {
                 binary: None,
@@ -19092,6 +19316,109 @@ async fn test_document_format_with_prettier(cx: &mut TestAppContext) {
     );
 }
 
+#[gpui::test]
+async fn test_document_format_with_prettier_explicit_language(cx: &mut TestAppContext) {
+    init_test(cx, |settings| {
+        settings.defaults.formatter = Some(FormatterList::Single(Formatter::Prettier))
+    });
+
+    let fs = FakeFs::new(cx.executor());
+    fs.insert_file(path!("/file.settings"), Default::default())
+        .await;
+
+    let project = Project::test(fs, [path!("/file.settings").as_ref()], cx).await;
+    let language_registry = project.read_with(cx, |project, _| project.languages().clone());
+
+    let ts_lang = Arc::new(Language::new(
+        LanguageConfig {
+            name: "TypeScript".into(),
+            matcher: LanguageMatcher {
+                path_suffixes: vec!["ts".to_string()],
+                ..LanguageMatcher::default()
+            },
+            prettier_parser_name: Some("typescript".to_string()),
+            ..LanguageConfig::default()
+        },
+        Some(tree_sitter_typescript::LANGUAGE_TYPESCRIPT.into()),
+    ));
+
+    language_registry.add(ts_lang.clone());
+
+    update_test_language_settings(cx, |settings| {
+        settings.defaults.prettier.get_or_insert_default().allowed = Some(true);
+    });
+
+    let test_plugin = "test_plugin";
+    let _ = language_registry.register_fake_lsp(
+        "TypeScript",
+        FakeLspAdapter {
+            prettier_plugins: vec![test_plugin],
+            ..Default::default()
+        },
+    );
+
+    let prettier_format_suffix = project::TEST_PRETTIER_FORMAT_SUFFIX;
+    let buffer = project
+        .update(cx, |project, cx| {
+            project.open_local_buffer(path!("/file.settings"), cx)
+        })
+        .await
+        .unwrap();
+
+    project.update(cx, |project, cx| {
+        project.set_language_for_buffer(&buffer, ts_lang, cx)
+    });
+
+    let buffer_text = "one\ntwo\nthree\n";
+    let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
+    let (editor, cx) = cx.add_window_view(|window, cx| build_editor(buffer, window, cx));
+    editor.update_in(cx, |editor, window, cx| {
+        editor.set_text(buffer_text, window, cx)
+    });
+
+    editor
+        .update_in(cx, |editor, window, cx| {
+            editor.perform_format(
+                project.clone(),
+                FormatTrigger::Manual,
+                FormatTarget::Buffers(editor.buffer().read(cx).all_buffers()),
+                window,
+                cx,
+            )
+        })
+        .unwrap()
+        .await;
+    assert_eq!(
+        editor.update(cx, |editor, cx| editor.text(cx)),
+        buffer_text.to_string() + prettier_format_suffix + "\ntypescript",
+        "Test prettier formatting was not applied to the original buffer text",
+    );
+
+    update_test_language_settings(cx, |settings| {
+        settings.defaults.formatter = Some(FormatterList::default())
+    });
+    let format = editor.update_in(cx, |editor, window, cx| {
+        editor.perform_format(
+            project.clone(),
+            FormatTrigger::Manual,
+            FormatTarget::Buffers(editor.buffer().read(cx).all_buffers()),
+            window,
+            cx,
+        )
+    });
+    format.await.unwrap();
+
+    assert_eq!(
+        editor.update(cx, |editor, cx| editor.text(cx)),
+        buffer_text.to_string()
+            + prettier_format_suffix
+            + "\ntypescript\n"
+            + prettier_format_suffix
+            + "\ntypescript",
+        "Autoformatting (via test prettier) was not applied to the original buffer text",
+    );
+}
+
 #[gpui::test]
 async fn test_addition_reverts(cx: &mut TestAppContext) {
     init_test(cx, |_| {});
@@ -20558,6 +20885,36 @@ async fn test_toggling_adjacent_diff_hunks(cx: &mut TestAppContext) {
         .to_string(),
     );
 
+    cx.update_editor(|editor, window, cx| {
+        editor.move_up(&MoveUp, window, cx);
+        editor.toggle_selected_diff_hunks(&Default::default(), window, cx);
+    });
+    cx.assert_state_with_diff(
+        indoc! { "
+        ˇone
+      - two
+        three
+        five
+    "}
+        .to_string(),
+    );
+
+    cx.update_editor(|editor, window, cx| {
+        editor.move_down(&MoveDown, window, cx);
+        editor.move_down(&MoveDown, window, cx);
+        editor.toggle_selected_diff_hunks(&Default::default(), window, cx);
+    });
+    cx.assert_state_with_diff(
+        indoc! { "
+        one
+      - two
+        ˇthree
+      - four
+        five
+    "}
+        .to_string(),
+    );
+
     cx.set_state(indoc! { "
         one
         ˇTWO
@@ -20598,7 +20955,7 @@ async fn test_toggling_adjacent_diff_hunks(cx: &mut TestAppContext) {
 }
 
 #[gpui::test]
-async fn test_edits_around_expanded_deletion_hunks(
+async fn test_toggling_adjacent_diff_hunks_2(
     executor: BackgroundExecutor,
     cx: &mut TestAppContext,
 ) {
@@ -20607,15 +20964,75 @@ async fn test_edits_around_expanded_deletion_hunks(
     let mut cx = EditorTestContext::new(cx).await;
 
     let diff_base = r#"
-        use some::mod1;
-        use some::mod2;
-
-        const A: u32 = 42;
-        const B: u32 = 42;
-        const C: u32 = 42;
-
+        lineA
+        lineB
+        lineC
+        lineD
+        "#
+    .unindent();
 
-        fn main() {
+    cx.set_state(
+        &r#"
+        ˇlineA1
+        lineB
+        lineD
+        "#
+        .unindent(),
+    );
+    cx.set_head_text(&diff_base);
+    executor.run_until_parked();
+
+    cx.update_editor(|editor, window, cx| {
+        editor.toggle_selected_diff_hunks(&ToggleSelectedDiffHunks, window, cx);
+    });
+    executor.run_until_parked();
+    cx.assert_state_with_diff(
+        r#"
+        - lineA
+        + ˇlineA1
+          lineB
+          lineD
+        "#
+        .unindent(),
+    );
+
+    cx.update_editor(|editor, window, cx| {
+        editor.move_down(&MoveDown, window, cx);
+        editor.move_right(&MoveRight, window, cx);
+        editor.toggle_selected_diff_hunks(&ToggleSelectedDiffHunks, window, cx);
+    });
+    executor.run_until_parked();
+    cx.assert_state_with_diff(
+        r#"
+        - lineA
+        + lineA1
+          lˇineB
+        - lineC
+          lineD
+        "#
+        .unindent(),
+    );
+}
+
+#[gpui::test]
+async fn test_edits_around_expanded_deletion_hunks(
+    executor: BackgroundExecutor,
+    cx: &mut TestAppContext,
+) {
+    init_test(cx, |_| {});
+
+    let mut cx = EditorTestContext::new(cx).await;
+
+    let diff_base = r#"
+        use some::mod1;
+        use some::mod2;
+
+        const A: u32 = 42;
+        const B: u32 = 42;
+        const C: u32 = 42;
+
+
+        fn main() {
             println!("hello");
 
             println!("world");
@@ -21914,6 +22331,40 @@ async fn test_toggle_deletion_hunk_at_start_of_file(
     cx.assert_state_with_diff(hunk_expanded);
 }
 
+#[gpui::test]
+async fn test_expand_first_line_diff_hunk_keeps_deleted_lines_visible(
+    executor: BackgroundExecutor,
+    cx: &mut TestAppContext,
+) {
+    init_test(cx, |_| {});
+    let mut cx = EditorTestContext::new(cx).await;
+
+    cx.set_state("ˇnew\nsecond\nthird\n");
+    cx.set_head_text("old\nsecond\nthird\n");
+    cx.update_editor(|editor, window, cx| {
+        editor.scroll(gpui::Point { x: 0., y: 0. }, None, window, cx);
+    });
+    executor.run_until_parked();
+    assert_eq!(cx.update_editor(|e, _, cx| e.scroll_position(cx)).y, 0.0);
+
+    // Expanding a diff hunk at the first line inserts deleted lines above the first buffer line.
+    cx.update_editor(|editor, window, cx| {
+        let snapshot = editor.snapshot(window, cx);
+        let excerpt_id = editor.buffer.read(cx).excerpt_ids()[0];
+        let hunks = editor
+            .diff_hunks_in_ranges(&[Anchor::min()..Anchor::max()], &snapshot.buffer_snapshot())
+            .collect::<Vec<_>>();
+        assert_eq!(hunks.len(), 1);
+        let hunk_range = Anchor::range_in_buffer(excerpt_id, hunks[0].buffer_range.clone());
+        editor.toggle_single_diff_hunk(hunk_range, cx)
+    });
+    executor.run_until_parked();
+    cx.assert_state_with_diff("- old\n+ ˇnew\n  second\n  third\n".to_string());
+
+    // Keep the editor scrolled to the top so the full hunk remains visible.
+    assert_eq!(cx.update_editor(|e, _, cx| e.scroll_position(cx)).y, 0.0);
+}
+
 #[gpui::test]
 async fn test_display_diff_hunks(cx: &mut TestAppContext) {
     init_test(cx, |_| {});
@@ -22481,7 +22932,7 @@ async fn test_find_all_references_editor_reuse(cx: &mut TestAppContext) {
         });
     let navigated = cx
         .update_editor(|editor, window, cx| {
-            editor.find_all_references(&FindAllReferences, window, cx)
+            editor.find_all_references(&FindAllReferences::default(), window, cx)
         })
         .unwrap()
         .await
@@ -22517,7 +22968,7 @@ async fn test_find_all_references_editor_reuse(cx: &mut TestAppContext) {
     );
     let navigated = cx
         .update_editor(|editor, window, cx| {
-            editor.find_all_references(&FindAllReferences, window, cx)
+            editor.find_all_references(&FindAllReferences::default(), window, cx)
         })
         .unwrap()
         .await
@@ -22569,7 +23020,7 @@ async fn test_find_all_references_editor_reuse(cx: &mut TestAppContext) {
         });
     let navigated = cx
         .update_editor(|editor, window, cx| {
-            editor.find_all_references(&FindAllReferences, window, cx)
+            editor.find_all_references(&FindAllReferences::default(), window, cx)
         })
         .unwrap()
         .await
@@ -23978,7 +24429,7 @@ async fn test_rename_with_duplicate_edits(cx: &mut TestAppContext) {
         let highlight_range = highlight_range.to_anchors(&editor.buffer().read(cx).snapshot(cx));
         editor.highlight_background::<DocumentHighlightRead>(
             &[highlight_range],
-            |theme| theme.colors().editor_document_highlight_read_background,
+            |_, theme| theme.colors().editor_document_highlight_read_background,
             cx,
         );
     });
@@ -24056,7 +24507,7 @@ async fn test_rename_without_prepare(cx: &mut TestAppContext) {
         let highlight_range = highlight_range.to_anchors(&editor.buffer().read(cx).snapshot(cx));
         editor.highlight_background::<DocumentHighlightRead>(
             &[highlight_range],
-            |theme| theme.colors().editor_document_highlight_read_background,
+            |_, theme| theme.colors().editor_document_highlight_read_background,
             cx,
         );
     });
@@ -25225,6 +25676,7 @@ async fn test_tab_in_leading_whitespace_auto_indents_for_python(cx: &mut TestApp
         ˇ        log('for else')
     "});
     cx.update_editor(|e, window, cx| e.tab(&Tab, window, cx));
+    cx.wait_for_autoindent_applied().await;
     cx.assert_editor_state(indoc! {"
         def main():
             ˇfor item in items:
@@ -25244,6 +25696,7 @@ async fn test_tab_in_leading_whitespace_auto_indents_for_python(cx: &mut TestApp
     // test relative indent is preserved when tab
     // for `if`, `elif`, `else`, `while`, `with` and `for`
     cx.update_editor(|e, window, cx| e.tab(&Tab, window, cx));
+    cx.wait_for_autoindent_applied().await;
     cx.assert_editor_state(indoc! {"
         def main():
                 ˇfor item in items:
@@ -25277,6 +25730,7 @@ async fn test_tab_in_leading_whitespace_auto_indents_for_python(cx: &mut TestApp
         ˇ            return 0
     "});
     cx.update_editor(|e, window, cx| e.tab(&Tab, window, cx));
+    cx.wait_for_autoindent_applied().await;
     cx.assert_editor_state(indoc! {"
         def main():
             ˇtry:
@@ -25293,6 +25747,7 @@ async fn test_tab_in_leading_whitespace_auto_indents_for_python(cx: &mut TestApp
     // test relative indent is preserved when tab
     // for `try`, `except`, `else`, `finally`, `match` and `def`
     cx.update_editor(|e, window, cx| e.tab(&Tab, window, cx));
+    cx.wait_for_autoindent_applied().await;
     cx.assert_editor_state(indoc! {"
         def main():
                 ˇtry:
@@ -25326,6 +25781,7 @@ async fn test_outdent_after_input_for_python(cx: &mut TestAppContext) {
     cx.update_editor(|editor, window, cx| {
         editor.handle_input("else:", window, cx);
     });
+    cx.wait_for_autoindent_applied().await;
     cx.assert_editor_state(indoc! {"
         def main():
             if i == 2:
@@ -25343,6 +25799,7 @@ async fn test_outdent_after_input_for_python(cx: &mut TestAppContext) {
     cx.update_editor(|editor, window, cx| {
         editor.handle_input("except:", window, cx);
     });
+    cx.wait_for_autoindent_applied().await;
     cx.assert_editor_state(indoc! {"
         def main():
             try:
@@ -25362,6 +25819,7 @@ async fn test_outdent_after_input_for_python(cx: &mut TestAppContext) {
     cx.update_editor(|editor, window, cx| {
         editor.handle_input("else:", window, cx);
     });
+    cx.wait_for_autoindent_applied().await;
     cx.assert_editor_state(indoc! {"
         def main():
             try:
@@ -25385,6 +25843,7 @@ async fn test_outdent_after_input_for_python(cx: &mut TestAppContext) {
     cx.update_editor(|editor, window, cx| {
         editor.handle_input("finally:", window, cx);
     });
+    cx.wait_for_autoindent_applied().await;
     cx.assert_editor_state(indoc! {"
         def main():
             try:
@@ -25409,6 +25868,7 @@ async fn test_outdent_after_input_for_python(cx: &mut TestAppContext) {
     cx.update_editor(|editor, window, cx| {
         editor.handle_input("else:", window, cx);
     });
+    cx.wait_for_autoindent_applied().await;
     cx.assert_editor_state(indoc! {"
         def main():
             try:
@@ -25434,6 +25894,7 @@ async fn test_outdent_after_input_for_python(cx: &mut TestAppContext) {
     cx.update_editor(|editor, window, cx| {
         editor.handle_input("finally:", window, cx);
     });
+    cx.wait_for_autoindent_applied().await;
     cx.assert_editor_state(indoc! {"
         def main():
             try:
@@ -25459,6 +25920,7 @@ async fn test_outdent_after_input_for_python(cx: &mut TestAppContext) {
     cx.update_editor(|editor, window, cx| {
         editor.handle_input("except:", window, cx);
     });
+    cx.wait_for_autoindent_applied().await;
     cx.assert_editor_state(indoc! {"
         def main():
             try:
@@ -25482,6 +25944,7 @@ async fn test_outdent_after_input_for_python(cx: &mut TestAppContext) {
     cx.update_editor(|editor, window, cx| {
         editor.handle_input("except:", window, cx);
     });
+    cx.wait_for_autoindent_applied().await;
     cx.assert_editor_state(indoc! {"
         def main():
             try:
@@ -25503,6 +25966,7 @@ async fn test_outdent_after_input_for_python(cx: &mut TestAppContext) {
     cx.update_editor(|editor, window, cx| {
         editor.handle_input("else:", window, cx);
     });
+    cx.wait_for_autoindent_applied().await;
     cx.assert_editor_state(indoc! {"
         def main():
             for i in range(10):
@@ -25519,6 +25983,7 @@ async fn test_outdent_after_input_for_python(cx: &mut TestAppContext) {
     cx.update_editor(|editor, window, cx| {
         editor.handle_input("a", window, cx);
     });
+    cx.wait_for_autoindent_applied().await;
     cx.assert_editor_state(indoc! {"
         def f() -> list[str]:
             aˇ
@@ -25532,6 +25997,7 @@ async fn test_outdent_after_input_for_python(cx: &mut TestAppContext) {
     cx.update_editor(|editor, window, cx| {
         editor.handle_input(":", window, cx);
     });
+    cx.wait_for_autoindent_applied().await;
     cx.assert_editor_state(indoc! {"
         match 1:
             case:ˇ
@@ -25555,6 +26021,7 @@ async fn test_indent_on_newline_for_python(cx: &mut TestAppContext) {
     cx.update_editor(|editor, window, cx| {
         editor.newline(&Newline, window, cx);
     });
+    cx.wait_for_autoindent_applied().await;
     cx.assert_editor_state(indoc! {"
         # COMMENT:
         ˇ
@@ -25567,7 +26034,7 @@ async fn test_indent_on_newline_for_python(cx: &mut TestAppContext) {
     cx.update_editor(|editor, window, cx| {
         editor.newline(&Newline, window, cx);
     });
-    cx.run_until_parked();
+    cx.wait_for_autoindent_applied().await;
     cx.assert_editor_state(indoc! {"
         {
             ˇ
@@ -25601,6 +26068,48 @@ async fn test_indent_on_newline_for_python(cx: &mut TestAppContext) {
     "});
 }
 
+#[gpui::test]
+async fn test_python_indent_in_markdown(cx: &mut TestAppContext) {
+    init_test(cx, |_| {});
+
+    let language_registry = Arc::new(language::LanguageRegistry::test(cx.executor()));
+    let python_lang = languages::language("python", tree_sitter_python::LANGUAGE.into());
+    language_registry.add(markdown_lang());
+    language_registry.add(python_lang);
+
+    let mut cx = EditorTestContext::new(cx).await;
+    cx.update_buffer(|buffer, cx| {
+        buffer.set_language_registry(language_registry);
+        buffer.set_language(Some(markdown_lang()), cx);
+    });
+
+    // Test that `else:` correctly outdents to match `if:` inside the Python code block
+    cx.set_state(indoc! {"
+        # Heading
+
+        ```python
+        def main():
+            if condition:
+                pass
+                ˇ
+        ```
+    "});
+    cx.update_editor(|editor, window, cx| {
+        editor.handle_input("else:", window, cx);
+    });
+    cx.run_until_parked();
+    cx.assert_editor_state(indoc! {"
+        # Heading
+
+        ```python
+        def main():
+            if condition:
+                pass
+            else:ˇ
+        ```
+    "});
+}
+
 #[gpui::test]
 async fn test_tab_in_leading_whitespace_auto_indents_for_bash(cx: &mut TestAppContext) {
     init_test(cx, |_| {});
@@ -25627,6 +26136,7 @@ async fn test_tab_in_leading_whitespace_auto_indents_for_bash(cx: &mut TestAppCo
         ˇ}
     "});
     cx.update_editor(|e, window, cx| e.tab(&Tab, window, cx));
+    cx.wait_for_autoindent_applied().await;
     cx.assert_editor_state(indoc! {"
         function main() {
             ˇfor item in $items; do

crates/editor/src/element.rs 🔗

@@ -11,6 +11,7 @@ use crate::{
     SelectedTextHighlight, Selection, SelectionDragState, SelectionEffects, SizingBehavior,
     SoftWrap, StickyHeaderExcerpt, ToPoint, ToggleFold, ToggleFoldAll,
     code_context_menus::{CodeActionsMenu, MENU_ASIDE_MAX_WIDTH, MENU_ASIDE_MIN_WIDTH, MENU_GAP},
+    column_pixels,
     display_map::{
         Block, BlockContext, BlockStyle, ChunkRendererId, DisplaySnapshot, EditorMargins,
         HighlightKey, HighlightedChunk, ToDisplayPoint,
@@ -36,22 +37,18 @@ use crate::{
 use buffer_diff::{DiffHunkStatus, DiffHunkStatusKind};
 use collections::{BTreeMap, HashMap};
 use file_icons::FileIcons;
-use git::{
-    Oid,
-    blame::{BlameEntry, ParsedCommitMessage},
-    status::FileStatus,
-};
+use git::{Oid, blame::BlameEntry, commit::ParsedCommitMessage, status::FileStatus};
 use gpui::{
     Action, Along, AnyElement, App, AppContext, AvailableSpace, Axis as ScrollbarAxis, BorderStyle,
     Bounds, ClickEvent, ClipboardItem, ContentMask, Context, Corner, Corners, CursorStyle,
     DispatchPhase, Edges, Element, ElementInputHandler, Entity, Focusable as _, FontId,
     GlobalElementId, Hitbox, HitboxBehavior, Hsla, InteractiveElement, IntoElement, IsZero,
     KeybindingKeystroke, Length, Modifiers, ModifiersChangedEvent, MouseButton, MouseClickEvent,
-    MouseDownEvent, MouseMoveEvent, MouseUpEvent, PaintQuad, ParentElement, Pixels, ScrollDelta,
-    ScrollHandle, ScrollWheelEvent, ShapedLine, SharedString, Size, StatefulInteractiveElement,
-    Style, Styled, TextRun, TextStyleRefinement, WeakEntity, Window, anchored, deferred, div, fill,
-    linear_color_stop, linear_gradient, outline, point, px, quad, relative, size, solid_background,
-    transparent_black,
+    MouseDownEvent, MouseMoveEvent, MousePressureEvent, MouseUpEvent, PaintQuad, ParentElement,
+    Pixels, PressureStage, ScrollDelta, ScrollHandle, ScrollWheelEvent, ShapedLine, SharedString,
+    Size, StatefulInteractiveElement, Style, Styled, TextAlign, TextRun, TextStyleRefinement,
+    WeakEntity, Window, anchored, deferred, div, fill, linear_color_stop, linear_gradient, outline,
+    point, px, quad, relative, size, solid_background, transparent_black,
 };
 use itertools::Itertools;
 use language::{IndentGuideSettings, language_settings::ShowWhitespaceSetting};
@@ -61,6 +58,7 @@ use multi_buffer::{
     MultiBufferRow, RowInfo,
 };
 
+use edit_prediction_types::EditPredictionGranularity;
 use project::{
     Entry, ProjectPath,
     debugger::breakpoint_store::{Breakpoint, BreakpointSessionState},
@@ -68,7 +66,7 @@ use project::{
 };
 use settings::{
     GitGutterSetting, GitHunkStyleSetting, IndentGuideBackgroundColoring, IndentGuideColoring,
-    Settings,
+    RelativeLineNumbers, Settings,
 };
 use smallvec::{SmallVec, smallvec};
 use std::{
@@ -131,6 +129,7 @@ impl SelectionLayout {
     fn new<T: ToPoint + ToDisplayPoint + Clone>(
         selection: Selection<T>,
         line_mode: bool,
+        cursor_offset: bool,
         cursor_shape: CursorShape,
         map: &DisplaySnapshot,
         is_newest: bool,
@@ -151,12 +150,9 @@ impl SelectionLayout {
         }
 
         // any vim visual mode (including line mode)
-        if (cursor_shape == CursorShape::Block || cursor_shape == CursorShape::Hollow)
-            && !range.is_empty()
-            && !selection.reversed
-        {
+        if cursor_offset && !range.is_empty() && !selection.reversed {
             if head.column() > 0 {
-                head = map.clip_point(DisplayPoint::new(head.row(), head.column() - 1), Bias::Left)
+                head = map.clip_point(DisplayPoint::new(head.row(), head.column() - 1), Bias::Left);
             } else if head.row().0 > 0 && head != map.max_point() {
                 head = map.clip_point(
                     DisplayPoint::new(
@@ -198,8 +194,6 @@ pub struct EditorElement {
     style: EditorStyle,
 }
 
-type DisplayRowDelta = u32;
-
 impl EditorElement {
     pub(crate) const SCROLLBAR_WIDTH: Pixels = px(15.);
 
@@ -253,6 +247,8 @@ impl EditorElement {
         register_action(editor, window, Editor::sort_lines_case_insensitive);
         register_action(editor, window, Editor::reverse_lines);
         register_action(editor, window, Editor::shuffle_lines);
+        register_action(editor, window, Editor::rotate_selections_forward);
+        register_action(editor, window, Editor::rotate_selections_backward);
         register_action(editor, window, Editor::convert_indentation_to_spaces);
         register_action(editor, window, Editor::convert_indentation_to_tabs);
         register_action(editor, window, Editor::convert_to_upper_case);
@@ -365,6 +361,7 @@ impl EditorElement {
         register_action(editor, window, Editor::split_selection_into_lines);
         register_action(editor, window, Editor::add_selection_above);
         register_action(editor, window, Editor::add_selection_below);
+        register_action(editor, window, Editor::insert_snippet_at_selections);
         register_action(editor, window, |editor, action, window, cx| {
             editor.select_next(action, window, cx).log_err();
         });
@@ -591,8 +588,6 @@ impl EditorElement {
         register_action(editor, window, Editor::show_signature_help);
         register_action(editor, window, Editor::signature_help_prev);
         register_action(editor, window, Editor::signature_help_next);
-        register_action(editor, window, Editor::next_edit_prediction);
-        register_action(editor, window, Editor::previous_edit_prediction);
         register_action(editor, window, Editor::show_edit_prediction);
         register_action(editor, window, Editor::context_menu_first);
         register_action(editor, window, Editor::context_menu_prev);
@@ -601,7 +596,8 @@ impl EditorElement {
         register_action(editor, window, Editor::display_cursor_names);
         register_action(editor, window, Editor::unique_lines_case_insensitive);
         register_action(editor, window, Editor::unique_lines_case_sensitive);
-        register_action(editor, window, Editor::accept_partial_edit_prediction);
+        register_action(editor, window, Editor::accept_next_word_edit_prediction);
+        register_action(editor, window, Editor::accept_next_line_edit_prediction);
         register_action(editor, window, Editor::accept_edit_prediction);
         register_action(editor, window, Editor::restore_file);
         register_action(editor, window, Editor::git_restore);
@@ -1013,10 +1009,16 @@ impl EditorElement {
         let pending_nonempty_selections = editor.has_pending_nonempty_selection();
 
         let hovered_link_modifier = Editor::is_cmd_or_ctrl_pressed(&event.modifiers(), cx);
+        let mouse_down_hovered_link_modifier = if let ClickEvent::Mouse(mouse_event) = event {
+            Editor::is_cmd_or_ctrl_pressed(&mouse_event.down.modifiers, cx)
+        } else {
+            true
+        };
 
         if let Some(mouse_position) = event.mouse_position()
             && !pending_nonempty_selections
             && hovered_link_modifier
+            && mouse_down_hovered_link_modifier
             && text_hitbox.is_hovered(window)
         {
             let point = position_map.point_for_position(mouse_position);
@@ -1027,6 +1029,28 @@ impl EditorElement {
         }
     }
 
+    fn pressure_click(
+        editor: &mut Editor,
+        event: &MousePressureEvent,
+        position_map: &PositionMap,
+        window: &mut Window,
+        cx: &mut Context<Editor>,
+    ) {
+        let text_hitbox = &position_map.text_hitbox;
+        let force_click_possible =
+            matches!(editor.prev_pressure_stage, Some(PressureStage::Normal))
+                && event.stage == PressureStage::Force;
+
+        editor.prev_pressure_stage = Some(event.stage);
+
+        if force_click_possible && text_hitbox.is_hovered(window) {
+            let point = position_map.point_for_position(event.position);
+            editor.handle_click_hovered_link(point, event.modifiers, window, cx);
+            editor.selection_drag_state = SelectionDragState::None;
+            cx.stop_propagation();
+        }
+    }
+
     fn mouse_dragged(
         editor: &mut Editor,
         event: &MouseMoveEvent,
@@ -1227,7 +1251,13 @@ impl EditorElement {
                 editor.hide_blame_popover(false, cx);
             }
         } else {
-            editor.hide_blame_popover(false, cx);
+            let keyboard_grace = editor
+                .inline_blame_popover
+                .as_ref()
+                .is_some_and(|state| state.keyboard_grace);
+            if !keyboard_grace {
+                editor.hide_blame_popover(false, cx);
+            }
         }
 
         let breakpoint_indicator = if gutter_hovered {
@@ -1425,6 +1455,7 @@ impl EditorElement {
                     let layout = SelectionLayout::new(
                         selection,
                         editor.selections.line_mode(),
+                        editor.cursor_offset_on_selection,
                         editor.cursor_shape,
                         &snapshot.display_snapshot,
                         is_newest,
@@ -1471,6 +1502,7 @@ impl EditorElement {
                     let drag_cursor_layout = SelectionLayout::new(
                         drop_cursor.clone(),
                         false,
+                        editor.cursor_offset_on_selection,
                         CursorShape::Bar,
                         &snapshot.display_snapshot,
                         false,
@@ -1534,6 +1566,7 @@ impl EditorElement {
                         .push(SelectionLayout::new(
                             selection.selection,
                             selection.line_mode,
+                            editor.cursor_offset_on_selection,
                             selection.cursor_shape,
                             &snapshot.display_snapshot,
                             false,
@@ -1544,6 +1577,8 @@ impl EditorElement {
 
                 selections.extend(remote_selections.into_values());
             } else if !editor.is_focused(window) && editor.show_cursor_when_unfocused {
+                let cursor_offset_on_selection = editor.cursor_offset_on_selection;
+
                 let layouts = snapshot
                     .buffer_snapshot()
                     .selections_in_range(&(start_anchor..end_anchor), true)
@@ -1551,6 +1586,7 @@ impl EditorElement {
                         SelectionLayout::new(
                             selection,
                             line_mode,
+                            cursor_offset_on_selection,
                             cursor_shape,
                             &snapshot.display_snapshot,
                             false,
@@ -1659,9 +1695,13 @@ impl EditorElement {
                         [cursor_position.row().minus(visible_display_row_range.start) as usize];
                     let cursor_column = cursor_position.column() as usize;
 
-                    let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
-                    let mut block_width =
-                        cursor_row_layout.x_for_index(cursor_column + 1) - cursor_character_x;
+                    let cursor_character_x = cursor_row_layout.x_for_index(cursor_column)
+                        + cursor_row_layout
+                            .alignment_offset(self.style.text.text_align, text_hitbox.size.width);
+                    let cursor_next_x = cursor_row_layout.x_for_index(cursor_column + 1)
+                        + cursor_row_layout
+                            .alignment_offset(self.style.text.text_align, text_hitbox.size.width);
+                    let mut block_width = cursor_next_x - cursor_character_x;
                     if block_width == Pixels::ZERO {
                         block_width = em_advance;
                     }
@@ -2260,7 +2300,8 @@ impl EditorElement {
         };
 
         let padding = ProjectSettings::get_global(cx).diagnostics.inline.padding as f32 * em_width;
-        let min_x = self.column_pixels(
+        let min_x = column_pixels(
+            &self.style,
             ProjectSettings::get_global(cx)
                 .diagnostics
                 .inline
@@ -2334,7 +2375,7 @@ impl EditorElement {
                     .opacity(0.05))
                 .text_color(severity_to_color(&diagnostic_to_render.severity).color(cx))
                 .text_sm()
-                .font_family(style.text.font().family)
+                .font(style.text.font())
                 .child(diagnostic_to_render.message.clone())
                 .into_any();
 
@@ -2511,7 +2552,6 @@ impl EditorElement {
         scroll_position: gpui::Point<ScrollOffset>,
         scroll_pixel_position: gpui::Point<ScrollPixelOffset>,
         line_height: Pixels,
-        text_hitbox: &Hitbox,
         window: &mut Window,
         cx: &mut App,
     ) -> Option<InlineBlameLayout> {
@@ -2564,7 +2604,8 @@ impl EditorElement {
 
             let padded_line_end = line_end + padding;
 
-            let min_column_in_pixels = self.column_pixels(
+            let min_column_in_pixels = column_pixels(
+                &self.style,
                 ProjectSettings::get_global(cx).git.inline_blame.min_column as usize,
                 window,
             );
@@ -2580,16 +2621,6 @@ impl EditorElement {
         let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
         let bounds = Bounds::new(absolute_offset, size);
 
-        self.layout_blame_entry_popover(
-            entry.clone(),
-            blame,
-            line_height,
-            text_hitbox,
-            row_info.buffer_id?,
-            window,
-            cx,
-        );
-
         element.prepaint_as_root(absolute_offset, AvailableSpace::min_size(), window, cx);
 
         Some(InlineBlameLayout {
@@ -2600,16 +2631,48 @@ impl EditorElement {
         })
     }
 
-    fn layout_blame_entry_popover(
+    fn layout_blame_popover(
         &self,
-        blame_entry: BlameEntry,
-        blame: Entity<GitBlame>,
-        line_height: Pixels,
+        editor_snapshot: &EditorSnapshot,
         text_hitbox: &Hitbox,
-        buffer: BufferId,
+        line_height: Pixels,
         window: &mut Window,
         cx: &mut App,
     ) {
+        if !self.editor.read(cx).inline_blame_popover.is_some() {
+            return;
+        }
+
+        let Some(blame) = self.editor.read(cx).blame.clone() else {
+            return;
+        };
+        let cursor_point = self
+            .editor
+            .read(cx)
+            .selections
+            .newest::<language::Point>(&editor_snapshot.display_snapshot)
+            .head();
+
+        let Some((buffer, buffer_point, _)) = editor_snapshot
+            .buffer_snapshot()
+            .point_to_buffer_point(cursor_point)
+        else {
+            return;
+        };
+
+        let row_info = RowInfo {
+            buffer_id: Some(buffer.remote_id()),
+            buffer_row: Some(buffer_point.row),
+            ..Default::default()
+        };
+
+        let Some((buffer_id, blame_entry)) = blame
+            .update(cx, |blame, cx| blame.blame_for_rows(&[row_info], cx).next())
+            .flatten()
+        else {
+            return;
+        };
+
         let Some((popover_state, target_point)) = self.editor.read_with(cx, |editor, _| {
             editor
                 .inline_blame_popover
@@ -2631,7 +2694,7 @@ impl EditorElement {
                 popover_state.markdown,
                 workspace,
                 &blame,
-                buffer,
+                buffer_id,
                 window,
                 cx,
             )
@@ -2766,7 +2829,7 @@ impl EditorElement {
                 .enumerate()
                 .filter_map(|(i, indent_guide)| {
                     let single_indent_width =
-                        self.column_pixels(indent_guide.tab_size as usize, window);
+                        column_pixels(&self.style, indent_guide.tab_size as usize, window);
                     let total_width = single_indent_width * indent_guide.depth as f32;
                     let start_x = Pixels::from(
                         ScrollOffset::from(content_origin.x + total_width)
@@ -2823,7 +2886,7 @@ impl EditorElement {
             .wrap_guides(cx)
             .into_iter()
             .flat_map(|(guide, active)| {
-                let wrap_position = self.column_pixels(guide, window);
+                let wrap_position = column_pixels(&self.style, guide, window);
                 let wrap_guide_x = wrap_position + horizontal_offset;
                 let display_wrap_guide = wrap_guide_x >= content_origin
                     && wrap_guide_x <= hitbox.bounds.right() - vertical_scrollbar_width;
@@ -3164,64 +3227,6 @@ impl EditorElement {
             .collect()
     }
 
-    fn calculate_relative_line_numbers(
-        &self,
-        snapshot: &EditorSnapshot,
-        rows: &Range<DisplayRow>,
-        relative_to: Option<DisplayRow>,
-        count_wrapped_lines: bool,
-    ) -> HashMap<DisplayRow, DisplayRowDelta> {
-        let mut relative_rows: HashMap<DisplayRow, DisplayRowDelta> = Default::default();
-        let Some(relative_to) = relative_to else {
-            return relative_rows;
-        };
-
-        let start = rows.start.min(relative_to);
-        let end = rows.end.max(relative_to);
-
-        let buffer_rows = snapshot
-            .row_infos(start)
-            .take(1 + end.minus(start) as usize)
-            .collect::<Vec<_>>();
-
-        let head_idx = relative_to.minus(start);
-        let mut delta = 1;
-        let mut i = head_idx + 1;
-        let should_count_line = |row_info: &RowInfo| {
-            if count_wrapped_lines {
-                row_info.buffer_row.is_some() || row_info.wrapped_buffer_row.is_some()
-            } else {
-                row_info.buffer_row.is_some()
-            }
-        };
-        while i < buffer_rows.len() as u32 {
-            if should_count_line(&buffer_rows[i as usize]) {
-                if rows.contains(&DisplayRow(i + start.0)) {
-                    relative_rows.insert(DisplayRow(i + start.0), delta);
-                }
-                delta += 1;
-            }
-            i += 1;
-        }
-        delta = 1;
-        i = head_idx.min(buffer_rows.len().saturating_sub(1) as u32);
-        while i > 0 && buffer_rows[i as usize].buffer_row.is_none() && !count_wrapped_lines {
-            i -= 1;
-        }
-
-        while i > 0 {
-            i -= 1;
-            if should_count_line(&buffer_rows[i as usize]) {
-                if rows.contains(&DisplayRow(i + start.0)) {
-                    relative_rows.insert(DisplayRow(i + start.0), delta);
-                }
-                delta += 1;
-            }
-        }
-
-        relative_rows
-    }
-
     fn layout_line_numbers(
         &self,
         gutter_hitbox: Option<&Hitbox>,
@@ -3231,7 +3236,7 @@ impl EditorElement {
         rows: Range<DisplayRow>,
         buffer_rows: &[RowInfo],
         active_rows: &BTreeMap<DisplayRow, LineHighlightSpec>,
-        newest_selection_head: Option<DisplayPoint>,
+        relative_line_base: Option<DisplayRow>,
         snapshot: &EditorSnapshot,
         window: &mut Window,
         cx: &mut App,
@@ -3243,31 +3248,16 @@ impl EditorElement {
             return Arc::default();
         }
 
-        let (newest_selection_head, relative) = self.editor.update(cx, |editor, cx| {
-            let newest_selection_head = newest_selection_head.unwrap_or_else(|| {
-                let newest = editor
-                    .selections
-                    .newest::<Point>(&editor.display_snapshot(cx));
-                SelectionLayout::new(
-                    newest,
-                    editor.selections.line_mode(),
-                    editor.cursor_shape,
-                    &snapshot.display_snapshot,
-                    true,
-                    true,
-                    None,
-                )
-                .head
-            });
-            let relative = editor.relative_line_numbers(cx);
-            (newest_selection_head, relative)
-        });
+        let relative = self.editor.read(cx).relative_line_numbers(cx);
 
         let relative_line_numbers_enabled = relative.enabled();
-        let relative_to = relative_line_numbers_enabled.then(|| newest_selection_head.row());
+        let relative_rows = if relative_line_numbers_enabled && let Some(base) = relative_line_base
+        {
+            snapshot.calculate_relative_line_numbers(&rows, base, relative.wrapped())
+        } else {
+            Default::default()
+        };
 
-        let relative_rows =
-            self.calculate_relative_line_numbers(snapshot, &rows, relative_to, relative.wrapped());
         let mut line_number = String::new();
         let segments = buffer_rows.iter().enumerate().flat_map(|(ix, row_info)| {
             let display_row = DisplayRow(rows.start.0 + ix as u32);
@@ -3886,6 +3876,8 @@ impl EditorElement {
     ) -> impl IntoElement {
         let editor = self.editor.read(cx);
         let multi_buffer = editor.buffer.read(cx);
+        let is_read_only = self.editor.read(cx).read_only(cx);
+
         let file_status = multi_buffer
             .all_diff_hunks_expanded()
             .then(|| editor.status_for_buffer_id(for_excerpt.buffer_id, cx))
@@ -3938,7 +3930,7 @@ impl EditorElement {
                     .gap_1p5()
                     .when(is_sticky, |el| el.shadow_md())
                     .border_1()
-                    .map(|div| {
+                    .map(|border| {
                         let border_color = if is_selected
                             && is_folded
                             && focus_handle.contains_focused(window, cx)
@@ -3947,7 +3939,7 @@ impl EditorElement {
                         } else {
                             colors.border
                         };
-                        div.border_color(border_color)
+                        border.border_color(border_color)
                     })
                     .bg(colors.editor_subheader_background)
                     .hover(|style| style.bg(colors.element_hover))
@@ -4027,13 +4019,15 @@ impl EditorElement {
                             })
                             .take(1),
                     )
-                    .child(
-                        h_flex()
-                            .size_3()
-                            .justify_center()
-                            .flex_shrink_0()
-                            .children(indicator),
-                    )
+                    .when(!is_read_only, |this| {
+                        this.child(
+                            h_flex()
+                                .size_3()
+                                .justify_center()
+                                .flex_shrink_0()
+                                .children(indicator),
+                        )
+                    })
                     .child(
                         h_flex()
                             .cursor_pointer()
@@ -4583,6 +4577,9 @@ impl EditorElement {
         gutter_dimensions: &GutterDimensions,
         gutter_hitbox: &Hitbox,
         text_hitbox: &Hitbox,
+        style: &EditorStyle,
+        relative_line_numbers: RelativeLineNumbers,
+        relative_to: Option<DisplayRow>,
         window: &mut Window,
         cx: &mut App,
     ) -> Option<StickyHeaders> {
@@ -4590,7 +4587,7 @@ impl EditorElement {
             .show_line_numbers
             .unwrap_or_else(|| EditorSettings::get_global(cx).gutter.line_numbers);
 
-        let rows = Self::sticky_headers(self.editor.read(cx), snapshot, cx);
+        let rows = Self::sticky_headers(self.editor.read(cx), snapshot, style, cx);
 
         let mut lines = Vec::<StickyHeaderLine>::new();
 
@@ -4612,9 +4609,21 @@ impl EditorElement {
             );
 
             let line_number = show_line_numbers.then(|| {
-                let number = (start_point.row + 1).to_string();
+                let relative_number = relative_to.and_then(|base| match relative_line_numbers {
+                    RelativeLineNumbers::Disabled => None,
+                    RelativeLineNumbers::Enabled => {
+                        Some(snapshot.relative_line_delta_to_point(base, start_point))
+                    }
+                    RelativeLineNumbers::Wrapped => {
+                        Some(snapshot.relative_wrapped_line_delta_to_point(base, start_point))
+                    }
+                });
+                let number = relative_number
+                    .filter(|&delta| delta != 0)
+                    .map(|delta| delta.unsigned_abs() as u32)
+                    .unwrap_or(start_point.row + 1);
                 let color = cx.theme().colors().editor_line_number;
-                self.shape_line_number(SharedString::from(number), color, window)
+                self.shape_line_number(SharedString::from(number.to_string()), color, window)
             });
 
             lines.push(StickyHeaderLine::new(
@@ -4649,6 +4658,7 @@ impl EditorElement {
     pub(crate) fn sticky_headers(
         editor: &Editor,
         snapshot: &EditorSnapshot,
+        style: &EditorStyle,
         cx: &App,
     ) -> Vec<StickyHeader> {
         let scroll_top = snapshot.scroll_position().y;
@@ -4656,7 +4666,7 @@ impl EditorElement {
         let mut end_rows = Vec::<DisplayRow>::new();
         let mut rows = Vec::<StickyHeader>::new();
 
-        let items = editor.sticky_headers(cx).unwrap_or_default();
+        let items = editor.sticky_headers(style, cx).unwrap_or_default();
 
         for item in items {
             let start_point = item.range.start.to_point(snapshot.buffer_snapshot());
@@ -4826,8 +4836,11 @@ impl EditorElement {
 
                 let edit_prediction = if edit_prediction_popover_visible {
                     self.editor.update(cx, move |editor, cx| {
-                        let accept_binding =
-                            editor.accept_edit_prediction_keybind(false, window, cx);
+                        let accept_binding = editor.accept_edit_prediction_keybind(
+                            EditPredictionGranularity::Full,
+                            window,
+                            cx,
+                        );
                         let mut element = editor.render_edit_prediction_cursor_popover(
                             min_width,
                             max_width,
@@ -5219,7 +5232,7 @@ impl EditorElement {
     ) -> Option<AnyElement> {
         let max_height_in_lines = ((height - POPOVER_Y_PADDING) / line_height).floor() as u32;
         self.editor.update(cx, |editor, cx| {
-            editor.render_context_menu(&self.style, max_height_in_lines, window, cx)
+            editor.render_context_menu(max_height_in_lines, window, cx)
         })
     }
 
@@ -5246,16 +5259,18 @@ impl EditorElement {
         window: &mut Window,
         cx: &mut App,
     ) -> Option<AnyElement> {
-        let position = self.editor.update(cx, |editor, _cx| {
+        let position = self.editor.update(cx, |editor, cx| {
             let visible_start_point = editor.display_to_pixel_point(
                 DisplayPoint::new(visible_range.start, 0),
                 editor_snapshot,
                 window,
+                cx,
             )?;
             let visible_end_point = editor.display_to_pixel_point(
                 DisplayPoint::new(visible_range.end, 0),
                 editor_snapshot,
                 window,
+                cx,
             )?;
 
             let mouse_context_menu = editor.mouse_context_menu.as_ref()?;
@@ -5263,7 +5278,8 @@ impl EditorElement {
                 MenuPosition::PinnedToScreen(point) => (None, point),
                 MenuPosition::PinnedToEditor { source, offset } => {
                     let source_display_point = source.to_display_point(editor_snapshot);
-                    let source_point = editor.to_pixel_point(source, editor_snapshot, window)?;
+                    let source_point =
+                        editor.to_pixel_point(source, editor_snapshot, window, cx)?;
                     let position = content_origin + source_point + offset;
                     (Some(source_display_point), position)
                 }
@@ -5341,6 +5357,12 @@ impl EditorElement {
                 .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
         );
 
+        // Don't show hover popovers when context menu is open to avoid overlap
+        let has_context_menu = self.editor.read(cx).mouse_context_menu.is_some();
+        if has_context_menu {
+            return;
+        }
+
         let hover_popovers = self.editor.update(cx, |editor, cx| {
             editor.hover_state.render(
                 snapshot,
@@ -6140,10 +6162,25 @@ impl EditorElement {
                     let color = cx.theme().colors().editor_hover_line_number;
 
                     let line = self.shape_line_number(shaped_line.text.clone(), color, window);
-                    line.paint(hitbox.origin, line_height, window, cx).log_err()
+                    line.paint(
+                        hitbox.origin,
+                        line_height,
+                        TextAlign::Left,
+                        None,
+                        window,
+                        cx,
+                    )
+                    .log_err()
                 } else {
                     shaped_line
-                        .paint(hitbox.origin, line_height, window, cx)
+                        .paint(
+                            hitbox.origin,
+                            line_height,
+                            TextAlign::Left,
+                            None,
+                            window,
+                            cx,
+                        )
                         .log_err()
                 }) else {
                     continue;
@@ -7232,23 +7269,27 @@ impl EditorElement {
                     .map(|row| {
                         let line_layout =
                             &layout.position_map.line_layouts[row.minus(start_row) as usize];
+                        let alignment_offset =
+                            line_layout.alignment_offset(layout.text_align, layout.content_width);
                         HighlightedRangeLine {
                             start_x: if row == range.start.row() {
                                 layout.content_origin.x
                                     + Pixels::from(
                                         ScrollPixelOffset::from(
-                                            line_layout.x_for_index(range.start.column() as usize),
+                                            line_layout.x_for_index(range.start.column() as usize)
+                                                + alignment_offset,
                                         ) - layout.position_map.scroll_pixel_position.x,
                                     )
                             } else {
-                                layout.content_origin.x
+                                layout.content_origin.x + alignment_offset
                                     - Pixels::from(layout.position_map.scroll_pixel_position.x)
                             },
                             end_x: if row == range.end.row() {
                                 layout.content_origin.x
                                     + Pixels::from(
                                         ScrollPixelOffset::from(
-                                            line_layout.x_for_index(range.end.column() as usize),
+                                            line_layout.x_for_index(range.end.column() as usize)
+                                                + alignment_offset,
                                         ) - layout.position_map.scroll_pixel_position.x,
                                     )
                             } else {
@@ -7256,6 +7297,7 @@ impl EditorElement {
                                     ScrollPixelOffset::from(
                                         layout.content_origin.x
                                             + line_layout.width
+                                            + alignment_offset
                                             + line_end_overshoot,
                                     ) - layout.position_map.scroll_pixel_position.x,
                                 )
@@ -7714,6 +7756,19 @@ impl EditorElement {
             }
         });
 
+        window.on_mouse_event({
+            let position_map = layout.position_map.clone();
+            let editor = self.editor.clone();
+
+            move |event: &MousePressureEvent, phase, window, cx| {
+                if phase == DispatchPhase::Bubble {
+                    editor.update(cx, |editor, cx| {
+                        Self::pressure_click(editor, &event, &position_map, window, cx);
+                    })
+                }
+            }
+        });
+
         window.on_mouse_event({
             let position_map = layout.position_map.clone();
             let editor = self.editor.clone();
@@ -7737,29 +7792,6 @@ impl EditorElement {
         });
     }
 
-    fn column_pixels(&self, column: usize, window: &Window) -> Pixels {
-        let style = &self.style;
-        let font_size = style.text.font_size.to_pixels(window.rem_size());
-        let layout = window.text_system().shape_line(
-            SharedString::from(" ".repeat(column)),
-            font_size,
-            &[TextRun {
-                len: column,
-                font: style.text.font(),
-                color: Hsla::default(),
-                ..Default::default()
-            }],
-            None,
-        );
-
-        layout.width
-    }
-
-    fn max_line_number_width(&self, snapshot: &EditorSnapshot, window: &mut Window) -> Pixels {
-        let digit_count = snapshot.widest_line_number().ilog10() + 1;
-        self.column_pixels(digit_count as usize, window)
-    }
-
     fn shape_line_number(
         &self,
         text: SharedString,
@@ -8506,8 +8538,15 @@ impl LineWithInvisibles {
         for fragment in &self.fragments {
             match fragment {
                 LineFragment::Text(line) => {
-                    line.paint(fragment_origin, line_height, window, cx)
-                        .log_err();
+                    line.paint(
+                        fragment_origin,
+                        line_height,
+                        layout.text_align,
+                        Some(layout.content_width),
+                        window,
+                        cx,
+                    )
+                    .log_err();
                     fragment_origin.x += line.width;
                 }
                 LineFragment::Element { size, .. } => {
@@ -8549,8 +8588,15 @@ impl LineWithInvisibles {
         for fragment in &self.fragments {
             match fragment {
                 LineFragment::Text(line) => {
-                    line.paint_background(fragment_origin, line_height, window, cx)
-                        .log_err();
+                    line.paint_background(
+                        fragment_origin,
+                        line_height,
+                        layout.text_align,
+                        Some(layout.content_width),
+                        window,
+                        cx,
+                    )
+                    .log_err();
                     fragment_origin.x += line.width;
                 }
                 LineFragment::Element { size, .. } => {
@@ -8599,7 +8645,7 @@ impl LineWithInvisibles {
                 [token_offset, token_end_offset],
                 Box::new(move |window: &mut Window, cx: &mut App| {
                     invisible_symbol
-                        .paint(origin, line_height, window, cx)
+                        .paint(origin, line_height, TextAlign::Left, None, window, cx)
                         .log_err();
                 }),
             )
@@ -8760,6 +8806,15 @@ impl LineWithInvisibles {
 
         None
     }
+
+    pub fn alignment_offset(&self, text_align: TextAlign, content_width: Pixels) -> Pixels {
+        let line_width = self.width;
+        match text_align {
+            TextAlign::Left => px(0.0),
+            TextAlign::Center => (content_width - line_width) / 2.0,
+            TextAlign::Right => content_width - line_width,
+        }
+    }
 }
 
 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -8907,8 +8962,6 @@ impl Element for EditorElement {
                         max_lines,
                     } => {
                         let editor_handle = cx.entity();
-                        let max_line_number_width =
-                            self.max_line_number_width(&editor.snapshot(window, cx), window);
                         window.request_measured_layout(
                             Style::default(),
                             move |known_dimensions, available_space, window, cx| {
@@ -8918,7 +8971,6 @@ impl Element for EditorElement {
                                             editor,
                                             min_lines,
                                             max_lines,
-                                            max_line_number_width,
                                             known_dimensions,
                                             available_space.width,
                                             window,
@@ -9005,15 +9057,10 @@ impl Element for EditorElement {
                         .gutter_dimensions(
                             font_id,
                             font_size,
-                            self.max_line_number_width(&snapshot, window),
+                            style,
+                            window,
                             cx,
-                        )
-                        .or_else(|| {
-                            self.editor.read(cx).offset_content.then(|| {
-                                GutterDimensions::default_with_margin(font_id, font_size, cx)
-                            })
-                        })
-                        .unwrap_or_default();
+                        );
                     let text_width = bounds.size.width - gutter_dimensions.width;
 
                     let settings = EditorSettings::get_global(cx);
@@ -9100,6 +9147,15 @@ impl Element for EditorElement {
                     let height_in_lines = f64::from(bounds.size.height / line_height);
                     let max_row = snapshot.max_point().row().as_f64();
 
+                    // Calculate how much of the editor is clipped by parent containers (e.g., List).
+                    // This allows us to only render lines that are actually visible, which is
+                    // critical for performance when large AutoHeight editors are inside Lists.
+                    let visible_bounds = window.content_mask().bounds;
+                    let clipped_top = (visible_bounds.origin.y - bounds.origin.y).max(px(0.));
+                    let clipped_top_in_lines = f64::from(clipped_top / line_height);
+                    let visible_height_in_lines =
+                        f64::from(visible_bounds.size.height / line_height);
+
                     // The max scroll position for the top of the window
                     let max_scroll_top = if matches!(
                         snapshot.mode,
@@ -9156,10 +9212,16 @@ impl Element for EditorElement {
                     let mut scroll_position = snapshot.scroll_position();
                     // The scroll position is a fractional point, the whole number of which represents
                     // the top of the window in terms of display rows.
-                    let start_row = DisplayRow(scroll_position.y as u32);
+                    // We add clipped_top_in_lines to skip rows that are clipped by parent containers,
+                    // but we don't modify scroll_position itself since the parent handles positioning.
                     let max_row = snapshot.max_point().row();
+                    let start_row = cmp::min(
+                        DisplayRow((scroll_position.y + clipped_top_in_lines).floor() as u32),
+                        max_row,
+                    );
                     let end_row = cmp::min(
-                        (scroll_position.y + height_in_lines).ceil() as u32,
+                        (scroll_position.y + clipped_top_in_lines + visible_height_in_lines).ceil()
+                            as u32,
                         max_row.next_row().0,
                     );
                     let end_row = DisplayRow(end_row);
@@ -9357,6 +9419,28 @@ impl Element for EditorElement {
                             window,
                             cx,
                         );
+
+                    // relative rows are based on newest selection, even outside the visible area
+                    let relative_row_base =  self.editor.update(cx, |editor, cx| {
+                        if editor.selections.count()==0 {
+                            return None;
+                        }
+                            let newest = editor
+                                .selections
+                                .newest::<Point>(&editor.display_snapshot(cx));
+                            Some(SelectionLayout::new(
+                                newest,
+                                editor.selections.line_mode(),
+                                editor.cursor_offset_on_selection,
+                                editor.cursor_shape,
+                                &snapshot.display_snapshot,
+                                true,
+                                true,
+                                None,
+                            )
+                            .head.row())
+                        });
+
                     let mut breakpoint_rows = self.editor.update(cx, |editor, cx| {
                         editor.active_breakpoints(start_row..end_row, window, cx)
                     });
@@ -9374,7 +9458,7 @@ impl Element for EditorElement {
                         start_row..end_row,
                         &row_infos,
                         &active_rows,
-                        newest_selection_head,
+                        relative_row_base,
                         &snapshot,
                         window,
                         cx,
@@ -9694,6 +9778,7 @@ impl Element for EditorElement {
                         && is_singleton
                         && EditorSettings::get_global(cx).sticky_scroll.enabled
                     {
+                        let relative = self.editor.read(cx).relative_line_numbers(cx);
                         self.layout_sticky_headers(
                             &snapshot,
                             editor_width,
@@ -9704,6 +9789,9 @@ impl Element for EditorElement {
                             &gutter_dimensions,
                             &gutter_hitbox,
                             &text_hitbox,
+                            &style,
+                            relative,
+                            relative_row_base,
                             window,
                             cx,
                         )
@@ -9811,7 +9899,6 @@ impl Element for EditorElement {
                                     scroll_position,
                                     scroll_pixel_position,
                                     line_height,
-                                    &text_hitbox,
                                     window,
                                     cx,
                                 ) {
@@ -10009,6 +10096,8 @@ impl Element for EditorElement {
                             window,
                             cx,
                         );
+
+                        self.layout_blame_popover(&snapshot, &hitbox, line_height, window, cx);
                     }
 
                     let mouse_context_menu = self.layout_mouse_context_menu(
@@ -10128,6 +10217,8 @@ impl Element for EditorElement {
                         em_width,
                         em_advance,
                         snapshot,
+                        text_align: self.style.text.text_align,
+                        content_width: text_hitbox.size.width,
                         gutter_hitbox: gutter_hitbox.clone(),
                         text_hitbox: text_hitbox.clone(),
                         inline_blame_bounds: inline_blame_layout
@@ -10181,6 +10272,8 @@ impl Element for EditorElement {
                         sticky_buffer_header,
                         sticky_headers,
                         expand_toggles,
+                        text_align: self.style.text.text_align,
+                        content_width: text_hitbox.size.width,
                     }
                 })
             })

crates/editor/src/git/blame.rs 🔗

@@ -1,11 +1,11 @@
 use crate::Editor;
-use anyhow::Result;
+use anyhow::{Context as _, Result};
 use collections::HashMap;
-use futures::StreamExt;
+
 use git::{
-    GitHostingProviderRegistry, GitRemote, Oid,
-    blame::{Blame, BlameEntry, ParsedCommitMessage},
-    parse_git_remote_url,
+    GitHostingProviderRegistry, Oid,
+    blame::{Blame, BlameEntry},
+    commit::ParsedCommitMessage,
 };
 use gpui::{
     AnyElement, App, AppContext as _, Context, Entity, Hsla, ScrollHandle, Subscription, Task,
@@ -494,76 +494,103 @@ impl GitBlame {
             self.changed_while_blurred = true;
             return;
         }
-        let blame = self.project.update(cx, |project, cx| {
-            let Some(multi_buffer) = self.multi_buffer.upgrade() else {
-                return Vec::new();
-            };
-            multi_buffer
-                .read(cx)
-                .all_buffer_ids()
-                .into_iter()
-                .filter_map(|id| {
-                    let buffer = multi_buffer.read(cx).buffer(id)?;
-                    let snapshot = buffer.read(cx).snapshot();
-                    let buffer_edits = buffer.update(cx, |buffer, _| buffer.subscribe());
-
-                    let blame_buffer = project.blame_buffer(&buffer, None, cx);
-                    Some(async move { (id, snapshot, buffer_edits, blame_buffer.await) })
-                })
-                .collect::<Vec<_>>()
-        });
-        let provider_registry = GitHostingProviderRegistry::default_global(cx);
+        let buffers_to_blame = self
+            .multi_buffer
+            .update(cx, |multi_buffer, _| {
+                multi_buffer
+                    .all_buffer_ids()
+                    .into_iter()
+                    .filter_map(|id| Some(multi_buffer.buffer(id)?.downgrade()))
+                    .collect::<Vec<_>>()
+            })
+            .unwrap_or_default();
+        let project = self.project.downgrade();
 
         self.task = cx.spawn(async move |this, cx| {
-            let (result, errors) = cx
-                .background_spawn({
-                    async move {
-                        let blame = futures::stream::iter(blame)
-                            .buffered(4)
-                            .collect::<Vec<_>>()
-                            .await;
-                        let mut res = vec![];
-                        let mut errors = vec![];
-                        for (id, snapshot, buffer_edits, blame) in blame {
-                            match blame {
-                                Ok(Some(Blame {
-                                    entries,
-                                    messages,
-                                    remote_url,
-                                })) => {
-                                    let entries = build_blame_entry_sum_tree(
-                                        entries,
-                                        snapshot.max_point().row,
-                                    );
-                                    let commit_details = parse_commit_messages(
-                                        messages,
-                                        remote_url,
-                                        provider_registry.clone(),
-                                    )
-                                    .await;
-
-                                    res.push((
+            let mut all_results = Vec::new();
+            let mut all_errors = Vec::new();
+
+            for buffers in buffers_to_blame.chunks(4) {
+                let blame = cx.update(|cx| {
+                    buffers
+                        .iter()
+                        .map(|buffer| {
+                            let buffer = buffer.upgrade().context("buffer was dropped")?;
+                            let project = project.upgrade().context("project was dropped")?;
+                            let id = buffer.read(cx).remote_id();
+                            let snapshot = buffer.read(cx).snapshot();
+                            let buffer_edits = buffer.update(cx, |buffer, _| buffer.subscribe());
+                            let remote_url = project
+                                .read(cx)
+                                .git_store()
+                                .read(cx)
+                                .repository_and_path_for_buffer_id(buffer.read(cx).remote_id(), cx)
+                                .and_then(|(repo, _)| repo.read(cx).default_remote_url());
+                            let blame_buffer = project
+                                .update(cx, |project, cx| project.blame_buffer(&buffer, None, cx));
+                            Ok(async move {
+                                (id, snapshot, buffer_edits, blame_buffer.await, remote_url)
+                            })
+                        })
+                        .collect::<Result<Vec<_>>>()
+                })??;
+                let provider_registry =
+                    cx.update(|cx| GitHostingProviderRegistry::default_global(cx))?;
+                let (results, errors) = cx
+                    .background_spawn({
+                        async move {
+                            let blame = futures::future::join_all(blame).await;
+                            let mut res = vec![];
+                            let mut errors = vec![];
+                            for (id, snapshot, buffer_edits, blame, remote_url) in blame {
+                                match blame {
+                                    Ok(Some(Blame { entries, messages })) => {
+                                        let entries = build_blame_entry_sum_tree(
+                                            entries,
+                                            snapshot.max_point().row,
+                                        );
+                                        let commit_details = messages
+                                            .into_iter()
+                                            .map(|(oid, message)| {
+                                                let parsed_commit_message =
+                                                    ParsedCommitMessage::parse(
+                                                        oid.to_string(),
+                                                        message,
+                                                        remote_url.as_deref(),
+                                                        Some(provider_registry.clone()),
+                                                    );
+                                                (oid, parsed_commit_message)
+                                            })
+                                            .collect();
+                                        res.push((
+                                            id,
+                                            snapshot,
+                                            buffer_edits,
+                                            Some(entries),
+                                            commit_details,
+                                        ));
+                                    }
+                                    Ok(None) => res.push((
                                         id,
                                         snapshot,
                                         buffer_edits,
-                                        Some(entries),
-                                        commit_details,
-                                    ));
+                                        None,
+                                        Default::default(),
+                                    )),
+                                    Err(e) => errors.push(e),
                                 }
-                                Ok(None) => {
-                                    res.push((id, snapshot, buffer_edits, None, Default::default()))
-                                }
-                                Err(e) => errors.push(e),
                             }
+                            (res, errors)
                         }
-                        (res, errors)
-                    }
-                })
-                .await;
+                    })
+                    .await;
+                all_results.extend(results);
+                all_errors.extend(errors)
+            }
 
             this.update(cx, |this, cx| {
                 this.buffers.clear();
-                for (id, snapshot, buffer_edits, entries, commit_details) in result {
+                for (id, snapshot, buffer_edits, entries, commit_details) in all_results {
                     let Some(entries) = entries else {
                         continue;
                     };
@@ -578,11 +605,11 @@ impl GitBlame {
                     );
                 }
                 cx.notify();
-                if !errors.is_empty() {
+                if !all_errors.is_empty() {
                     this.project.update(cx, |_, cx| {
                         if this.user_triggered {
-                            log::error!("failed to get git blame data: {errors:?}");
-                            let notification = errors
+                            log::error!("failed to get git blame data: {all_errors:?}");
+                            let notification = all_errors
                                 .into_iter()
                                 .format_with(",", |e, f| f(&format_args!("{:#}", e)))
                                 .to_string();
@@ -593,7 +620,7 @@ impl GitBlame {
                         } else {
                             // If we weren't triggered by a user, we just log errors in the background, instead of sending
                             // notifications.
-                            log::debug!("failed to get git blame data: {errors:?}");
+                            log::debug!("failed to get git blame data: {all_errors:?}");
                         }
                     })
                 }
@@ -654,55 +681,6 @@ fn build_blame_entry_sum_tree(entries: Vec<BlameEntry>, max_row: u32) -> SumTree
     entries
 }
 
-async fn parse_commit_messages(
-    messages: impl IntoIterator<Item = (Oid, String)>,
-    remote_url: Option<String>,
-    provider_registry: Arc<GitHostingProviderRegistry>,
-) -> HashMap<Oid, ParsedCommitMessage> {
-    let mut commit_details = HashMap::default();
-
-    let parsed_remote_url = remote_url
-        .as_deref()
-        .and_then(|remote_url| parse_git_remote_url(provider_registry, remote_url));
-
-    for (oid, message) in messages {
-        let permalink = if let Some((provider, git_remote)) = parsed_remote_url.as_ref() {
-            Some(provider.build_commit_permalink(
-                git_remote,
-                git::BuildCommitPermalinkParams {
-                    sha: oid.to_string().as_str(),
-                },
-            ))
-        } else {
-            None
-        };
-
-        let remote = parsed_remote_url
-            .as_ref()
-            .map(|(provider, remote)| GitRemote {
-                host: provider.clone(),
-                owner: remote.owner.clone().into(),
-                repo: remote.repo.clone().into(),
-            });
-
-        let pull_request = parsed_remote_url
-            .as_ref()
-            .and_then(|(provider, remote)| provider.extract_pull_request(remote, &message));
-
-        commit_details.insert(
-            oid,
-            ParsedCommitMessage {
-                message: message.into(),
-                permalink,
-                remote,
-                pull_request,
-            },
-        );
-    }
-
-    commit_details
-}
-
 #[cfg(test)]
 mod tests {
     use super::*;

crates/editor/src/hover_links.rs 🔗

@@ -9,8 +9,10 @@ use language::{Bias, ToOffset};
 use linkify::{LinkFinder, LinkKind};
 use lsp::LanguageServerId;
 use project::{InlayId, LocationLink, Project, ResolvedPath};
+use regex::Regex;
 use settings::Settings;
-use std::ops::Range;
+use std::{ops::Range, sync::LazyLock};
+use text::OffsetRangeExt;
 use theme::ActiveTheme as _;
 use util::{ResultExt, TryFutureExt as _, maybe};
 
@@ -168,7 +170,7 @@ impl Editor {
                     match EditorSettings::get_global(cx).go_to_definition_fallback {
                         GoToDefinitionFallback::None => None,
                         GoToDefinitionFallback::FindAllReferences => {
-                            editor.find_all_references(&FindAllReferences, window, cx)
+                            editor.find_all_references(&FindAllReferences::default(), window, cx)
                         }
                     }
                 })
@@ -216,7 +218,7 @@ impl Editor {
             self.hide_hovered_link(cx);
             if !hovered_link_state.links.is_empty() {
                 if !self.focus_handle.is_focused(window) {
-                    window.focus(&self.focus_handle);
+                    window.focus(&self.focus_handle, cx);
                 }
 
                 // exclude links pointing back to the current anchor
@@ -595,7 +597,8 @@ pub(crate) async fn find_file(
     let project = project?;
     let snapshot = buffer.read_with(cx, |buffer, _| buffer.snapshot()).ok()?;
     let scope = snapshot.language_scope_at(position);
-    let (range, candidate_file_path) = surrounding_filename(snapshot, position)?;
+    let (range, candidate_file_path) = surrounding_filename(&snapshot, position)?;
+    let candidate_len = candidate_file_path.len();
 
     async fn check_path(
         candidate_file_path: &str,
@@ -612,29 +615,66 @@ pub(crate) async fn find_file(
             .filter(|s| s.is_file())
     }
 
-    if let Some(existing_path) = check_path(&candidate_file_path, &project, buffer, cx).await {
-        return Some((range, existing_path));
+    let pattern_candidates = link_pattern_file_candidates(&candidate_file_path);
+
+    for (pattern_candidate, pattern_range) in &pattern_candidates {
+        if let Some(existing_path) = check_path(&pattern_candidate, &project, buffer, cx).await {
+            let offset_range = range.to_offset(&snapshot);
+            let actual_start = offset_range.start + pattern_range.start;
+            let actual_end = offset_range.end - (candidate_len - pattern_range.end);
+            return Some((
+                snapshot.anchor_before(actual_start)..snapshot.anchor_after(actual_end),
+                existing_path,
+            ));
+        }
     }
-
     if let Some(scope) = scope {
-        for suffix in scope.path_suffixes() {
-            if candidate_file_path.ends_with(format!(".{suffix}").as_str()) {
-                continue;
-            }
+        for (pattern_candidate, pattern_range) in pattern_candidates {
+            for suffix in scope.path_suffixes() {
+                if pattern_candidate.ends_with(format!(".{suffix}").as_str()) {
+                    continue;
+                }
 
-            let suffixed_candidate = format!("{candidate_file_path}.{suffix}");
-            if let Some(existing_path) = check_path(&suffixed_candidate, &project, buffer, cx).await
-            {
-                return Some((range, existing_path));
+                let suffixed_candidate = format!("{pattern_candidate}.{suffix}");
+                if let Some(existing_path) =
+                    check_path(&suffixed_candidate, &project, buffer, cx).await
+                {
+                    let offset_range = range.to_offset(&snapshot);
+                    let actual_start = offset_range.start + pattern_range.start;
+                    let actual_end = offset_range.end - (candidate_len - pattern_range.end);
+                    return Some((
+                        snapshot.anchor_before(actual_start)..snapshot.anchor_after(actual_end),
+                        existing_path,
+                    ));
+                }
             }
         }
     }
-
     None
 }
 
+// Tries to capture potentially inlined links, like those found in markdown,
+// e.g. [LinkTitle](link_file.txt)
+// Since files can have parens, we should always return the full string
+// (literally, [LinkTitle](link_file.txt)) as a candidate.
+fn link_pattern_file_candidates(candidate: &str) -> Vec<(String, Range<usize>)> {
+    static MD_LINK_REGEX: LazyLock<Regex> =
+        LazyLock::new(|| Regex::new(r"\(([^)]*)\)").expect("Failed to create REGEX"));
+
+    let candidate_len = candidate.len();
+
+    let mut candidates = vec![(candidate.to_string(), 0..candidate_len)];
+
+    if let Some(captures) = MD_LINK_REGEX.captures(candidate) {
+        if let Some(link) = captures.get(1) {
+            candidates.push((link.as_str().to_string(), link.range()));
+        }
+    }
+    candidates
+}
+
 fn surrounding_filename(
-    snapshot: language::BufferSnapshot,
+    snapshot: &language::BufferSnapshot,
     position: text::Anchor,
 ) -> Option<(Range<text::Anchor>, String)> {
     const LIMIT: usize = 2048;
@@ -735,7 +775,7 @@ mod tests {
         test::editor_lsp_test_context::EditorLspTestContext,
     };
     use futures::StreamExt;
-    use gpui::Modifiers;
+    use gpui::{Modifiers, MousePressureEvent, PressureStage};
     use indoc::indoc;
     use lsp::request::{GotoDefinition, GotoTypeDefinition};
     use multi_buffer::MultiBufferOffset;
@@ -1316,6 +1356,58 @@ mod tests {
         assert_eq!(cx.opened_url(), Some("https://zed.dev/releases".into()));
     }
 
+    #[test]
+    fn test_link_pattern_file_candidates() {
+        let candidates: Vec<String> = link_pattern_file_candidates("[LinkTitle](link_file.txt)")
+            .into_iter()
+            .map(|(c, _)| c)
+            .collect();
+        assert_eq!(
+            candidates,
+            vec!["[LinkTitle](link_file.txt)", "link_file.txt",]
+        );
+        // Link title with spaces in it
+        let candidates: Vec<String> = link_pattern_file_candidates("LinkTitle](link_file.txt)")
+            .into_iter()
+            .map(|(c, _)| c)
+            .collect();
+        assert_eq!(
+            candidates,
+            vec!["LinkTitle](link_file.txt)", "link_file.txt",]
+        );
+
+        // Link with spaces
+        let candidates: Vec<String> = link_pattern_file_candidates("LinkTitle](link\\ _file.txt)")
+            .into_iter()
+            .map(|(c, _)| c)
+            .collect();
+
+        assert_eq!(
+            candidates,
+            vec!["LinkTitle](link\\ _file.txt)", "link\\ _file.txt",]
+        );
+        //
+        // Square brackets not strictly necessary
+        let candidates: Vec<String> = link_pattern_file_candidates("(link_file.txt)")
+            .into_iter()
+            .map(|(c, _)| c)
+            .collect();
+
+        assert_eq!(candidates, vec!["(link_file.txt)", "link_file.txt",]);
+
+        // No nesting
+        let candidates: Vec<String> =
+            link_pattern_file_candidates("LinkTitle](link_(link_file)file.txt)")
+                .into_iter()
+                .map(|(c, _)| c)
+                .collect();
+
+        assert_eq!(
+            candidates,
+            vec!["LinkTitle](link_(link_file)file.txt)", "link_(link_file",]
+        )
+    }
+
     #[gpui::test]
     async fn test_surrounding_filename(cx: &mut gpui::TestAppContext) {
         init_test(cx, |_| {});
@@ -1374,7 +1466,7 @@ mod tests {
                 (positions, snapshot)
             });
 
-            let result = surrounding_filename(snapshot, position);
+            let result = surrounding_filename(&snapshot, position);
 
             if let Some(expected) = expected {
                 assert!(result.is_some(), "Failed to find file path: {}", input);
@@ -1706,4 +1798,77 @@ mod tests {
         cx.simulate_click(screen_coord, Modifiers::secondary_key());
         cx.update_workspace(|workspace, _, cx| assert_eq!(workspace.items(cx).count(), 1));
     }
+
+    #[gpui::test]
+    async fn test_pressure_links(cx: &mut gpui::TestAppContext) {
+        init_test(cx, |_| {});
+
+        let mut cx = EditorLspTestContext::new_rust(
+            lsp::ServerCapabilities {
+                hover_provider: Some(lsp::HoverProviderCapability::Simple(true)),
+                definition_provider: Some(lsp::OneOf::Left(true)),
+                ..Default::default()
+            },
+            cx,
+        )
+        .await;
+
+        cx.set_state(indoc! {"
+                    fn ˇtest() { do_work(); }
+                    fn do_work() { test(); }
+                "});
+
+        // Position the mouse over a symbol that has a definition
+        let hover_point = cx.pixel_position(indoc! {"
+                    fn test() { do_wˇork(); }
+                    fn do_work() { test(); }
+                "});
+        let symbol_range = cx.lsp_range(indoc! {"
+                    fn test() { «do_work»(); }
+                    fn do_work() { test(); }
+                "});
+        let target_range = cx.lsp_range(indoc! {"
+                    fn test() { do_work(); }
+                    fn «do_work»() { test(); }
+                "});
+
+        let mut requests =
+            cx.set_request_handler::<GotoDefinition, _, _>(move |url, _, _| async move {
+                Ok(Some(lsp::GotoDefinitionResponse::Link(vec![
+                    lsp::LocationLink {
+                        origin_selection_range: Some(symbol_range),
+                        target_uri: url.clone(),
+                        target_range,
+                        target_selection_range: target_range,
+                    },
+                ])))
+            });
+
+        cx.simulate_mouse_move(hover_point, None, Modifiers::none());
+
+        // First simulate Normal pressure to set up the previous stage
+        cx.simulate_event(MousePressureEvent {
+            pressure: 0.5,
+            stage: PressureStage::Normal,
+            position: hover_point,
+            modifiers: Modifiers::none(),
+        });
+        cx.background_executor.run_until_parked();
+
+        // Now simulate Force pressure to trigger the force click and go-to definition
+        cx.simulate_event(MousePressureEvent {
+            pressure: 1.0,
+            stage: PressureStage::Force,
+            position: hover_point,
+            modifiers: Modifiers::none(),
+        });
+        requests.next().await;
+        cx.background_executor.run_until_parked();
+
+        // Assert that we navigated to the definition
+        cx.assert_editor_state(indoc! {"
+                    fn test() { do_work(); }
+                    fn «do_workˇ»() { test(); }
+                "});
+    }
 }

crates/editor/src/hover_popover.rs 🔗

@@ -151,7 +151,7 @@ pub fn hover_at_inlay(
                 false
             })
         {
-            hide_hover(editor, cx);
+            return;
         }
 
         let hover_popover_delay = EditorSettings::get_global(cx).hover_popover_delay.0;
@@ -518,7 +518,7 @@ fn show_hover(
                     // Highlight the selected symbol using a background highlight
                     editor.highlight_background::<HoverState>(
                         &hover_highlights,
-                        |theme| theme.colors().element_hover, // todo update theme
+                        |_, theme| theme.colors().element_hover, // todo update theme
                         cx,
                     );
                 }
@@ -607,23 +607,30 @@ async fn parse_blocks(
 pub fn hover_markdown_style(window: &Window, cx: &App) -> MarkdownStyle {
     let settings = ThemeSettings::get_global(cx);
     let ui_font_family = settings.ui_font.family.clone();
+    let ui_font_features = settings.ui_font.features.clone();
     let ui_font_fallbacks = settings.ui_font.fallbacks.clone();
     let buffer_font_family = settings.buffer_font.family.clone();
+    let buffer_font_features = settings.buffer_font.features.clone();
     let buffer_font_fallbacks = settings.buffer_font.fallbacks.clone();
 
     let mut base_text_style = window.text_style();
     base_text_style.refine(&TextStyleRefinement {
         font_family: Some(ui_font_family),
+        font_features: Some(ui_font_features),
         font_fallbacks: ui_font_fallbacks,
         color: Some(cx.theme().colors().editor_foreground),
         ..Default::default()
     });
     MarkdownStyle {
         base_text_style,
-        code_block: StyleRefinement::default().my(rems(1.)).font_buffer(cx),
+        code_block: StyleRefinement::default()
+            .my(rems(1.))
+            .font_buffer(cx)
+            .font_features(buffer_font_features.clone()),
         inline_code: TextStyleRefinement {
             background_color: Some(cx.theme().colors().background),
             font_family: Some(buffer_font_family),
+            font_features: Some(buffer_font_features),
             font_fallbacks: buffer_font_fallbacks,
             ..Default::default()
         },
@@ -649,6 +656,7 @@ pub fn hover_markdown_style(window: &Window, cx: &App) -> MarkdownStyle {
             .text_base()
             .mt(rems(1.))
             .mb_0(),
+        table_columns_min_size: true,
         ..Default::default()
     }
 }
@@ -657,12 +665,15 @@ pub fn diagnostics_markdown_style(window: &Window, cx: &App) -> MarkdownStyle {
     let settings = ThemeSettings::get_global(cx);
     let ui_font_family = settings.ui_font.family.clone();
     let ui_font_fallbacks = settings.ui_font.fallbacks.clone();
+    let ui_font_features = settings.ui_font.features.clone();
     let buffer_font_family = settings.buffer_font.family.clone();
+    let buffer_font_features = settings.buffer_font.features.clone();
     let buffer_font_fallbacks = settings.buffer_font.fallbacks.clone();
 
     let mut base_text_style = window.text_style();
     base_text_style.refine(&TextStyleRefinement {
         font_family: Some(ui_font_family),
+        font_features: Some(ui_font_features),
         font_fallbacks: ui_font_fallbacks,
         color: Some(cx.theme().colors().editor_foreground),
         ..Default::default()
@@ -673,6 +684,7 @@ pub fn diagnostics_markdown_style(window: &Window, cx: &App) -> MarkdownStyle {
         inline_code: TextStyleRefinement {
             background_color: Some(cx.theme().colors().editor_background.opacity(0.5)),
             font_family: Some(buffer_font_family),
+            font_features: Some(buffer_font_features),
             font_fallbacks: buffer_font_fallbacks,
             ..Default::default()
         },
@@ -698,6 +710,7 @@ pub fn diagnostics_markdown_style(window: &Window, cx: &App) -> MarkdownStyle {
             .font_weight(FontWeight::BOLD)
             .text_base()
             .mb_0(),
+        table_columns_min_size: true,
         ..Default::default()
     }
 }

crates/editor/src/indent_guides.rs 🔗

@@ -181,6 +181,10 @@ pub fn indent_guides_in_range(
         .buffer_snapshot()
         .indent_guides_in_range(start_anchor..end_anchor, ignore_disabled_for_language, cx)
         .filter(|indent_guide| {
+            if editor.has_indent_guides_disabled_for_buffer(indent_guide.buffer_id) {
+                return false;
+            }
+
             if editor.is_buffer_folded(indent_guide.buffer_id, cx) {
                 return false;
             }

crates/editor/src/items.rs 🔗

@@ -17,8 +17,8 @@ use gpui::{
     ParentElement, Pixels, SharedString, Styled, Task, WeakEntity, Window, point,
 };
 use language::{
-    Bias, Buffer, BufferRow, CharKind, CharScopeContext, DiskState, LocalFile, Point,
-    SelectionGoal, proto::serialize_anchor as serialize_text_anchor,
+    Bias, Buffer, BufferRow, CharKind, CharScopeContext, LocalFile, Point, SelectionGoal,
+    proto::serialize_anchor as serialize_text_anchor,
 };
 use lsp::DiagnosticSeverity;
 use multi_buffer::MultiBufferOffset;
@@ -722,7 +722,7 @@ impl Item for Editor {
             .read(cx)
             .as_singleton()
             .and_then(|buffer| buffer.read(cx).file())
-            .is_some_and(|file| file.disk_state() == DiskState::Deleted);
+            .is_some_and(|file| file.disk_state().is_deleted());
 
         h_flex()
             .gap_2()
@@ -842,7 +842,6 @@ impl Item for Editor {
             .map(|handle| handle.read(cx).base_buffer().unwrap_or(handle.clone()))
             .collect::<HashSet<_>>();
 
-        // let mut buffers_to_save =
         let buffers_to_save = if self.buffer.read(cx).is_singleton() && !options.autosave {
             buffers
         } else {
@@ -1487,6 +1486,7 @@ impl SearchableItem for Editor {
     fn update_matches(
         &mut self,
         matches: &[Range<Anchor>],
+        active_match_index: Option<usize>,
         _: &mut Window,
         cx: &mut Context<Self>,
     ) {
@@ -1497,7 +1497,13 @@ impl SearchableItem for Editor {
         let updated = existing_range != Some(matches);
         self.highlight_background::<BufferSearchHighlights>(
             matches,
-            |theme| theme.colors().search_match_background,
+            move |index, theme| {
+                if active_match_index == Some(*index) {
+                    theme.colors().search_active_match_background
+                } else {
+                    theme.colors().search_match_background
+                }
+            },
             cx,
         );
         if updated {
@@ -1891,15 +1897,20 @@ fn path_for_buffer<'a>(
     cx: &'a App,
 ) -> Option<Cow<'a, str>> {
     let file = buffer.read(cx).as_singleton()?.read(cx).file()?;
-    path_for_file(file.as_ref(), height, include_filename, cx)
+    path_for_file(file, height, include_filename, cx)
 }
 
 fn path_for_file<'a>(
-    file: &'a dyn language::File,
+    file: &'a Arc<dyn language::File>,
     mut height: usize,
     include_filename: bool,
     cx: &'a App,
 ) -> Option<Cow<'a, str>> {
+    if project::File::from_dyn(Some(file)).is_none() {
+        return None;
+    }
+
+    let file = file.as_ref();
     // Ensure we always render at least the filename.
     height += 1;
 
@@ -1939,18 +1950,18 @@ mod tests {
     use super::*;
     use fs::MTime;
     use gpui::{App, VisualTestContext};
-    use language::{LanguageMatcher, TestFile};
+    use language::TestFile;
     use project::FakeFs;
     use std::path::{Path, PathBuf};
     use util::{path, rel_path::RelPath};
 
     #[gpui::test]
     fn test_path_for_file(cx: &mut App) {
-        let file = TestFile {
+        let file: Arc<dyn language::File> = Arc::new(TestFile {
             path: RelPath::empty().into(),
             root_name: String::new(),
             local_root: None,
-        };
+        });
         assert_eq!(path_for_file(&file, 0, false, cx), None);
     }
 
@@ -1979,20 +1990,6 @@ mod tests {
             .unwrap()
     }
 
-    fn rust_language() -> Arc<language::Language> {
-        Arc::new(language::Language::new(
-            language::LanguageConfig {
-                name: "Rust".into(),
-                matcher: LanguageMatcher {
-                    path_suffixes: vec!["rs".to_string()],
-                    ..Default::default()
-                },
-                ..Default::default()
-            },
-            Some(tree_sitter_rust::LANGUAGE.into()),
-        ))
-    }
-
     #[gpui::test]
     async fn test_deserialize(cx: &mut gpui::TestAppContext) {
         init_test(cx, |_| {});
@@ -2074,7 +2071,9 @@ mod tests {
         {
             let project = Project::test(fs.clone(), [path!("/file.rs").as_ref()], cx).await;
             // Add Rust to the language, so that we can restore the language of the buffer
-            project.read_with(cx, |project, _| project.languages().add(rust_language()));
+            project.read_with(cx, |project, _| {
+                project.languages().add(languages::rust_lang())
+            });
 
             let (workspace, cx) =
                 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));

crates/editor/src/jsx_tag_auto_close.rs 🔗

@@ -19,7 +19,7 @@ pub struct JsxTagCompletionState {
 /// that corresponds to the tag name
 /// Note that this is not configurable, i.e. we assume the first
 /// named child of a tag node is the tag name
-const TS_NODE_TAG_NAME_CHILD_INDEX: usize = 0;
+const TS_NODE_TAG_NAME_CHILD_INDEX: u32 = 0;
 
 /// Maximum number of parent elements to walk back when checking if an open tag
 /// is already closed.

crates/editor/src/mouse_context_menu.rs 🔗

@@ -59,7 +59,7 @@ impl MouseContextMenu {
                 x: editor.gutter_dimensions.width,
                 y: Pixels::ZERO,
             };
-        let source_position = editor.to_pixel_point(source, &editor_snapshot, window)?;
+        let source_position = editor.to_pixel_point(source, &editor_snapshot, window, cx)?;
         let menu_position = MenuPosition::PinnedToEditor {
             source,
             offset: position - (source_position + content_origin),
@@ -90,8 +90,8 @@ impl MouseContextMenu {
         // `true` when the `ContextMenu` is focused.
         let focus_handle = context_menu_focus.clone();
         cx.on_next_frame(window, move |_, window, cx| {
-            cx.on_next_frame(window, move |_, window, _cx| {
-                window.focus(&focus_handle);
+            cx.on_next_frame(window, move |_, window, cx| {
+                window.focus(&focus_handle, cx);
             });
         });
 
@@ -100,7 +100,7 @@ impl MouseContextMenu {
             move |editor, _, _event: &DismissEvent, window, cx| {
                 editor.mouse_context_menu.take();
                 if context_menu_focus.contains_focused(window, cx) {
-                    window.focus(&editor.focus_handle(cx));
+                    window.focus(&editor.focus_handle(cx), cx);
                 }
             }
         });
@@ -127,7 +127,7 @@ impl MouseContextMenu {
                 }
                 editor.mouse_context_menu.take();
                 if context_menu_focus.contains_focused(window, cx) {
-                    window.focus(&editor.focus_handle(cx));
+                    window.focus(&editor.focus_handle(cx), cx);
                 }
             },
         );
@@ -161,12 +161,7 @@ pub fn deploy_context_menu(
     cx: &mut Context<Editor>,
 ) {
     if !editor.is_focused(window) {
-        window.focus(&editor.focus_handle(cx));
-    }
-
-    // Don't show context menu for inline editors
-    if !editor.mode().is_full() {
-        return;
+        window.focus(&editor.focus_handle(cx), cx);
     }
 
     let display_map = editor.display_snapshot(cx);
@@ -179,6 +174,11 @@ pub fn deploy_context_menu(
         };
         menu
     } else {
+        // Don't show context menu for inline editors (only applies to default menu)
+        if !editor.mode().is_full() {
+            return;
+        }
+
         // Don't show the context menu if there isn't a project associated with this editor
         let Some(project) = editor.project.clone() else {
             return;
@@ -235,7 +235,10 @@ pub fn deploy_context_menu(
                 .action("Go to Declaration", Box::new(GoToDeclaration))
                 .action("Go to Type Definition", Box::new(GoToTypeDefinition))
                 .action("Go to Implementation", Box::new(GoToImplementation))
-                .action("Find All References", Box::new(FindAllReferences))
+                .action(
+                    "Find All References",
+                    Box::new(FindAllReferences::default()),
+                )
                 .separator()
                 .action("Rename Symbol", Box::new(Rename))
                 .action("Format Buffer", Box::new(Format))
@@ -277,7 +280,11 @@ pub fn deploy_context_menu(
                     "Copy Permalink",
                     Box::new(CopyPermalinkToLine),
                 )
-                .action_disabled_when(!has_git_repo, "File History", Box::new(git::FileHistory));
+                .action_disabled_when(
+                    !has_git_repo,
+                    "View File History",
+                    Box::new(git::FileHistory),
+                );
             match focus {
                 Some(focus) => builder.context(focus),
                 None => builder,

crates/editor/src/scroll.rs 🔗

@@ -251,7 +251,11 @@ impl ScrollManager {
                 Bias::Left,
             )
             .to_point(map);
-        let top_anchor = map.buffer_snapshot().anchor_after(scroll_top_buffer_point);
+        // Anchor the scroll position to the *left* of the first visible buffer point.
+        //
+        // This prevents the viewport from shifting down when blocks (e.g. expanded diff hunk
+        // deletions) are inserted *above* the first buffer character in the file.
+        let top_anchor = map.buffer_snapshot().anchor_before(scroll_top_buffer_point);
 
         self.set_anchor(
             ScrollAnchor {

crates/editor/src/scroll/autoscroll.rs 🔗

@@ -5,7 +5,7 @@ use crate::{
 };
 use gpui::{Bounds, Context, Pixels, Window};
 use language::Point;
-use multi_buffer::Anchor;
+use multi_buffer::{Anchor, ToPoint};
 use std::cmp;
 
 #[derive(Debug, PartialEq, Eq, Clone, Copy)]
@@ -186,6 +186,19 @@ impl Editor {
             }
         }
 
+        let style = self.style(cx).clone();
+        let sticky_headers = self.sticky_headers(&style, cx).unwrap_or_default();
+        let visible_sticky_headers = sticky_headers
+            .iter()
+            .filter(|h| {
+                let buffer_snapshot = display_map.buffer_snapshot();
+                let buffer_range =
+                    h.range.start.to_point(buffer_snapshot)..h.range.end.to_point(buffer_snapshot);
+
+                buffer_range.contains(&Point::new(target_top as u32, 0))
+            })
+            .count();
+
         let margin = if matches!(self.mode, EditorMode::AutoHeight { .. }) {
             0.
         } else {
@@ -218,7 +231,7 @@ impl Editor {
         let was_autoscrolled = match strategy {
             AutoscrollStrategy::Fit | AutoscrollStrategy::Newest => {
                 let margin = margin.min(self.scroll_manager.vertical_scroll_margin);
-                let target_top = (target_top - margin).max(0.0);
+                let target_top = (target_top - margin - visible_sticky_headers as f64).max(0.0);
                 let target_bottom = target_bottom + margin;
                 let start_row = scroll_position.y;
                 let end_row = start_row + visible_lines;

crates/editor/src/selections_collection.rs 🔗

@@ -136,7 +136,13 @@ impl SelectionsCollection {
         iter::from_fn(move || {
             if let Some(pending) = pending_opt.as_mut() {
                 while let Some(next_selection) = disjoint.peek() {
-                    if pending.start <= next_selection.end && pending.end >= next_selection.start {
+                    if should_merge(
+                        pending.start,
+                        pending.end,
+                        next_selection.start,
+                        next_selection.end,
+                        false,
+                    ) {
                         let next_selection = disjoint.next().unwrap();
                         if next_selection.start < pending.start {
                             pending.start = next_selection.start;
@@ -236,7 +242,13 @@ impl SelectionsCollection {
         iter::from_fn(move || {
             if let Some(pending) = pending_opt.as_mut() {
                 while let Some(next_selection) = disjoint.peek() {
-                    if pending.start <= next_selection.end && pending.end >= next_selection.start {
+                    if should_merge(
+                        pending.start,
+                        pending.end,
+                        next_selection.start,
+                        next_selection.end,
+                        false,
+                    ) {
                         let next_selection = disjoint.next().unwrap();
                         if next_selection.start < pending.start {
                             pending.start = next_selection.start;
@@ -419,22 +431,30 @@ impl SelectionsCollection {
             mutable_collection.disjoint.iter().for_each(|selection| {
                 assert!(
                     snapshot.can_resolve(&selection.start),
-                    "disjoint selection start is not resolvable for the given snapshot:\n{selection:?}",
+                    "disjoint selection start is not resolvable for the given snapshot:\n{selection:?}, {excerpt:?}",
+                    excerpt = snapshot.buffer_for_excerpt(selection.start.excerpt_id).map(|snapshot| snapshot.remote_id()),
                 );
                 assert!(
                     snapshot.can_resolve(&selection.end),
-                    "disjoint selection end is not resolvable for the given snapshot: {selection:?}",
+                    "disjoint selection end is not resolvable for the given snapshot: {selection:?}, {excerpt:?}",
+                    excerpt = snapshot.buffer_for_excerpt(selection.end.excerpt_id).map(|snapshot| snapshot.remote_id()),
                 );
             });
             if let Some(pending) = &mutable_collection.pending {
                 let selection = &pending.selection;
                 assert!(
                     snapshot.can_resolve(&selection.start),
-                    "pending selection start is not resolvable for the given snapshot: {pending:?}",
+                    "pending selection start is not resolvable for the given snapshot: {pending:?}, {excerpt:?}",
+                    excerpt = snapshot
+                        .buffer_for_excerpt(selection.start.excerpt_id)
+                        .map(|snapshot| snapshot.remote_id()),
                 );
                 assert!(
                     snapshot.can_resolve(&selection.end),
-                    "pending selection end is not resolvable for the given snapshot: {pending:?}",
+                    "pending selection end is not resolvable for the given snapshot: {pending:?}, {excerpt:?}",
+                    excerpt = snapshot
+                        .buffer_for_excerpt(selection.end.excerpt_id)
+                        .map(|snapshot| snapshot.remote_id()),
                 );
             }
         }
@@ -532,11 +552,18 @@ impl<'snap, 'a> MutableSelectionsCollection<'snap, 'a> {
         };
 
         if filtered_selections.is_empty() {
-            let default_anchor = self.snapshot.anchor_before(MultiBufferOffset(0));
+            let buffer_snapshot = self.snapshot.buffer_snapshot();
+            let anchor = buffer_snapshot
+                .excerpts()
+                .find(|(_, buffer, _)| buffer.remote_id() == buffer_id)
+                .and_then(|(excerpt_id, _, range)| {
+                    buffer_snapshot.anchor_in_excerpt(excerpt_id, range.context.start)
+                })
+                .unwrap_or_else(|| self.snapshot.anchor_before(MultiBufferOffset(0)));
             self.collection.disjoint = Arc::from([Selection {
                 id: post_inc(&mut self.collection.next_selection_id),
-                start: default_anchor,
-                end: default_anchor,
+                start: anchor,
+                end: anchor,
                 reversed: false,
                 goal: SelectionGoal::None,
             }]);
@@ -651,10 +678,13 @@ impl<'snap, 'a> MutableSelectionsCollection<'snap, 'a> {
             })
             .collect::<Vec<_>>();
         selections.sort_unstable_by_key(|s| s.start);
-        // Merge overlapping selections.
+
         let mut i = 1;
         while i < selections.len() {
-            if selections[i].start <= selections[i - 1].end {
+            let prev = &selections[i - 1];
+            let current = &selections[i];
+
+            if should_merge(prev.start, prev.end, current.start, current.end, true) {
                 let removed = selections.remove(i);
                 if removed.start < selections[i - 1].start {
                     selections[i - 1].start = removed.start;
@@ -1124,7 +1154,13 @@ fn coalesce_selections<D: Ord + fmt::Debug + Copy>(
     iter::from_fn(move || {
         let mut selection = selections.next()?;
         while let Some(next_selection) = selections.peek() {
-            if selection.end >= next_selection.start {
+            if should_merge(
+                selection.start,
+                selection.end,
+                next_selection.start,
+                next_selection.end,
+                true,
+            ) {
                 if selection.reversed == next_selection.reversed {
                     selection.end = cmp::max(selection.end, next_selection.end);
                     selections.next();
@@ -1146,3 +1182,35 @@ fn coalesce_selections<D: Ord + fmt::Debug + Copy>(
         Some(selection)
     })
 }
+
+/// Determines whether two selections should be merged into one.
+///
+/// Two selections should be merged when:
+/// 1. They overlap: the selections share at least one position
+/// 2. They have the same start position: one contains or equals the other
+/// 3. A cursor touches a selection boundary: a zero-width selection (cursor) at the
+///    start or end of another selection should be absorbed into it
+///
+/// Note: two selections that merely touch (one ends exactly where the other begins)
+/// but don't share any positions remain separate, see: https://github.com/zed-industries/zed/issues/24748
+fn should_merge<T: Ord + Copy>(a_start: T, a_end: T, b_start: T, b_end: T, sorted: bool) -> bool {
+    let is_overlapping = if sorted {
+        // When sorted, `a` starts before or at `b`, so overlap means `b` starts before `a` ends
+        b_start < a_end
+    } else {
+        a_start < b_end && b_start < a_end
+    };
+
+    // Selections starting at the same position should always merge (one contains the other)
+    let same_start = a_start == b_start;
+
+    // A cursor (zero-width selection) touching another selection's boundary should merge.
+    // This handles cases like a cursor at position X merging with a selection that
+    // starts or ends at X.
+    let is_cursor_a = a_start == a_end;
+    let is_cursor_b = b_start == b_end;
+    let cursor_at_boundary = (is_cursor_a && (a_start == b_start || a_end == b_end))
+        || (is_cursor_b && (b_start == a_start || b_end == a_end));
+
+    is_overlapping || same_start || cursor_at_boundary
+}

crates/editor/src/split.rs 🔗

@@ -211,7 +211,7 @@ impl SplittableEditor {
         self.primary_editor.update(cx, |editor, cx| {
             editor.buffer().update(cx, |primary_multibuffer, cx| {
                 primary_multibuffer.set_show_deleted_hunks(false, cx);
-                let paths = primary_multibuffer.paths().collect::<Vec<_>>();
+                let paths = primary_multibuffer.paths().cloned().collect::<Vec<_>>();
                 for path in paths {
                     let Some(excerpt_id) = primary_multibuffer.excerpts_for_path(&path).next()
                     else {
@@ -220,7 +220,7 @@ impl SplittableEditor {
                     let snapshot = primary_multibuffer.snapshot(cx);
                     let buffer = snapshot.buffer_for_excerpt(excerpt_id).unwrap();
                     let diff = primary_multibuffer.diff_for(buffer.remote_id()).unwrap();
-                    secondary.sync_path_excerpts(path, primary_multibuffer, diff, cx);
+                    secondary.sync_path_excerpts(path.clone(), primary_multibuffer, diff, cx);
                 }
             })
         });
@@ -228,7 +228,7 @@ impl SplittableEditor {
 
         let primary_pane = self.panes.first_pane();
         self.panes
-            .split(&primary_pane, &secondary_pane, SplitDirection::Left)
+            .split(&primary_pane, &secondary_pane, SplitDirection::Left, cx)
             .unwrap();
         cx.notify();
     }
@@ -237,7 +237,7 @@ impl SplittableEditor {
         let Some(secondary) = self.secondary.take() else {
             return;
         };
-        self.panes.remove(&secondary.pane).unwrap();
+        self.panes.remove(&secondary.pane, cx).unwrap();
         self.primary_editor.update(cx, |primary, cx| {
             primary.buffer().update(cx, |buffer, cx| {
                 buffer.set_show_deleted_hunks(true, cx);
@@ -308,7 +308,7 @@ impl SplittableEditor {
                 corresponding_paths = excerpt_ids
                     .clone()
                     .map(|excerpt_id| {
-                        let path = multibuffer.path_for_excerpt(excerpt_id).cloned().unwrap();
+                        let path = multibuffer.path_for_excerpt(excerpt_id).unwrap();
                         let buffer = snapshot.buffer_for_excerpt(excerpt_id).unwrap();
                         let diff = multibuffer.diff_for(buffer.remote_id()).unwrap();
                         (path, diff)
@@ -465,6 +465,7 @@ impl SplittableEditor {
                 .primary_multibuffer
                 .read(cx)
                 .paths()
+                .cloned()
                 .collect::<Vec<_>>();
             let excerpt_ids = self.primary_multibuffer.read(cx).excerpt_ids();
 
@@ -519,7 +520,7 @@ impl SplittableEditor {
                     .cloned()
                     .collect::<Vec<_>>();
                 for path in paths_to_remove {
-                    self.remove_excerpts_for_path(path, cx);
+                    self.remove_excerpts_for_path(path.clone(), cx);
                 }
             }
         }

crates/editor/src/test.rs 🔗

@@ -176,11 +176,9 @@ pub fn block_content_for_tests(
 }
 
 pub fn editor_content_with_blocks(editor: &Entity<Editor>, cx: &mut VisualTestContext) -> String {
-    cx.draw(
-        gpui::Point::default(),
-        size(px(3000.0), px(3000.0)),
-        |_, _| editor.clone(),
-    );
+    let draw_size = size(px(3000.0), px(3000.0));
+    cx.simulate_resize(draw_size);
+    cx.draw(gpui::Point::default(), draw_size, |_, _| editor.clone());
     let (snapshot, mut lines, blocks) = editor.update_in(cx, |editor, window, cx| {
         let snapshot = editor.snapshot(window, cx);
         let text = editor.display_text(cx);

crates/editor/src/test/editor_lsp_test_context.rs 🔗

@@ -126,7 +126,7 @@ impl EditorLspTestContext {
                 .read(cx)
                 .nav_history_for_item(&cx.entity());
             editor.set_nav_history(Some(nav_history));
-            window.focus(&editor.focus_handle(cx))
+            window.focus(&editor.focus_handle(cx), cx)
         });
 
         let lsp = fake_servers.next().await.unwrap();
@@ -205,6 +205,49 @@ impl EditorLspTestContext {
                 (_ "{" "}" @end) @indent
                 (_ "(" ")" @end) @indent
                 "#})),
+            text_objects: Some(Cow::from(indoc! {r#"
+                (function_declaration
+                    body: (_
+                        "{"
+                        (_)* @function.inside
+                        "}")) @function.around
+
+                (method_definition
+                    body: (_
+                        "{"
+                        (_)* @function.inside
+                        "}")) @function.around
+
+                ; Arrow function in variable declaration - capture the full declaration
+                ([
+                    (lexical_declaration
+                        (variable_declarator
+                            value: (arrow_function
+                                body: (statement_block
+                                    "{"
+                                    (_)* @function.inside
+                                    "}"))))
+                    (variable_declaration
+                        (variable_declarator
+                            value: (arrow_function
+                                body: (statement_block
+                                    "{"
+                                    (_)* @function.inside
+                                    "}"))))
+                ]) @function.around
+
+                ([
+                    (lexical_declaration
+                        (variable_declarator
+                            value: (arrow_function)))
+                    (variable_declaration
+                        (variable_declarator
+                            value: (arrow_function)))
+                ]) @function.around
+
+                ; Catch-all for arrow functions in other contexts (callbacks, etc.)
+                ((arrow_function) @function.around (#not-has-parent? @function.around variable_declarator))
+                "#})),
             ..Default::default()
         })
         .expect("Could not parse queries");
@@ -276,6 +319,49 @@ impl EditorLspTestContext {
                   (jsx_opening_element) @start
                   (jsx_closing_element)? @end) @indent
                 "#})),
+            text_objects: Some(Cow::from(indoc! {r#"
+                (function_declaration
+                    body: (_
+                        "{"
+                        (_)* @function.inside
+                        "}")) @function.around
+
+                (method_definition
+                    body: (_
+                        "{"
+                        (_)* @function.inside
+                        "}")) @function.around
+
+                ; Arrow function in variable declaration - capture the full declaration
+                ([
+                    (lexical_declaration
+                        (variable_declarator
+                            value: (arrow_function
+                                body: (statement_block
+                                    "{"
+                                    (_)* @function.inside
+                                    "}"))))
+                    (variable_declaration
+                        (variable_declarator
+                            value: (arrow_function
+                                body: (statement_block
+                                    "{"
+                                    (_)* @function.inside
+                                    "}"))))
+                ]) @function.around
+
+                ([
+                    (lexical_declaration
+                        (variable_declarator
+                            value: (arrow_function)))
+                    (variable_declaration
+                        (variable_declarator
+                            value: (arrow_function)))
+                ]) @function.around
+
+                ; Catch-all for arrow functions in other contexts (callbacks, etc.)
+                ((arrow_function) @function.around (#not-has-parent? @function.around variable_declarator))
+                "#})),
             ..Default::default()
         })
         .expect("Could not parse queries");

crates/editor/src/test/editor_test_context.rs 🔗

@@ -78,7 +78,7 @@ impl EditorTestContext {
                 cx,
             );
 
-            window.focus(&editor.focus_handle(cx));
+            window.focus(&editor.focus_handle(cx), cx);
             editor
         });
         let editor_view = editor.root(cx).unwrap();
@@ -139,7 +139,7 @@ impl EditorTestContext {
 
         let editor = cx.add_window(|window, cx| {
             let editor = build_editor(buffer, window, cx);
-            window.focus(&editor.focus_handle(cx));
+            window.focus(&editor.focus_handle(cx), cx);
 
             editor
         });
@@ -283,8 +283,7 @@ impl EditorTestContext {
                 .head();
             let pixel_position = editor.pixel_position_of_newest_cursor.unwrap();
             let line_height = editor
-                .style()
-                .unwrap()
+                .style(cx)
                 .text
                 .line_height_in_pixels(window.rem_size());
             let snapshot = editor.snapshot(window, cx);
@@ -306,6 +305,12 @@ impl EditorTestContext {
         snapshot.anchor_before(ranges[0].start)..snapshot.anchor_after(ranges[0].end)
     }
 
+    pub async fn wait_for_autoindent_applied(&mut self) {
+        if let Some(fut) = self.update_buffer(|buffer, _| buffer.wait_for_autoindent_applied()) {
+            fut.await.ok();
+        }
+    }
+
     pub fn set_head_text(&mut self, diff_base: &str) {
         self.cx.run_until_parked();
         let fs =

crates/eval/src/example.rs 🔗

@@ -261,7 +261,7 @@ impl ExampleContext {
                             .expect("Unknown tool_name content in meta");
 
                         tool_uses_by_id.insert(
-                            tool_call.id,
+                            tool_call.tool_call_id,
                             ToolUse {
                                 name: tool_name.to_string(),
                                 value: tool_call.raw_input.unwrap_or_default(),
@@ -277,7 +277,9 @@ impl ExampleContext {
                     ThreadEvent::ToolCallUpdate(tool_call_update) => {
                         if let acp_thread::ToolCallUpdate::UpdateFields(update) = tool_call_update {
                             if let Some(raw_input) = update.fields.raw_input {
-                                if let Some(tool_use) = tool_uses_by_id.get_mut(&update.id) {
+                                if let Some(tool_use) =
+                                    tool_uses_by_id.get_mut(&update.tool_call_id)
+                                {
                                     tool_use.value = raw_input;
                                 }
                             }
@@ -290,7 +292,7 @@ impl ExampleContext {
                                     update.fields.status == Some(acp::ToolCallStatus::Completed);
 
                                 let tool_use = tool_uses_by_id
-                                    .remove(&update.id)
+                                    .remove(&update.tool_call_id)
                                     .expect("Unrecognized tool call completed");
 
                                 let log_message = if succeeded {
@@ -337,10 +339,7 @@ impl ExampleContext {
                         acp::StopReason::MaxTurnRequests => {
                             return Err(anyhow!("Exceeded maximum turn requests"));
                         }
-                        acp::StopReason::Refusal => {
-                            return Err(anyhow!("Refusal"));
-                        }
-                        acp::StopReason::Cancelled => return Err(anyhow!("Cancelled")),
+                        stop_reason => return Err(anyhow!("{stop_reason:?}")),
                     },
                 }
             }

crates/eval/src/instance.rs 🔗

@@ -202,6 +202,7 @@ impl ExampleInstance {
             app_state.languages.clone(),
             app_state.fs.clone(),
             None,
+            false,
             cx,
         );
 
@@ -303,13 +304,12 @@ impl ExampleInstance {
                 let context_server_registry = cx.new(|cx| ContextServerRegistry::new(project.read(cx).context_server_store(), cx));
 
                 let thread = if let Some(json) = &meta.existing_thread_json {
-                    let session_id = acp::SessionId(
+                    let session_id = acp::SessionId::new(
                         rand::rng()
                             .sample_iter(&distr::Alphanumeric)
                             .take(7)
                             .map(char::from)
-                            .collect::<String>()
-                            .into(),
+                            .collect::<String>(),
                     );
 
                     let db_thread = agent::DbThread::from_json(json.as_bytes()).expect("Can't read serialized thread");
@@ -626,6 +626,15 @@ impl agent::TerminalHandle for EvalTerminalHandle {
         self.terminal
             .read_with(cx, |term, cx| term.current_output(cx))
     }
+
+    fn kill(&self, cx: &AsyncApp) -> Result<()> {
+        cx.update(|cx| {
+            self.terminal.update(cx, |terminal, cx| {
+                terminal.kill(cx);
+            });
+        })?;
+        Ok(())
+    }
 }
 
 impl agent::ThreadEnvironment for EvalThreadEnvironment {
@@ -640,7 +649,7 @@ impl agent::ThreadEnvironment for EvalThreadEnvironment {
         cx.spawn(async move |cx| {
             let language_registry =
                 project.read_with(cx, |project, _cx| project.languages().clone())?;
-            let id = acp::TerminalId(uuid::Uuid::new_v4().to_string().into());
+            let id = acp::TerminalId::new(uuid::Uuid::new_v4().to_string());
             let terminal =
                 acp_thread::create_terminal_entity(command, &[], vec![], cwd.clone(), &project, cx)
                     .await?;
@@ -893,7 +902,7 @@ pub fn wait_for_lang_server(
         .update(cx, |buffer, cx| {
             lsp_store.update(cx, |lsp_store, cx| {
                 lsp_store
-                    .language_servers_for_local_buffer(buffer, cx)
+                    .running_language_servers_for_local_buffer(buffer, cx)
                     .next()
                     .is_some()
             })

crates/eval_utils/Cargo.toml 🔗

@@ -0,0 +1,18 @@
+[package]
+name = "eval_utils"
+version = "0.1.0"
+edition.workspace = true
+publish.workspace = true
+license = "GPL-3.0-or-later"
+
+[lints]
+workspace = true
+
+[lib]
+path = "src/eval_utils.rs"
+doctest = false
+
+[dependencies]
+gpui.workspace = true
+serde.workspace = true
+smol.workspace = true

crates/eval_utils/src/eval_utils.rs 🔗

@@ -0,0 +1,146 @@
+//! Utilities for evaluation and benchmarking.
+
+use std::{
+    collections::HashMap,
+    sync::{Arc, mpsc},
+};
+
+fn report_progress(evaluated_count: usize, failed_count: usize, iterations: usize) {
+    let passed_count = evaluated_count - failed_count;
+    let passed_ratio = if evaluated_count == 0 {
+        0.0
+    } else {
+        passed_count as f64 / evaluated_count as f64
+    };
+    println!(
+        "\r\x1b[KEvaluated {}/{} ({:.2}% passed)",
+        evaluated_count,
+        iterations,
+        passed_ratio * 100.0
+    )
+}
+
+#[derive(Clone, Debug, Eq, PartialEq)]
+pub enum OutcomeKind {
+    Passed,
+    Failed,
+    Error,
+}
+
+pub trait EvalOutputProcessor {
+    type Metadata: 'static + Send;
+    fn process(&mut self, output: &EvalOutput<Self::Metadata>);
+    fn assert(&mut self);
+}
+
+#[derive(Clone, Debug)]
+pub struct EvalOutput<M> {
+    pub outcome: OutcomeKind,
+    pub data: String,
+    pub metadata: M,
+}
+
+impl<M: Default> EvalOutput<M> {
+    pub fn passed(message: impl Into<String>) -> Self {
+        EvalOutput {
+            outcome: OutcomeKind::Passed,
+            data: message.into(),
+            metadata: M::default(),
+        }
+    }
+
+    pub fn failed(message: impl Into<String>) -> Self {
+        EvalOutput {
+            outcome: OutcomeKind::Failed,
+            data: message.into(),
+            metadata: M::default(),
+        }
+    }
+}
+
+pub struct NoProcessor;
+impl EvalOutputProcessor for NoProcessor {
+    type Metadata = ();
+
+    fn process(&mut self, _output: &EvalOutput<Self::Metadata>) {}
+
+    fn assert(&mut self) {}
+}
+
+pub fn eval<P>(
+    iterations: usize,
+    expected_pass_ratio: f32,
+    mut processor: P,
+    evalf: impl Fn() -> EvalOutput<P::Metadata> + Send + Sync + 'static,
+) where
+    P: EvalOutputProcessor,
+{
+    let mut evaluated_count = 0;
+    let mut failed_count = 0;
+    let evalf = Arc::new(evalf);
+    report_progress(evaluated_count, failed_count, iterations);
+
+    let (tx, rx) = mpsc::channel();
+
+    let executor = gpui::background_executor();
+    let semaphore = Arc::new(smol::lock::Semaphore::new(32));
+    let evalf = Arc::new(evalf);
+    // Warm the cache once
+    let first_output = evalf();
+    tx.send(first_output).ok();
+
+    for _ in 1..iterations {
+        let tx = tx.clone();
+        let semaphore = semaphore.clone();
+        let evalf = evalf.clone();
+        executor
+            .spawn(async move {
+                let _guard = semaphore.acquire().await;
+                let output = evalf();
+                tx.send(output).ok();
+            })
+            .detach();
+    }
+    drop(tx);
+
+    let mut failed_evals = Vec::new();
+    let mut errored_evals = HashMap::new();
+    while let Ok(output) = rx.recv() {
+        processor.process(&output);
+
+        match output.outcome {
+            OutcomeKind::Passed => {}
+            OutcomeKind::Failed => {
+                failed_count += 1;
+                failed_evals.push(output);
+            }
+            OutcomeKind::Error => {
+                failed_count += 1;
+                *errored_evals.entry(output.data).or_insert(0) += 1;
+            }
+        }
+
+        evaluated_count += 1;
+        report_progress(evaluated_count, failed_count, iterations);
+    }
+
+    let actual_pass_ratio = (iterations - failed_count) as f32 / iterations as f32;
+    println!("Actual pass ratio: {}\n", actual_pass_ratio);
+    if actual_pass_ratio < expected_pass_ratio {
+        for (error, count) in errored_evals {
+            println!("Eval errored {} times. Error: {}", count, error);
+        }
+
+        for failed in failed_evals {
+            println!("Eval failed");
+            println!("{}", failed.data);
+        }
+
+        panic!(
+            "Actual pass ratio: {}\nExpected pass ratio: {}",
+            actual_pass_ratio, expected_pass_ratio
+        );
+    }
+
+    processor.assert();
+}

crates/extension/Cargo.toml 🔗

@@ -37,4 +37,8 @@ wasm-encoder.workspace = true
 wasmparser.workspace = true
 
 [dev-dependencies]
+fs = { workspace = true, "features" = ["test-support"] }
+gpui = { workspace = true, "features" = ["test-support"] }
+indoc.workspace = true
 pretty_assertions.workspace = true
+tempfile.workspace = true

crates/extension/src/extension_builder.rs 🔗

@@ -2,8 +2,9 @@ use crate::{
     ExtensionLibraryKind, ExtensionManifest, GrammarManifestEntry, build_debug_adapter_schema_path,
     parse_wasm_extension_version,
 };
+use ::fs::Fs;
 use anyhow::{Context as _, Result, bail};
-use futures::AsyncReadExt;
+use futures::{AsyncReadExt, StreamExt};
 use heck::ToSnakeCase;
 use http_client::{self, AsyncBody, HttpClient};
 use serde::Deserialize;
@@ -77,8 +78,9 @@ impl ExtensionBuilder {
         extension_dir: &Path,
         extension_manifest: &mut ExtensionManifest,
         options: CompileExtensionOptions,
+        fs: Arc<dyn Fs>,
     ) -> Result<()> {
-        populate_defaults(extension_manifest, extension_dir)?;
+        populate_defaults(extension_manifest, extension_dir, fs).await?;
 
         if extension_dir.is_relative() {
             bail!(
@@ -247,26 +249,34 @@ impl ExtensionBuilder {
         let parser_path = src_path.join("parser.c");
         let scanner_path = src_path.join("scanner.c");
 
-        log::info!("compiling {grammar_name} parser");
-        let clang_output = util::command::new_smol_command(&clang_path)
-            .args(["-fPIC", "-shared", "-Os"])
-            .arg(format!("-Wl,--export=tree_sitter_{grammar_name}"))
-            .arg("-o")
-            .arg(&grammar_wasm_path)
-            .arg("-I")
-            .arg(&src_path)
-            .arg(&parser_path)
-            .args(scanner_path.exists().then_some(scanner_path))
-            .output()
-            .await
-            .context("failed to run clang")?;
-
-        if !clang_output.status.success() {
-            bail!(
-                "failed to compile {} parser with clang: {}",
-                grammar_name,
-                String::from_utf8_lossy(&clang_output.stderr),
+        // Skip recompiling if the WASM object is already newer than the source files
+        if file_newer_than_deps(&grammar_wasm_path, &[&parser_path, &scanner_path]).unwrap_or(false)
+        {
+            log::info!(
+                "skipping compilation of {grammar_name} parser because the existing compiled grammar is up to date"
             );
+        } else {
+            log::info!("compiling {grammar_name} parser");
+            let clang_output = util::command::new_smol_command(&clang_path)
+                .args(["-fPIC", "-shared", "-Os"])
+                .arg(format!("-Wl,--export=tree_sitter_{grammar_name}"))
+                .arg("-o")
+                .arg(&grammar_wasm_path)
+                .arg("-I")
+                .arg(&src_path)
+                .arg(&parser_path)
+                .args(scanner_path.exists().then_some(scanner_path))
+                .output()
+                .await
+                .context("failed to run clang")?;
+
+            if !clang_output.status.success() {
+                bail!(
+                    "failed to compile {} parser with clang: {}",
+                    grammar_name,
+                    String::from_utf8_lossy(&clang_output.stderr),
+                );
+            }
         }
 
         Ok(())
@@ -538,7 +548,11 @@ impl ExtensionBuilder {
     }
 }
 
-fn populate_defaults(manifest: &mut ExtensionManifest, extension_path: &Path) -> Result<()> {
+async fn populate_defaults(
+    manifest: &mut ExtensionManifest,
+    extension_path: &Path,
+    fs: Arc<dyn Fs>,
+) -> Result<()> {
     // For legacy extensions on the v0 schema (aka, using `extension.json`), clear out any existing
     // contents of the computed fields, since we don't care what the existing values are.
     if manifest.schema_version.is_v0() {
@@ -553,12 +567,16 @@ fn populate_defaults(manifest: &mut ExtensionManifest, extension_path: &Path) ->
     }
 
     let languages_dir = extension_path.join("languages");
-    if languages_dir.exists() {
-        for entry in fs::read_dir(&languages_dir).context("failed to list languages dir")? {
-            let entry = entry?;
-            let language_dir = entry.path();
+    if fs.is_dir(&languages_dir).await {
+        let mut language_dir_entries = fs
+            .read_dir(&languages_dir)
+            .await
+            .context("failed to list languages dir")?;
+
+        while let Some(language_dir) = language_dir_entries.next().await {
+            let language_dir = language_dir?;
             let config_path = language_dir.join("config.toml");
-            if config_path.exists() {
+            if fs.is_file(config_path.as_path()).await {
                 let relative_language_dir =
                     language_dir.strip_prefix(extension_path)?.to_path_buf();
                 if !manifest.languages.contains(&relative_language_dir) {
@@ -569,10 +587,14 @@ fn populate_defaults(manifest: &mut ExtensionManifest, extension_path: &Path) ->
     }
 
     let themes_dir = extension_path.join("themes");
-    if themes_dir.exists() {
-        for entry in fs::read_dir(&themes_dir).context("failed to list themes dir")? {
-            let entry = entry?;
-            let theme_path = entry.path();
+    if fs.is_dir(&themes_dir).await {
+        let mut theme_dir_entries = fs
+            .read_dir(&themes_dir)
+            .await
+            .context("failed to list themes dir")?;
+
+        while let Some(theme_path) = theme_dir_entries.next().await {
+            let theme_path = theme_path?;
             if theme_path.extension() == Some("json".as_ref()) {
                 let relative_theme_path = theme_path.strip_prefix(extension_path)?.to_path_buf();
                 if !manifest.themes.contains(&relative_theme_path) {
@@ -583,10 +605,14 @@ fn populate_defaults(manifest: &mut ExtensionManifest, extension_path: &Path) ->
     }
 
     let icon_themes_dir = extension_path.join("icon_themes");
-    if icon_themes_dir.exists() {
-        for entry in fs::read_dir(&icon_themes_dir).context("failed to list icon themes dir")? {
-            let entry = entry?;
-            let icon_theme_path = entry.path();
+    if fs.is_dir(&icon_themes_dir).await {
+        let mut icon_theme_dir_entries = fs
+            .read_dir(&icon_themes_dir)
+            .await
+            .context("failed to list icon themes dir")?;
+
+        while let Some(icon_theme_path) = icon_theme_dir_entries.next().await {
+            let icon_theme_path = icon_theme_path?;
             if icon_theme_path.extension() == Some("json".as_ref()) {
                 let relative_icon_theme_path =
                     icon_theme_path.strip_prefix(extension_path)?.to_path_buf();
@@ -595,21 +621,26 @@ fn populate_defaults(manifest: &mut ExtensionManifest, extension_path: &Path) ->
                 }
             }
         }
-    }
-
-    let snippets_json_path = extension_path.join("snippets.json");
-    if snippets_json_path.exists() {
-        manifest.snippets = Some(snippets_json_path);
+    };
+    if manifest.snippets.is_none()
+        && let snippets_json_path = extension_path.join("snippets.json")
+        && fs.is_file(&snippets_json_path).await
+    {
+        manifest.snippets = Some("snippets.json".into());
     }
 
     // For legacy extensions on the v0 schema (aka, using `extension.json`), we want to populate the grammars in
     // the manifest using the contents of the `grammars` directory.
     if manifest.schema_version.is_v0() {
         let grammars_dir = extension_path.join("grammars");
-        if grammars_dir.exists() {
-            for entry in fs::read_dir(&grammars_dir).context("failed to list grammars dir")? {
-                let entry = entry?;
-                let grammar_path = entry.path();
+        if fs.is_dir(&grammars_dir).await {
+            let mut grammar_dir_entries = fs
+                .read_dir(&grammars_dir)
+                .await
+                .context("failed to list grammars dir")?;
+
+            while let Some(grammar_path) = grammar_dir_entries.next().await {
+                let grammar_path = grammar_path?;
                 if grammar_path.extension() == Some("toml".as_ref()) {
                     #[derive(Deserialize)]
                     struct GrammarConfigToml {
@@ -619,7 +650,7 @@ fn populate_defaults(manifest: &mut ExtensionManifest, extension_path: &Path) ->
                         pub path: Option<String>,
                     }
 
-                    let grammar_config = fs::read_to_string(&grammar_path)?;
+                    let grammar_config = fs.load(&grammar_path).await?;
                     let grammar_config: GrammarConfigToml = toml::from_str(&grammar_config)?;
 
                     let grammar_name = grammar_path
@@ -643,3 +674,153 @@ fn populate_defaults(manifest: &mut ExtensionManifest, extension_path: &Path) ->
 
     Ok(())
 }
+
+/// Returns `true` if the target exists and its last modified time is greater than that
+/// of each dependency which exists (i.e., dependency paths which do not exist are ignored).
+///
+/// # Errors
+///
+/// Returns `Err` if any of the underlying file I/O operations fail.
+fn file_newer_than_deps(target: &Path, dependencies: &[&Path]) -> Result<bool, std::io::Error> {
+    if !target.try_exists()? {
+        return Ok(false);
+    }
+    let target_modified = target.metadata()?.modified()?;
+    for dependency in dependencies {
+        if !dependency.try_exists()? {
+            continue;
+        }
+        let dep_modified = dependency.metadata()?.modified()?;
+        if target_modified < dep_modified {
+            return Ok(false);
+        }
+    }
+    Ok(true)
+}
+
+#[cfg(test)]
+mod tests {
+    use std::{
+        path::{Path, PathBuf},
+        str::FromStr,
+        thread::sleep,
+        time::Duration,
+    };
+
+    use gpui::TestAppContext;
+    use indoc::indoc;
+
+    use crate::{
+        ExtensionManifest,
+        extension_builder::{file_newer_than_deps, populate_defaults},
+    };
+
+    #[test]
+    fn test_file_newer_than_deps() {
+        // Don't use TempTree because we need to guarantee the order
+        let tmpdir = tempfile::tempdir().unwrap();
+        let target = tmpdir.path().join("target.wasm");
+        let dep1 = tmpdir.path().join("parser.c");
+        let dep2 = tmpdir.path().join("scanner.c");
+
+        assert!(
+            !file_newer_than_deps(&target, &[&dep1, &dep2]).unwrap(),
+            "target doesn't exist"
+        );
+        std::fs::write(&target, "foo").unwrap(); // Create target
+        assert!(
+            file_newer_than_deps(&target, &[&dep1, &dep2]).unwrap(),
+            "dependencies don't exist; target is newer"
+        );
+        sleep(Duration::from_secs(1));
+        std::fs::write(&dep1, "foo").unwrap(); // Create dep1 (newer than target)
+        // Dependency is newer
+        assert!(
+            !file_newer_than_deps(&target, &[&dep1, &dep2]).unwrap(),
+            "a dependency is newer (target {:?}, dep1 {:?})",
+            target.metadata().unwrap().modified().unwrap(),
+            dep1.metadata().unwrap().modified().unwrap(),
+        );
+        sleep(Duration::from_secs(1));
+        std::fs::write(&dep2, "foo").unwrap(); // Create dep2
+        sleep(Duration::from_secs(1));
+        std::fs::write(&target, "foobar").unwrap(); // Update target
+        assert!(
+            file_newer_than_deps(&target, &[&dep1, &dep2]).unwrap(),
+            "target is newer than dependencies (target {:?}, dep2 {:?})",
+            target.metadata().unwrap().modified().unwrap(),
+            dep2.metadata().unwrap().modified().unwrap(),
+        );
+    }
+
+    #[gpui::test]
+    async fn test_snippet_location_is_kept(cx: &mut TestAppContext) {
+        let fs = fs::FakeFs::new(cx.executor());
+        let extension_path = Path::new("/extension");
+
+        fs.insert_tree(
+            extension_path,
+            serde_json::json!({
+                "extension.toml": indoc! {r#"
+                    id = "test-manifest"
+                    name = "Test Manifest"
+                    version = "0.0.1"
+                    schema_version = 1
+
+                    snippets = "./snippets/snippets.json"
+                    "#
+                },
+                "snippets.json": "",
+            }),
+        )
+        .await;
+
+        let mut manifest = ExtensionManifest::load(fs.clone(), extension_path)
+            .await
+            .unwrap();
+
+        populate_defaults(&mut manifest, extension_path, fs.clone())
+            .await
+            .unwrap();
+
+        assert_eq!(
+            manifest.snippets,
+            Some(PathBuf::from_str("./snippets/snippets.json").unwrap())
+        )
+    }
+
+    #[gpui::test]
+    async fn test_automatic_snippet_location_is_relative(cx: &mut TestAppContext) {
+        let fs = fs::FakeFs::new(cx.executor());
+        let extension_path = Path::new("/extension");
+
+        fs.insert_tree(
+            extension_path,
+            serde_json::json!({
+                "extension.toml": indoc! {r#"
+                    id = "test-manifest"
+                    name = "Test Manifest"
+                    version = "0.0.1"
+                    schema_version = 1
+
+                    "#
+                },
+                "snippets.json": "",
+            }),
+        )
+        .await;
+
+        let mut manifest = ExtensionManifest::load(fs.clone(), extension_path)
+            .await
+            .unwrap();
+
+        populate_defaults(&mut manifest, extension_path, fs.clone())
+            .await
+            .unwrap();
+
+        assert_eq!(
+            manifest.snippets,
+            Some(PathBuf::from_str("snippets.json").unwrap())
+        )
+    }
+}

crates/extension/src/extension_host_proxy.rs 🔗

@@ -19,6 +19,9 @@ impl Global for GlobalExtensionHostProxy {}
 ///
 /// This object implements each of the individual proxy types so that their
 /// methods can be called directly on it.
+/// Registration function for language model providers.
+pub type LanguageModelProviderRegistration = Box<dyn FnOnce(&mut App) + Send>;
+
 #[derive(Default)]
 pub struct ExtensionHostProxy {
     theme_proxy: RwLock<Option<Arc<dyn ExtensionThemeProxy>>>,
@@ -29,6 +32,7 @@ pub struct ExtensionHostProxy {
     slash_command_proxy: RwLock<Option<Arc<dyn ExtensionSlashCommandProxy>>>,
     context_server_proxy: RwLock<Option<Arc<dyn ExtensionContextServerProxy>>>,
     debug_adapter_provider_proxy: RwLock<Option<Arc<dyn ExtensionDebugAdapterProviderProxy>>>,
+    language_model_provider_proxy: RwLock<Option<Arc<dyn ExtensionLanguageModelProviderProxy>>>,
 }
 
 impl ExtensionHostProxy {
@@ -54,6 +58,7 @@ impl ExtensionHostProxy {
             slash_command_proxy: RwLock::default(),
             context_server_proxy: RwLock::default(),
             debug_adapter_provider_proxy: RwLock::default(),
+            language_model_provider_proxy: RwLock::default(),
         }
     }
 
@@ -90,6 +95,15 @@ impl ExtensionHostProxy {
             .write()
             .replace(Arc::new(proxy));
     }
+
+    pub fn register_language_model_provider_proxy(
+        &self,
+        proxy: impl ExtensionLanguageModelProviderProxy,
+    ) {
+        self.language_model_provider_proxy
+            .write()
+            .replace(Arc::new(proxy));
+    }
 }
 
 pub trait ExtensionThemeProxy: Send + Sync + 'static {
@@ -446,3 +460,37 @@ impl ExtensionDebugAdapterProviderProxy for ExtensionHostProxy {
         proxy.unregister_debug_locator(locator_name)
     }
 }
+
+pub trait ExtensionLanguageModelProviderProxy: Send + Sync + 'static {
+    fn register_language_model_provider(
+        &self,
+        provider_id: Arc<str>,
+        register_fn: LanguageModelProviderRegistration,
+        cx: &mut App,
+    );
+
+    fn unregister_language_model_provider(&self, provider_id: Arc<str>, cx: &mut App);
+}
+
+impl ExtensionLanguageModelProviderProxy for ExtensionHostProxy {
+    fn register_language_model_provider(
+        &self,
+        provider_id: Arc<str>,
+        register_fn: LanguageModelProviderRegistration,
+        cx: &mut App,
+    ) {
+        let Some(proxy) = self.language_model_provider_proxy.read().clone() else {
+            return;
+        };
+
+        proxy.register_language_model_provider(provider_id, register_fn, cx)
+    }
+
+    fn unregister_language_model_provider(&self, provider_id: Arc<str>, cx: &mut App) {
+        let Some(proxy) = self.language_model_provider_proxy.read().clone() else {
+            return;
+        };
+
+        proxy.unregister_language_model_provider(provider_id, cx)
+    }
+}

crates/extension/src/extension_manifest.rs 🔗

@@ -93,6 +93,8 @@ pub struct ExtensionManifest {
     pub debug_adapters: BTreeMap<Arc<str>, DebugAdapterManifestEntry>,
     #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
     pub debug_locators: BTreeMap<Arc<str>, DebugLocatorManifestEntry>,
+    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
+    pub language_model_providers: BTreeMap<Arc<str>, LanguageModelProviderManifestEntry>,
 }
 
 impl ExtensionManifest {
@@ -288,6 +290,16 @@ pub struct DebugAdapterManifestEntry {
 #[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
 pub struct DebugLocatorManifestEntry {}
 
+/// Manifest entry for a language model provider.
+#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
+pub struct LanguageModelProviderManifestEntry {
+    /// Display name for the provider.
+    pub name: String,
+    /// Path to an SVG icon file relative to the extension root (e.g., "icons/provider.svg").
+    #[serde(default)]
+    pub icon: Option<String>,
+}
+
 impl ExtensionManifest {
     pub async fn load(fs: Arc<dyn Fs>, extension_dir: &Path) -> Result<Self> {
         let extension_name = extension_dir
@@ -358,6 +370,7 @@ fn manifest_from_old_manifest(
         capabilities: Vec::new(),
         debug_adapters: Default::default(),
         debug_locators: Default::default(),
+        language_model_providers: Default::default(),
     }
 }
 
@@ -391,6 +404,7 @@ mod tests {
             capabilities: vec![],
             debug_adapters: Default::default(),
             debug_locators: Default::default(),
+            language_model_providers: BTreeMap::default(),
         }
     }
 

crates/extension_api/Cargo.toml 🔗

@@ -1,12 +1,13 @@
 [package]
 name = "zed_extension_api"
-version = "0.7.0"
+version = "0.8.0"
 description = "APIs for creating Zed extensions in Rust"
 repository = "https://github.com/zed-industries/zed"
 documentation = "https://docs.rs/zed_extension_api"
 keywords = ["zed", "extension"]
 edition.workspace = true
-publish = true
+# Change back to `true` when we're ready to publish v0.8.0.
+publish = false
 license = "Apache-2.0"
 
 [lints]

crates/extension_api/src/extension_api.rs 🔗

@@ -331,10 +331,9 @@ static mut EXTENSION: Option<Box<dyn Extension>> = None;
 pub static ZED_API_VERSION: [u8; 6] = *include_bytes!(concat!(env!("OUT_DIR"), "/version_bytes"));
 
 mod wit {
-
     wit_bindgen::generate!({
         skip: ["init-extension"],
-        path: "./wit/since_v0.6.0",
+        path: "./wit/since_v0.8.0",
     });
 }
 
@@ -524,6 +523,12 @@ impl wit::Guest for Component {
 #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]
 pub struct LanguageServerId(String);
 
+impl LanguageServerId {
+    pub fn new(value: String) -> Self {
+        Self(value)
+    }
+}
+
 impl AsRef<str> for LanguageServerId {
     fn as_ref(&self) -> &str {
         &self.0
@@ -540,6 +545,12 @@ impl fmt::Display for LanguageServerId {
 #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]
 pub struct ContextServerId(String);
 
+impl ContextServerId {
+    pub fn new(value: String) -> Self {
+        Self(value)
+    }
+}
+
 impl AsRef<str> for ContextServerId {
     fn as_ref(&self) -> &str {
         &self.0

crates/extension_api/wit/since_v0.8.0/common.wit 🔗

@@ -0,0 +1,12 @@
+interface common {
+    /// A (half-open) range (`[start, end)`).
+    record range {
+        /// The start of the range (inclusive).
+        start: u32,
+        /// The end of the range (exclusive).
+        end: u32,
+    }
+
+    /// A list of environment variables.
+    type env-vars = list<tuple<string, string>>;
+}

crates/extension_api/wit/since_v0.8.0/context-server.wit 🔗

@@ -0,0 +1,11 @@
+interface context-server {
+    /// Configuration for context server setup and installation.
+    record context-server-configuration {
+        /// Installation instructions in Markdown format.
+        installation-instructions: string,
+        /// JSON schema for settings validation.
+        settings-schema: string,
+        /// Default settings template.
+        default-settings: string,
+    }
+}

crates/extension_api/wit/since_v0.8.0/dap.wit 🔗

@@ -0,0 +1,123 @@
+interface dap {
+    use common.{env-vars};
+
+    /// Resolves a specified TcpArgumentsTemplate into TcpArguments
+    resolve-tcp-template: func(template: tcp-arguments-template) -> result<tcp-arguments, string>;
+
+    record launch-request {
+        program: string,
+        cwd: option<string>,
+        args: list<string>,
+        envs: env-vars,
+    }
+
+    record attach-request {
+        process-id: option<u32>,
+    }
+
+    variant debug-request {
+        launch(launch-request),
+        attach(attach-request)
+    }
+
+    record tcp-arguments {
+        port: u16,
+        host: u32,
+        timeout: option<u64>,
+    }
+
+    record tcp-arguments-template {
+        port: option<u16>,
+        host: option<u32>,
+        timeout: option<u64>,
+    }
+
+    /// Debug Config is the "highest-level" configuration for a debug session.
+    /// It comes from a new process modal UI; thus, it is essentially debug-adapter-agnostic.
+    /// It is expected of the extension to translate this generic configuration into something that can be debugged by the adapter (debug scenario).
+    record debug-config {
+        /// Name of the debug task
+        label: string,
+        /// The debug adapter to use
+        adapter: string,
+        request: debug-request,
+        stop-on-entry: option<bool>,
+    }
+
+    record task-template {
+        /// Human readable name of the task to display in the UI.
+        label: string,
+        /// Executable command to spawn.
+        command: string,
+        args: list<string>,
+        env: env-vars,
+        cwd: option<string>,
+    }
+
+    /// A task template with substituted task variables.
+    type resolved-task = task-template;
+
+    /// A task template for building a debug target.
+    type build-task-template = task-template;
+
+    variant build-task-definition {
+        by-name(string),
+        template(build-task-definition-template-payload )
+    }
+    record build-task-definition-template-payload {
+        locator-name: option<string>,
+        template: build-task-template
+    }
+
+    /// Debug Scenario is the user-facing configuration type (used in debug.json). It is still concerned with what to debug and not necessarily how to do it (except for any
+    /// debug-adapter-specific configuration options).
+    record debug-scenario {
+        /// Unsubstituted label for the task.DebugAdapterBinary
+        label: string,
+        /// Name of the Debug Adapter this configuration is intended for.
+        adapter: string,
+        /// An optional build step to be ran prior to starting a debug session. Build steps are used by Zed's locators to locate the executable to debug.
+        build: option<build-task-definition>,
+        /// JSON-encoded configuration for a given debug adapter.
+        config: string,
+        /// TCP connection parameters (if they were specified by user)
+        tcp-connection: option<tcp-arguments-template>,
+    }
+
+    enum start-debugging-request-arguments-request {
+        launch,
+        attach,
+    }
+
+    record debug-task-definition {
+        /// Unsubstituted label for the task.DebugAdapterBinary
+        label: string,
+        /// Name of the Debug Adapter this configuration is intended for.
+        adapter: string,
+        /// JSON-encoded configuration for a given debug adapter.
+        config: string,
+        /// TCP connection parameters (if they were specified by user)
+        tcp-connection: option<tcp-arguments-template>,
+    }
+
+    record start-debugging-request-arguments {
+        /// JSON-encoded configuration for a given debug adapter. It is specific to each debug adapter.
+        /// `configuration` will have it's Zed variable references substituted prior to being passed to the debug adapter.
+        configuration: string,
+        request: start-debugging-request-arguments-request,
+    }
+
+    /// The lowest-level representation of a debug session, which specifies:
+    /// - How to start a debug adapter process
+    /// - How to start a debug session with it (using DAP protocol)
+    /// for a given debug scenario.
+    record debug-adapter-binary {
+        command: option<string>,
+        arguments: list<string>,
+        envs: env-vars,
+        cwd: option<string>,
+        /// Zed will use TCP transport if `connection` is specified.
+        connection: option<tcp-arguments>,
+        request-args: start-debugging-request-arguments
+    }
+}

crates/extension_api/wit/since_v0.8.0/extension.wit 🔗

@@ -0,0 +1,167 @@
+package zed:extension;
+
+world extension {
+    import context-server;
+    import dap;
+    import github;
+    import http-client;
+    import platform;
+    import process;
+    import nodejs;
+
+    use common.{env-vars, range};
+    use context-server.{context-server-configuration};
+    use dap.{attach-request, build-task-template, debug-config, debug-adapter-binary, debug-task-definition, debug-request, debug-scenario, launch-request, resolved-task, start-debugging-request-arguments-request};
+    use lsp.{completion, symbol};
+    use process.{command};
+    use slash-command.{slash-command, slash-command-argument-completion, slash-command-output};
+
+    /// Initializes the extension.
+    export init-extension: func();
+
+    /// The type of a downloaded file.
+    enum downloaded-file-type {
+        /// A gzipped file (`.gz`).
+        gzip,
+        /// A gzipped tar archive (`.tar.gz`).
+        gzip-tar,
+        /// A ZIP file (`.zip`).
+        zip,
+        /// An uncompressed file.
+        uncompressed,
+    }
+
+    /// The installation status for a language server.
+    variant language-server-installation-status {
+        /// The language server has no installation status.
+        none,
+        /// The language server is being downloaded.
+        downloading,
+        /// The language server is checking for updates.
+        checking-for-update,
+        /// The language server installation failed for specified reason.
+        failed(string),
+    }
+
+    record settings-location {
+        worktree-id: u64,
+        path: string,
+    }
+
+    import get-settings: func(path: option<settings-location>, category: string, key: option<string>) -> result<string, string>;
+
+    /// Downloads a file from the given URL and saves it to the given path within the extension's
+    /// working directory.
+    ///
+    /// The file will be extracted according to the given file type.
+    import download-file: func(url: string, file-path: string, file-type: downloaded-file-type) -> result<_, string>;
+
+    /// Makes the file at the given path executable.
+    import make-file-executable: func(filepath: string) -> result<_, string>;
+
+    /// Updates the installation status for the given language server.
+    import set-language-server-installation-status: func(language-server-name: string, status: language-server-installation-status);
+
+    /// A Zed worktree.
+    resource worktree {
+        /// Returns the ID of the worktree.
+        id: func() -> u64;
+        /// Returns the root path of the worktree.
+        root-path: func() -> string;
+        /// Returns the textual contents of the specified file in the worktree.
+        read-text-file: func(path: string) -> result<string, string>;
+        /// Returns the path to the given binary name, if one is present on the `$PATH`.
+        which: func(binary-name: string) -> option<string>;
+        /// Returns the current shell environment.
+        shell-env: func() -> env-vars;
+    }
+
+    /// A Zed project.
+    resource project {
+        /// Returns the IDs of all of the worktrees in this project.
+        worktree-ids: func() -> list<u64>;
+    }
+
+    /// A key-value store.
+    resource key-value-store {
+        /// Inserts an entry under the specified key.
+        insert: func(key: string, value: string) -> result<_, string>;
+    }
+
+    /// Returns the command used to start up the language server.
+    export language-server-command: func(language-server-id: string, worktree: borrow<worktree>) -> result<command, string>;
+
+    /// Returns the initialization options to pass to the language server on startup.
+    ///
+    /// The initialization options are represented as a JSON string.
+    export language-server-initialization-options: func(language-server-id: string, worktree: borrow<worktree>) -> result<option<string>, string>;
+
+    /// Returns the workspace configuration options to pass to the language server.
+    export language-server-workspace-configuration: func(language-server-id: string, worktree: borrow<worktree>) -> result<option<string>, string>;
+
+    /// Returns the initialization options to pass to the other language server.
+    export language-server-additional-initialization-options: func(language-server-id: string, target-language-server-id: string, worktree: borrow<worktree>) -> result<option<string>, string>;
+
+    /// Returns the workspace configuration options to pass to the other language server.
+    export language-server-additional-workspace-configuration: func(language-server-id: string, target-language-server-id: string, worktree: borrow<worktree>) -> result<option<string>, string>;
+
+    /// A label containing some code.
+    record code-label {
+        /// The source code to parse with Tree-sitter.
+        code: string,
+        /// The spans to display in the label.
+        spans: list<code-label-span>,
+        /// The range of the displayed label to include when filtering.
+        filter-range: range,
+    }
+
+    /// A span within a code label.
+    variant code-label-span {
+        /// A range into the parsed code.
+        code-range(range),
+        /// A span containing a code literal.
+        literal(code-label-span-literal),
+    }
+
+    /// A span containing a code literal.
+    record code-label-span-literal {
+        /// The literal text.
+        text: string,
+        /// The name of the highlight to use for this literal.
+        highlight-name: option<string>,
+    }
+
+    export labels-for-completions: func(language-server-id: string, completions: list<completion>) -> result<list<option<code-label>>, string>;
+    export labels-for-symbols: func(language-server-id: string, symbols: list<symbol>) -> result<list<option<code-label>>, string>;
+
+
+    /// Returns the completions that should be shown when completing the provided slash command with the given query.
+    export complete-slash-command-argument: func(command: slash-command, args: list<string>) -> result<list<slash-command-argument-completion>, string>;
+
+    /// Returns the output from running the provided slash command.
+    export run-slash-command: func(command: slash-command, args: list<string>, worktree: option<borrow<worktree>>) -> result<slash-command-output, string>;
+
+    /// Returns the command used to start up a context server.
+    export context-server-command: func(context-server-id: string, project: borrow<project>) -> result<command, string>;
+
+    /// Returns the configuration for a context server.
+    export context-server-configuration: func(context-server-id: string, project: borrow<project>) -> result<option<context-server-configuration>, string>;
+
+    /// Returns a list of packages as suggestions to be included in the `/docs`
+    /// search results.
+    ///
+    /// This can be used to provide completions for known packages (e.g., from the
+    /// local project or a registry) before a package has been indexed.
+    export suggest-docs-packages: func(provider-name: string) -> result<list<string>, string>;
+
+    /// Indexes the docs for the specified package.
+    export index-docs: func(provider-name: string, package-name: string, database: borrow<key-value-store>) -> result<_, string>;
+
+    /// Returns a configured debug adapter binary for a given debug task.
+    export get-dap-binary: func(adapter-name: string, config: debug-task-definition, user-installed-path: option<string>, worktree: borrow<worktree>) -> result<debug-adapter-binary, string>;
+    /// Returns the kind of a debug scenario (launch or attach).
+    export dap-request-kind: func(adapter-name: string, config: string) -> result<start-debugging-request-arguments-request, string>;
+    export dap-config-to-scenario: func(config: debug-config) -> result<debug-scenario, string>;
+    export dap-locator-create-scenario: func(locator-name: string, build-config-template: build-task-template, resolved-label: string, debug-adapter-name: string) -> option<debug-scenario>;
+    export run-dap-locator: func(locator-name: string, config: resolved-task) -> result<debug-request, string>;
+}

crates/extension_api/wit/since_v0.8.0/github.wit 🔗

@@ -0,0 +1,35 @@
+interface github {
+    /// A GitHub release.
+    record github-release {
+        /// The version of the release.
+        version: string,
+        /// The list of assets attached to the release.
+        assets: list<github-release-asset>,
+    }
+
+    /// An asset from a GitHub release.
+    record github-release-asset {
+        /// The name of the asset.
+        name: string,
+        /// The download URL for the asset.
+        download-url: string,
+    }
+
+    /// The options used to filter down GitHub releases.
+    record github-release-options {
+        /// Whether releases without assets should be included.
+        require-assets: bool,
+        /// Whether pre-releases should be included.
+        pre-release: bool,
+    }
+
+    /// Returns the latest release for the given GitHub repository.
+    ///
+    /// Takes repo as a string in the form "<owner-name>/<repo-name>", for example: "zed-industries/zed".
+    latest-github-release: func(repo: string, options: github-release-options) -> result<github-release, string>;
+
+    /// Returns the GitHub release with the specified tag name for the given GitHub repository.
+    ///
+    /// Returns an error if a release with the given tag name does not exist.
+    github-release-by-tag-name: func(repo: string, tag: string) -> result<github-release, string>;
+}

crates/extension_api/wit/since_v0.8.0/http-client.wit 🔗

@@ -0,0 +1,67 @@
+interface http-client {
+    /// An HTTP request.
+    record http-request {
+        /// The HTTP method for the request.
+        method: http-method,
+        /// The URL to which the request should be made.
+        url: string,
+        /// The headers for the request.
+        headers: list<tuple<string, string>>,
+        /// The request body.
+        body: option<list<u8>>,
+        /// The policy to use for redirects.
+        redirect-policy: redirect-policy,
+    }
+
+    /// HTTP methods.
+    enum http-method {
+        /// `GET`
+        get,
+        /// `HEAD`
+        head,
+        /// `POST`
+        post,
+        /// `PUT`
+        put,
+        /// `DELETE`
+        delete,
+        /// `OPTIONS`
+        options,
+        /// `PATCH`
+        patch,
+    }
+
+    /// The policy for dealing with redirects received from the server.
+    variant redirect-policy {
+        /// Redirects from the server will not be followed.
+        ///
+        /// This is the default behavior.
+        no-follow,
+        /// Redirects from the server will be followed up to the specified limit.
+        follow-limit(u32),
+        /// All redirects from the server will be followed.
+        follow-all,
+    }
+
+    /// An HTTP response.
+    record http-response {
+        /// The response headers.
+        headers: list<tuple<string, string>>,
+        /// The response body.
+        body: list<u8>,
+    }
+
+    /// Performs an HTTP request and returns the response.
+    fetch: func(req: http-request) -> result<http-response, string>;
+
+    /// An HTTP response stream.
+    resource http-response-stream {
+        /// Retrieves the next chunk of data from the response stream.
+        ///
+        /// Returns `Ok(None)` if the stream has ended.
+        next-chunk: func() -> result<option<list<u8>>, string>;
+    }
+
+    /// Performs an HTTP request and returns a response stream.
+    fetch-stream: func(req: http-request) -> result<http-response-stream, string>;
+}

crates/extension_api/wit/since_v0.8.0/lsp.wit 🔗

@@ -0,0 +1,90 @@
+interface lsp {
+    /// An LSP completion.
+    record completion {
+        label: string,
+        label-details: option<completion-label-details>,
+        detail: option<string>,
+        kind: option<completion-kind>,
+        insert-text-format: option<insert-text-format>,
+    }
+
+    /// The kind of an LSP completion.
+    variant completion-kind {
+        text,
+        method,
+        function,
+        %constructor,
+        field,
+        variable,
+        class,
+        %interface,
+        module,
+        property,
+        unit,
+        value,
+        %enum,
+        keyword,
+        snippet,
+        color,
+        file,
+        reference,
+        folder,
+        enum-member,
+        constant,
+        struct,
+        event,
+        operator,
+        type-parameter,
+        other(s32),
+    }
+
+    /// Label details for an LSP completion.
+    record completion-label-details {
+        detail: option<string>,
+        description: option<string>,
+    }
+
+    /// Defines how to interpret the insert text in a completion item.
+    variant insert-text-format {
+        plain-text,
+        snippet,
+        other(s32),
+    }
+
+    /// An LSP symbol.
+    record symbol {
+        kind: symbol-kind,
+        name: string,
+    }
+
+    /// The kind of an LSP symbol.
+    variant symbol-kind {
+        file,
+        module,
+        namespace,
+        %package,
+        class,
+        method,
+        property,
+        field,
+        %constructor,
+        %enum,
+        %interface,
+        function,
+        variable,
+        constant,
+        %string,
+        number,
+        boolean,
+        array,
+        object,
+        key,
+        null,
+        enum-member,
+        struct,
+        event,
+        operator,
+        type-parameter,
+        other(s32),
+    }
+}

crates/extension_api/wit/since_v0.8.0/nodejs.wit 🔗

@@ -0,0 +1,13 @@
+interface nodejs {
+    /// Returns the path to the Node binary used by Zed.
+    node-binary-path: func() -> result<string, string>;
+
+    /// Returns the latest version of the given NPM package.
+    npm-package-latest-version: func(package-name: string) -> result<string, string>;
+
+    /// Returns the installed version of the given NPM package, if it exists.
+    npm-package-installed-version: func(package-name: string) -> result<option<string>, string>;
+
+    /// Installs the specified NPM package.
+    npm-install-package: func(package-name: string, version: string) -> result<_, string>;
+}

crates/extension_api/wit/since_v0.8.0/platform.wit 🔗

@@ -0,0 +1,24 @@
+interface platform {
+    /// An operating system.
+    enum os {
+        /// macOS.
+        mac,
+        /// Linux.
+        linux,
+        /// Windows.
+        windows,
+    }
+
+    /// A platform architecture.
+    enum architecture {
+        /// AArch64 (e.g., Apple Silicon).
+        aarch64,
+        /// x86.
+        x86,
+        /// x86-64.
+        x8664,
+    }
+
+    /// Gets the current operating system and architecture.
+    current-platform: func() -> tuple<os, architecture>;
+}

crates/extension_api/wit/since_v0.8.0/process.wit 🔗

@@ -0,0 +1,29 @@
+interface process {
+    use common.{env-vars};
+
+    /// A command.
+    record command {
+        /// The command to execute.
+        command: string,
+        /// The arguments to pass to the command.
+        args: list<string>,
+        /// The environment variables to set for the command.
+        env: env-vars,
+    }
+
+    /// The output of a finished process.
+    record output {
+        /// The status (exit code) of the process.
+        ///
+        /// On Unix, this will be `None` if the process was terminated by a signal.
+        status: option<s32>,
+        /// The data that the process wrote to stdout.
+        stdout: list<u8>,
+        /// The data that the process wrote to stderr.
+        stderr: list<u8>,
+    }
+
+    /// Executes the given command as a child process, waiting for it to finish
+    /// and collecting all of its output.
+    run-command: func(command: command) -> result<output, string>;
+}

crates/extension_api/wit/since_v0.8.0/settings.rs 🔗

@@ -0,0 +1,40 @@
+use serde::{Deserialize, Serialize};
+use std::{collections::HashMap, num::NonZeroU32};
+
+/// The settings for a particular language.
+#[derive(Debug, Serialize, Deserialize)]
+pub struct LanguageSettings {
+    /// How many columns a tab should occupy.
+    pub tab_size: NonZeroU32,
+}
+
+/// The settings for a particular language server.
+#[derive(Default, Debug, Serialize, Deserialize)]
+pub struct LspSettings {
+    /// The settings for the language server binary.
+    pub binary: Option<CommandSettings>,
+    /// The initialization options to pass to the language server.
+    pub initialization_options: Option<serde_json::Value>,
+    /// The settings to pass to language server.
+    pub settings: Option<serde_json::Value>,
+}
+
+/// The settings for a particular context server.
+#[derive(Default, Debug, Serialize, Deserialize, PartialEq, Eq)]
+pub struct ContextServerSettings {
+    /// The settings for the context server binary.
+    pub command: Option<CommandSettings>,
+    /// The settings to pass to the context server.
+    pub settings: Option<serde_json::Value>,
+}
+
+/// The settings for a command.
+#[derive(Debug, Serialize, Deserialize, PartialEq, Eq)]
+pub struct CommandSettings {
+    /// The path to the command.
+    pub path: Option<String>,
+    /// The arguments to pass to the command.
+    pub arguments: Option<Vec<String>>,
+    /// The environment variables.
+    pub env: Option<HashMap<String, String>>,
+}

crates/extension_api/wit/since_v0.8.0/slash-command.wit 🔗

@@ -0,0 +1,41 @@
+interface slash-command {
+    use common.{range};
+
+    /// A slash command for use in the Assistant.
+    record slash-command {
+        /// The name of the slash command.
+        name: string,
+        /// The description of the slash command.
+        description: string,
+        /// The tooltip text to display for the run button.
+        tooltip-text: string,
+        /// Whether this slash command requires an argument.
+        requires-argument: bool,
+    }
+
+    /// The output of a slash command.
+    record slash-command-output {
+        /// The text produced by the slash command.
+        text: string,
+        /// The list of sections to show in the slash command placeholder.
+        sections: list<slash-command-output-section>,
+    }
+
+    /// A section in the slash command output.
+    record slash-command-output-section {
+        /// The range this section occupies.
+        range: range,
+        /// The label to display in the placeholder for this section.
+        label: string,
+    }
+
+    /// A completion for a slash command argument.
+    record slash-command-argument-completion {
+        /// The label to display for this completion.
+        label: string,
+        /// The new text that should be inserted into the command when this completion is accepted.
+        new-text: string,
+        /// Whether the command should be run when accepting this completion.
+        run-command: bool,
+    }
+}

crates/extension_cli/src/main.rs 🔗

@@ -71,6 +71,7 @@ async fn main() -> Result<()> {
             &extension_path,
             &mut manifest,
             CompileExtensionOptions { release: true },
+            fs.clone(),
         )
         .await
         .context("failed to compile extension")?;

crates/extension_host/benches/extension_compilation_benchmark.rs 🔗

@@ -7,7 +7,7 @@ use extension::{
     extension_builder::{CompileExtensionOptions, ExtensionBuilder},
 };
 use extension_host::wasm_host::WasmHost;
-use fs::RealFs;
+use fs::{Fs, RealFs};
 use gpui::{TestAppContext, TestDispatcher};
 use http_client::{FakeHttpClient, Response};
 use node_runtime::NodeRuntime;
@@ -24,7 +24,11 @@ fn extension_benchmarks(c: &mut Criterion) {
     let mut group = c.benchmark_group("load");
 
     let mut manifest = manifest();
-    let wasm_bytes = wasm_bytes(&cx, &mut manifest);
+    let wasm_bytes = wasm_bytes(
+        &cx,
+        &mut manifest,
+        Arc::new(RealFs::new(None, cx.executor())),
+    );
     let manifest = Arc::new(manifest);
     let extensions_dir = TempTree::new(json!({
         "installed": {},
@@ -60,7 +64,7 @@ fn init() -> TestAppContext {
     cx
 }
 
-fn wasm_bytes(cx: &TestAppContext, manifest: &mut ExtensionManifest) -> Vec<u8> {
+fn wasm_bytes(cx: &TestAppContext, manifest: &mut ExtensionManifest, fs: Arc<dyn Fs>) -> Vec<u8> {
     let extension_builder = extension_builder();
     let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
         .parent()
@@ -73,6 +77,7 @@ fn wasm_bytes(cx: &TestAppContext, manifest: &mut ExtensionManifest) -> Vec<u8>
             &path,
             manifest,
             CompileExtensionOptions { release: true },
+            fs,
         ))
         .unwrap();
     std::fs::read(path.join("extension.wasm")).unwrap()
@@ -143,6 +148,7 @@ fn manifest() -> ExtensionManifest {
         )],
         debug_adapters: Default::default(),
         debug_locators: Default::default(),
+        language_model_providers: BTreeMap::default(),
     }
 }
 

crates/extension_host/src/extension_host.rs 🔗

@@ -980,12 +980,14 @@ impl ExtensionStore {
 
             cx.background_spawn({
                 let extension_source_path = extension_source_path.clone();
+                let fs = fs.clone();
                 async move {
                     builder
                         .compile_extension(
                             &extension_source_path,
                             &mut extension_manifest,
                             CompileExtensionOptions { release: false },
+                            fs,
                         )
                         .await
                 }
@@ -1042,12 +1044,13 @@ impl ExtensionStore {
 
         cx.notify();
         let compile = cx.background_spawn(async move {
-            let mut manifest = ExtensionManifest::load(fs, &path).await?;
+            let mut manifest = ExtensionManifest::load(fs.clone(), &path).await?;
             builder
                 .compile_extension(
                     &path,
                     &mut manifest,
                     CompileExtensionOptions { release: true },
+                    fs,
                 )
                 .await
         });

crates/extension_host/src/extension_store_test.rs 🔗

@@ -165,6 +165,7 @@ async fn test_extension_store(cx: &mut TestAppContext) {
                         capabilities: Vec::new(),
                         debug_adapters: Default::default(),
                         debug_locators: Default::default(),
+                        language_model_providers: BTreeMap::default(),
                     }),
                     dev: false,
                 },
@@ -196,6 +197,7 @@ async fn test_extension_store(cx: &mut TestAppContext) {
                         capabilities: Vec::new(),
                         debug_adapters: Default::default(),
                         debug_locators: Default::default(),
+                        language_model_providers: BTreeMap::default(),
                     }),
                     dev: false,
                 },
@@ -307,9 +309,9 @@ async fn test_extension_store(cx: &mut TestAppContext) {
         assert_eq!(
             language_registry.language_names(),
             [
-                LanguageName::new("ERB"),
-                LanguageName::new("Plain Text"),
-                LanguageName::new("Ruby"),
+                LanguageName::new_static("ERB"),
+                LanguageName::new_static("Plain Text"),
+                LanguageName::new_static("Ruby"),
             ]
         );
         assert_eq!(
@@ -376,6 +378,7 @@ async fn test_extension_store(cx: &mut TestAppContext) {
                 capabilities: Vec::new(),
                 debug_adapters: Default::default(),
                 debug_locators: Default::default(),
+                language_model_providers: BTreeMap::default(),
             }),
             dev: false,
         },
@@ -463,9 +466,9 @@ async fn test_extension_store(cx: &mut TestAppContext) {
         assert_eq!(
             language_registry.language_names(),
             [
-                LanguageName::new("ERB"),
-                LanguageName::new("Plain Text"),
-                LanguageName::new("Ruby"),
+                LanguageName::new_static("ERB"),
+                LanguageName::new_static("Plain Text"),
+                LanguageName::new_static("Ruby"),
             ]
         );
         assert_eq!(
@@ -523,7 +526,7 @@ async fn test_extension_store(cx: &mut TestAppContext) {
 
         assert_eq!(
             language_registry.language_names(),
-            [LanguageName::new("Plain Text")]
+            [LanguageName::new_static("Plain Text")]
         );
         assert_eq!(language_registry.grammar_names(), []);
     });
@@ -705,7 +708,7 @@ async fn test_extension_store_with_test_extension(cx: &mut TestAppContext) {
         .await
         .unwrap();
 
-    let mut fake_servers = language_registry.register_fake_language_server(
+    let mut fake_servers = language_registry.register_fake_lsp_server(
         LanguageServerName("gleam".into()),
         lsp::ServerCapabilities {
             completion_provider: Some(Default::default()),

crates/extension_host/src/wasm_host.rs 🔗

@@ -45,7 +45,7 @@ use wasmtime::{
     CacheStore, Engine, Store,
     component::{Component, ResourceTable},
 };
-use wasmtime_wasi::{self as wasi, WasiView};
+use wasmtime_wasi::p2::{self as wasi, IoView as _};
 use wit::Extension;
 
 pub struct WasmHost {
@@ -685,8 +685,8 @@ impl WasmHost {
             .await
             .context("failed to create extension work dir")?;
 
-        let file_perms = wasi::FilePerms::all();
-        let dir_perms = wasi::DirPerms::all();
+        let file_perms = wasmtime_wasi::FilePerms::all();
+        let dir_perms = wasmtime_wasi::DirPerms::all();
         let path = SanitizedPath::new(&extension_work_dir).to_string();
         #[cfg(target_os = "windows")]
         let path = path.replace('\\', "/");
@@ -856,11 +856,13 @@ impl WasmState {
     }
 }
 
-impl wasi::WasiView for WasmState {
+impl wasi::IoView for WasmState {
     fn table(&mut self) -> &mut ResourceTable {
         &mut self.table
     }
+}
 
+impl wasi::WasiView for WasmState {
     fn ctx(&mut self) -> &mut wasi::WasiCtx {
         &mut self.ctx
     }

crates/extension_host/src/wasm_host/wit.rs 🔗

@@ -7,6 +7,7 @@ mod since_v0_3_0;
 mod since_v0_4_0;
 mod since_v0_5_0;
 mod since_v0_6_0;
+mod since_v0_8_0;
 use dap::DebugRequest;
 use extension::{DebugTaskDefinition, KeyValueStoreDelegate, WorktreeDelegate};
 use gpui::BackgroundExecutor;
@@ -20,7 +21,7 @@ use crate::wasm_host::wit::since_v0_6_0::dap::StartDebuggingRequestArgumentsRequ
 use super::{WasmState, wasm_engine};
 use anyhow::{Context as _, Result, anyhow};
 use semver::Version;
-use since_v0_6_0 as latest;
+use since_v0_8_0 as latest;
 use std::{ops::RangeInclusive, path::PathBuf, sync::Arc};
 use wasmtime::{
     Store,
@@ -44,7 +45,7 @@ pub fn new_linker(
     f: impl Fn(&mut Linker<WasmState>, fn(&mut WasmState) -> &mut WasmState) -> Result<()>,
 ) -> Linker<WasmState> {
     let mut linker = Linker::new(&wasm_engine(executor));
-    wasmtime_wasi::add_to_linker_async(&mut linker).unwrap();
+    wasmtime_wasi::p2::add_to_linker_async(&mut linker).unwrap();
     f(&mut linker, wasi_view).unwrap();
     linker
 }
@@ -66,7 +67,7 @@ pub fn wasm_api_version_range(release_channel: ReleaseChannel) -> RangeInclusive
 
     let max_version = match release_channel {
         ReleaseChannel::Dev | ReleaseChannel::Nightly => latest::MAX_VERSION,
-        ReleaseChannel::Stable | ReleaseChannel::Preview => latest::MAX_VERSION,
+        ReleaseChannel::Stable | ReleaseChannel::Preview => since_v0_6_0::MAX_VERSION,
     };
 
     since_v0_0_1::MIN_VERSION..=max_version
@@ -95,6 +96,7 @@ pub fn authorize_access_to_unreleased_wasm_api_version(
 }
 
 pub enum Extension {
+    V0_8_0(since_v0_8_0::Extension),
     V0_6_0(since_v0_6_0::Extension),
     V0_5_0(since_v0_5_0::Extension),
     V0_4_0(since_v0_4_0::Extension),
@@ -118,10 +120,21 @@ impl Extension {
         let _ = release_channel;
 
         if version >= latest::MIN_VERSION {
+            authorize_access_to_unreleased_wasm_api_version(release_channel)?;
+
             let extension =
                 latest::Extension::instantiate_async(store, component, latest::linker(executor))
                     .await
                     .context("failed to instantiate wasm extension")?;
+            Ok(Self::V0_8_0(extension))
+        } else if version >= since_v0_6_0::MIN_VERSION {
+            let extension = since_v0_6_0::Extension::instantiate_async(
+                store,
+                component,
+                since_v0_6_0::linker(executor),
+            )
+            .await
+            .context("failed to instantiate wasm extension")?;
             Ok(Self::V0_6_0(extension))
         } else if version >= since_v0_5_0::MIN_VERSION {
             let extension = since_v0_5_0::Extension::instantiate_async(
@@ -200,6 +213,7 @@ impl Extension {
 
     pub async fn call_init_extension(&self, store: &mut Store<WasmState>) -> Result<()> {
         match self {
+            Extension::V0_8_0(ext) => ext.call_init_extension(store).await,
             Extension::V0_6_0(ext) => ext.call_init_extension(store).await,
             Extension::V0_5_0(ext) => ext.call_init_extension(store).await,
             Extension::V0_4_0(ext) => ext.call_init_extension(store).await,
@@ -220,6 +234,10 @@ impl Extension {
         resource: Resource<Arc<dyn WorktreeDelegate>>,
     ) -> Result<Result<Command, String>> {
         match self {
+            Extension::V0_8_0(ext) => {
+                ext.call_language_server_command(store, &language_server_id.0, resource)
+                    .await
+            }
             Extension::V0_6_0(ext) => {
                 ext.call_language_server_command(store, &language_server_id.0, resource)
                     .await
@@ -282,6 +300,14 @@ impl Extension {
         resource: Resource<Arc<dyn WorktreeDelegate>>,
     ) -> Result<Result<Option<String>, String>> {
         match self {
+            Extension::V0_8_0(ext) => {
+                ext.call_language_server_initialization_options(
+                    store,
+                    &language_server_id.0,
+                    resource,
+                )
+                .await
+            }
             Extension::V0_6_0(ext) => {
                 ext.call_language_server_initialization_options(
                     store,
@@ -371,6 +397,14 @@ impl Extension {
         resource: Resource<Arc<dyn WorktreeDelegate>>,
     ) -> Result<Result<Option<String>, String>> {
         match self {
+            Extension::V0_8_0(ext) => {
+                ext.call_language_server_workspace_configuration(
+                    store,
+                    &language_server_id.0,
+                    resource,
+                )
+                .await
+            }
             Extension::V0_6_0(ext) => {
                 ext.call_language_server_workspace_configuration(
                     store,
@@ -439,6 +473,15 @@ impl Extension {
         resource: Resource<Arc<dyn WorktreeDelegate>>,
     ) -> Result<Result<Option<String>, String>> {
         match self {
+            Extension::V0_8_0(ext) => {
+                ext.call_language_server_additional_initialization_options(
+                    store,
+                    &language_server_id.0,
+                    &target_language_server_id.0,
+                    resource,
+                )
+                .await
+            }
             Extension::V0_6_0(ext) => {
                 ext.call_language_server_additional_initialization_options(
                     store,
@@ -483,6 +526,15 @@ impl Extension {
         resource: Resource<Arc<dyn WorktreeDelegate>>,
     ) -> Result<Result<Option<String>, String>> {
         match self {
+            Extension::V0_8_0(ext) => {
+                ext.call_language_server_additional_workspace_configuration(
+                    store,
+                    &language_server_id.0,
+                    &target_language_server_id.0,
+                    resource,
+                )
+                .await
+            }
             Extension::V0_6_0(ext) => {
                 ext.call_language_server_additional_workspace_configuration(
                     store,
@@ -526,10 +578,23 @@ impl Extension {
         completions: Vec<latest::Completion>,
     ) -> Result<Result<Vec<Option<CodeLabel>>, String>> {
         match self {
-            Extension::V0_6_0(ext) => {
+            Extension::V0_8_0(ext) => {
                 ext.call_labels_for_completions(store, &language_server_id.0, &completions)
                     .await
             }
+            Extension::V0_6_0(ext) => Ok(ext
+                .call_labels_for_completions(
+                    store,
+                    &language_server_id.0,
+                    &completions.into_iter().collect::<Vec<_>>(),
+                )
+                .await?
+                .map(|labels| {
+                    labels
+                        .into_iter()
+                        .map(|label| label.map(Into::into))
+                        .collect()
+                })),
             Extension::V0_5_0(ext) => Ok(ext
                 .call_labels_for_completions(
                     store,
@@ -619,10 +684,23 @@ impl Extension {
         symbols: Vec<latest::Symbol>,
     ) -> Result<Result<Vec<Option<CodeLabel>>, String>> {
         match self {
-            Extension::V0_6_0(ext) => {
+            Extension::V0_8_0(ext) => {
                 ext.call_labels_for_symbols(store, &language_server_id.0, &symbols)
                     .await
             }
+            Extension::V0_6_0(ext) => Ok(ext
+                .call_labels_for_symbols(
+                    store,
+                    &language_server_id.0,
+                    &symbols.into_iter().collect::<Vec<_>>(),
+                )
+                .await?
+                .map(|labels| {
+                    labels
+                        .into_iter()
+                        .map(|label| label.map(Into::into))
+                        .collect()
+                })),
             Extension::V0_5_0(ext) => Ok(ext
                 .call_labels_for_symbols(
                     store,
@@ -712,6 +790,10 @@ impl Extension {
         arguments: &[String],
     ) -> Result<Result<Vec<SlashCommandArgumentCompletion>, String>> {
         match self {
+            Extension::V0_8_0(ext) => {
+                ext.call_complete_slash_command_argument(store, command, arguments)
+                    .await
+            }
             Extension::V0_6_0(ext) => {
                 ext.call_complete_slash_command_argument(store, command, arguments)
                     .await
@@ -750,6 +832,10 @@ impl Extension {
         resource: Option<Resource<Arc<dyn WorktreeDelegate>>>,
     ) -> Result<Result<SlashCommandOutput, String>> {
         match self {
+            Extension::V0_8_0(ext) => {
+                ext.call_run_slash_command(store, command, arguments, resource)
+                    .await
+            }
             Extension::V0_6_0(ext) => {
                 ext.call_run_slash_command(store, command, arguments, resource)
                     .await
@@ -787,6 +873,10 @@ impl Extension {
         project: Resource<ExtensionProject>,
     ) -> Result<Result<Command, String>> {
         match self {
+            Extension::V0_8_0(ext) => {
+                ext.call_context_server_command(store, &context_server_id, project)
+                    .await
+            }
             Extension::V0_6_0(ext) => {
                 ext.call_context_server_command(store, &context_server_id, project)
                     .await
@@ -823,6 +913,10 @@ impl Extension {
         project: Resource<ExtensionProject>,
     ) -> Result<Result<Option<ContextServerConfiguration>, String>> {
         match self {
+            Extension::V0_8_0(ext) => {
+                ext.call_context_server_configuration(store, &context_server_id, project)
+                    .await
+            }
             Extension::V0_6_0(ext) => {
                 ext.call_context_server_configuration(store, &context_server_id, project)
                     .await
@@ -849,6 +943,7 @@ impl Extension {
         provider: &str,
     ) -> Result<Result<Vec<String>, String>> {
         match self {
+            Extension::V0_8_0(ext) => ext.call_suggest_docs_packages(store, provider).await,
             Extension::V0_6_0(ext) => ext.call_suggest_docs_packages(store, provider).await,
             Extension::V0_5_0(ext) => ext.call_suggest_docs_packages(store, provider).await,
             Extension::V0_4_0(ext) => ext.call_suggest_docs_packages(store, provider).await,
@@ -869,6 +964,10 @@ impl Extension {
         kv_store: Resource<Arc<dyn KeyValueStoreDelegate>>,
     ) -> Result<Result<(), String>> {
         match self {
+            Extension::V0_8_0(ext) => {
+                ext.call_index_docs(store, provider, package_name, kv_store)
+                    .await
+            }
             Extension::V0_6_0(ext) => {
                 ext.call_index_docs(store, provider, package_name, kv_store)
                     .await
@@ -898,6 +997,7 @@ impl Extension {
             }
         }
     }
+
     pub async fn call_get_dap_binary(
         &self,
         store: &mut Store<WasmState>,
@@ -924,6 +1024,7 @@ impl Extension {
             _ => anyhow::bail!("`get_dap_binary` not available prior to v0.6.0"),
         }
     }
+
     pub async fn call_dap_request_kind(
         &self,
         store: &mut Store<WasmState>,
@@ -944,6 +1045,7 @@ impl Extension {
             _ => anyhow::bail!("`dap_request_kind` not available prior to v0.6.0"),
         }
     }
+
     pub async fn call_dap_config_to_scenario(
         &self,
         store: &mut Store<WasmState>,
@@ -962,6 +1064,7 @@ impl Extension {
             _ => anyhow::bail!("`dap_config_to_scenario` not available prior to v0.6.0"),
         }
     }
+
     pub async fn call_dap_locator_create_scenario(
         &self,
         store: &mut Store<WasmState>,
@@ -988,6 +1091,7 @@ impl Extension {
             _ => anyhow::bail!("`dap_locator_create_scenario` not available prior to v0.6.0"),
         }
     }
+
     pub async fn call_run_dap_locator(
         &self,
         store: &mut Store<WasmState>,

crates/extension_host/src/wasm_host/wit/since_v0_6_0.rs 🔗

@@ -1,41 +1,13 @@
-use crate::wasm_host::wit::since_v0_6_0::{
-    dap::{
-        AttachRequest, BuildTaskDefinition, BuildTaskDefinitionTemplatePayload, LaunchRequest,
-        StartDebuggingRequestArguments, TcpArguments, TcpArgumentsTemplate,
-    },
-    slash_command::SlashCommandOutputSection,
-};
-use crate::wasm_host::wit::{CompletionKind, CompletionLabelDetails, InsertTextFormat, SymbolKind};
-use crate::wasm_host::{WasmState, wit::ToWasmtimeResult};
-use ::http_client::{AsyncBody, HttpRequestExt};
-use ::settings::{Settings, WorktreeId};
-use anyhow::{Context as _, Result, bail};
-use async_compression::futures::bufread::GzipDecoder;
-use async_tar::Archive;
-use async_trait::async_trait;
-use extension::{
-    ExtensionLanguageServerProxy, KeyValueStoreDelegate, ProjectDelegate, WorktreeDelegate,
-};
-use futures::{AsyncReadExt, lock::Mutex};
-use futures::{FutureExt as _, io::BufReader};
-use gpui::{BackgroundExecutor, SharedString};
-use language::{BinaryStatus, LanguageName, language_settings::AllLanguageSettings};
-use project::project_settings::ProjectSettings;
+use crate::wasm_host::WasmState;
+use anyhow::Result;
+use extension::{KeyValueStoreDelegate, ProjectDelegate, WorktreeDelegate};
+use gpui::BackgroundExecutor;
 use semver::Version;
-use std::{
-    env,
-    net::Ipv4Addr,
-    path::{Path, PathBuf},
-    str::FromStr,
-    sync::{Arc, OnceLock},
-};
-use task::{SpawnInTerminal, ZedDebugConfig};
-use url::Url;
-use util::{
-    archive::extract_zip, fs::make_file_executable, maybe, paths::PathStyle, rel_path::RelPath,
-};
+use std::sync::{Arc, OnceLock};
 use wasmtime::component::{Linker, Resource};
 
+use super::latest;
+
 pub const MIN_VERSION: Version = Version::new(0, 6, 0);
 pub const MAX_VERSION: Version = Version::new(0, 7, 0);
 
@@ -44,10 +16,19 @@ wasmtime::component::bindgen!({
     trappable_imports: true,
     path: "../extension_api/wit/since_v0.6.0",
     with: {
-         "worktree": ExtensionWorktree,
-         "project": ExtensionProject,
-         "key-value-store": ExtensionKeyValueStore,
-         "zed:extension/http-client/http-response-stream": ExtensionHttpResponseStream
+        "worktree": ExtensionWorktree,
+        "project": ExtensionProject,
+        "key-value-store": ExtensionKeyValueStore,
+        "zed:extension/common": latest::zed::extension::common,
+        "zed:extension/github": latest::zed::extension::github,
+        "zed:extension/http-client": latest::zed::extension::http_client,
+        "zed:extension/lsp": latest::zed::extension::lsp,
+        "zed:extension/nodejs": latest::zed::extension::nodejs,
+        "zed:extension/platform": latest::zed::extension::platform,
+        "zed:extension/process": latest::zed::extension::process,
+        "zed:extension/slash-command": latest::zed::extension::slash_command,
+        "zed:extension/context-server": latest::zed::extension::context_server,
+        "zed:extension/dap": latest::zed::extension::dap,
     },
 });
 
@@ -61,289 +42,32 @@ mod settings {
 pub type ExtensionWorktree = Arc<dyn WorktreeDelegate>;
 pub type ExtensionProject = Arc<dyn ProjectDelegate>;
 pub type ExtensionKeyValueStore = Arc<dyn KeyValueStoreDelegate>;
-pub type ExtensionHttpResponseStream = Arc<Mutex<::http_client::Response<AsyncBody>>>;
 
 pub fn linker(executor: &BackgroundExecutor) -> &'static Linker<WasmState> {
     static LINKER: OnceLock<Linker<WasmState>> = OnceLock::new();
     LINKER.get_or_init(|| super::new_linker(executor, Extension::add_to_linker))
 }
 
-impl From<Range> for std::ops::Range<usize> {
-    fn from(range: Range) -> Self {
-        let start = range.start as usize;
-        let end = range.end as usize;
-        start..end
-    }
-}
-
-impl From<Command> for extension::Command {
-    fn from(value: Command) -> Self {
-        Self {
-            command: value.command.into(),
-            args: value.args,
-            env: value.env,
-        }
-    }
-}
-
-impl From<StartDebuggingRequestArgumentsRequest>
-    for extension::StartDebuggingRequestArgumentsRequest
-{
-    fn from(value: StartDebuggingRequestArgumentsRequest) -> Self {
-        match value {
-            StartDebuggingRequestArgumentsRequest::Launch => Self::Launch,
-            StartDebuggingRequestArgumentsRequest::Attach => Self::Attach,
-        }
-    }
-}
-impl TryFrom<StartDebuggingRequestArguments> for extension::StartDebuggingRequestArguments {
-    type Error = anyhow::Error;
-
-    fn try_from(value: StartDebuggingRequestArguments) -> Result<Self, Self::Error> {
-        Ok(Self {
-            configuration: serde_json::from_str(&value.configuration)?,
-            request: value.request.into(),
-        })
-    }
-}
-impl From<TcpArguments> for extension::TcpArguments {
-    fn from(value: TcpArguments) -> Self {
-        Self {
-            host: value.host.into(),
-            port: value.port,
-            timeout: value.timeout,
-        }
-    }
-}
-
-impl From<extension::TcpArgumentsTemplate> for TcpArgumentsTemplate {
-    fn from(value: extension::TcpArgumentsTemplate) -> Self {
-        Self {
-            host: value.host.map(Ipv4Addr::to_bits),
-            port: value.port,
-            timeout: value.timeout,
-        }
-    }
-}
-
-impl From<TcpArgumentsTemplate> for extension::TcpArgumentsTemplate {
-    fn from(value: TcpArgumentsTemplate) -> Self {
-        Self {
-            host: value.host.map(Ipv4Addr::from_bits),
-            port: value.port,
-            timeout: value.timeout,
-        }
-    }
-}
-
-impl TryFrom<extension::DebugTaskDefinition> for DebugTaskDefinition {
-    type Error = anyhow::Error;
-    fn try_from(value: extension::DebugTaskDefinition) -> Result<Self, Self::Error> {
-        Ok(Self {
-            label: value.label.to_string(),
-            adapter: value.adapter.to_string(),
-            config: value.config.to_string(),
-            tcp_connection: value.tcp_connection.map(Into::into),
-        })
-    }
-}
-
-impl From<task::DebugRequest> for DebugRequest {
-    fn from(value: task::DebugRequest) -> Self {
-        match value {
-            task::DebugRequest::Launch(launch_request) => Self::Launch(launch_request.into()),
-            task::DebugRequest::Attach(attach_request) => Self::Attach(attach_request.into()),
-        }
-    }
-}
-
-impl From<DebugRequest> for task::DebugRequest {
-    fn from(value: DebugRequest) -> Self {
-        match value {
-            DebugRequest::Launch(launch_request) => Self::Launch(launch_request.into()),
-            DebugRequest::Attach(attach_request) => Self::Attach(attach_request.into()),
-        }
-    }
-}
-
-impl From<task::LaunchRequest> for LaunchRequest {
-    fn from(value: task::LaunchRequest) -> Self {
-        Self {
-            program: value.program,
-            cwd: value.cwd.map(|p| p.to_string_lossy().into_owned()),
-            args: value.args,
-            envs: value.env.into_iter().collect(),
-        }
-    }
-}
-
-impl From<task::AttachRequest> for AttachRequest {
-    fn from(value: task::AttachRequest) -> Self {
-        Self {
-            process_id: value.process_id,
-        }
-    }
-}
-
-impl From<LaunchRequest> for task::LaunchRequest {
-    fn from(value: LaunchRequest) -> Self {
-        Self {
-            program: value.program,
-            cwd: value.cwd.map(|p| p.into()),
-            args: value.args,
-            env: value.envs.into_iter().collect(),
-        }
-    }
-}
-impl From<AttachRequest> for task::AttachRequest {
-    fn from(value: AttachRequest) -> Self {
-        Self {
-            process_id: value.process_id,
-        }
-    }
-}
-
-impl From<ZedDebugConfig> for DebugConfig {
-    fn from(value: ZedDebugConfig) -> Self {
-        Self {
-            label: value.label.into(),
-            adapter: value.adapter.into(),
-            request: value.request.into(),
-            stop_on_entry: value.stop_on_entry,
-        }
-    }
-}
-impl TryFrom<DebugAdapterBinary> for extension::DebugAdapterBinary {
-    type Error = anyhow::Error;
-    fn try_from(value: DebugAdapterBinary) -> Result<Self, Self::Error> {
-        Ok(Self {
-            command: value.command,
-            arguments: value.arguments,
-            envs: value.envs.into_iter().collect(),
-            cwd: value.cwd.map(|s| s.into()),
-            connection: value.connection.map(Into::into),
-            request_args: value.request_args.try_into()?,
-        })
-    }
-}
-
-impl From<BuildTaskDefinition> for extension::BuildTaskDefinition {
-    fn from(value: BuildTaskDefinition) -> Self {
-        match value {
-            BuildTaskDefinition::ByName(name) => Self::ByName(name.into()),
-            BuildTaskDefinition::Template(build_task_template) => Self::Template {
-                task_template: build_task_template.template.into(),
-                locator_name: build_task_template.locator_name.map(SharedString::from),
-            },
-        }
-    }
-}
-
-impl From<extension::BuildTaskDefinition> for BuildTaskDefinition {
-    fn from(value: extension::BuildTaskDefinition) -> Self {
-        match value {
-            extension::BuildTaskDefinition::ByName(name) => Self::ByName(name.into()),
-            extension::BuildTaskDefinition::Template {
-                task_template,
-                locator_name,
-            } => Self::Template(BuildTaskDefinitionTemplatePayload {
-                template: task_template.into(),
-                locator_name: locator_name.map(String::from),
-            }),
-        }
-    }
-}
-impl From<BuildTaskTemplate> for extension::BuildTaskTemplate {
-    fn from(value: BuildTaskTemplate) -> Self {
-        Self {
-            label: value.label,
-            command: value.command,
-            args: value.args,
-            env: value.env.into_iter().collect(),
-            cwd: value.cwd,
-            ..Default::default()
-        }
-    }
-}
-impl From<extension::BuildTaskTemplate> for BuildTaskTemplate {
-    fn from(value: extension::BuildTaskTemplate) -> Self {
-        Self {
-            label: value.label,
-            command: value.command,
-            args: value.args,
-            env: value.env.into_iter().collect(),
-            cwd: value.cwd,
-        }
-    }
-}
-
-impl TryFrom<DebugScenario> for extension::DebugScenario {
-    type Error = anyhow::Error;
-
-    fn try_from(value: DebugScenario) -> std::result::Result<Self, Self::Error> {
-        Ok(Self {
-            adapter: value.adapter.into(),
-            label: value.label.into(),
-            build: value.build.map(Into::into),
-            config: serde_json::Value::from_str(&value.config)?,
-            tcp_connection: value.tcp_connection.map(Into::into),
-        })
-    }
-}
-
-impl From<extension::DebugScenario> for DebugScenario {
-    fn from(value: extension::DebugScenario) -> Self {
-        Self {
-            adapter: value.adapter.into(),
-            label: value.label.into(),
-            build: value.build.map(Into::into),
-            config: value.config.to_string(),
-            tcp_connection: value.tcp_connection.map(Into::into),
-        }
-    }
-}
-
-impl TryFrom<SpawnInTerminal> for ResolvedTask {
-    type Error = anyhow::Error;
-
-    fn try_from(value: SpawnInTerminal) -> Result<Self, Self::Error> {
-        Ok(Self {
-            label: value.label,
-            command: value.command.context("missing command")?,
-            args: value.args,
-            env: value.env.into_iter().collect(),
-            cwd: value.cwd.map(|s| {
-                let s = s.to_string_lossy();
-                if cfg!(target_os = "windows") {
-                    s.replace('\\', "/")
-                } else {
-                    s.into_owned()
-                }
-            }),
-        })
-    }
-}
-
-impl From<CodeLabel> for extension::CodeLabel {
+impl From<CodeLabel> for latest::CodeLabel {
     fn from(value: CodeLabel) -> Self {
         Self {
             code: value.code,
             spans: value.spans.into_iter().map(Into::into).collect(),
-            filter_range: value.filter_range.into(),
+            filter_range: value.filter_range,
         }
     }
 }
 
-impl From<CodeLabelSpan> for extension::CodeLabelSpan {
+impl From<CodeLabelSpan> for latest::CodeLabelSpan {
     fn from(value: CodeLabelSpan) -> Self {
         match value {
-            CodeLabelSpan::CodeRange(range) => Self::CodeRange(range.into()),
+            CodeLabelSpan::CodeRange(range) => Self::CodeRange(range),
             CodeLabelSpan::Literal(literal) => Self::Literal(literal.into()),
         }
     }
 }
 
-impl From<CodeLabelSpanLiteral> for extension::CodeLabelSpanLiteral {
+impl From<CodeLabelSpanLiteral> for latest::CodeLabelSpanLiteral {
     fn from(value: CodeLabelSpanLiteral) -> Self {
         Self {
             text: value.text,
@@ -352,167 +76,37 @@ impl From<CodeLabelSpanLiteral> for extension::CodeLabelSpanLiteral {
     }
 }
 
-impl From<extension::Completion> for Completion {
-    fn from(value: extension::Completion) -> Self {
+impl From<SettingsLocation> for latest::SettingsLocation {
+    fn from(value: SettingsLocation) -> Self {
         Self {
-            label: value.label,
-            label_details: value.label_details.map(Into::into),
-            detail: value.detail,
-            kind: value.kind.map(Into::into),
-            insert_text_format: value.insert_text_format.map(Into::into),
+            worktree_id: value.worktree_id,
+            path: value.path,
         }
     }
 }
 
-impl From<extension::CompletionLabelDetails> for CompletionLabelDetails {
-    fn from(value: extension::CompletionLabelDetails) -> Self {
-        Self {
-            detail: value.detail,
-            description: value.description,
-        }
-    }
-}
-
-impl From<extension::CompletionKind> for CompletionKind {
-    fn from(value: extension::CompletionKind) -> Self {
+impl From<LanguageServerInstallationStatus> for latest::LanguageServerInstallationStatus {
+    fn from(value: LanguageServerInstallationStatus) -> Self {
         match value {
-            extension::CompletionKind::Text => Self::Text,
-            extension::CompletionKind::Method => Self::Method,
-            extension::CompletionKind::Function => Self::Function,
-            extension::CompletionKind::Constructor => Self::Constructor,
-            extension::CompletionKind::Field => Self::Field,
-            extension::CompletionKind::Variable => Self::Variable,
-            extension::CompletionKind::Class => Self::Class,
-            extension::CompletionKind::Interface => Self::Interface,
-            extension::CompletionKind::Module => Self::Module,
-            extension::CompletionKind::Property => Self::Property,
-            extension::CompletionKind::Unit => Self::Unit,
-            extension::CompletionKind::Value => Self::Value,
-            extension::CompletionKind::Enum => Self::Enum,
-            extension::CompletionKind::Keyword => Self::Keyword,
-            extension::CompletionKind::Snippet => Self::Snippet,
-            extension::CompletionKind::Color => Self::Color,
-            extension::CompletionKind::File => Self::File,
-            extension::CompletionKind::Reference => Self::Reference,
-            extension::CompletionKind::Folder => Self::Folder,
-            extension::CompletionKind::EnumMember => Self::EnumMember,
-            extension::CompletionKind::Constant => Self::Constant,
-            extension::CompletionKind::Struct => Self::Struct,
-            extension::CompletionKind::Event => Self::Event,
-            extension::CompletionKind::Operator => Self::Operator,
-            extension::CompletionKind::TypeParameter => Self::TypeParameter,
-            extension::CompletionKind::Other(value) => Self::Other(value),
+            LanguageServerInstallationStatus::None => Self::None,
+            LanguageServerInstallationStatus::Downloading => Self::Downloading,
+            LanguageServerInstallationStatus::CheckingForUpdate => Self::CheckingForUpdate,
+            LanguageServerInstallationStatus::Failed(message) => Self::Failed(message),
         }
     }
 }
 
-impl From<extension::InsertTextFormat> for InsertTextFormat {
-    fn from(value: extension::InsertTextFormat) -> Self {
+impl From<DownloadedFileType> for latest::DownloadedFileType {
+    fn from(value: DownloadedFileType) -> Self {
         match value {
-            extension::InsertTextFormat::PlainText => Self::PlainText,
-            extension::InsertTextFormat::Snippet => Self::Snippet,
-            extension::InsertTextFormat::Other(value) => Self::Other(value),
+            DownloadedFileType::Gzip => Self::Gzip,
+            DownloadedFileType::GzipTar => Self::GzipTar,
+            DownloadedFileType::Zip => Self::Zip,
+            DownloadedFileType::Uncompressed => Self::Uncompressed,
         }
     }
 }
 
-impl From<extension::Symbol> for Symbol {
-    fn from(value: extension::Symbol) -> Self {
-        Self {
-            kind: value.kind.into(),
-            name: value.name,
-        }
-    }
-}
-
-impl From<extension::SymbolKind> for SymbolKind {
-    fn from(value: extension::SymbolKind) -> Self {
-        match value {
-            extension::SymbolKind::File => Self::File,
-            extension::SymbolKind::Module => Self::Module,
-            extension::SymbolKind::Namespace => Self::Namespace,
-            extension::SymbolKind::Package => Self::Package,
-            extension::SymbolKind::Class => Self::Class,
-            extension::SymbolKind::Method => Self::Method,
-            extension::SymbolKind::Property => Self::Property,
-            extension::SymbolKind::Field => Self::Field,
-            extension::SymbolKind::Constructor => Self::Constructor,
-            extension::SymbolKind::Enum => Self::Enum,
-            extension::SymbolKind::Interface => Self::Interface,
-            extension::SymbolKind::Function => Self::Function,
-            extension::SymbolKind::Variable => Self::Variable,
-            extension::SymbolKind::Constant => Self::Constant,
-            extension::SymbolKind::String => Self::String,
-            extension::SymbolKind::Number => Self::Number,
-            extension::SymbolKind::Boolean => Self::Boolean,
-            extension::SymbolKind::Array => Self::Array,
-            extension::SymbolKind::Object => Self::Object,
-            extension::SymbolKind::Key => Self::Key,
-            extension::SymbolKind::Null => Self::Null,
-            extension::SymbolKind::EnumMember => Self::EnumMember,
-            extension::SymbolKind::Struct => Self::Struct,
-            extension::SymbolKind::Event => Self::Event,
-            extension::SymbolKind::Operator => Self::Operator,
-            extension::SymbolKind::TypeParameter => Self::TypeParameter,
-            extension::SymbolKind::Other(value) => Self::Other(value),
-        }
-    }
-}
-
-impl From<extension::SlashCommand> for SlashCommand {
-    fn from(value: extension::SlashCommand) -> Self {
-        Self {
-            name: value.name,
-            description: value.description,
-            tooltip_text: value.tooltip_text,
-            requires_argument: value.requires_argument,
-        }
-    }
-}
-
-impl From<SlashCommandOutput> for extension::SlashCommandOutput {
-    fn from(value: SlashCommandOutput) -> Self {
-        Self {
-            text: value.text,
-            sections: value.sections.into_iter().map(Into::into).collect(),
-        }
-    }
-}
-
-impl From<SlashCommandOutputSection> for extension::SlashCommandOutputSection {
-    fn from(value: SlashCommandOutputSection) -> Self {
-        Self {
-            range: value.range.start as usize..value.range.end as usize,
-            label: value.label,
-        }
-    }
-}
-
-impl From<SlashCommandArgumentCompletion> for extension::SlashCommandArgumentCompletion {
-    fn from(value: SlashCommandArgumentCompletion) -> Self {
-        Self {
-            label: value.label,
-            new_text: value.new_text,
-            run_command: value.run_command,
-        }
-    }
-}
-
-impl TryFrom<ContextServerConfiguration> for extension::ContextServerConfiguration {
-    type Error = anyhow::Error;
-
-    fn try_from(value: ContextServerConfiguration) -> Result<Self, Self::Error> {
-        let settings_schema: serde_json::Value = serde_json::from_str(&value.settings_schema)
-            .context("Failed to parse settings_schema")?;
-
-        Ok(Self {
-            installation_instructions: value.installation_instructions,
-            default_settings: value.default_settings,
-            settings_schema,
-        })
-    }
-}
-
 impl HostKeyValueStore for WasmState {
     async fn insert(
         &mut self,
@@ -520,8 +114,7 @@ impl HostKeyValueStore for WasmState {
         key: String,
         value: String,
     ) -> wasmtime::Result<Result<(), String>> {
-        let kv_store = self.table.get(&kv_store)?;
-        kv_store.insert(key, value).await.to_wasmtime_result()
+        latest::HostKeyValueStore::insert(self, kv_store, key, value).await
     }
 
     async fn drop(&mut self, _worktree: Resource<ExtensionKeyValueStore>) -> Result<()> {
@@ -535,8 +128,7 @@ impl HostProject for WasmState {
         &mut self,
         project: Resource<ExtensionProject>,
     ) -> wasmtime::Result<Vec<u64>> {
-        let project = self.table.get(&project)?;
-        Ok(project.worktree_ids())
+        latest::HostProject::worktree_ids(self, project).await
     }
 
     async fn drop(&mut self, _project: Resource<Project>) -> Result<()> {
@@ -547,16 +139,14 @@ impl HostProject for WasmState {
 
 impl HostWorktree for WasmState {
     async fn id(&mut self, delegate: Resource<Arc<dyn WorktreeDelegate>>) -> wasmtime::Result<u64> {
-        let delegate = self.table.get(&delegate)?;
-        Ok(delegate.id())
+        latest::HostWorktree::id(self, delegate).await
     }
 
     async fn root_path(
         &mut self,
         delegate: Resource<Arc<dyn WorktreeDelegate>>,
     ) -> wasmtime::Result<String> {
-        let delegate = self.table.get(&delegate)?;
-        Ok(delegate.root_path())
+        latest::HostWorktree::root_path(self, delegate).await
     }
 
     async fn read_text_file(
@@ -564,19 +154,14 @@ impl HostWorktree for WasmState {
         delegate: Resource<Arc<dyn WorktreeDelegate>>,
         path: String,
     ) -> wasmtime::Result<Result<String, String>> {
-        let delegate = self.table.get(&delegate)?;
-        Ok(delegate
-            .read_text_file(&RelPath::new(Path::new(&path), PathStyle::Posix)?)
-            .await
-            .map_err(|error| error.to_string()))
+        latest::HostWorktree::read_text_file(self, delegate, path).await
     }
 
     async fn shell_env(
         &mut self,
         delegate: Resource<Arc<dyn WorktreeDelegate>>,
     ) -> wasmtime::Result<EnvVars> {
-        let delegate = self.table.get(&delegate)?;
-        Ok(delegate.shell_env().await.into_iter().collect())
+        latest::HostWorktree::shell_env(self, delegate).await
     }
 
     async fn which(
@@ -584,8 +169,7 @@ impl HostWorktree for WasmState {
         delegate: Resource<Arc<dyn WorktreeDelegate>>,
         binary_name: String,
     ) -> wasmtime::Result<Option<String>> {
-        let delegate = self.table.get(&delegate)?;
-        Ok(delegate.which(binary_name).await)
+        latest::HostWorktree::which(self, delegate, binary_name).await
     }
 
     async fn drop(&mut self, _worktree: Resource<Worktree>) -> Result<()> {
@@ -594,319 +178,6 @@ impl HostWorktree for WasmState {
     }
 }
 
-impl common::Host for WasmState {}
-
-impl http_client::Host for WasmState {
-    async fn fetch(
-        &mut self,
-        request: http_client::HttpRequest,
-    ) -> wasmtime::Result<Result<http_client::HttpResponse, String>> {
-        maybe!(async {
-            let url = &request.url;
-            let request = convert_request(&request)?;
-            let mut response = self.host.http_client.send(request).await?;
-
-            if response.status().is_client_error() || response.status().is_server_error() {
-                bail!("failed to fetch '{url}': status code {}", response.status())
-            }
-            convert_response(&mut response).await
-        })
-        .await
-        .to_wasmtime_result()
-    }
-
-    async fn fetch_stream(
-        &mut self,
-        request: http_client::HttpRequest,
-    ) -> wasmtime::Result<Result<Resource<ExtensionHttpResponseStream>, String>> {
-        let request = convert_request(&request)?;
-        let response = self.host.http_client.send(request);
-        maybe!(async {
-            let response = response.await?;
-            let stream = Arc::new(Mutex::new(response));
-            let resource = self.table.push(stream)?;
-            Ok(resource)
-        })
-        .await
-        .to_wasmtime_result()
-    }
-}
-
-impl http_client::HostHttpResponseStream for WasmState {
-    async fn next_chunk(
-        &mut self,
-        resource: Resource<ExtensionHttpResponseStream>,
-    ) -> wasmtime::Result<Result<Option<Vec<u8>>, String>> {
-        let stream = self.table.get(&resource)?.clone();
-        maybe!(async move {
-            let mut response = stream.lock().await;
-            let mut buffer = vec![0; 8192]; // 8KB buffer
-            let bytes_read = response.body_mut().read(&mut buffer).await?;
-            if bytes_read == 0 {
-                Ok(None)
-            } else {
-                buffer.truncate(bytes_read);
-                Ok(Some(buffer))
-            }
-        })
-        .await
-        .to_wasmtime_result()
-    }
-
-    async fn drop(&mut self, _resource: Resource<ExtensionHttpResponseStream>) -> Result<()> {
-        Ok(())
-    }
-}
-
-impl From<http_client::HttpMethod> for ::http_client::Method {
-    fn from(value: http_client::HttpMethod) -> Self {
-        match value {
-            http_client::HttpMethod::Get => Self::GET,
-            http_client::HttpMethod::Post => Self::POST,
-            http_client::HttpMethod::Put => Self::PUT,
-            http_client::HttpMethod::Delete => Self::DELETE,
-            http_client::HttpMethod::Head => Self::HEAD,
-            http_client::HttpMethod::Options => Self::OPTIONS,
-            http_client::HttpMethod::Patch => Self::PATCH,
-        }
-    }
-}
-
-fn convert_request(
-    extension_request: &http_client::HttpRequest,
-) -> anyhow::Result<::http_client::Request<AsyncBody>> {
-    let mut request = ::http_client::Request::builder()
-        .method(::http_client::Method::from(extension_request.method))
-        .uri(&extension_request.url)
-        .follow_redirects(match extension_request.redirect_policy {
-            http_client::RedirectPolicy::NoFollow => ::http_client::RedirectPolicy::NoFollow,
-            http_client::RedirectPolicy::FollowLimit(limit) => {
-                ::http_client::RedirectPolicy::FollowLimit(limit)
-            }
-            http_client::RedirectPolicy::FollowAll => ::http_client::RedirectPolicy::FollowAll,
-        });
-    for (key, value) in &extension_request.headers {
-        request = request.header(key, value);
-    }
-    let body = extension_request
-        .body
-        .clone()
-        .map(AsyncBody::from)
-        .unwrap_or_default();
-    request.body(body).map_err(anyhow::Error::from)
-}
-
-async fn convert_response(
-    response: &mut ::http_client::Response<AsyncBody>,
-) -> anyhow::Result<http_client::HttpResponse> {
-    let mut extension_response = http_client::HttpResponse {
-        body: Vec::new(),
-        headers: Vec::new(),
-    };
-
-    for (key, value) in response.headers() {
-        extension_response
-            .headers
-            .push((key.to_string(), value.to_str().unwrap_or("").to_string()));
-    }
-
-    response
-        .body_mut()
-        .read_to_end(&mut extension_response.body)
-        .await?;
-
-    Ok(extension_response)
-}
-
-impl nodejs::Host for WasmState {
-    async fn node_binary_path(&mut self) -> wasmtime::Result<Result<String, String>> {
-        self.host
-            .node_runtime
-            .binary_path()
-            .await
-            .map(|path| path.to_string_lossy().into_owned())
-            .to_wasmtime_result()
-    }
-
-    async fn npm_package_latest_version(
-        &mut self,
-        package_name: String,
-    ) -> wasmtime::Result<Result<String, String>> {
-        self.host
-            .node_runtime
-            .npm_package_latest_version(&package_name)
-            .await
-            .to_wasmtime_result()
-    }
-
-    async fn npm_package_installed_version(
-        &mut self,
-        package_name: String,
-    ) -> wasmtime::Result<Result<Option<String>, String>> {
-        self.host
-            .node_runtime
-            .npm_package_installed_version(&self.work_dir(), &package_name)
-            .await
-            .to_wasmtime_result()
-    }
-
-    async fn npm_install_package(
-        &mut self,
-        package_name: String,
-        version: String,
-    ) -> wasmtime::Result<Result<(), String>> {
-        self.capability_granter
-            .grant_npm_install_package(&package_name)?;
-
-        self.host
-            .node_runtime
-            .npm_install_packages(&self.work_dir(), &[(&package_name, &version)])
-            .await
-            .to_wasmtime_result()
-    }
-}
-
-#[async_trait]
-impl lsp::Host for WasmState {}
-
-impl From<::http_client::github::GithubRelease> for github::GithubRelease {
-    fn from(value: ::http_client::github::GithubRelease) -> Self {
-        Self {
-            version: value.tag_name,
-            assets: value.assets.into_iter().map(Into::into).collect(),
-        }
-    }
-}
-
-impl From<::http_client::github::GithubReleaseAsset> for github::GithubReleaseAsset {
-    fn from(value: ::http_client::github::GithubReleaseAsset) -> Self {
-        Self {
-            name: value.name,
-            download_url: value.browser_download_url,
-        }
-    }
-}
-
-impl github::Host for WasmState {
-    async fn latest_github_release(
-        &mut self,
-        repo: String,
-        options: github::GithubReleaseOptions,
-    ) -> wasmtime::Result<Result<github::GithubRelease, String>> {
-        maybe!(async {
-            let release = ::http_client::github::latest_github_release(
-                &repo,
-                options.require_assets,
-                options.pre_release,
-                self.host.http_client.clone(),
-            )
-            .await?;
-            Ok(release.into())
-        })
-        .await
-        .to_wasmtime_result()
-    }
-
-    async fn github_release_by_tag_name(
-        &mut self,
-        repo: String,
-        tag: String,
-    ) -> wasmtime::Result<Result<github::GithubRelease, String>> {
-        maybe!(async {
-            let release = ::http_client::github::get_release_by_tag_name(
-                &repo,
-                &tag,
-                self.host.http_client.clone(),
-            )
-            .await?;
-            Ok(release.into())
-        })
-        .await
-        .to_wasmtime_result()
-    }
-}
-
-impl platform::Host for WasmState {
-    async fn current_platform(&mut self) -> Result<(platform::Os, platform::Architecture)> {
-        Ok((
-            match env::consts::OS {
-                "macos" => platform::Os::Mac,
-                "linux" => platform::Os::Linux,
-                "windows" => platform::Os::Windows,
-                _ => panic!("unsupported os"),
-            },
-            match env::consts::ARCH {
-                "aarch64" => platform::Architecture::Aarch64,
-                "x86" => platform::Architecture::X86,
-                "x86_64" => platform::Architecture::X8664,
-                _ => panic!("unsupported architecture"),
-            },
-        ))
-    }
-}
-
-impl From<std::process::Output> for process::Output {
-    fn from(output: std::process::Output) -> Self {
-        Self {
-            status: output.status.code(),
-            stdout: output.stdout,
-            stderr: output.stderr,
-        }
-    }
-}
-
-impl process::Host for WasmState {
-    async fn run_command(
-        &mut self,
-        command: process::Command,
-    ) -> wasmtime::Result<Result<process::Output, String>> {
-        maybe!(async {
-            self.capability_granter
-                .grant_exec(&command.command, &command.args)?;
-
-            let output = util::command::new_smol_command(command.command.as_str())
-                .args(&command.args)
-                .envs(command.env)
-                .output()
-                .await?;
-
-            Ok(output.into())
-        })
-        .await
-        .to_wasmtime_result()
-    }
-}
-
-#[async_trait]
-impl slash_command::Host for WasmState {}
-
-#[async_trait]
-impl context_server::Host for WasmState {}
-
-impl dap::Host for WasmState {
-    async fn resolve_tcp_template(
-        &mut self,
-        template: TcpArgumentsTemplate,
-    ) -> wasmtime::Result<Result<TcpArguments, String>> {
-        maybe!(async {
-            let (host, port, timeout) =
-                ::dap::configure_tcp_connection(task::TcpArgumentsTemplate {
-                    port: template.port,
-                    host: template.host.map(Ipv4Addr::from_bits),
-                    timeout: template.timeout,
-                })
-                .await?;
-            Ok(TcpArguments {
-                port,
-                host: host.to_bits(),
-                timeout,
-            })
-        })
-        .await
-        .to_wasmtime_result()
-    }
-}
-
 impl ExtensionImports for WasmState {
     async fn get_settings(
         &mut self,
@@ -914,96 +185,13 @@ impl ExtensionImports for WasmState {
         category: String,
         key: Option<String>,
     ) -> wasmtime::Result<Result<String, String>> {
-        self.on_main_thread(|cx| {
-            async move {
-                let path = location.as_ref().and_then(|location| {
-                    RelPath::new(Path::new(&location.path), PathStyle::Posix).ok()
-                });
-                let location = path
-                    .as_ref()
-                    .zip(location.as_ref())
-                    .map(|(path, location)| ::settings::SettingsLocation {
-                        worktree_id: WorktreeId::from_proto(location.worktree_id),
-                        path,
-                    });
-
-                cx.update(|cx| match category.as_str() {
-                    "language" => {
-                        let key = key.map(|k| LanguageName::new(&k));
-                        let settings = AllLanguageSettings::get(location, cx).language(
-                            location,
-                            key.as_ref(),
-                            cx,
-                        );
-                        Ok(serde_json::to_string(&settings::LanguageSettings {
-                            tab_size: settings.tab_size,
-                        })?)
-                    }
-                    "lsp" => {
-                        let settings = key
-                            .and_then(|key| {
-                                ProjectSettings::get(location, cx)
-                                    .lsp
-                                    .get(&::lsp::LanguageServerName::from_proto(key))
-                            })
-                            .cloned()
-                            .unwrap_or_default();
-                        Ok(serde_json::to_string(&settings::LspSettings {
-                            binary: settings.binary.map(|binary| settings::CommandSettings {
-                                path: binary.path,
-                                arguments: binary.arguments,
-                                env: binary.env.map(|env| env.into_iter().collect()),
-                            }),
-                            settings: settings.settings,
-                            initialization_options: settings.initialization_options,
-                        })?)
-                    }
-                    "context_servers" => {
-                        let settings = key
-                            .and_then(|key| {
-                                ProjectSettings::get(location, cx)
-                                    .context_servers
-                                    .get(key.as_str())
-                            })
-                            .cloned()
-                            .unwrap_or_else(|| {
-                                project::project_settings::ContextServerSettings::default_extension(
-                                )
-                            });
-
-                        match settings {
-                            project::project_settings::ContextServerSettings::Stdio {
-                                enabled: _,
-                                command,
-                            } => Ok(serde_json::to_string(&settings::ContextServerSettings {
-                                command: Some(settings::CommandSettings {
-                                    path: command.path.to_str().map(|path| path.to_string()),
-                                    arguments: Some(command.args),
-                                    env: command.env.map(|env| env.into_iter().collect()),
-                                }),
-                                settings: None,
-                            })?),
-                            project::project_settings::ContextServerSettings::Extension {
-                                enabled: _,
-                                settings,
-                            } => Ok(serde_json::to_string(&settings::ContextServerSettings {
-                                command: None,
-                                settings: Some(settings),
-                            })?),
-                            project::project_settings::ContextServerSettings::Http { .. } => {
-                                bail!("remote context server settings not supported in 0.6.0")
-                            }
-                        }
-                    }
-                    _ => {
-                        bail!("Unknown settings category: {}", category);
-                    }
-                })
-            }
-            .boxed_local()
-        })
-        .await?
-        .to_wasmtime_result()
+        latest::ExtensionImports::get_settings(
+            self,
+            location.map(|location| location.into()),
+            category,
+            key,
+        )
+        .await
     }
 
     async fn set_language_server_installation_status(

crates/extension_host/src/wasm_host/wit/since_v0_8_0.rs 🔗

@@ -0,0 +1,1111 @@
+use crate::wasm_host::wit::since_v0_6_0::{
+    dap::{
+        BuildTaskDefinition, BuildTaskDefinitionTemplatePayload, StartDebuggingRequestArguments,
+        TcpArguments, TcpArgumentsTemplate,
+    },
+    slash_command::SlashCommandOutputSection,
+};
+use crate::wasm_host::wit::{CompletionKind, CompletionLabelDetails, InsertTextFormat, SymbolKind};
+use crate::wasm_host::{WasmState, wit::ToWasmtimeResult};
+use ::http_client::{AsyncBody, HttpRequestExt};
+use ::settings::{Settings, WorktreeId};
+use anyhow::{Context as _, Result, bail};
+use async_compression::futures::bufread::GzipDecoder;
+use async_tar::Archive;
+use async_trait::async_trait;
+use extension::{
+    ExtensionLanguageServerProxy, KeyValueStoreDelegate, ProjectDelegate, WorktreeDelegate,
+};
+use futures::{AsyncReadExt, lock::Mutex};
+use futures::{FutureExt as _, io::BufReader};
+use gpui::{BackgroundExecutor, SharedString};
+use language::{BinaryStatus, LanguageName, language_settings::AllLanguageSettings};
+use project::project_settings::ProjectSettings;
+use semver::Version;
+use std::{
+    env,
+    net::Ipv4Addr,
+    path::{Path, PathBuf},
+    str::FromStr,
+    sync::{Arc, OnceLock},
+};
+use task::{SpawnInTerminal, ZedDebugConfig};
+use url::Url;
+use util::{
+    archive::extract_zip, fs::make_file_executable, maybe, paths::PathStyle, rel_path::RelPath,
+};
+use wasmtime::component::{Linker, Resource};
+
+pub const MIN_VERSION: Version = Version::new(0, 8, 0);
+pub const MAX_VERSION: Version = Version::new(0, 8, 0);
+
+wasmtime::component::bindgen!({
+    async: true,
+    trappable_imports: true,
+    path: "../extension_api/wit/since_v0.8.0",
+    with: {
+         "worktree": ExtensionWorktree,
+         "project": ExtensionProject,
+         "key-value-store": ExtensionKeyValueStore,
+         "zed:extension/http-client/http-response-stream": ExtensionHttpResponseStream
+    },
+});
+
+pub use self::zed::extension::*;
+
+mod settings {
+    #![allow(dead_code)]
+    include!(concat!(env!("OUT_DIR"), "/since_v0.8.0/settings.rs"));
+}
+
+pub type ExtensionWorktree = Arc<dyn WorktreeDelegate>;
+pub type ExtensionProject = Arc<dyn ProjectDelegate>;
+pub type ExtensionKeyValueStore = Arc<dyn KeyValueStoreDelegate>;
+pub type ExtensionHttpResponseStream = Arc<Mutex<::http_client::Response<AsyncBody>>>;
+
+pub fn linker(executor: &BackgroundExecutor) -> &'static Linker<WasmState> {
+    static LINKER: OnceLock<Linker<WasmState>> = OnceLock::new();
+    LINKER.get_or_init(|| super::new_linker(executor, Extension::add_to_linker))
+}
+
+impl From<Range> for std::ops::Range<usize> {
+    fn from(range: Range) -> Self {
+        let start = range.start as usize;
+        let end = range.end as usize;
+        start..end
+    }
+}
+
+impl From<Command> for extension::Command {
+    fn from(value: Command) -> Self {
+        Self {
+            command: value.command.into(),
+            args: value.args,
+            env: value.env,
+        }
+    }
+}
+
+impl From<StartDebuggingRequestArgumentsRequest>
+    for extension::StartDebuggingRequestArgumentsRequest
+{
+    fn from(value: StartDebuggingRequestArgumentsRequest) -> Self {
+        match value {
+            StartDebuggingRequestArgumentsRequest::Launch => Self::Launch,
+            StartDebuggingRequestArgumentsRequest::Attach => Self::Attach,
+        }
+    }
+}
+impl TryFrom<StartDebuggingRequestArguments> for extension::StartDebuggingRequestArguments {
+    type Error = anyhow::Error;
+
+    fn try_from(value: StartDebuggingRequestArguments) -> Result<Self, Self::Error> {
+        Ok(Self {
+            configuration: serde_json::from_str(&value.configuration)?,
+            request: value.request.into(),
+        })
+    }
+}
+impl From<TcpArguments> for extension::TcpArguments {
+    fn from(value: TcpArguments) -> Self {
+        Self {
+            host: value.host.into(),
+            port: value.port,
+            timeout: value.timeout,
+        }
+    }
+}
+
+impl From<extension::TcpArgumentsTemplate> for TcpArgumentsTemplate {
+    fn from(value: extension::TcpArgumentsTemplate) -> Self {
+        Self {
+            host: value.host.map(Ipv4Addr::to_bits),
+            port: value.port,
+            timeout: value.timeout,
+        }
+    }
+}
+
+impl From<TcpArgumentsTemplate> for extension::TcpArgumentsTemplate {
+    fn from(value: TcpArgumentsTemplate) -> Self {
+        Self {
+            host: value.host.map(Ipv4Addr::from_bits),
+            port: value.port,
+            timeout: value.timeout,
+        }
+    }
+}
+
+impl TryFrom<extension::DebugTaskDefinition> for DebugTaskDefinition {
+    type Error = anyhow::Error;
+    fn try_from(value: extension::DebugTaskDefinition) -> Result<Self, Self::Error> {
+        Ok(Self {
+            label: value.label.to_string(),
+            adapter: value.adapter.to_string(),
+            config: value.config.to_string(),
+            tcp_connection: value.tcp_connection.map(Into::into),
+        })
+    }
+}
+
+impl From<task::DebugRequest> for DebugRequest {
+    fn from(value: task::DebugRequest) -> Self {
+        match value {
+            task::DebugRequest::Launch(launch_request) => Self::Launch(launch_request.into()),
+            task::DebugRequest::Attach(attach_request) => Self::Attach(attach_request.into()),
+        }
+    }
+}
+
+impl From<DebugRequest> for task::DebugRequest {
+    fn from(value: DebugRequest) -> Self {
+        match value {
+            DebugRequest::Launch(launch_request) => Self::Launch(launch_request.into()),
+            DebugRequest::Attach(attach_request) => Self::Attach(attach_request.into()),
+        }
+    }
+}
+
+impl From<task::LaunchRequest> for LaunchRequest {
+    fn from(value: task::LaunchRequest) -> Self {
+        Self {
+            program: value.program,
+            cwd: value.cwd.map(|p| p.to_string_lossy().into_owned()),
+            args: value.args,
+            envs: value.env.into_iter().collect(),
+        }
+    }
+}
+
+impl From<task::AttachRequest> for AttachRequest {
+    fn from(value: task::AttachRequest) -> Self {
+        Self {
+            process_id: value.process_id,
+        }
+    }
+}
+
+impl From<LaunchRequest> for task::LaunchRequest {
+    fn from(value: LaunchRequest) -> Self {
+        Self {
+            program: value.program,
+            cwd: value.cwd.map(|p| p.into()),
+            args: value.args,
+            env: value.envs.into_iter().collect(),
+        }
+    }
+}
+impl From<AttachRequest> for task::AttachRequest {
+    fn from(value: AttachRequest) -> Self {
+        Self {
+            process_id: value.process_id,
+        }
+    }
+}
+
+impl From<ZedDebugConfig> for DebugConfig {
+    fn from(value: ZedDebugConfig) -> Self {
+        Self {
+            label: value.label.into(),
+            adapter: value.adapter.into(),
+            request: value.request.into(),
+            stop_on_entry: value.stop_on_entry,
+        }
+    }
+}
+impl TryFrom<DebugAdapterBinary> for extension::DebugAdapterBinary {
+    type Error = anyhow::Error;
+    fn try_from(value: DebugAdapterBinary) -> Result<Self, Self::Error> {
+        Ok(Self {
+            command: value.command,
+            arguments: value.arguments,
+            envs: value.envs.into_iter().collect(),
+            cwd: value.cwd.map(|s| s.into()),
+            connection: value.connection.map(Into::into),
+            request_args: value.request_args.try_into()?,
+        })
+    }
+}
+
+impl From<BuildTaskDefinition> for extension::BuildTaskDefinition {
+    fn from(value: BuildTaskDefinition) -> Self {
+        match value {
+            BuildTaskDefinition::ByName(name) => Self::ByName(name.into()),
+            BuildTaskDefinition::Template(build_task_template) => Self::Template {
+                task_template: build_task_template.template.into(),
+                locator_name: build_task_template.locator_name.map(SharedString::from),
+            },
+        }
+    }
+}
+
+impl From<extension::BuildTaskDefinition> for BuildTaskDefinition {
+    fn from(value: extension::BuildTaskDefinition) -> Self {
+        match value {
+            extension::BuildTaskDefinition::ByName(name) => Self::ByName(name.into()),
+            extension::BuildTaskDefinition::Template {
+                task_template,
+                locator_name,
+            } => Self::Template(BuildTaskDefinitionTemplatePayload {
+                template: task_template.into(),
+                locator_name: locator_name.map(String::from),
+            }),
+        }
+    }
+}
+impl From<BuildTaskTemplate> for extension::BuildTaskTemplate {
+    fn from(value: BuildTaskTemplate) -> Self {
+        Self {
+            label: value.label,
+            command: value.command,
+            args: value.args,
+            env: value.env.into_iter().collect(),
+            cwd: value.cwd,
+            ..Default::default()
+        }
+    }
+}
+impl From<extension::BuildTaskTemplate> for BuildTaskTemplate {
+    fn from(value: extension::BuildTaskTemplate) -> Self {
+        Self {
+            label: value.label,
+            command: value.command,
+            args: value.args,
+            env: value.env.into_iter().collect(),
+            cwd: value.cwd,
+        }
+    }
+}
+
+impl TryFrom<DebugScenario> for extension::DebugScenario {
+    type Error = anyhow::Error;
+
+    fn try_from(value: DebugScenario) -> std::result::Result<Self, Self::Error> {
+        Ok(Self {
+            adapter: value.adapter.into(),
+            label: value.label.into(),
+            build: value.build.map(Into::into),
+            config: serde_json::Value::from_str(&value.config)?,
+            tcp_connection: value.tcp_connection.map(Into::into),
+        })
+    }
+}
+
+impl From<extension::DebugScenario> for DebugScenario {
+    fn from(value: extension::DebugScenario) -> Self {
+        Self {
+            adapter: value.adapter.into(),
+            label: value.label.into(),
+            build: value.build.map(Into::into),
+            config: value.config.to_string(),
+            tcp_connection: value.tcp_connection.map(Into::into),
+        }
+    }
+}
+
+impl TryFrom<SpawnInTerminal> for ResolvedTask {
+    type Error = anyhow::Error;
+
+    fn try_from(value: SpawnInTerminal) -> Result<Self, Self::Error> {
+        Ok(Self {
+            label: value.label,
+            command: value.command.context("missing command")?,
+            args: value.args,
+            env: value.env.into_iter().collect(),
+            cwd: value.cwd.map(|s| {
+                let s = s.to_string_lossy();
+                if cfg!(target_os = "windows") {
+                    s.replace('\\', "/")
+                } else {
+                    s.into_owned()
+                }
+            }),
+        })
+    }
+}
+
+impl From<CodeLabel> for extension::CodeLabel {
+    fn from(value: CodeLabel) -> Self {
+        Self {
+            code: value.code,
+            spans: value.spans.into_iter().map(Into::into).collect(),
+            filter_range: value.filter_range.into(),
+        }
+    }
+}
+
+impl From<CodeLabelSpan> for extension::CodeLabelSpan {
+    fn from(value: CodeLabelSpan) -> Self {
+        match value {
+            CodeLabelSpan::CodeRange(range) => Self::CodeRange(range.into()),
+            CodeLabelSpan::Literal(literal) => Self::Literal(literal.into()),
+        }
+    }
+}
+
+impl From<CodeLabelSpanLiteral> for extension::CodeLabelSpanLiteral {
+    fn from(value: CodeLabelSpanLiteral) -> Self {
+        Self {
+            text: value.text,
+            highlight_name: value.highlight_name,
+        }
+    }
+}
+
+impl From<extension::Completion> for Completion {
+    fn from(value: extension::Completion) -> Self {
+        Self {
+            label: value.label,
+            label_details: value.label_details.map(Into::into),
+            detail: value.detail,
+            kind: value.kind.map(Into::into),
+            insert_text_format: value.insert_text_format.map(Into::into),
+        }
+    }
+}
+
+impl From<extension::CompletionLabelDetails> for CompletionLabelDetails {
+    fn from(value: extension::CompletionLabelDetails) -> Self {
+        Self {
+            detail: value.detail,
+            description: value.description,
+        }
+    }
+}
+
+impl From<extension::CompletionKind> for CompletionKind {
+    fn from(value: extension::CompletionKind) -> Self {
+        match value {
+            extension::CompletionKind::Text => Self::Text,
+            extension::CompletionKind::Method => Self::Method,
+            extension::CompletionKind::Function => Self::Function,
+            extension::CompletionKind::Constructor => Self::Constructor,
+            extension::CompletionKind::Field => Self::Field,
+            extension::CompletionKind::Variable => Self::Variable,
+            extension::CompletionKind::Class => Self::Class,
+            extension::CompletionKind::Interface => Self::Interface,
+            extension::CompletionKind::Module => Self::Module,
+            extension::CompletionKind::Property => Self::Property,
+            extension::CompletionKind::Unit => Self::Unit,
+            extension::CompletionKind::Value => Self::Value,
+            extension::CompletionKind::Enum => Self::Enum,
+            extension::CompletionKind::Keyword => Self::Keyword,
+            extension::CompletionKind::Snippet => Self::Snippet,
+            extension::CompletionKind::Color => Self::Color,
+            extension::CompletionKind::File => Self::File,
+            extension::CompletionKind::Reference => Self::Reference,
+            extension::CompletionKind::Folder => Self::Folder,
+            extension::CompletionKind::EnumMember => Self::EnumMember,
+            extension::CompletionKind::Constant => Self::Constant,
+            extension::CompletionKind::Struct => Self::Struct,
+            extension::CompletionKind::Event => Self::Event,
+            extension::CompletionKind::Operator => Self::Operator,
+            extension::CompletionKind::TypeParameter => Self::TypeParameter,
+            extension::CompletionKind::Other(value) => Self::Other(value),
+        }
+    }
+}
+
+impl From<extension::InsertTextFormat> for InsertTextFormat {
+    fn from(value: extension::InsertTextFormat) -> Self {
+        match value {
+            extension::InsertTextFormat::PlainText => Self::PlainText,
+            extension::InsertTextFormat::Snippet => Self::Snippet,
+            extension::InsertTextFormat::Other(value) => Self::Other(value),
+        }
+    }
+}
+
+impl From<extension::Symbol> for Symbol {
+    fn from(value: extension::Symbol) -> Self {
+        Self {
+            kind: value.kind.into(),
+            name: value.name,
+        }
+    }
+}
+
+impl From<extension::SymbolKind> for SymbolKind {
+    fn from(value: extension::SymbolKind) -> Self {
+        match value {
+            extension::SymbolKind::File => Self::File,
+            extension::SymbolKind::Module => Self::Module,
+            extension::SymbolKind::Namespace => Self::Namespace,
+            extension::SymbolKind::Package => Self::Package,
+            extension::SymbolKind::Class => Self::Class,
+            extension::SymbolKind::Method => Self::Method,
+            extension::SymbolKind::Property => Self::Property,
+            extension::SymbolKind::Field => Self::Field,
+            extension::SymbolKind::Constructor => Self::Constructor,
+            extension::SymbolKind::Enum => Self::Enum,
+            extension::SymbolKind::Interface => Self::Interface,
+            extension::SymbolKind::Function => Self::Function,
+            extension::SymbolKind::Variable => Self::Variable,
+            extension::SymbolKind::Constant => Self::Constant,
+            extension::SymbolKind::String => Self::String,
+            extension::SymbolKind::Number => Self::Number,
+            extension::SymbolKind::Boolean => Self::Boolean,
+            extension::SymbolKind::Array => Self::Array,
+            extension::SymbolKind::Object => Self::Object,
+            extension::SymbolKind::Key => Self::Key,
+            extension::SymbolKind::Null => Self::Null,
+            extension::SymbolKind::EnumMember => Self::EnumMember,
+            extension::SymbolKind::Struct => Self::Struct,
+            extension::SymbolKind::Event => Self::Event,
+            extension::SymbolKind::Operator => Self::Operator,
+            extension::SymbolKind::TypeParameter => Self::TypeParameter,
+            extension::SymbolKind::Other(value) => Self::Other(value),
+        }
+    }
+}
+
+impl From<extension::SlashCommand> for SlashCommand {
+    fn from(value: extension::SlashCommand) -> Self {
+        Self {
+            name: value.name,
+            description: value.description,
+            tooltip_text: value.tooltip_text,
+            requires_argument: value.requires_argument,
+        }
+    }
+}
+
+impl From<SlashCommandOutput> for extension::SlashCommandOutput {
+    fn from(value: SlashCommandOutput) -> Self {
+        Self {
+            text: value.text,
+            sections: value.sections.into_iter().map(Into::into).collect(),
+        }
+    }
+}
+
+impl From<SlashCommandOutputSection> for extension::SlashCommandOutputSection {
+    fn from(value: SlashCommandOutputSection) -> Self {
+        Self {
+            range: value.range.start as usize..value.range.end as usize,
+            label: value.label,
+        }
+    }
+}
+
+impl From<SlashCommandArgumentCompletion> for extension::SlashCommandArgumentCompletion {
+    fn from(value: SlashCommandArgumentCompletion) -> Self {
+        Self {
+            label: value.label,
+            new_text: value.new_text,
+            run_command: value.run_command,
+        }
+    }
+}
+
+impl TryFrom<ContextServerConfiguration> for extension::ContextServerConfiguration {
+    type Error = anyhow::Error;
+
+    fn try_from(value: ContextServerConfiguration) -> Result<Self, Self::Error> {
+        let settings_schema: serde_json::Value = serde_json::from_str(&value.settings_schema)
+            .context("Failed to parse settings_schema")?;
+
+        Ok(Self {
+            installation_instructions: value.installation_instructions,
+            default_settings: value.default_settings,
+            settings_schema,
+        })
+    }
+}
+
+impl HostKeyValueStore for WasmState {
+    async fn insert(
+        &mut self,
+        kv_store: Resource<ExtensionKeyValueStore>,
+        key: String,
+        value: String,
+    ) -> wasmtime::Result<Result<(), String>> {
+        let kv_store = self.table.get(&kv_store)?;
+        kv_store.insert(key, value).await.to_wasmtime_result()
+    }
+
+    async fn drop(&mut self, _worktree: Resource<ExtensionKeyValueStore>) -> Result<()> {
+        // We only ever hand out borrows of key-value stores.
+        Ok(())
+    }
+}
+
+impl HostProject for WasmState {
+    async fn worktree_ids(
+        &mut self,
+        project: Resource<ExtensionProject>,
+    ) -> wasmtime::Result<Vec<u64>> {
+        let project = self.table.get(&project)?;
+        Ok(project.worktree_ids())
+    }
+
+    async fn drop(&mut self, _project: Resource<Project>) -> Result<()> {
+        // We only ever hand out borrows of projects.
+        Ok(())
+    }
+}
+
+impl HostWorktree for WasmState {
+    async fn id(&mut self, delegate: Resource<Arc<dyn WorktreeDelegate>>) -> wasmtime::Result<u64> {
+        let delegate = self.table.get(&delegate)?;
+        Ok(delegate.id())
+    }
+
+    async fn root_path(
+        &mut self,
+        delegate: Resource<Arc<dyn WorktreeDelegate>>,
+    ) -> wasmtime::Result<String> {
+        let delegate = self.table.get(&delegate)?;
+        Ok(delegate.root_path())
+    }
+
+    async fn read_text_file(
+        &mut self,
+        delegate: Resource<Arc<dyn WorktreeDelegate>>,
+        path: String,
+    ) -> wasmtime::Result<Result<String, String>> {
+        let delegate = self.table.get(&delegate)?;
+        Ok(delegate
+            .read_text_file(&RelPath::new(Path::new(&path), PathStyle::Posix)?)
+            .await
+            .map_err(|error| error.to_string()))
+    }
+
+    async fn shell_env(
+        &mut self,
+        delegate: Resource<Arc<dyn WorktreeDelegate>>,
+    ) -> wasmtime::Result<EnvVars> {
+        let delegate = self.table.get(&delegate)?;
+        Ok(delegate.shell_env().await.into_iter().collect())
+    }
+
+    async fn which(
+        &mut self,
+        delegate: Resource<Arc<dyn WorktreeDelegate>>,
+        binary_name: String,
+    ) -> wasmtime::Result<Option<String>> {
+        let delegate = self.table.get(&delegate)?;
+        Ok(delegate.which(binary_name).await)
+    }
+
+    async fn drop(&mut self, _worktree: Resource<Worktree>) -> Result<()> {
+        // We only ever hand out borrows of worktrees.
+        Ok(())
+    }
+}
+
+impl common::Host for WasmState {}
+
+impl http_client::Host for WasmState {
+    async fn fetch(
+        &mut self,
+        request: http_client::HttpRequest,
+    ) -> wasmtime::Result<Result<http_client::HttpResponse, String>> {
+        maybe!(async {
+            let url = &request.url;
+            let request = convert_request(&request)?;
+            let mut response = self.host.http_client.send(request).await?;
+
+            if response.status().is_client_error() || response.status().is_server_error() {
+                bail!("failed to fetch '{url}': status code {}", response.status())
+            }
+            convert_response(&mut response).await
+        })
+        .await
+        .to_wasmtime_result()
+    }
+
+    async fn fetch_stream(
+        &mut self,
+        request: http_client::HttpRequest,
+    ) -> wasmtime::Result<Result<Resource<ExtensionHttpResponseStream>, String>> {
+        let request = convert_request(&request)?;
+        let response = self.host.http_client.send(request);
+        maybe!(async {
+            let response = response.await?;
+            let stream = Arc::new(Mutex::new(response));
+            let resource = self.table.push(stream)?;
+            Ok(resource)
+        })
+        .await
+        .to_wasmtime_result()
+    }
+}
+
+impl http_client::HostHttpResponseStream for WasmState {
+    async fn next_chunk(
+        &mut self,
+        resource: Resource<ExtensionHttpResponseStream>,
+    ) -> wasmtime::Result<Result<Option<Vec<u8>>, String>> {
+        let stream = self.table.get(&resource)?.clone();
+        maybe!(async move {
+            let mut response = stream.lock().await;
+            let mut buffer = vec![0; 8192]; // 8KB buffer
+            let bytes_read = response.body_mut().read(&mut buffer).await?;
+            if bytes_read == 0 {
+                Ok(None)
+            } else {
+                buffer.truncate(bytes_read);
+                Ok(Some(buffer))
+            }
+        })
+        .await
+        .to_wasmtime_result()
+    }
+
+    async fn drop(&mut self, _resource: Resource<ExtensionHttpResponseStream>) -> Result<()> {
+        Ok(())
+    }
+}
+
+impl From<http_client::HttpMethod> for ::http_client::Method {
+    fn from(value: http_client::HttpMethod) -> Self {
+        match value {
+            http_client::HttpMethod::Get => Self::GET,
+            http_client::HttpMethod::Post => Self::POST,
+            http_client::HttpMethod::Put => Self::PUT,
+            http_client::HttpMethod::Delete => Self::DELETE,
+            http_client::HttpMethod::Head => Self::HEAD,
+            http_client::HttpMethod::Options => Self::OPTIONS,
+            http_client::HttpMethod::Patch => Self::PATCH,
+        }
+    }
+}
+
+fn convert_request(
+    extension_request: &http_client::HttpRequest,
+) -> anyhow::Result<::http_client::Request<AsyncBody>> {
+    let mut request = ::http_client::Request::builder()
+        .method(::http_client::Method::from(extension_request.method))
+        .uri(&extension_request.url)
+        .follow_redirects(match extension_request.redirect_policy {
+            http_client::RedirectPolicy::NoFollow => ::http_client::RedirectPolicy::NoFollow,
+            http_client::RedirectPolicy::FollowLimit(limit) => {
+                ::http_client::RedirectPolicy::FollowLimit(limit)
+            }
+            http_client::RedirectPolicy::FollowAll => ::http_client::RedirectPolicy::FollowAll,
+        });
+    for (key, value) in &extension_request.headers {
+        request = request.header(key, value);
+    }
+    let body = extension_request
+        .body
+        .clone()
+        .map(AsyncBody::from)
+        .unwrap_or_default();
+    request.body(body).map_err(anyhow::Error::from)
+}
+
+async fn convert_response(
+    response: &mut ::http_client::Response<AsyncBody>,
+) -> anyhow::Result<http_client::HttpResponse> {
+    let mut extension_response = http_client::HttpResponse {
+        body: Vec::new(),
+        headers: Vec::new(),
+    };
+
+    for (key, value) in response.headers() {
+        extension_response
+            .headers
+            .push((key.to_string(), value.to_str().unwrap_or("").to_string()));
+    }
+
+    response
+        .body_mut()
+        .read_to_end(&mut extension_response.body)
+        .await?;
+
+    Ok(extension_response)
+}
+
+impl nodejs::Host for WasmState {
+    async fn node_binary_path(&mut self) -> wasmtime::Result<Result<String, String>> {
+        self.host
+            .node_runtime
+            .binary_path()
+            .await
+            .map(|path| path.to_string_lossy().into_owned())
+            .to_wasmtime_result()
+    }
+
+    async fn npm_package_latest_version(
+        &mut self,
+        package_name: String,
+    ) -> wasmtime::Result<Result<String, String>> {
+        self.host
+            .node_runtime
+            .npm_package_latest_version(&package_name)
+            .await
+            .map(|v| v.to_string())
+            .to_wasmtime_result()
+    }
+
+    async fn npm_package_installed_version(
+        &mut self,
+        package_name: String,
+    ) -> wasmtime::Result<Result<Option<String>, String>> {
+        self.host
+            .node_runtime
+            .npm_package_installed_version(&self.work_dir(), &package_name)
+            .await
+            .map(|option| option.map(|version| version.to_string()))
+            .to_wasmtime_result()
+    }
+
+    async fn npm_install_package(
+        &mut self,
+        package_name: String,
+        version: String,
+    ) -> wasmtime::Result<Result<(), String>> {
+        self.capability_granter
+            .grant_npm_install_package(&package_name)?;
+
+        self.host
+            .node_runtime
+            .npm_install_packages(&self.work_dir(), &[(&package_name, &version)])
+            .await
+            .to_wasmtime_result()
+    }
+}
+
+#[async_trait]
+impl lsp::Host for WasmState {}
+
+impl From<::http_client::github::GithubRelease> for github::GithubRelease {
+    fn from(value: ::http_client::github::GithubRelease) -> Self {
+        Self {
+            version: value.tag_name,
+            assets: value.assets.into_iter().map(Into::into).collect(),
+        }
+    }
+}
+
+impl From<::http_client::github::GithubReleaseAsset> for github::GithubReleaseAsset {
+    fn from(value: ::http_client::github::GithubReleaseAsset) -> Self {
+        Self {
+            name: value.name,
+            download_url: value.browser_download_url,
+        }
+    }
+}
+
+impl github::Host for WasmState {
+    async fn latest_github_release(
+        &mut self,
+        repo: String,
+        options: github::GithubReleaseOptions,
+    ) -> wasmtime::Result<Result<github::GithubRelease, String>> {
+        maybe!(async {
+            let release = ::http_client::github::latest_github_release(
+                &repo,
+                options.require_assets,
+                options.pre_release,
+                self.host.http_client.clone(),
+            )
+            .await?;
+            Ok(release.into())
+        })
+        .await
+        .to_wasmtime_result()
+    }
+
+    async fn github_release_by_tag_name(
+        &mut self,
+        repo: String,
+        tag: String,
+    ) -> wasmtime::Result<Result<github::GithubRelease, String>> {
+        maybe!(async {
+            let release = ::http_client::github::get_release_by_tag_name(
+                &repo,
+                &tag,
+                self.host.http_client.clone(),
+            )
+            .await?;
+            Ok(release.into())
+        })
+        .await
+        .to_wasmtime_result()
+    }
+}
+
+impl platform::Host for WasmState {
+    async fn current_platform(&mut self) -> Result<(platform::Os, platform::Architecture)> {
+        Ok((
+            match env::consts::OS {
+                "macos" => platform::Os::Mac,
+                "linux" => platform::Os::Linux,
+                "windows" => platform::Os::Windows,
+                _ => panic!("unsupported os"),
+            },
+            match env::consts::ARCH {
+                "aarch64" => platform::Architecture::Aarch64,
+                "x86" => platform::Architecture::X86,
+                "x86_64" => platform::Architecture::X8664,
+                _ => panic!("unsupported architecture"),
+            },
+        ))
+    }
+}
+
+impl From<std::process::Output> for process::Output {
+    fn from(output: std::process::Output) -> Self {
+        Self {
+            status: output.status.code(),
+            stdout: output.stdout,
+            stderr: output.stderr,
+        }
+    }
+}
+
+impl process::Host for WasmState {
+    async fn run_command(
+        &mut self,
+        command: process::Command,
+    ) -> wasmtime::Result<Result<process::Output, String>> {
+        maybe!(async {
+            self.capability_granter
+                .grant_exec(&command.command, &command.args)?;
+
+            let output = util::command::new_smol_command(command.command.as_str())
+                .args(&command.args)
+                .envs(command.env)
+                .output()
+                .await?;
+
+            Ok(output.into())
+        })
+        .await
+        .to_wasmtime_result()
+    }
+}
+
+#[async_trait]
+impl slash_command::Host for WasmState {}
+
+#[async_trait]
+impl context_server::Host for WasmState {}
+
+impl dap::Host for WasmState {
+    async fn resolve_tcp_template(
+        &mut self,
+        template: TcpArgumentsTemplate,
+    ) -> wasmtime::Result<Result<TcpArguments, String>> {
+        maybe!(async {
+            let (host, port, timeout) =
+                ::dap::configure_tcp_connection(task::TcpArgumentsTemplate {
+                    port: template.port,
+                    host: template.host.map(Ipv4Addr::from_bits),
+                    timeout: template.timeout,
+                })
+                .await?;
+            Ok(TcpArguments {
+                port,
+                host: host.to_bits(),
+                timeout,
+            })
+        })
+        .await
+        .to_wasmtime_result()
+    }
+}
+
+impl ExtensionImports for WasmState {
+    async fn get_settings(
+        &mut self,
+        location: Option<self::SettingsLocation>,
+        category: String,
+        key: Option<String>,
+    ) -> wasmtime::Result<Result<String, String>> {
+        self.on_main_thread(|cx| {
+            async move {
+                let path = location.as_ref().and_then(|location| {
+                    RelPath::new(Path::new(&location.path), PathStyle::Posix).ok()
+                });
+                let location = path
+                    .as_ref()
+                    .zip(location.as_ref())
+                    .map(|(path, location)| ::settings::SettingsLocation {
+                        worktree_id: WorktreeId::from_proto(location.worktree_id),
+                        path,
+                    });
+
+                cx.update(|cx| match category.as_str() {
+                    "language" => {
+                        let key = key.map(|k| LanguageName::new(&k));
+                        let settings = AllLanguageSettings::get(location, cx).language(
+                            location,
+                            key.as_ref(),
+                            cx,
+                        );
+                        Ok(serde_json::to_string(&settings::LanguageSettings {
+                            tab_size: settings.tab_size,
+                        })?)
+                    }
+                    "lsp" => {
+                        let settings = key
+                            .and_then(|key| {
+                                ProjectSettings::get(location, cx)
+                                    .lsp
+                                    .get(&::lsp::LanguageServerName::from_proto(key))
+                            })
+                            .cloned()
+                            .unwrap_or_default();
+                        Ok(serde_json::to_string(&settings::LspSettings {
+                            binary: settings.binary.map(|binary| settings::CommandSettings {
+                                path: binary.path,
+                                arguments: binary.arguments,
+                                env: binary.env.map(|env| env.into_iter().collect()),
+                            }),
+                            settings: settings.settings,
+                            initialization_options: settings.initialization_options,
+                        })?)
+                    }
+                    "context_servers" => {
+                        let settings = key
+                            .and_then(|key| {
+                                ProjectSettings::get(location, cx)
+                                    .context_servers
+                                    .get(key.as_str())
+                            })
+                            .cloned()
+                            .unwrap_or_else(|| {
+                                project::project_settings::ContextServerSettings::default_extension(
+                                )
+                            });
+
+                        match settings {
+                            project::project_settings::ContextServerSettings::Stdio {
+                                enabled: _,
+                                command,
+                            } => Ok(serde_json::to_string(&settings::ContextServerSettings {
+                                command: Some(settings::CommandSettings {
+                                    path: command.path.to_str().map(|path| path.to_string()),
+                                    arguments: Some(command.args),
+                                    env: command.env.map(|env| env.into_iter().collect()),
+                                }),
+                                settings: None,
+                            })?),
+                            project::project_settings::ContextServerSettings::Extension {
+                                enabled: _,
+                                settings,
+                            } => Ok(serde_json::to_string(&settings::ContextServerSettings {
+                                command: None,
+                                settings: Some(settings),
+                            })?),
+                            project::project_settings::ContextServerSettings::Http { .. } => {
+                                bail!("remote context server settings not supported in 0.6.0")
+                            }
+                        }
+                    }
+                    _ => {
+                        bail!("Unknown settings category: {}", category);
+                    }
+                })
+            }
+            .boxed_local()
+        })
+        .await?
+        .to_wasmtime_result()
+    }
+
+    async fn set_language_server_installation_status(
+        &mut self,
+        server_name: String,
+        status: LanguageServerInstallationStatus,
+    ) -> wasmtime::Result<()> {
+        let status = match status {
+            LanguageServerInstallationStatus::CheckingForUpdate => BinaryStatus::CheckingForUpdate,
+            LanguageServerInstallationStatus::Downloading => BinaryStatus::Downloading,
+            LanguageServerInstallationStatus::None => BinaryStatus::None,
+            LanguageServerInstallationStatus::Failed(error) => BinaryStatus::Failed { error },
+        };
+
+        self.host
+            .proxy
+            .update_language_server_status(::lsp::LanguageServerName(server_name.into()), status);
+
+        Ok(())
+    }
+
+    async fn download_file(
+        &mut self,
+        url: String,
+        path: String,
+        file_type: DownloadedFileType,
+    ) -> wasmtime::Result<Result<(), String>> {
+        maybe!(async {
+            let parsed_url = Url::parse(&url)?;
+            self.capability_granter.grant_download_file(&parsed_url)?;
+
+            let path = PathBuf::from(path);
+            let extension_work_dir = self.host.work_dir.join(self.manifest.id.as_ref());
+
+            self.host.fs.create_dir(&extension_work_dir).await?;
+
+            let destination_path = self
+                .host
+                .writeable_path_from_extension(&self.manifest.id, &path)?;
+
+            let mut response = self
+                .host
+                .http_client
+                .get(&url, Default::default(), true)
+                .await
+                .context("downloading release")?;
+
+            anyhow::ensure!(
+                response.status().is_success(),
+                "download failed with status {}",
+                response.status()
+            );
+            let body = BufReader::new(response.body_mut());
+
+            match file_type {
+                DownloadedFileType::Uncompressed => {
+                    futures::pin_mut!(body);
+                    self.host
+                        .fs
+                        .create_file_with(&destination_path, body)
+                        .await?;
+                }
+                DownloadedFileType::Gzip => {
+                    let body = GzipDecoder::new(body);
+                    futures::pin_mut!(body);
+                    self.host
+                        .fs
+                        .create_file_with(&destination_path, body)
+                        .await?;
+                }
+                DownloadedFileType::GzipTar => {
+                    let body = GzipDecoder::new(body);
+                    futures::pin_mut!(body);
+                    self.host
+                        .fs
+                        .extract_tar_file(&destination_path, Archive::new(body))
+                        .await?;
+                }
+                DownloadedFileType::Zip => {
+                    futures::pin_mut!(body);
+                    extract_zip(&destination_path, body)
+                        .await
+                        .with_context(|| format!("unzipping {path:?} archive"))?;
+                }
+            }
+
+            Ok(())
+        })
+        .await
+        .to_wasmtime_result()
+    }
+
+    async fn make_file_executable(&mut self, path: String) -> wasmtime::Result<Result<(), String>> {
+        let path = self
+            .host
+            .writeable_path_from_extension(&self.manifest.id, Path::new(&path))?;
+
+        make_file_executable(&path)
+            .await
+            .with_context(|| format!("setting permissions for path {path:?}"))
+            .to_wasmtime_result()
+    }
+}

crates/extensions_ui/src/extensions_ui.rs 🔗

@@ -229,8 +229,10 @@ enum Feature {
     AgentClaude,
     AgentCodex,
     AgentGemini,
+    ExtensionBasedpyright,
     ExtensionRuff,
     ExtensionTailwind,
+    ExtensionTy,
     Git,
     LanguageBash,
     LanguageC,
@@ -251,8 +253,13 @@ fn keywords_by_feature() -> &'static BTreeMap<Feature, Vec<&'static str>> {
             (Feature::AgentClaude, vec!["claude", "claude code"]),
             (Feature::AgentCodex, vec!["codex", "codex cli"]),
             (Feature::AgentGemini, vec!["gemini", "gemini cli"]),
+            (
+                Feature::ExtensionBasedpyright,
+                vec!["basedpyright", "pyright"],
+            ),
             (Feature::ExtensionRuff, vec!["ruff"]),
             (Feature::ExtensionTailwind, vec!["tail", "tailwind"]),
+            (Feature::ExtensionTy, vec!["ty"]),
             (Feature::Git, vec!["git"]),
             (Feature::LanguageBash, vec!["sh", "bash"]),
             (Feature::LanguageC, vec!["c", "clang"]),
@@ -732,7 +739,7 @@ impl ExtensionsPage {
         extension: &ExtensionMetadata,
         cx: &mut Context<Self>,
     ) -> ExtensionCard {
-        let this = cx.entity();
+        let this = cx.weak_entity();
         let status = Self::extension_status(&extension.id, cx);
         let has_dev_extension = Self::dev_extension_exists(&extension.id, cx);
 
@@ -882,13 +889,15 @@ impl ExtensionsPage {
                                     y: px(2.0),
                                 })
                                 .menu(move |window, cx| {
-                                    Some(Self::render_remote_extension_context_menu(
-                                        &this,
-                                        extension_id.clone(),
-                                        authors.clone(),
-                                        window,
-                                        cx,
-                                    ))
+                                    this.upgrade().map(|this| {
+                                        Self::render_remote_extension_context_menu(
+                                            &this,
+                                            extension_id.clone(),
+                                            authors.clone(),
+                                            window,
+                                            cx,
+                                        )
+                                    })
                                 }),
                             ),
                     ),
@@ -1364,6 +1373,23 @@ impl ExtensionsPage {
             return;
         };
 
+        if let Some(id) = search.strip_prefix("id:") {
+            self.upsells.clear();
+
+            let upsell = match id.to_lowercase().as_str() {
+                "ruff" => Some(Feature::ExtensionRuff),
+                "basedpyright" => Some(Feature::ExtensionBasedpyright),
+                "ty" => Some(Feature::ExtensionTy),
+                _ => None,
+            };
+
+            if let Some(upsell) = upsell {
+                self.upsells.insert(upsell);
+            }
+
+            return;
+        }
+
         let search = search.to_lowercase();
         let search_terms = search
             .split_whitespace()
@@ -1446,8 +1472,7 @@ impl ExtensionsPage {
                                                             },
                                                         );
                                                     },
-                                                ))
-                                                .color(ui::SwitchColor::Accent),
+                                                )),
                                             ),
                                     ),
                             )
@@ -1482,6 +1507,12 @@ impl ExtensionsPage {
                     false,
                     cx,
                 ),
+                Feature::ExtensionBasedpyright => self.render_feature_upsell_banner(
+                    "Basedpyright (Python language server) support is built-in to Zed!".into(),
+                    "https://zed.dev/docs/languages/python#basedpyright".into(),
+                    false,
+                    cx,
+                ),
                 Feature::ExtensionRuff => self.render_feature_upsell_banner(
                     "Ruff (linter for Python) support is built-in to Zed!".into(),
                     "https://zed.dev/docs/languages/python#code-formatting--linting".into(),
@@ -1494,6 +1525,12 @@ impl ExtensionsPage {
                     false,
                     cx,
                 ),
+                Feature::ExtensionTy => self.render_feature_upsell_banner(
+                    "Ty (Python language server) support is built-in to Zed!".into(),
+                    "https://zed.dev/docs/languages/python".into(),
+                    false,
+                    cx,
+                ),
                 Feature::Git => self.render_feature_upsell_banner(
                     "Zed comes with basic Git support—more features are coming in the future."
                         .into(),

crates/feature_flags/src/flags.rs 🔗

@@ -1,11 +1,5 @@
 use crate::FeatureFlag;
 
-pub struct PredictEditsRateCompletionsFeatureFlag;
-
-impl FeatureFlag for PredictEditsRateCompletionsFeatureFlag {
-    const NAME: &'static str = "predict-edits-rate-completions";
-}
-
 pub struct NotebookFeatureFlag;
 
 impl FeatureFlag for NotebookFeatureFlag {
@@ -17,3 +11,15 @@ pub struct PanicFeatureFlag;
 impl FeatureFlag for PanicFeatureFlag {
     const NAME: &'static str = "panic";
 }
+
+pub struct InlineAssistantUseToolFeatureFlag;
+
+impl FeatureFlag for InlineAssistantUseToolFeatureFlag {
+    const NAME: &'static str = "inline-assistant-use-tool";
+}
+
+pub struct AgentV2FeatureFlag;
+
+impl FeatureFlag for AgentV2FeatureFlag {
+    const NAME: &'static str = "agent-v2";
+}

crates/file_finder/src/file_finder.rs 🔗

@@ -1713,7 +1713,7 @@ impl PickerDelegate for FileFinderDelegate {
                                                 ui::IconPosition::End,
                                                 Some(ToggleIncludeIgnored.boxed_clone()),
                                                 move |window, cx| {
-                                                    window.focus(&focus_handle);
+                                                    window.focus(&focus_handle, cx);
                                                     window.dispatch_action(
                                                         ToggleIncludeIgnored.boxed_clone(),
                                                         cx,
@@ -1760,16 +1760,19 @@ impl PickerDelegate for FileFinderDelegate {
                                                 menu.context(focus_handle)
                                                     .action(
                                                         "Split Left",
-                                                        pane::SplitLeft.boxed_clone(),
+                                                        pane::SplitLeft::default().boxed_clone(),
                                                     )
                                                     .action(
                                                         "Split Right",
-                                                        pane::SplitRight.boxed_clone(),
+                                                        pane::SplitRight::default().boxed_clone(),
+                                                    )
+                                                    .action(
+                                                        "Split Up",
+                                                        pane::SplitUp::default().boxed_clone(),
                                                     )
-                                                    .action("Split Up", pane::SplitUp.boxed_clone())
                                                     .action(
                                                         "Split Down",
-                                                        pane::SplitDown.boxed_clone(),
+                                                        pane::SplitDown::default().boxed_clone(),
                                                     )
                                             }
                                         }))

crates/file_finder/src/open_path_prompt.rs 🔗

@@ -44,8 +44,9 @@ impl OpenPathDelegate {
         tx: oneshot::Sender<Option<Vec<PathBuf>>>,
         lister: DirectoryLister,
         creating_path: bool,
-        path_style: PathStyle,
+        cx: &App,
     ) -> Self {
+        let path_style = lister.path_style(cx);
         Self {
             tx: Some(tx),
             lister,
@@ -216,8 +217,7 @@ impl OpenPathPrompt {
         cx: &mut Context<Workspace>,
     ) {
         workspace.toggle_modal(window, cx, |window, cx| {
-            let delegate =
-                OpenPathDelegate::new(tx, lister.clone(), creating_path, PathStyle::local());
+            let delegate = OpenPathDelegate::new(tx, lister.clone(), creating_path, cx);
             let picker = Picker::uniform_list(delegate, window, cx).width(rems(34.));
             let query = lister.default_query(cx);
             picker.set_query(query, window, cx);

crates/file_finder/src/open_path_prompt_tests.rs 🔗

@@ -5,7 +5,7 @@ use picker::{Picker, PickerDelegate};
 use project::Project;
 use serde_json::json;
 use ui::rems;
-use util::{path, paths::PathStyle};
+use util::path;
 use workspace::{AppState, Workspace};
 
 use crate::OpenPathDelegate;
@@ -37,7 +37,7 @@ async fn test_open_path_prompt(cx: &mut TestAppContext) {
 
     let project = Project::test(app_state.fs.clone(), [path!("/root").as_ref()], cx).await;
 
-    let (picker, cx) = build_open_path_prompt(project, false, PathStyle::local(), cx);
+    let (picker, cx) = build_open_path_prompt(project, false, cx);
 
     insert_query(path!("sadjaoislkdjasldj"), &picker, cx).await;
     assert_eq!(collect_match_candidates(&picker, cx), Vec::<String>::new());
@@ -119,7 +119,7 @@ async fn test_open_path_prompt_completion(cx: &mut TestAppContext) {
 
     let project = Project::test(app_state.fs.clone(), [path!("/root").as_ref()], cx).await;
 
-    let (picker, cx) = build_open_path_prompt(project, false, PathStyle::local(), cx);
+    let (picker, cx) = build_open_path_prompt(project, false, cx);
 
     // Confirm completion for the query "/root", since it's a directory, it should add a trailing slash.
     let query = path!("/root");
@@ -227,7 +227,7 @@ async fn test_open_path_prompt_on_windows(cx: &mut TestAppContext) {
 
     let project = Project::test(app_state.fs.clone(), [path!("/root").as_ref()], cx).await;
 
-    let (picker, cx) = build_open_path_prompt(project, false, PathStyle::local(), cx);
+    let (picker, cx) = build_open_path_prompt(project, false, cx);
 
     // Support both forward and backward slashes.
     let query = "C:/root/";
@@ -295,56 +295,6 @@ async fn test_open_path_prompt_on_windows(cx: &mut TestAppContext) {
     );
 }
 
-#[gpui::test]
-#[cfg_attr(not(target_os = "windows"), ignore)]
-async fn test_open_path_prompt_on_windows_with_remote(cx: &mut TestAppContext) {
-    let app_state = init_test(cx);
-    app_state
-        .fs
-        .as_fake()
-        .insert_tree(
-            "/root",
-            json!({
-                "a": "A",
-                "dir1": {},
-                "dir2": {}
-            }),
-        )
-        .await;
-
-    let project = Project::test(app_state.fs.clone(), ["/root".as_ref()], cx).await;
-
-    let (picker, cx) = build_open_path_prompt(project, false, PathStyle::Posix, cx);
-
-    let query = "/root/";
-    insert_query(query, &picker, cx).await;
-    assert_eq!(
-        collect_match_candidates(&picker, cx),
-        vec!["./", "a", "dir1", "dir2"]
-    );
-    assert_eq!(
-        confirm_completion(query, 1, &picker, cx).unwrap(),
-        "/root/a"
-    );
-
-    // Confirm completion for the query "/root/d", selecting the second candidate "dir2", since it's a directory, it should add a trailing slash.
-    let query = "/root/d";
-    insert_query(query, &picker, cx).await;
-    assert_eq!(collect_match_candidates(&picker, cx), vec!["dir1", "dir2"]);
-    assert_eq!(
-        confirm_completion(query, 1, &picker, cx).unwrap(),
-        "/root/dir2/"
-    );
-
-    let query = "/root/d";
-    insert_query(query, &picker, cx).await;
-    assert_eq!(collect_match_candidates(&picker, cx), vec!["dir1", "dir2"]);
-    assert_eq!(
-        confirm_completion(query, 0, &picker, cx).unwrap(),
-        "/root/dir1/"
-    );
-}
-
 #[gpui::test]
 async fn test_new_path_prompt(cx: &mut TestAppContext) {
     let app_state = init_test(cx);
@@ -372,7 +322,7 @@ async fn test_new_path_prompt(cx: &mut TestAppContext) {
 
     let project = Project::test(app_state.fs.clone(), [path!("/root").as_ref()], cx).await;
 
-    let (picker, cx) = build_open_path_prompt(project, true, PathStyle::local(), cx);
+    let (picker, cx) = build_open_path_prompt(project, true, cx);
 
     insert_query(path!("/root"), &picker, cx).await;
     assert_eq!(collect_match_candidates(&picker, cx), vec!["root"]);
@@ -406,16 +356,15 @@ fn init_test(cx: &mut TestAppContext) -> Arc<AppState> {
 fn build_open_path_prompt(
     project: Entity<Project>,
     creating_path: bool,
-    path_style: PathStyle,
     cx: &mut TestAppContext,
 ) -> (Entity<Picker<OpenPathDelegate>>, &mut VisualTestContext) {
     let (tx, _) = futures::channel::oneshot::channel();
     let lister = project::DirectoryLister::Project(project.clone());
-    let delegate = OpenPathDelegate::new(tx, lister.clone(), creating_path, path_style);
 
     let (workspace, cx) = cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
     (
         workspace.update_in(cx, |_, window, cx| {
+            let delegate = OpenPathDelegate::new(tx, lister.clone(), creating_path, cx);
             cx.new(|cx| {
                 let picker = Picker::uniform_list(delegate, window, cx)
                     .width(rems(34.))

crates/fs/src/fake_git_repo.rs 🔗

@@ -23,6 +23,7 @@ use std::{
     path::PathBuf,
     sync::{Arc, LazyLock},
 };
+use text::LineEnding;
 use util::{paths::PathStyle, rel_path::RelPath};
 
 pub static LOAD_INDEX_TEXT_TASK: LazyLock<TaskLabel> = LazyLock::new(TaskLabel::new);
@@ -50,6 +51,8 @@ pub struct FakeGitRepositoryState {
     pub blames: HashMap<RepoPath, Blame>,
     pub current_branch_name: Option<String>,
     pub branches: HashSet<String>,
+    /// List of remotes, keys are names and values are URLs
+    pub remotes: HashMap<String, String>,
     pub simulated_index_write_error_message: Option<String>,
     pub refs: HashMap<String, String>,
 }
@@ -68,6 +71,7 @@ impl FakeGitRepositoryState {
             refs: HashMap::from_iter([("HEAD".into(), "abc".into())]),
             merge_base_contents: Default::default(),
             oids: Default::default(),
+            remotes: HashMap::default(),
         }
     }
 }
@@ -152,8 +156,16 @@ impl GitRepository for FakeGitRepository {
         })
     }
 
-    fn remote_url(&self, _name: &str) -> Option<String> {
-        None
+    fn remote_url(&self, name: &str) -> BoxFuture<'_, Option<String>> {
+        let name = name.to_string();
+        let fut = self.with_state_async(false, move |state| {
+            state
+                .remotes
+                .get(&name)
+                .context("remote not found")
+                .cloned()
+        });
+        async move { fut.await.ok() }.boxed()
     }
 
     fn diff_tree(&self, _request: DiffTreeType) -> BoxFuture<'_, Result<TreeDiff>> {
@@ -197,6 +209,7 @@ impl GitRepository for FakeGitRepository {
         async {
             Ok(CommitDetails {
                 sha: commit.into(),
+                message: "initial commit".into(),
                 ..Default::default()
             })
         }
@@ -378,11 +391,18 @@ impl GitRepository for FakeGitRepository {
             Ok(state
                 .branches
                 .iter()
-                .map(|branch_name| Branch {
-                    is_head: Some(branch_name) == current_branch.as_ref(),
-                    ref_name: branch_name.into(),
-                    most_recent_commit: None,
-                    upstream: None,
+                .map(|branch_name| {
+                    let ref_name = if branch_name.starts_with("refs/") {
+                        branch_name.into()
+                    } else {
+                        format!("refs/heads/{branch_name}").into()
+                    };
+                    Branch {
+                        is_head: Some(branch_name) == current_branch.as_ref(),
+                        ref_name,
+                        most_recent_commit: None,
+                        upstream: None,
+                    }
                 })
                 .collect())
         })
@@ -432,11 +452,21 @@ impl GitRepository for FakeGitRepository {
         })
     }
 
-    fn delete_branch(&self, _name: String) -> BoxFuture<'_, Result<()>> {
-        unimplemented!()
+    fn delete_branch(&self, name: String) -> BoxFuture<'_, Result<()>> {
+        self.with_state_async(true, move |state| {
+            if !state.branches.remove(&name) {
+                bail!("no such branch: {name}");
+            }
+            Ok(())
+        })
     }
 
-    fn blame(&self, path: RepoPath, _content: Rope) -> BoxFuture<'_, Result<git::blame::Blame>> {
+    fn blame(
+        &self,
+        path: RepoPath,
+        _content: Rope,
+        _line_ending: LineEnding,
+    ) -> BoxFuture<'_, Result<git::blame::Blame>> {
         self.with_state_async(false, move |state| {
             state
                 .blames
@@ -553,7 +583,7 @@ impl GitRepository for FakeGitRepository {
         _askpass: AskPassDelegate,
         _env: Arc<HashMap<String, String>>,
     ) -> BoxFuture<'_, Result<()>> {
-        unimplemented!()
+        async { Ok(()) }.boxed()
     }
 
     fn run_hook(
@@ -561,7 +591,7 @@ impl GitRepository for FakeGitRepository {
         _hook: RunHook,
         _env: Arc<HashMap<String, String>>,
     ) -> BoxFuture<'_, Result<()>> {
-        unimplemented!()
+        async { Ok(()) }.boxed()
     }
 
     fn push(
@@ -598,15 +628,24 @@ impl GitRepository for FakeGitRepository {
         unimplemented!()
     }
 
-    fn get_push_remote(&self, _branch: String) -> BoxFuture<'_, Result<Option<Remote>>> {
-        unimplemented!()
+    fn get_all_remotes(&self) -> BoxFuture<'_, Result<Vec<Remote>>> {
+        self.with_state_async(false, move |state| {
+            let remotes = state
+                .remotes
+                .keys()
+                .map(|r| Remote {
+                    name: r.clone().into(),
+                })
+                .collect::<Vec<_>>();
+            Ok(remotes)
+        })
     }
 
-    fn get_branch_remote(&self, _branch: String) -> BoxFuture<'_, Result<Option<Remote>>> {
+    fn get_push_remote(&self, _branch: String) -> BoxFuture<'_, Result<Option<Remote>>> {
         unimplemented!()
     }
 
-    fn get_all_remotes(&self) -> BoxFuture<'_, Result<Vec<Remote>>> {
+    fn get_branch_remote(&self, _branch: String) -> BoxFuture<'_, Result<Option<Remote>>> {
         unimplemented!()
     }
 
@@ -683,6 +722,20 @@ impl GitRepository for FakeGitRepository {
     fn default_branch(&self) -> BoxFuture<'_, Result<Option<SharedString>>> {
         async { Ok(Some("main".into())) }.boxed()
     }
+
+    fn create_remote(&self, name: String, url: String) -> BoxFuture<'_, Result<()>> {
+        self.with_state_async(true, move |state| {
+            state.remotes.insert(name, url);
+            Ok(())
+        })
+    }
+
+    fn remove_remote(&self, name: String) -> BoxFuture<'_, Result<()>> {
+        self.with_state_async(true, move |state| {
+            state.remotes.remove(&name);
+            Ok(())
+        })
+    }
 }
 
 #[cfg(test)]

crates/fs/src/fs.rs 🔗

@@ -434,7 +434,18 @@ impl RealFs {
         for component in path.components() {
             match component {
                 std::path::Component::Prefix(_) => {
-                    let canonicalized = std::fs::canonicalize(component)?;
+                    let component = component.as_os_str();
+                    let canonicalized = if component
+                        .to_str()
+                        .map(|e| e.ends_with("\\"))
+                        .unwrap_or(false)
+                    {
+                        std::fs::canonicalize(component)
+                    } else {
+                        let mut component = component.to_os_string();
+                        component.push("\\");
+                        std::fs::canonicalize(component)
+                    }?;
 
                     let mut strip = PathBuf::new();
                     for component in canonicalized.components() {
@@ -641,6 +652,8 @@ impl Fs for RealFs {
         use objc::{class, msg_send, sel, sel_impl};
 
         unsafe {
+            /// Allow NSString::alloc use here because it sets autorelease
+            #[allow(clippy::disallowed_methods)]
             unsafe fn ns_string(string: &str) -> id {
                 unsafe { NSString::alloc(nil).init_str(string).autorelease() }
             }
@@ -803,7 +816,7 @@ impl Fs for RealFs {
         }
         let file = smol::fs::File::create(path).await?;
         let mut writer = smol::io::BufWriter::with_capacity(buffer_size, file);
-        for chunk in chunks(text, line_ending) {
+        for chunk in text::chunks_with_line_ending(text, line_ending) {
             writer.write_all(chunk.as_bytes()).await?;
         }
         writer.flush().await?;
@@ -1844,6 +1857,18 @@ impl FakeFs {
         .unwrap();
     }
 
+    pub fn set_remote_for_repo(
+        &self,
+        dot_git: &Path,
+        name: impl Into<String>,
+        url: impl Into<String>,
+    ) {
+        self.with_git_state(dot_git, true, |state| {
+            state.remotes.insert(name.into(), url.into());
+        })
+        .unwrap();
+    }
+
     pub fn insert_branches(&self, dot_git: &Path, branches: &[&str]) {
         self.with_git_state(dot_git, true, |state| {
             if let Some(first) = branches.first()
@@ -2555,7 +2580,7 @@ impl Fs for FakeFs {
     async fn save(&self, path: &Path, text: &Rope, line_ending: LineEnding) -> Result<()> {
         self.simulate_random_delay().await;
         let path = normalize_path(path);
-        let content = chunks(text, line_ending).collect::<String>();
+        let content = text::chunks_with_line_ending(text, line_ending).collect::<String>();
         if let Some(path) = path.parent() {
             self.create_dir(path).await?;
         }
@@ -2773,25 +2798,6 @@ impl Fs for FakeFs {
     }
 }
 
-fn chunks(rope: &Rope, line_ending: LineEnding) -> impl Iterator<Item = &str> {
-    rope.chunks().flat_map(move |chunk| {
-        let mut newline = false;
-        let end_with_newline = chunk.ends_with('\n').then_some(line_ending.as_str());
-        chunk
-            .lines()
-            .flat_map(move |line| {
-                let ending = if newline {
-                    Some(line_ending.as_str())
-                } else {
-                    None
-                };
-                newline = true;
-                ending.into_iter().chain([line])
-            })
-            .chain(end_with_newline)
-    })
-}
-
 pub fn normalize_path(path: &Path) -> PathBuf {
     let mut components = path.components().peekable();
     let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek().cloned() {
@@ -3411,6 +3417,26 @@ mod tests {
         assert_eq!(content, "Hello");
     }
 
+    #[gpui::test]
+    #[cfg(target_os = "windows")]
+    async fn test_realfs_canonicalize(executor: BackgroundExecutor) {
+        use util::paths::SanitizedPath;
+
+        let fs = RealFs {
+            bundled_git_binary_path: None,
+            executor,
+            next_job_id: Arc::new(AtomicUsize::new(0)),
+            job_event_subscribers: Arc::new(Mutex::new(Vec::new())),
+        };
+        let temp_dir = TempDir::new().unwrap();
+        let file = temp_dir.path().join("test (1).txt");
+        let file = SanitizedPath::new(&file);
+        std::fs::write(&file, "test").unwrap();
+
+        let canonicalized = fs.canonicalize(file.as_path()).await;
+        assert!(canonicalized.is_ok());
+    }
+
     #[gpui::test]
     async fn test_rename(executor: BackgroundExecutor) {
         let fs = FakeFs::new(executor.clone());

crates/fuzzy/src/matcher.rs 🔗

@@ -96,7 +96,8 @@ impl<'a> Matcher<'a> {
                 continue;
             }
 
-            let matrix_len = self.query.len() * (prefix.len() + candidate_chars.len());
+            let matrix_len =
+                self.query.len() * (lowercase_prefix.len() + lowercase_candidate_chars.len());
             self.score_matrix.clear();
             self.score_matrix.resize(matrix_len, None);
             self.best_position_matrix.clear();
@@ -596,4 +597,15 @@ mod tests {
             })
             .collect()
     }
+
+    /// Test for https://github.com/zed-industries/zed/issues/44324
+    #[test]
+    fn test_recursive_score_match_index_out_of_bounds() {
+        let paths = vec!["İ/İ/İ/İ"];
+        let query = "İ/İ";
+
+        // This panicked with "index out of bounds: the len is 21 but the index is 22"
+        let result = match_single_path_query(query, false, &paths);
+        let _ = result;
+    }
 }

crates/git/src/blame.rs 🔗

@@ -1,14 +1,13 @@
+use crate::Oid;
 use crate::commit::get_messages;
 use crate::repository::RepoPath;
-use crate::{GitRemote, Oid};
 use anyhow::{Context as _, Result};
 use collections::{HashMap, HashSet};
 use futures::AsyncWriteExt;
-use gpui::SharedString;
 use serde::{Deserialize, Serialize};
 use std::process::Stdio;
 use std::{ops::Range, path::Path};
-use text::Rope;
+use text::{LineEnding, Rope};
 use time::OffsetDateTime;
 use time::UtcOffset;
 use time::macros::format_description;
@@ -19,15 +18,6 @@ pub use git2 as libgit;
 pub struct Blame {
     pub entries: Vec<BlameEntry>,
     pub messages: HashMap<Oid, String>,
-    pub remote_url: Option<String>,
-}
-
-#[derive(Clone, Debug, Default)]
-pub struct ParsedCommitMessage {
-    pub message: SharedString,
-    pub permalink: Option<url::Url>,
-    pub pull_request: Option<crate::hosting_provider::PullRequest>,
-    pub remote: Option<GitRemote>,
 }
 
 impl Blame {
@@ -36,9 +26,10 @@ impl Blame {
         working_directory: &Path,
         path: &RepoPath,
         content: &Rope,
-        remote_url: Option<String>,
+        line_ending: LineEnding,
     ) -> Result<Self> {
-        let output = run_git_blame(git_binary, working_directory, path, content).await?;
+        let output =
+            run_git_blame(git_binary, working_directory, path, content, line_ending).await?;
         let mut entries = parse_git_blame(&output)?;
         entries.sort_unstable_by(|a, b| a.range.start.cmp(&b.range.start));
 
@@ -53,11 +44,7 @@ impl Blame {
             .await
             .context("failed to get commit messages")?;
 
-        Ok(Self {
-            entries,
-            messages,
-            remote_url,
-        })
+        Ok(Self { entries, messages })
     }
 }
 
@@ -69,12 +56,12 @@ async fn run_git_blame(
     working_directory: &Path,
     path: &RepoPath,
     contents: &Rope,
+    line_ending: LineEnding,
 ) -> Result<String> {
     let mut child = util::command::new_smol_command(git_binary)
         .current_dir(working_directory)
         .arg("blame")
         .arg("--incremental")
-        .arg("-w")
         .arg("--contents")
         .arg("-")
         .arg(path.as_unix_str())
@@ -89,7 +76,7 @@ async fn run_git_blame(
         .as_mut()
         .context("failed to get pipe to stdin of git blame command")?;
 
-    for chunk in contents.chunks() {
+    for chunk in text::chunks_with_line_ending(contents, line_ending) {
         stdin.write_all(chunk.as_bytes()).await?;
     }
     stdin.flush().await?;

crates/git/src/commit.rs 🔗

@@ -1,7 +1,52 @@
-use crate::{Oid, status::StatusCode};
+use crate::{
+    BuildCommitPermalinkParams, GitHostingProviderRegistry, GitRemote, Oid, parse_git_remote_url,
+    status::StatusCode,
+};
 use anyhow::{Context as _, Result};
 use collections::HashMap;
-use std::path::Path;
+use gpui::SharedString;
+use std::{path::Path, sync::Arc};
+
+#[derive(Clone, Debug, Default)]
+pub struct ParsedCommitMessage {
+    pub message: SharedString,
+    pub permalink: Option<url::Url>,
+    pub pull_request: Option<crate::hosting_provider::PullRequest>,
+    pub remote: Option<GitRemote>,
+}
+
+impl ParsedCommitMessage {
+    pub fn parse(
+        sha: String,
+        message: String,
+        remote_url: Option<&str>,
+        provider_registry: Option<Arc<GitHostingProviderRegistry>>,
+    ) -> Self {
+        if let Some((hosting_provider, remote)) = provider_registry
+            .and_then(|reg| remote_url.and_then(|url| parse_git_remote_url(reg, url)))
+        {
+            let pull_request = hosting_provider.extract_pull_request(&remote, &message);
+            Self {
+                message: message.into(),
+                permalink: Some(
+                    hosting_provider
+                        .build_commit_permalink(&remote, BuildCommitPermalinkParams { sha: &sha }),
+                ),
+                pull_request,
+                remote: Some(GitRemote {
+                    host: hosting_provider,
+                    owner: remote.owner.into(),
+                    repo: remote.repo.into(),
+                }),
+            }
+        } else {
+            Self {
+                message: message.into(),
+                ..Default::default()
+            }
+        }
+    }
+}
 
 pub async fn get_messages(working_directory: &Path, shas: &[Oid]) -> Result<HashMap<Oid, String>> {
     if shas.is_empty() {

crates/git/src/git.rs 🔗

@@ -23,6 +23,7 @@ pub const FSMONITOR_DAEMON: &str = "fsmonitor--daemon";
 pub const LFS_DIR: &str = "lfs";
 pub const COMMIT_MESSAGE: &str = "COMMIT_EDITMSG";
 pub const INDEX_LOCK: &str = "index.lock";
+pub const REPO_EXCLUDE: &str = "info/exclude";
 
 actions!(
     git,
@@ -232,14 +233,12 @@ impl From<Oid> for usize {
 #[derive(Copy, Clone, Debug)]
 pub enum RunHook {
     PreCommit,
-    PrePush,
 }
 
 impl RunHook {
     pub fn as_str(&self) -> &str {
         match self {
             Self::PreCommit => "pre-commit",
-            Self::PrePush => "pre-push",
         }
     }
 
@@ -250,7 +249,6 @@ impl RunHook {
     pub fn from_proto(value: i32) -> Option<Self> {
         match value {
             0 => Some(Self::PreCommit),
-            1 => Some(Self::PrePush),
             _ => None,
         }
     }

crates/git/src/remote.rs 🔗

@@ -1,3 +1,4 @@
+use std::str::FromStr;
 use std::sync::LazyLock;
 
 use derive_more::Deref;
@@ -11,7 +12,7 @@ pub struct RemoteUrl(Url);
 static USERNAME_REGEX: LazyLock<Regex> =
     LazyLock::new(|| Regex::new(r"^[0-9a-zA-Z\-_]+@").expect("Failed to create USERNAME_REGEX"));
 
-impl std::str::FromStr for RemoteUrl {
+impl FromStr for RemoteUrl {
     type Err = url::ParseError;
 
     fn from_str(input: &str) -> Result<Self, Self::Err> {

crates/git/src/repository.rs 🔗

@@ -7,13 +7,16 @@ use collections::HashMap;
 use futures::future::BoxFuture;
 use futures::io::BufWriter;
 use futures::{AsyncWriteExt, FutureExt as _, select_biased};
-use git2::BranchType;
+use git2::{BranchType, ErrorCode};
 use gpui::{AppContext as _, AsyncApp, BackgroundExecutor, SharedString, Task};
 use parking_lot::Mutex;
 use rope::Rope;
 use schemars::JsonSchema;
 use serde::Deserialize;
 use smol::io::{AsyncBufReadExt, AsyncReadExt, BufReader};
+use text::LineEnding;
+
+use std::collections::HashSet;
 use std::ffi::{OsStr, OsString};
 use std::process::{ExitStatus, Stdio};
 use std::{
@@ -55,6 +58,12 @@ impl Branch {
         self.ref_name.starts_with("refs/remotes/")
     }
 
+    pub fn remote_name(&self) -> Option<&str> {
+        self.ref_name
+            .strip_prefix("refs/remotes/")
+            .and_then(|stripped| stripped.split("/").next())
+    }
+
     pub fn tracking_status(&self) -> Option<UpstreamTrackingStatus> {
         self.upstream
             .as_ref()
@@ -420,7 +429,7 @@ pub trait GitRepository: Send + Sync {
     ) -> BoxFuture<'_, anyhow::Result<()>>;
 
     /// Returns the URL of the remote with the given name.
-    fn remote_url(&self, name: &str) -> Option<String>;
+    fn remote_url(&self, name: &str) -> BoxFuture<'_, Option<String>>;
 
     /// Resolve a list of refs to SHAs.
     fn revparse_batch(&self, revs: Vec<String>) -> BoxFuture<'_, Result<Vec<Option<String>>>>;
@@ -479,7 +488,12 @@ pub trait GitRepository: Send + Sync {
     fn show(&self, commit: String) -> BoxFuture<'_, Result<CommitDetails>>;
 
     fn load_commit(&self, commit: String, cx: AsyncApp) -> BoxFuture<'_, Result<CommitDiff>>;
-    fn blame(&self, path: RepoPath, content: Rope) -> BoxFuture<'_, Result<crate::blame::Blame>>;
+    fn blame(
+        &self,
+        path: RepoPath,
+        content: Rope,
+        line_ending: LineEnding,
+    ) -> BoxFuture<'_, Result<crate::blame::Blame>>;
     fn file_history(&self, path: RepoPath) -> BoxFuture<'_, Result<FileHistory>>;
     fn file_history_paginated(
         &self,
@@ -590,6 +604,10 @@ pub trait GitRepository: Send + Sync {
 
     fn get_all_remotes(&self) -> BoxFuture<'_, Result<Vec<Remote>>>;
 
+    fn remove_remote(&self, name: String) -> BoxFuture<'_, Result<()>>;
+
+    fn create_remote(&self, name: String, url: String) -> BoxFuture<'_, Result<()>>;
+
     /// returns a list of remote branches that contain HEAD
     fn check_for_pushed_commit(&self) -> BoxFuture<'_, Result<Vec<SharedString>>>;
 
@@ -640,6 +658,7 @@ pub struct RealGitRepository {
     pub repository: Arc<Mutex<git2::Repository>>,
     pub system_git_binary_path: Option<PathBuf>,
     pub any_git_binary_path: PathBuf,
+    any_git_binary_help_output: Arc<Mutex<Option<SharedString>>>,
     executor: BackgroundExecutor,
 }
 
@@ -658,6 +677,7 @@ impl RealGitRepository {
             system_git_binary_path,
             any_git_binary_path,
             executor,
+            any_git_binary_help_output: Arc::new(Mutex::new(None)),
         })
     }
 
@@ -668,6 +688,27 @@ impl RealGitRepository {
             .context("failed to read git work directory")
             .map(Path::to_path_buf)
     }
+
+    async fn any_git_binary_help_output(&self) -> SharedString {
+        if let Some(output) = self.any_git_binary_help_output.lock().clone() {
+            return output;
+        }
+        let git_binary_path = self.any_git_binary_path.clone();
+        let executor = self.executor.clone();
+        let working_directory = self.working_directory();
+        let output: SharedString = self
+            .executor
+            .spawn(async move {
+                GitBinary::new(git_binary_path, working_directory?, executor)
+                    .run(["help", "-a"])
+                    .await
+            })
+            .await
+            .unwrap_or_default()
+            .into();
+        *self.any_git_binary_help_output.lock() = Some(output.clone());
+        output
+    }
 }
 
 #[derive(Clone, Debug)]
@@ -967,7 +1008,15 @@ impl GitRepository for RealGitRepository {
                     index.read(false)?;
 
                     const STAGE_NORMAL: i32 = 0;
-                    let oid = match index.get_path(path.as_std_path(), STAGE_NORMAL) {
+                    let path = path.as_std_path();
+                    // `RepoPath` contains a `RelPath` which normalizes `.` into an empty path
+                    // `get_path` unwraps on empty paths though, so undo that normalization here
+                    let path = if path.components().next().is_none() {
+                        ".".as_ref()
+                    } else {
+                        path
+                    };
+                    let oid = match index.get_path(path, STAGE_NORMAL) {
                         Some(entry) if entry.mode != GIT_MODE_SYMLINK => entry.id,
                         _ => return Ok(None),
                     };
@@ -1077,10 +1126,16 @@ impl GitRepository for RealGitRepository {
             .boxed()
     }
 
-    fn remote_url(&self, name: &str) -> Option<String> {
-        let repo = self.repository.lock();
-        let remote = repo.find_remote(name).ok()?;
-        remote.url().map(|url| url.to_string())
+    fn remote_url(&self, name: &str) -> BoxFuture<'_, Option<String>> {
+        let repo = self.repository.clone();
+        let name = name.to_owned();
+        self.executor
+            .spawn(async move {
+                let repo = repo.lock();
+                let remote = repo.find_remote(&name).ok()?;
+                remote.url().map(|url| url.to_string())
+            })
+            .boxed()
     }
 
     fn revparse_batch(&self, revs: Vec<String>) -> BoxFuture<'_, Result<Vec<Option<String>>>> {
@@ -1371,9 +1426,19 @@ impl GitRepository for RealGitRepository {
                 branch
             } else if let Ok(revision) = repo.find_branch(&name, BranchType::Remote) {
                 let (_, branch_name) = name.split_once("/").context("Unexpected branch format")?;
+
                 let revision = revision.get();
                 let branch_commit = revision.peel_to_commit()?;
-                let mut branch = repo.branch(&branch_name, &branch_commit, false)?;
+                let mut branch = match repo.branch(&branch_name, &branch_commit, false) {
+                    Ok(branch) => branch,
+                    Err(err) if err.code() == ErrorCode::Exists => {
+                        repo.find_branch(&branch_name, BranchType::Local)?
+                    }
+                    Err(err) => {
+                        return Err(err.into());
+                    }
+                };
+
                 branch.set_upstream(Some(&name))?;
                 branch
             } else {
@@ -1389,7 +1454,6 @@ impl GitRepository for RealGitRepository {
         self.executor
             .spawn(async move {
                 let branch = branch.await?;
-
                 GitBinary::new(git_binary_path, working_directory?, executor)
                     .run(&["checkout", &branch])
                     .await?;
@@ -1454,22 +1518,24 @@ impl GitRepository for RealGitRepository {
             .boxed()
     }
 
-    fn blame(&self, path: RepoPath, content: Rope) -> BoxFuture<'_, Result<crate::blame::Blame>> {
+    fn blame(
+        &self,
+        path: RepoPath,
+        content: Rope,
+        line_ending: LineEnding,
+    ) -> BoxFuture<'_, Result<crate::blame::Blame>> {
         let working_directory = self.working_directory();
         let git_binary_path = self.any_git_binary_path.clone();
+        let executor = self.executor.clone();
 
-        let remote_url = self
-            .remote_url("upstream")
-            .or_else(|| self.remote_url("origin"));
-
-        self.executor
+        executor
             .spawn(async move {
                 crate::blame::Blame::for_path(
                     &git_binary_path,
                     &working_directory?,
                     &path,
                     &content,
-                    remote_url,
+                    line_ending,
                 )
                 .await
             })
@@ -1972,7 +2038,7 @@ impl GitRepository for RealGitRepository {
                 let working_directory = working_directory?;
                 let output = new_smol_command(&git_binary_path)
                     .current_dir(&working_directory)
-                    .args(["remote"])
+                    .args(["remote", "-v"])
                     .output()
                     .await?;
 
@@ -1981,14 +2047,43 @@ impl GitRepository for RealGitRepository {
                     "Failed to get all remotes:\n{}",
                     String::from_utf8_lossy(&output.stderr)
                 );
-                let remote_names = String::from_utf8_lossy(&output.stdout)
-                    .split('\n')
-                    .filter(|name| !name.is_empty())
-                    .map(|name| Remote {
-                        name: name.trim().to_string().into(),
+                let remote_names: HashSet<Remote> = String::from_utf8_lossy(&output.stdout)
+                    .lines()
+                    .filter(|line| !line.is_empty())
+                    .filter_map(|line| {
+                        let mut split_line = line.split_whitespace();
+                        let remote_name = split_line.next()?;
+
+                        Some(Remote {
+                            name: remote_name.trim().to_string().into(),
+                        })
                     })
                     .collect();
-                Ok(remote_names)
+
+                Ok(remote_names.into_iter().collect())
+            })
+            .boxed()
+    }
+
+    fn remove_remote(&self, name: String) -> BoxFuture<'_, Result<()>> {
+        let repo = self.repository.clone();
+        self.executor
+            .spawn(async move {
+                let repo = repo.lock();
+                repo.remote_delete(&name)?;
+
+                Ok(())
+            })
+            .boxed()
+    }
+
+    fn create_remote(&self, name: String, url: String) -> BoxFuture<'_, Result<()>> {
+        let repo = self.repository.clone();
+        self.executor
+            .spawn(async move {
+                let repo = repo.lock();
+                repo.remote(&name, url.as_ref())?;
+                Ok(())
             })
             .boxed()
     }
@@ -2230,18 +2325,47 @@ impl GitRepository for RealGitRepository {
         env: Arc<HashMap<String, String>>,
     ) -> BoxFuture<'_, Result<()>> {
         let working_directory = self.working_directory();
+        let repository = self.repository.clone();
         let git_binary_path = self.any_git_binary_path.clone();
         let executor = self.executor.clone();
-        self.executor
-            .spawn(async move {
-                let working_directory = working_directory?;
-                let git = GitBinary::new(git_binary_path, working_directory, executor)
-                    .envs(HashMap::clone(&env));
-                git.run(&["hook", "run", "--ignore-missing", hook.as_str()])
-                    .await?;
-                Ok(())
-            })
-            .boxed()
+        let help_output = self.any_git_binary_help_output();
+
+        // Note: Do not spawn these commands on the background thread, as this causes some git hooks to hang.
+        async move {
+            let working_directory = working_directory?;
+            if !help_output
+                .await
+                .lines()
+                .any(|line| line.trim().starts_with("hook "))
+            {
+                let hook_abs_path = repository.lock().path().join("hooks").join(hook.as_str());
+                if hook_abs_path.is_file() {
+                    let output = new_smol_command(&hook_abs_path)
+                        .envs(env.iter())
+                        .current_dir(&working_directory)
+                        .output()
+                        .await?;
+
+                    if !output.status.success() {
+                        return Err(GitBinaryCommandError {
+                            stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
+                            stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
+                            status: output.status,
+                        }
+                        .into());
+                    }
+                }
+
+                return Ok(());
+            }
+
+            let git = GitBinary::new(git_binary_path, working_directory, executor)
+                .envs(HashMap::clone(&env));
+            git.run(&["hook", "run", "--ignore-missing", hook.as_str()])
+                .await?;
+            Ok(())
+        }
+        .boxed()
     }
 }
 

crates/git_hosting_providers/Cargo.toml 🔗

@@ -18,6 +18,7 @@ futures.workspace = true
 git.workspace = true
 gpui.workspace = true
 http_client.workspace = true
+itertools.workspace = true
 regex.workspace = true
 serde.workspace = true
 serde_json.workspace = true

crates/git_hosting_providers/src/git_hosting_providers.rs 🔗

@@ -26,18 +26,18 @@ pub fn init(cx: &mut App) {
     provider_registry.register_hosting_provider(Arc::new(Gitee));
     provider_registry.register_hosting_provider(Arc::new(Github::public_instance()));
     provider_registry.register_hosting_provider(Arc::new(Gitlab::public_instance()));
-    provider_registry.register_hosting_provider(Arc::new(Sourcehut));
+    provider_registry.register_hosting_provider(Arc::new(SourceHut::public_instance()));
 }
 
 /// Registers additional Git hosting providers.
 ///
 /// These require information from the Git repository to construct, so their
 /// registration is deferred until we have a Git repository initialized.
-pub fn register_additional_providers(
+pub async fn register_additional_providers(
     provider_registry: Arc<GitHostingProviderRegistry>,
     repository: Arc<dyn GitRepository>,
 ) {
-    let Some(origin_url) = repository.remote_url("origin") else {
+    let Some(origin_url) = repository.remote_url("origin").await else {
         return;
     };
 
@@ -51,6 +51,8 @@ pub fn register_additional_providers(
         provider_registry.register_hosting_provider(Arc::new(gitea_self_hosted));
     } else if let Ok(bitbucket_self_hosted) = Bitbucket::from_remote_url(&origin_url) {
         provider_registry.register_hosting_provider(Arc::new(bitbucket_self_hosted));
+    } else if let Ok(sourcehut_self_hosted) = SourceHut::from_remote_url(&origin_url) {
+        provider_registry.register_hosting_provider(Arc::new(sourcehut_self_hosted));
     }
 }
 

crates/git_hosting_providers/src/providers/bitbucket.rs 🔗

@@ -1,8 +1,14 @@
-use std::str::FromStr;
 use std::sync::LazyLock;
-
-use anyhow::{Result, bail};
+use std::{str::FromStr, sync::Arc};
+
+use anyhow::{Context as _, Result, bail};
+use async_trait::async_trait;
+use futures::AsyncReadExt;
+use gpui::SharedString;
+use http_client::{AsyncBody, HttpClient, HttpRequestExt, Request};
+use itertools::Itertools as _;
 use regex::Regex;
+use serde::Deserialize;
 use url::Url;
 
 use git::{
@@ -20,6 +26,42 @@ fn pull_request_regex() -> &'static Regex {
     &PULL_REQUEST_REGEX
 }
 
+#[derive(Debug, Deserialize)]
+struct CommitDetails {
+    author: Author,
+}
+
+#[derive(Debug, Deserialize)]
+struct Author {
+    user: Account,
+}
+
+#[derive(Debug, Deserialize)]
+struct Account {
+    links: AccountLinks,
+}
+
+#[derive(Debug, Deserialize)]
+struct AccountLinks {
+    avatar: Option<Link>,
+}
+
+#[derive(Debug, Deserialize)]
+struct Link {
+    href: String,
+}
+
+#[derive(Debug, Deserialize)]
+struct CommitDetailsSelfHosted {
+    author: AuthorSelfHosted,
+}
+
+#[derive(Debug, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct AuthorSelfHosted {
+    avatar_url: Option<String>,
+}
+
 pub struct Bitbucket {
     name: String,
     base_url: Url,
@@ -61,8 +103,60 @@ impl Bitbucket {
             .host_str()
             .is_some_and(|host| host != "bitbucket.org")
     }
+
+    async fn fetch_bitbucket_commit_author(
+        &self,
+        repo_owner: &str,
+        repo: &str,
+        commit: &str,
+        client: &Arc<dyn HttpClient>,
+    ) -> Result<Option<String>> {
+        let Some(host) = self.base_url.host_str() else {
+            bail!("failed to get host from bitbucket base url");
+        };
+        let is_self_hosted = self.is_self_hosted();
+        let url = if is_self_hosted {
+            format!(
+                "https://{host}/rest/api/latest/projects/{repo_owner}/repos/{repo}/commits/{commit}?avatarSize=128"
+            )
+        } else {
+            format!("https://api.{host}/2.0/repositories/{repo_owner}/{repo}/commit/{commit}")
+        };
+
+        let request = Request::get(&url)
+            .header("Content-Type", "application/json")
+            .follow_redirects(http_client::RedirectPolicy::FollowAll);
+
+        let mut response = client
+            .send(request.body(AsyncBody::default())?)
+            .await
+            .with_context(|| format!("error fetching BitBucket commit details at {:?}", url))?;
+
+        let mut body = Vec::new();
+        response.body_mut().read_to_end(&mut body).await?;
+
+        if response.status().is_client_error() {
+            let text = String::from_utf8_lossy(body.as_slice());
+            bail!(
+                "status error {}, response: {text:?}",
+                response.status().as_u16()
+            );
+        }
+
+        let body_str = std::str::from_utf8(&body)?;
+
+        if is_self_hosted {
+            serde_json::from_str::<CommitDetailsSelfHosted>(body_str)
+                .map(|commit| commit.author.avatar_url)
+        } else {
+            serde_json::from_str::<CommitDetails>(body_str)
+                .map(|commit| commit.author.user.links.avatar.map(|link| link.href))
+        }
+        .context("failed to deserialize BitBucket commit details")
+    }
 }
 
+#[async_trait]
 impl GitHostingProvider for Bitbucket {
     fn name(&self) -> String {
         self.name.clone()
@@ -73,7 +167,7 @@ impl GitHostingProvider for Bitbucket {
     }
 
     fn supports_avatars(&self) -> bool {
-        false
+        true
     }
 
     fn format_line_number(&self, line: u32) -> String {
@@ -98,9 +192,16 @@ impl GitHostingProvider for Bitbucket {
             return None;
         }
 
-        let mut path_segments = url.path_segments()?;
-        let owner = path_segments.next()?;
-        let repo = path_segments.next()?.trim_end_matches(".git");
+        let mut path_segments = url.path_segments()?.collect::<Vec<_>>();
+        let repo = path_segments.pop()?.trim_end_matches(".git");
+        let owner = if path_segments.get(0).is_some_and(|v| *v == "scm") && path_segments.len() > 1
+        {
+            // Skip the "scm" segment if it's not the only segment
+            // https://github.com/gitkraken/vscode-gitlens/blob/a6e3c6fbb255116507eaabaa9940c192ed7bb0e1/src/git/remotes/bitbucket-server.ts#L72-L74
+            path_segments.into_iter().skip(1).join("/")
+        } else {
+            path_segments.into_iter().join("/")
+        };
 
         Some(ParsedGitRemote {
             owner: owner.into(),
@@ -176,6 +277,22 @@ impl GitHostingProvider for Bitbucket {
 
         Some(PullRequest { number, url })
     }
+
+    async fn commit_author_avatar_url(
+        &self,
+        repo_owner: &str,
+        repo: &str,
+        commit: SharedString,
+        http_client: Arc<dyn HttpClient>,
+    ) -> Result<Option<Url>> {
+        let commit = commit.to_string();
+        let avatar_url = self
+            .fetch_bitbucket_commit_author(repo_owner, repo, &commit, &http_client)
+            .await?
+            .map(|avatar_url| Url::parse(&avatar_url))
+            .transpose()?;
+        Ok(avatar_url)
+    }
 }
 
 #[cfg(test)]
@@ -264,6 +381,38 @@ mod tests {
                 repo: "zed".into(),
             }
         );
+
+        // Test with "scm" in the path
+        let remote_url = "https://bitbucket.company.com/scm/zed-industries/zed.git";
+
+        let parsed_remote = Bitbucket::from_remote_url(remote_url)
+            .unwrap()
+            .parse_remote_url(remote_url)
+            .unwrap();
+
+        assert_eq!(
+            parsed_remote,
+            ParsedGitRemote {
+                owner: "zed-industries".into(),
+                repo: "zed".into(),
+            }
+        );
+
+        // Test with only "scm" as owner
+        let remote_url = "https://bitbucket.company.com/scm/zed.git";
+
+        let parsed_remote = Bitbucket::from_remote_url(remote_url)
+            .unwrap()
+            .parse_remote_url(remote_url)
+            .unwrap();
+
+        assert_eq!(
+            parsed_remote,
+            ParsedGitRemote {
+                owner: "scm".into(),
+                repo: "zed".into(),
+            }
+        );
     }
 
     #[test]

crates/git_hosting_providers/src/providers/sourcehut.rs 🔗

@@ -1,5 +1,6 @@
 use std::str::FromStr;
 
+use anyhow::{Result, bail};
 use url::Url;
 
 use git::{
@@ -7,15 +8,52 @@ use git::{
     RemoteUrl,
 };
 
-pub struct Sourcehut;
+use crate::get_host_from_git_remote_url;
 
-impl GitHostingProvider for Sourcehut {
+pub struct SourceHut {
+    name: String,
+    base_url: Url,
+}
+
+impl SourceHut {
+    pub fn new(name: &str, base_url: Url) -> Self {
+        Self {
+            name: name.to_string(),
+            base_url,
+        }
+    }
+
+    pub fn public_instance() -> Self {
+        Self::new("SourceHut", Url::parse("https://git.sr.ht").unwrap())
+    }
+
+    pub fn from_remote_url(remote_url: &str) -> Result<Self> {
+        let host = get_host_from_git_remote_url(remote_url)?;
+        if host == "git.sr.ht" {
+            bail!("the SourceHut instance is not self-hosted");
+        }
+
+        // TODO: detecting self hosted instances by checking whether "sourcehut" is in the url or not
+        // is not very reliable. See https://github.com/zed-industries/zed/issues/26393 for more
+        // information.
+        if !host.contains("sourcehut") {
+            bail!("not a SourceHut URL");
+        }
+
+        Ok(Self::new(
+            "SourceHut Self-Hosted",
+            Url::parse(&format!("https://{}", host))?,
+        ))
+    }
+}
+
+impl GitHostingProvider for SourceHut {
     fn name(&self) -> String {
-        "SourceHut".to_string()
+        self.name.clone()
     }
 
     fn base_url(&self) -> Url {
-        Url::parse("https://git.sr.ht").unwrap()
+        self.base_url.clone()
     }
 
     fn supports_avatars(&self) -> bool {
@@ -34,7 +72,7 @@ impl GitHostingProvider for Sourcehut {
         let url = RemoteUrl::from_str(url).ok()?;
 
         let host = url.host_str()?;
-        if host != "git.sr.ht" {
+        if host != self.base_url.host_str()? {
             return None;
         }
 
@@ -96,7 +134,7 @@ mod tests {
 
     #[test]
     fn test_parse_remote_url_given_ssh_url() {
-        let parsed_remote = Sourcehut
+        let parsed_remote = SourceHut::public_instance()
             .parse_remote_url("git@git.sr.ht:~zed-industries/zed")
             .unwrap();
 
@@ -111,7 +149,7 @@ mod tests {
 
     #[test]
     fn test_parse_remote_url_given_ssh_url_with_git_suffix() {
-        let parsed_remote = Sourcehut
+        let parsed_remote = SourceHut::public_instance()
             .parse_remote_url("git@git.sr.ht:~zed-industries/zed.git")
             .unwrap();
 
@@ -126,7 +164,7 @@ mod tests {
 
     #[test]
     fn test_parse_remote_url_given_https_url() {
-        let parsed_remote = Sourcehut
+        let parsed_remote = SourceHut::public_instance()
             .parse_remote_url("https://git.sr.ht/~zed-industries/zed")
             .unwrap();
 
@@ -139,9 +177,63 @@ mod tests {
         );
     }
 
+    #[test]
+    fn test_parse_remote_url_given_self_hosted_ssh_url() {
+        let remote_url = "git@sourcehut.org:~zed-industries/zed";
+
+        let parsed_remote = SourceHut::from_remote_url(remote_url)
+            .unwrap()
+            .parse_remote_url(remote_url)
+            .unwrap();
+
+        assert_eq!(
+            parsed_remote,
+            ParsedGitRemote {
+                owner: "zed-industries".into(),
+                repo: "zed".into(),
+            }
+        );
+    }
+
+    #[test]
+    fn test_parse_remote_url_given_self_hosted_ssh_url_with_git_suffix() {
+        let remote_url = "git@sourcehut.org:~zed-industries/zed.git";
+
+        let parsed_remote = SourceHut::from_remote_url(remote_url)
+            .unwrap()
+            .parse_remote_url(remote_url)
+            .unwrap();
+
+        assert_eq!(
+            parsed_remote,
+            ParsedGitRemote {
+                owner: "zed-industries".into(),
+                repo: "zed.git".into(),
+            }
+        );
+    }
+
+    #[test]
+    fn test_parse_remote_url_given_self_hosted_https_url() {
+        let remote_url = "https://sourcehut.org/~zed-industries/zed";
+
+        let parsed_remote = SourceHut::from_remote_url(remote_url)
+            .unwrap()
+            .parse_remote_url(remote_url)
+            .unwrap();
+
+        assert_eq!(
+            parsed_remote,
+            ParsedGitRemote {
+                owner: "zed-industries".into(),
+                repo: "zed".into(),
+            }
+        );
+    }
+
     #[test]
     fn test_build_sourcehut_permalink() {
-        let permalink = Sourcehut.build_permalink(
+        let permalink = SourceHut::public_instance().build_permalink(
             ParsedGitRemote {
                 owner: "zed-industries".into(),
                 repo: "zed".into(),
@@ -159,7 +251,7 @@ mod tests {
 
     #[test]
     fn test_build_sourcehut_permalink_with_git_suffix() {
-        let permalink = Sourcehut.build_permalink(
+        let permalink = SourceHut::public_instance().build_permalink(
             ParsedGitRemote {
                 owner: "zed-industries".into(),
                 repo: "zed.git".into(),
@@ -175,9 +267,49 @@ mod tests {
         assert_eq!(permalink.to_string(), expected_url.to_string())
     }
 
+    #[test]
+    fn test_build_sourcehut_self_hosted_permalink() {
+        let permalink = SourceHut::from_remote_url("https://sourcehut.org/~zed-industries/zed")
+            .unwrap()
+            .build_permalink(
+                ParsedGitRemote {
+                    owner: "zed-industries".into(),
+                    repo: "zed".into(),
+                },
+                BuildPermalinkParams::new(
+                    "faa6f979be417239b2e070dbbf6392b909224e0b",
+                    &repo_path("crates/editor/src/git/permalink.rs"),
+                    None,
+                ),
+            );
+
+        let expected_url = "https://sourcehut.org/~zed-industries/zed/tree/faa6f979be417239b2e070dbbf6392b909224e0b/item/crates/editor/src/git/permalink.rs";
+        assert_eq!(permalink.to_string(), expected_url.to_string())
+    }
+
+    #[test]
+    fn test_build_sourcehut_self_hosted_permalink_with_git_suffix() {
+        let permalink = SourceHut::from_remote_url("https://sourcehut.org/~zed-industries/zed.git")
+            .unwrap()
+            .build_permalink(
+                ParsedGitRemote {
+                    owner: "zed-industries".into(),
+                    repo: "zed.git".into(),
+                },
+                BuildPermalinkParams::new(
+                    "faa6f979be417239b2e070dbbf6392b909224e0b",
+                    &repo_path("crates/editor/src/git/permalink.rs"),
+                    None,
+                ),
+            );
+
+        let expected_url = "https://sourcehut.org/~zed-industries/zed.git/tree/faa6f979be417239b2e070dbbf6392b909224e0b/item/crates/editor/src/git/permalink.rs";
+        assert_eq!(permalink.to_string(), expected_url.to_string())
+    }
+
     #[test]
     fn test_build_sourcehut_permalink_with_single_line_selection() {
-        let permalink = Sourcehut.build_permalink(
+        let permalink = SourceHut::public_instance().build_permalink(
             ParsedGitRemote {
                 owner: "zed-industries".into(),
                 repo: "zed".into(),
@@ -195,7 +327,7 @@ mod tests {
 
     #[test]
     fn test_build_sourcehut_permalink_with_multi_line_selection() {
-        let permalink = Sourcehut.build_permalink(
+        let permalink = SourceHut::public_instance().build_permalink(
             ParsedGitRemote {
                 owner: "zed-industries".into(),
                 repo: "zed".into(),
@@ -210,4 +342,44 @@ mod tests {
         let expected_url = "https://git.sr.ht/~zed-industries/zed/tree/faa6f979be417239b2e070dbbf6392b909224e0b/item/crates/editor/src/git/permalink.rs#L24-48";
         assert_eq!(permalink.to_string(), expected_url.to_string())
     }
+
+    #[test]
+    fn test_build_sourcehut_self_hosted_permalink_with_single_line_selection() {
+        let permalink = SourceHut::from_remote_url("https://sourcehut.org/~zed-industries/zed")
+            .unwrap()
+            .build_permalink(
+                ParsedGitRemote {
+                    owner: "zed-industries".into(),
+                    repo: "zed".into(),
+                },
+                BuildPermalinkParams::new(
+                    "faa6f979be417239b2e070dbbf6392b909224e0b",
+                    &repo_path("crates/editor/src/git/permalink.rs"),
+                    Some(6..6),
+                ),
+            );
+
+        let expected_url = "https://sourcehut.org/~zed-industries/zed/tree/faa6f979be417239b2e070dbbf6392b909224e0b/item/crates/editor/src/git/permalink.rs#L7";
+        assert_eq!(permalink.to_string(), expected_url.to_string())
+    }
+
+    #[test]
+    fn test_build_sourcehut_self_hosted_permalink_with_multi_line_selection() {
+        let permalink = SourceHut::from_remote_url("https://sourcehut.org/~zed-industries/zed")
+            .unwrap()
+            .build_permalink(
+                ParsedGitRemote {
+                    owner: "zed-industries".into(),
+                    repo: "zed".into(),
+                },
+                BuildPermalinkParams::new(
+                    "faa6f979be417239b2e070dbbf6392b909224e0b",
+                    &repo_path("crates/editor/src/git/permalink.rs"),
+                    Some(23..47),
+                ),
+            );
+
+        let expected_url = "https://sourcehut.org/~zed-industries/zed/tree/faa6f979be417239b2e070dbbf6392b909224e0b/item/crates/editor/src/git/permalink.rs#L24-48";
+        assert_eq!(permalink.to_string(), expected_url.to_string())
+    }
 }

crates/git_hosting_providers/src/settings.rs 🔗

@@ -8,7 +8,7 @@ use settings::{
 use url::Url;
 use util::ResultExt as _;
 
-use crate::{Bitbucket, Github, Gitlab};
+use crate::{Bitbucket, Forgejo, Gitea, Github, Gitlab, SourceHut};
 
 pub(crate) fn init(cx: &mut App) {
     init_git_hosting_provider_settings(cx);
@@ -46,6 +46,11 @@ fn update_git_hosting_providers_from_settings(cx: &mut App) {
                 }
                 GitHostingProviderKind::Github => Arc::new(Github::new(&provider.name, url)) as _,
                 GitHostingProviderKind::Gitlab => Arc::new(Gitlab::new(&provider.name, url)) as _,
+                GitHostingProviderKind::Gitea => Arc::new(Gitea::new(&provider.name, url)) as _,
+                GitHostingProviderKind::Forgejo => Arc::new(Forgejo::new(&provider.name, url)) as _,
+                GitHostingProviderKind::SourceHut => {
+                    Arc::new(SourceHut::new(&provider.name, url)) as _
+                }
             })
         });
 

crates/git_ui/Cargo.toml 🔗

@@ -13,7 +13,6 @@ name = "git_ui"
 path = "src/git_ui.rs"
 
 [features]
-default = []
 test-support = ["multi_buffer/test-support"]
 
 [dependencies]
@@ -44,6 +43,7 @@ notifications.workspace = true
 panel.workspace = true
 picker.workspace = true
 project.workspace = true
+prompt_store.workspace = true
 recent_projects.workspace = true
 remote.workspace = true
 schemars.workspace = true
@@ -62,7 +62,8 @@ watch.workspace = true
 workspace.workspace = true
 zed_actions.workspace = true
 zeroize.workspace = true
-
+ztracing.workspace = true
+tracing.workspace = true
 [target.'cfg(windows)'.dependencies]
 windows.workspace = true
 
@@ -74,7 +75,11 @@ gpui = { workspace = true, features = ["test-support"] }
 indoc.workspace = true
 pretty_assertions.workspace = true
 project = { workspace = true, features = ["test-support"] }
+rand.workspace = true
 settings = { workspace = true, features = ["test-support"] }
 unindent.workspace = true
 workspace = { workspace = true, features = ["test-support"] }
 zlog.workspace = true
+
+[package.metadata.cargo-machete]
+ignored = ["tracing"]

crates/git_ui/src/blame_ui.rs 🔗

@@ -3,10 +3,7 @@ use crate::{
     commit_view::CommitView,
 };
 use editor::{BlameRenderer, Editor, hover_markdown_style};
-use git::{
-    blame::{BlameEntry, ParsedCommitMessage},
-    repository::CommitSummary,
-};
+use git::{blame::BlameEntry, commit::ParsedCommitMessage, repository::CommitSummary};
 use gpui::{
     ClipboardItem, Entity, Hsla, MouseButton, ScrollHandle, Subscription, TextStyle,
     TextStyleRefinement, UnderlineStyle, WeakEntity, prelude::*,
@@ -47,14 +44,17 @@ impl BlameRenderer for GitBlameRenderer {
         let name = util::truncate_and_trailoff(author_name, GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED);
 
         let avatar = if ProjectSettings::get_global(cx).git.blame.show_avatar {
-            CommitAvatar::new(
-                &blame_entry.sha.to_string().into(),
-                details.as_ref().and_then(|it| it.remote.as_ref()),
+            Some(
+                CommitAvatar::new(
+                    &blame_entry.sha.to_string().into(),
+                    details.as_ref().and_then(|it| it.remote.as_ref()),
+                )
+                .render(window, cx),
             )
-            .render(window, cx)
         } else {
             None
         };
+
         Some(
             div()
                 .mr_2()
@@ -64,7 +64,7 @@ impl BlameRenderer for GitBlameRenderer {
                         .w_full()
                         .gap_2()
                         .justify_between()
-                        .font_family(style.font().family)
+                        .font(style.font())
                         .line_height(style.line_height)
                         .text_color(cx.theme().status().hint)
                         .child(
@@ -80,7 +80,10 @@ impl BlameRenderer for GitBlameRenderer {
                         .on_mouse_down(MouseButton::Right, {
                             let blame_entry = blame_entry.clone();
                             let details = details.clone();
+                            let editor = editor.clone();
                             move |event, window, cx| {
+                                cx.stop_propagation();
+
                                 deploy_blame_entry_context_menu(
                                     &blame_entry,
                                     details.as_ref(),
@@ -107,17 +110,19 @@ impl BlameRenderer for GitBlameRenderer {
                                 )
                             }
                         })
-                        .hoverable_tooltip(move |_window, cx| {
-                            cx.new(|cx| {
-                                CommitTooltip::blame_entry(
-                                    &blame_entry,
-                                    details.clone(),
-                                    repository.clone(),
-                                    workspace.clone(),
-                                    cx,
-                                )
+                        .when(!editor.read(cx).has_mouse_context_menu(), |el| {
+                            el.hoverable_tooltip(move |_window, cx| {
+                                cx.new(|cx| {
+                                    CommitTooltip::blame_entry(
+                                        &blame_entry,
+                                        details.clone(),
+                                        repository.clone(),
+                                        workspace.clone(),
+                                        cx,
+                                    )
+                                })
+                                .into()
                             })
-                            .into()
                         }),
                 )
                 .into_any(),
@@ -148,7 +153,7 @@ impl BlameRenderer for GitBlameRenderer {
             h_flex()
                 .id("inline-blame")
                 .w_full()
-                .font_family(style.font().family)
+                .font(style.font())
                 .text_color(cx.theme().status().hint)
                 .line_height(style.line_height)
                 .child(Icon::new(IconName::FileGit).color(Color::Hint))
@@ -198,9 +203,6 @@ impl BlameRenderer for GitBlameRenderer {
         let link_color = cx.theme().colors().text_accent;
         let markdown_style = {
             let mut style = hover_markdown_style(window, cx);
-            if let Some(code_block) = &style.code_block.text {
-                style.base_text_style.refine(code_block);
-            }
             style.link.refine(&TextStyleRefinement {
                 color: Some(link_color),
                 underline: Some(UnderlineStyle {
@@ -261,7 +263,7 @@ impl BlameRenderer for GitBlameRenderer {
                                     .flex_wrap()
                                     .border_b_1()
                                     .border_color(cx.theme().colors().border_variant)
-                                    .children(avatar)
+                                    .child(avatar)
                                     .child(author)
                                     .when(!author_email.is_empty(), |this| {
                                         this.child(
@@ -399,6 +401,7 @@ fn deploy_blame_entry_context_menu(
     });
 
     editor.update(cx, move |editor, cx| {
+        editor.hide_blame_popover(false, cx);
         editor.deploy_mouse_context_menu(position, context_menu, window, cx);
         cx.notify();
     });

crates/git_ui/src/branch_picker.rs 🔗

@@ -1,8 +1,10 @@
 use anyhow::Context as _;
+use editor::Editor;
 use fuzzy::StringMatchCandidate;
 
 use collections::HashSet;
 use git::repository::Branch;
+use gpui::http_client::Url;
 use gpui::{
     Action, App, Context, DismissEvent, Entity, EventEmitter, FocusHandle, Focusable,
     InteractiveElement, IntoElement, Modifiers, ModifiersChangedEvent, ParentElement, Render,
@@ -14,7 +16,10 @@ use project::project_settings::ProjectSettings;
 use settings::Settings;
 use std::sync::Arc;
 use time::OffsetDateTime;
-use ui::{HighlightedLabel, KeyBinding, ListItem, ListItemSpacing, Tooltip, prelude::*};
+use ui::{
+    Divider, HighlightedLabel, KeyBinding, ListHeader, ListItem, ListItemSpacing, Tooltip,
+    prelude::*,
+};
 use util::ResultExt;
 use workspace::notifications::DetachAndPromptErr;
 use workspace::{ModalView, Workspace};
@@ -24,8 +29,10 @@ use crate::{branch_picker, git_panel::show_error_toast};
 actions!(
     branch_picker,
     [
-        /// Deletes the selected git branch.
-        DeleteBranch
+        /// Deletes the selected git branch or remote.
+        DeleteBranch,
+        /// Filter the list of remotes
+        FilterRemotes
     ]
 );
 
@@ -65,32 +72,26 @@ pub fn open(
     let repository = workspace.project().read(cx).active_repository(cx);
     let style = BranchListStyle::Modal;
     workspace.toggle_modal(window, cx, |window, cx| {
-        BranchList::new(
-            Some(workspace_handle),
-            repository,
-            style,
-            rems(34.),
-            window,
-            cx,
-        )
+        BranchList::new(workspace_handle, repository, style, rems(34.), window, cx)
     })
 }
 
 pub fn popover(
+    workspace: WeakEntity<Workspace>,
     repository: Option<Entity<Repository>>,
     window: &mut Window,
     cx: &mut App,
 ) -> Entity<BranchList> {
     cx.new(|cx| {
         let list = BranchList::new(
-            None,
+            workspace,
             repository,
             BranchListStyle::Popover,
             rems(20.),
             window,
             cx,
         );
-        list.focus_handle(cx).focus(window);
+        list.focus_handle(cx).focus(window, cx);
         list
     })
 }
@@ -110,7 +111,7 @@ pub struct BranchList {
 
 impl BranchList {
     fn new(
-        workspace: Option<WeakEntity<Workspace>>,
+        workspace: WeakEntity<Workspace>,
         repository: Option<Entity<Repository>>,
         style: BranchListStyle,
         width: Rems,
@@ -206,7 +207,7 @@ impl BranchList {
             .update(cx, |picker, _| picker.delegate.modifiers = ev.modifiers)
     }
 
-    fn handle_delete_branch(
+    fn handle_delete(
         &mut self,
         _: &branch_picker::DeleteBranch,
         window: &mut Window,
@@ -215,9 +216,23 @@ impl BranchList {
         self.picker.update(cx, |picker, cx| {
             picker
                 .delegate
-                .delete_branch_at(picker.delegate.selected_index, window, cx)
+                .delete_at(picker.delegate.selected_index, window, cx)
         })
     }
+
+    fn handle_filter(
+        &mut self,
+        _: &branch_picker::FilterRemotes,
+        window: &mut Window,
+        cx: &mut Context<Self>,
+    ) {
+        self.picker.update(cx, |picker, cx| {
+            picker.delegate.branch_filter = picker.delegate.branch_filter.invert();
+            picker.update_matches(picker.query(cx), window, cx);
+            picker.refresh_placeholder(window, cx);
+            cx.notify();
+        });
+    }
 }
 impl ModalView for BranchList {}
 impl EventEmitter<DismissEvent> for BranchList {}
@@ -234,7 +249,8 @@ impl Render for BranchList {
             .key_context("GitBranchSelector")
             .w(self.width)
             .on_modifiers_changed(cx.listener(Self::handle_modifiers_changed))
-            .on_action(cx.listener(Self::handle_delete_branch))
+            .on_action(cx.listener(Self::handle_delete))
+            .on_action(cx.listener(Self::handle_filter))
             .child(self.picker.clone())
             .on_mouse_down_out({
                 cx.listener(move |this, _, window, cx| {
@@ -246,16 +262,72 @@ impl Render for BranchList {
     }
 }
 
-#[derive(Debug, Clone)]
-struct BranchEntry {
-    branch: Branch,
-    positions: Vec<usize>,
-    is_new: bool,
+#[derive(Debug, Clone, PartialEq)]
+enum Entry {
+    Branch {
+        branch: Branch,
+        positions: Vec<usize>,
+    },
+    NewUrl {
+        url: String,
+    },
+    NewBranch {
+        name: String,
+    },
+    NewRemoteName {
+        name: String,
+        url: SharedString,
+    },
+}
+
+impl Entry {
+    fn as_branch(&self) -> Option<&Branch> {
+        match self {
+            Entry::Branch { branch, .. } => Some(branch),
+            _ => None,
+        }
+    }
+
+    fn name(&self) -> &str {
+        match self {
+            Entry::Branch { branch, .. } => branch.name(),
+            Entry::NewUrl { url, .. } => url.as_str(),
+            Entry::NewBranch { name, .. } => name.as_str(),
+            Entry::NewRemoteName { name, .. } => name.as_str(),
+        }
+    }
+
+    #[cfg(test)]
+    fn is_new_url(&self) -> bool {
+        matches!(self, Self::NewUrl { .. })
+    }
+
+    #[cfg(test)]
+    fn is_new_branch(&self) -> bool {
+        matches!(self, Self::NewBranch { .. })
+    }
+}
+
+#[derive(Clone, Copy, PartialEq)]
+enum BranchFilter {
+    /// Show both local and remote branches.
+    All,
+    /// Only show remote branches.
+    Remote,
+}
+
+impl BranchFilter {
+    fn invert(&self) -> Self {
+        match self {
+            BranchFilter::All => BranchFilter::Remote,
+            BranchFilter::Remote => BranchFilter::All,
+        }
+    }
 }
 
 pub struct BranchListDelegate {
-    workspace: Option<WeakEntity<Workspace>>,
-    matches: Vec<BranchEntry>,
+    workspace: WeakEntity<Workspace>,
+    matches: Vec<Entry>,
     all_branches: Option<Vec<Branch>>,
     default_branch: Option<SharedString>,
     repo: Option<Entity<Repository>>,
@@ -263,12 +335,26 @@ pub struct BranchListDelegate {
     selected_index: usize,
     last_query: String,
     modifiers: Modifiers,
+    branch_filter: BranchFilter,
+    state: PickerState,
     focus_handle: FocusHandle,
 }
 
+#[derive(Debug)]
+enum PickerState {
+    /// When we display list of branches/remotes
+    List,
+    /// When we set an url to create a new remote
+    NewRemote,
+    /// When we confirm the new remote url (after NewRemote)
+    CreateRemote(SharedString),
+    /// When we set a new branch to create
+    NewBranch,
+}
+
 impl BranchListDelegate {
     fn new(
-        workspace: Option<WeakEntity<Workspace>>,
+        workspace: WeakEntity<Workspace>,
         repo: Option<Entity<Repository>>,
         style: BranchListStyle,
         cx: &mut Context<BranchList>,
@@ -283,6 +369,8 @@ impl BranchListDelegate {
             selected_index: 0,
             last_query: Default::default(),
             modifiers: Default::default(),
+            branch_filter: BranchFilter::All,
+            state: PickerState::List,
             focus_handle: cx.focus_handle(),
         }
     }
@@ -313,8 +401,28 @@ impl BranchListDelegate {
         cx.emit(DismissEvent);
     }
 
-    fn delete_branch_at(&self, idx: usize, window: &mut Window, cx: &mut Context<Picker<Self>>) {
-        let Some(branch_entry) = self.matches.get(idx) else {
+    fn create_remote(
+        &self,
+        remote_name: String,
+        remote_url: String,
+        window: &mut Window,
+        cx: &mut Context<Picker<Self>>,
+    ) {
+        let Some(repo) = self.repo.clone() else {
+            return;
+        };
+
+        let receiver = repo.update(cx, |repo, _| repo.create_remote(remote_name, remote_url));
+
+        cx.background_spawn(async move { receiver.await? })
+            .detach_and_prompt_err("Failed to create remote", window, cx, |e, _, _cx| {
+                Some(e.to_string())
+            });
+        cx.emit(DismissEvent);
+    }
+
+    fn delete_at(&self, idx: usize, window: &mut Window, cx: &mut Context<Picker<Self>>) {
+        let Some(entry) = self.matches.get(idx).cloned() else {
             return;
         };
         let Some(repo) = self.repo.clone() else {
@@ -322,20 +430,51 @@ impl BranchListDelegate {
         };
 
         let workspace = self.workspace.clone();
-        let branch_name = branch_entry.branch.name().to_string();
-        let branch_ref = branch_entry.branch.ref_name.clone();
 
         cx.spawn_in(window, async move |picker, cx| {
-            let result = repo
-                .update(cx, |repo, _| repo.delete_branch(branch_name.clone()))?
-                .await?;
+            let mut is_remote = false;
+            let result = match &entry {
+                Entry::Branch { branch, .. } => match branch.remote_name() {
+                    Some(remote_name) => {
+                        is_remote = true;
+                        repo.update(cx, |repo, _| repo.remove_remote(remote_name.to_string()))?
+                            .await?
+                    }
+                    None => {
+                        repo.update(cx, |repo, _| repo.delete_branch(branch.name().to_string()))?
+                            .await?
+                    }
+                },
+                _ => {
+                    log::error!("Failed to delete remote: wrong entry to delete");
+                    return Ok(());
+                }
+            };
 
             if let Err(e) = result {
-                log::error!("Failed to delete branch: {}", e);
+                if is_remote {
+                    log::error!("Failed to delete remote: {}", e);
+                } else {
+                    log::error!("Failed to delete branch: {}", e);
+                }
 
-                if let Some(workspace) = workspace.and_then(|w| w.upgrade()) {
+                if let Some(workspace) = workspace.upgrade() {
                     cx.update(|_window, cx| {
-                        show_error_toast(workspace, format!("branch -d {branch_name}"), e, cx)
+                        if is_remote {
+                            show_error_toast(
+                                workspace,
+                                format!("remote remove {}", entry.name()),
+                                e,
+                                cx,
+                            )
+                        } else {
+                            show_error_toast(
+                                workspace,
+                                format!("branch -d {}", entry.name()),
+                                e,
+                                cx,
+                            )
+                        }
                     })?;
                 }
 
@@ -343,13 +482,12 @@ impl BranchListDelegate {
             }
 
             picker.update_in(cx, |picker, _, cx| {
-                picker
-                    .delegate
-                    .matches
-                    .retain(|entry| entry.branch.ref_name != branch_ref);
+                picker.delegate.matches.retain(|e| e != &entry);
 
-                if let Some(all_branches) = &mut picker.delegate.all_branches {
-                    all_branches.retain(|branch| branch.ref_name != branch_ref);
+                if let Entry::Branch { branch, .. } = &entry {
+                    if let Some(all_branches) = &mut picker.delegate.all_branches {
+                        all_branches.retain(|e| e.ref_name != branch.ref_name);
+                    }
                 }
 
                 if picker.delegate.matches.is_empty() {
@@ -371,7 +509,80 @@ impl PickerDelegate for BranchListDelegate {
     type ListItem = ListItem;
 
     fn placeholder_text(&self, _window: &mut Window, _cx: &mut App) -> Arc<str> {
-        "Select branch…".into()
+        match self.state {
+            PickerState::List | PickerState::NewRemote | PickerState::NewBranch => {
+                match self.branch_filter {
+                    BranchFilter::All => "Select branch or remote…",
+                    BranchFilter::Remote => "Select remote…",
+                }
+            }
+            PickerState::CreateRemote(_) => "Enter a name for this remote…",
+        }
+        .into()
+    }
+
+    fn no_matches_text(&self, _window: &mut Window, _cx: &mut App) -> Option<SharedString> {
+        match self.state {
+            PickerState::CreateRemote(_) => {
+                Some(SharedString::new_static("Remote name can't be empty"))
+            }
+            _ => None,
+        }
+    }
+
+    fn render_editor(
+        &self,
+        editor: &Entity<Editor>,
+        _window: &mut Window,
+        _cx: &mut Context<Picker<Self>>,
+    ) -> Div {
+        let focus_handle = self.focus_handle.clone();
+
+        v_flex()
+            .when(
+                self.editor_position() == PickerEditorPosition::End,
+                |this| this.child(Divider::horizontal()),
+            )
+            .child(
+                h_flex()
+                    .overflow_hidden()
+                    .flex_none()
+                    .h_9()
+                    .px_2p5()
+                    .child(editor.clone())
+                    .when(
+                        self.editor_position() == PickerEditorPosition::End,
+                        |this| {
+                            let tooltip_label = match self.branch_filter {
+                                BranchFilter::All => "Filter Remote Branches",
+                                BranchFilter::Remote => "Show All Branches",
+                            };
+
+                            this.gap_1().justify_between().child({
+                                IconButton::new("filter-remotes", IconName::Filter)
+                                    .toggle_state(self.branch_filter == BranchFilter::Remote)
+                                    .tooltip(move |_, cx| {
+                                        Tooltip::for_action_in(
+                                            tooltip_label,
+                                            &branch_picker::FilterRemotes,
+                                            &focus_handle,
+                                            cx,
+                                        )
+                                    })
+                                    .on_click(|_click, window, cx| {
+                                        window.dispatch_action(
+                                            branch_picker::FilterRemotes.boxed_clone(),
+                                            cx,
+                                        );
+                                    })
+                            })
+                        },
+                    ),
+            )
+            .when(
+                self.editor_position() == PickerEditorPosition::Start,
+                |this| this.child(Divider::horizontal()),
+            )
     }
 
     fn editor_position(&self) -> PickerEditorPosition {
@@ -408,26 +619,38 @@ impl PickerDelegate for BranchListDelegate {
             return Task::ready(());
         };
 
-        const RECENT_BRANCHES_COUNT: usize = 10;
+        let branch_filter = self.branch_filter;
         cx.spawn_in(window, async move |picker, cx| {
-            let mut matches: Vec<BranchEntry> = if query.is_empty() {
-                all_branches
+            let branch_matches_filter = |branch: &Branch| match branch_filter {
+                BranchFilter::All => true,
+                BranchFilter::Remote => branch.is_remote(),
+            };
+
+            let mut matches: Vec<Entry> = if query.is_empty() {
+                let mut matches: Vec<Entry> = all_branches
                     .into_iter()
-                    .filter(|branch| !branch.is_remote())
-                    .take(RECENT_BRANCHES_COUNT)
-                    .map(|branch| BranchEntry {
+                    .filter(|branch| branch_matches_filter(branch))
+                    .map(|branch| Entry::Branch {
                         branch,
                         positions: Vec::new(),
-                        is_new: false,
                     })
-                    .collect()
+                    .collect();
+
+                // Keep the existing recency sort within each group, but show local branches first.
+                matches.sort_by_key(|entry| entry.as_branch().is_some_and(|b| b.is_remote()));
+
+                matches
             } else {
-                let candidates = all_branches
+                let branches = all_branches
+                    .iter()
+                    .filter(|branch| branch_matches_filter(branch))
+                    .collect::<Vec<_>>();
+                let candidates = branches
                     .iter()
                     .enumerate()
                     .map(|(ix, branch)| StringMatchCandidate::new(ix, branch.name()))
                     .collect::<Vec<StringMatchCandidate>>();
-                fuzzy::match_strings(
+                let mut matches: Vec<Entry> = fuzzy::match_strings(
                     &candidates,
                     &query,
                     true,
@@ -438,31 +661,59 @@ impl PickerDelegate for BranchListDelegate {
                 )
                 .await
                 .into_iter()
-                .map(|candidate| BranchEntry {
-                    branch: all_branches[candidate.candidate_id].clone(),
+                .map(|candidate| Entry::Branch {
+                    branch: branches[candidate.candidate_id].clone(),
                     positions: candidate.positions,
-                    is_new: false,
                 })
-                .collect()
+                .collect();
+
+                // Keep fuzzy-relevance ordering within local/remote groups, but show locals first.
+                matches.sort_by_key(|entry| entry.as_branch().is_some_and(|b| b.is_remote()));
+
+                matches
             };
             picker
                 .update(cx, |picker, _| {
+                    if let PickerState::CreateRemote(url) = &picker.delegate.state {
+                        let query = query.replace(' ', "-");
+                        if !query.is_empty() {
+                            picker.delegate.matches = vec![Entry::NewRemoteName {
+                                name: query.clone(),
+                                url: url.clone(),
+                            }];
+                            picker.delegate.selected_index = 0;
+                        } else {
+                            picker.delegate.matches = Vec::new();
+                            picker.delegate.selected_index = 0;
+                        }
+                        picker.delegate.last_query = query;
+                        return;
+                    }
+
                     if !query.is_empty()
-                        && !matches
-                            .first()
-                            .is_some_and(|entry| entry.branch.name() == query)
+                        && !matches.first().is_some_and(|entry| entry.name() == query)
                     {
                         let query = query.replace(' ', "-");
-                        matches.push(BranchEntry {
-                            branch: Branch {
-                                ref_name: format!("refs/heads/{query}").into(),
-                                is_head: false,
-                                upstream: None,
-                                most_recent_commit: None,
-                            },
-                            positions: Vec::new(),
-                            is_new: true,
-                        })
+                        let is_url = query.trim_start_matches("git@").parse::<Url>().is_ok();
+                        let entry = if is_url {
+                            Entry::NewUrl { url: query }
+                        } else {
+                            Entry::NewBranch { name: query }
+                        };
+                        // Only transition to NewBranch/NewRemote states when we only show their list item
+                        // Otherwise, stay in List state so footer buttons remain visible
+                        picker.delegate.state = if matches.is_empty() {
+                            if is_url {
+                                PickerState::NewRemote
+                            } else {
+                                PickerState::NewBranch
+                            }
+                        } else {
+                            PickerState::List
+                        };
+                        matches.push(entry);
+                    } else {
+                        picker.delegate.state = PickerState::List;
                     }
                     let delegate = &mut picker.delegate;
                     delegate.matches = matches;
@@ -483,52 +734,73 @@ impl PickerDelegate for BranchListDelegate {
             return;
         };
 
-        if entry.is_new {
-            let from_branch = if secondary {
-                self.default_branch.clone()
-            } else {
-                None
-            };
-            self.create_branch(
-                from_branch,
-                entry.branch.name().to_owned().into(),
-                window,
-                cx,
-            );
-            return;
-        }
+        match entry {
+            Entry::Branch { branch, .. } => {
+                let current_branch = self.repo.as_ref().map(|repo| {
+                    repo.read_with(cx, |repo, _| {
+                        repo.branch.as_ref().map(|branch| branch.ref_name.clone())
+                    })
+                });
+
+                if current_branch
+                    .flatten()
+                    .is_some_and(|current_branch| current_branch == branch.ref_name)
+                {
+                    cx.emit(DismissEvent);
+                    return;
+                }
 
-        let current_branch = self.repo.as_ref().map(|repo| {
-            repo.read_with(cx, |repo, _| {
-                repo.branch.as_ref().map(|branch| branch.ref_name.clone())
-            })
-        });
+                let Some(repo) = self.repo.clone() else {
+                    return;
+                };
 
-        if current_branch
-            .flatten()
-            .is_some_and(|current_branch| current_branch == entry.branch.ref_name)
-        {
-            cx.emit(DismissEvent);
-            return;
-        }
+                let branch = branch.clone();
+                cx.spawn(async move |_, cx| {
+                    repo.update(cx, |repo, _| repo.change_branch(branch.name().to_string()))?
+                        .await??;
 
-        let Some(repo) = self.repo.clone() else {
-            return;
-        };
-
-        let branch = entry.branch.clone();
-        cx.spawn(async move |_, cx| {
-            repo.update(cx, |repo, _| repo.change_branch(branch.name().to_string()))?
-                .await??;
-
-            anyhow::Ok(())
-        })
-        .detach_and_prompt_err("Failed to change branch", window, cx, |_, _, _| None);
+                    anyhow::Ok(())
+                })
+                .detach_and_prompt_err(
+                    "Failed to change branch",
+                    window,
+                    cx,
+                    |_, _, _| None,
+                );
+            }
+            Entry::NewUrl { url } => {
+                self.state = PickerState::CreateRemote(url.clone().into());
+                self.matches = Vec::new();
+                self.selected_index = 0;
+
+                cx.defer_in(window, |picker, window, cx| {
+                    picker.refresh_placeholder(window, cx);
+                    picker.set_query("", window, cx);
+                    cx.notify();
+                });
+
+                // returning early to prevent dismissing the modal, so a user can enter
+                // a remote name first.
+                return;
+            }
+            Entry::NewRemoteName { name, url } => {
+                self.create_remote(name.clone(), url.to_string(), window, cx);
+            }
+            Entry::NewBranch { name } => {
+                let from_branch = if secondary {
+                    self.default_branch.clone()
+                } else {
+                    None
+                };
+                self.create_branch(from_branch, name.into(), window, cx);
+            }
+        }
 
         cx.emit(DismissEvent);
     }
 
     fn dismissed(&mut self, _: &mut Window, cx: &mut Context<Picker<Self>>) {
+        self.state = PickerState::List;
         cx.emit(DismissEvent);
     }
 
@@ -542,174 +814,1134 @@ impl PickerDelegate for BranchListDelegate {
         let entry = &self.matches.get(ix)?;
 
         let (commit_time, author_name, subject) = entry
-            .branch
-            .most_recent_commit
-            .as_ref()
-            .map(|commit| {
-                let subject = commit.subject.clone();
-                let commit_time = OffsetDateTime::from_unix_timestamp(commit.commit_timestamp)
-                    .unwrap_or_else(|_| OffsetDateTime::now_utc());
-                let local_offset =
-                    time::UtcOffset::current_local_offset().unwrap_or(time::UtcOffset::UTC);
-                let formatted_time = time_format::format_localized_timestamp(
-                    commit_time,
-                    OffsetDateTime::now_utc(),
-                    local_offset,
-                    time_format::TimestampFormat::Relative,
-                );
-                let author = commit.author_name.clone();
-                (Some(formatted_time), Some(author), Some(subject))
+            .as_branch()
+            .and_then(|branch| {
+                branch.most_recent_commit.as_ref().map(|commit| {
+                    let subject = commit.subject.clone();
+                    let commit_time = OffsetDateTime::from_unix_timestamp(commit.commit_timestamp)
+                        .unwrap_or_else(|_| OffsetDateTime::now_utc());
+                    let local_offset =
+                        time::UtcOffset::current_local_offset().unwrap_or(time::UtcOffset::UTC);
+                    let formatted_time = time_format::format_localized_timestamp(
+                        commit_time,
+                        OffsetDateTime::now_utc(),
+                        local_offset,
+                        time_format::TimestampFormat::Relative,
+                    );
+                    let author = commit.author_name.clone();
+                    (Some(formatted_time), Some(author), Some(subject))
+                })
             })
             .unwrap_or_else(|| (None, None, None));
 
-        let icon = if let Some(default_branch) = self.default_branch.clone()
-            && entry.is_new
-        {
-            Some(
-                IconButton::new("branch-from-default", IconName::GitBranchAlt)
-                    .on_click(cx.listener(move |this, _, window, cx| {
-                        this.delegate.set_selected_index(ix, window, cx);
-                        this.delegate.confirm(true, window, cx);
-                    }))
-                    .tooltip(move |_window, cx| {
-                        Tooltip::for_action(
-                            format!("Create branch based off default: {default_branch}"),
-                            &menu::SecondaryConfirm,
-                            cx,
-                        )
-                    }),
-            )
-        } else {
-            None
+        let entry_icon = match entry {
+            Entry::NewUrl { .. } | Entry::NewBranch { .. } | Entry::NewRemoteName { .. } => {
+                Icon::new(IconName::Plus).color(Color::Muted)
+            }
+            Entry::Branch { branch, .. } => {
+                if branch.is_remote() {
+                    Icon::new(IconName::Screen).color(Color::Muted)
+                } else {
+                    Icon::new(IconName::GitBranchAlt).color(Color::Muted)
+                }
+            }
         };
 
-        let branch_name = if entry.is_new {
-            h_flex()
-                .gap_1()
-                .child(
-                    Icon::new(IconName::Plus)
-                        .size(IconSize::Small)
-                        .color(Color::Muted),
-                )
-                .child(
-                    Label::new(format!("Create branch \"{}\"…", entry.branch.name()))
-                        .single_line()
-                        .truncate(),
-                )
-                .into_any_element()
-        } else {
-            h_flex()
-                .max_w_48()
-                .child(
-                    HighlightedLabel::new(entry.branch.name().to_owned(), entry.positions.clone())
-                        .truncate(),
-                )
-                .into_any_element()
+        let entry_title = match entry {
+            Entry::NewUrl { .. } => Label::new("Create Remote Repository")
+                .single_line()
+                .truncate()
+                .into_any_element(),
+            Entry::NewBranch { name } => Label::new(format!("Create Branch: \"{name}\"…"))
+                .single_line()
+                .truncate()
+                .into_any_element(),
+            Entry::NewRemoteName { name, .. } => Label::new(format!("Create Remote: \"{name}\""))
+                .single_line()
+                .truncate()
+                .into_any_element(),
+            Entry::Branch { branch, positions } => {
+                HighlightedLabel::new(branch.name().to_string(), positions.clone())
+                    .single_line()
+                    .truncate()
+                    .into_any_element()
+            }
+        };
+
+        let focus_handle = self.focus_handle.clone();
+        let is_new_items = matches!(
+            entry,
+            Entry::NewUrl { .. } | Entry::NewBranch { .. } | Entry::NewRemoteName { .. }
+        );
+
+        let deleted_branch_icon = |entry_ix: usize, is_head_branch: bool| {
+            IconButton::new(("delete", entry_ix), IconName::Trash)
+                .tooltip(move |_, cx| {
+                    Tooltip::for_action_in(
+                        "Delete Branch",
+                        &branch_picker::DeleteBranch,
+                        &focus_handle,
+                        cx,
+                    )
+                })
+                .disabled(is_head_branch)
+                .on_click(cx.listener(move |this, _, window, cx| {
+                    this.delegate.delete_at(entry_ix, window, cx);
+                }))
         };
 
+        let create_from_default_button = self.default_branch.as_ref().map(|default_branch| {
+            let tooltip_label: SharedString = format!("Create New From: {default_branch}").into();
+            let focus_handle = self.focus_handle.clone();
+
+            IconButton::new("create_from_default", IconName::GitBranchPlus)
+                .tooltip(move |_, cx| {
+                    Tooltip::for_action_in(
+                        tooltip_label.clone(),
+                        &menu::SecondaryConfirm,
+                        &focus_handle,
+                        cx,
+                    )
+                })
+                .on_click(cx.listener(|this, _, window, cx| {
+                    this.delegate.confirm(true, window, cx);
+                }))
+                .into_any_element()
+        });
+
         Some(
-            ListItem::new(SharedString::from(format!("vcs-menu-{ix}")))
+            ListItem::new(format!("vcs-menu-{ix}"))
                 .inset(true)
                 .spacing(ListItemSpacing::Sparse)
                 .toggle_state(selected)
-                .tooltip({
-                    let branch_name = entry.branch.name().to_string();
-                    if entry.is_new {
-                        Tooltip::text(format!("Create branch \"{}\"", branch_name))
-                    } else {
-                        Tooltip::text(branch_name)
-                    }
-                })
                 .child(
-                    v_flex()
+                    h_flex()
                         .w_full()
-                        .overflow_hidden()
+                        .gap_3()
+                        .flex_grow()
+                        .child(entry_icon)
                         .child(
-                            h_flex()
-                                .gap_6()
-                                .justify_between()
-                                .overflow_x_hidden()
-                                .child(branch_name)
-                                .when_some(commit_time, |label, commit_time| {
-                                    label.child(
-                                        Label::new(commit_time)
-                                            .size(LabelSize::Small)
-                                            .color(Color::Muted)
-                                            .into_element(),
-                                    )
-                                }),
-                        )
-                        .when(self.style == BranchListStyle::Modal, |el| {
-                            el.child(div().max_w_96().child({
-                                let message = if entry.is_new {
-                                    if let Some(current_branch) =
-                                        self.repo.as_ref().and_then(|repo| {
-                                            repo.read(cx).branch.as_ref().map(|b| b.name())
+                            v_flex()
+                                .id("info_container")
+                                .w_full()
+                                .child(entry_title)
+                                .child(
+                                    h_flex()
+                                        .w_full()
+                                        .justify_between()
+                                        .gap_1p5()
+                                        .when(self.style == BranchListStyle::Modal, |el| {
+                                            el.child(div().max_w_96().child({
+                                                let message = match entry {
+                                                    Entry::NewUrl { url } => {
+                                                        format!("Based off {url}")
+                                                    }
+                                                    Entry::NewRemoteName { url, .. } => {
+                                                        format!("Based off {url}")
+                                                    }
+                                                    Entry::NewBranch { .. } => {
+                                                        if let Some(current_branch) =
+                                                            self.repo.as_ref().and_then(|repo| {
+                                                                repo.read(cx)
+                                                                    .branch
+                                                                    .as_ref()
+                                                                    .map(|b| b.name())
+                                                            })
+                                                        {
+                                                            format!("Based off {}", current_branch)
+                                                        } else {
+                                                            "Based off the current branch"
+                                                                .to_string()
+                                                        }
+                                                    }
+                                                    Entry::Branch { .. } => {
+                                                        let show_author_name =
+                                                            ProjectSettings::get_global(cx)
+                                                                .git
+                                                                .branch_picker
+                                                                .show_author_name;
+
+                                                        subject.map_or(
+                                                            "No commits found".into(),
+                                                            |subject| {
+                                                                if show_author_name
+                                                                    && let Some(author) =
+                                                                        author_name
+                                                                {
+                                                                    format!(
+                                                                        "{}  •  {}",
+                                                                        author, subject
+                                                                    )
+                                                                } else {
+                                                                    subject.to_string()
+                                                                }
+                                                            },
+                                                        )
+                                                    }
+                                                };
+
+                                                Label::new(message)
+                                                    .size(LabelSize::Small)
+                                                    .color(Color::Muted)
+                                                    .truncate()
+                                            }))
                                         })
-                                    {
-                                        format!("based off {}", current_branch)
-                                    } else {
-                                        "based off the current branch".to_string()
-                                    }
-                                } else {
-                                    let show_author_name = ProjectSettings::get_global(cx)
-                                        .git
-                                        .branch_picker
-                                        .show_author_name;
-
-                                    subject.map_or("no commits found".into(), |subject| {
-                                        if show_author_name && author_name.is_some() {
-                                            format!("{} • {}", author_name.unwrap(), subject)
-                                        } else {
-                                            subject.to_string()
-                                        }
-                                    })
-                                };
-                                Label::new(message)
-                                    .size(LabelSize::Small)
-                                    .truncate()
-                                    .color(Color::Muted)
-                            }))
-                        }),
+                                        .when_some(commit_time, |label, commit_time| {
+                                            label.child(
+                                                Label::new(commit_time)
+                                                    .size(LabelSize::Small)
+                                                    .color(Color::Muted),
+                                            )
+                                        }),
+                                )
+                                .when_some(
+                                    entry.as_branch().map(|b| b.name().to_string()),
+                                    |this, branch_name| this.tooltip(Tooltip::text(branch_name)),
+                                ),
+                        ),
+                )
+                .when(
+                    self.editor_position() == PickerEditorPosition::End && !is_new_items,
+                    |this| {
+                        this.map(|this| {
+                            let is_head_branch =
+                                entry.as_branch().is_some_and(|branch| branch.is_head);
+                            if self.selected_index() == ix {
+                                this.end_slot(deleted_branch_icon(ix, is_head_branch))
+                            } else {
+                                this.end_hover_slot(deleted_branch_icon(ix, is_head_branch))
+                            }
+                        })
+                    },
                 )
-                .end_slot::<IconButton>(icon),
+                .when_some(
+                    if self.editor_position() == PickerEditorPosition::End && is_new_items {
+                        create_from_default_button
+                    } else {
+                        None
+                    },
+                    |this, create_from_default_button| {
+                        this.map(|this| {
+                            if self.selected_index() == ix {
+                                this.end_slot(create_from_default_button)
+                            } else {
+                                this.end_hover_slot(create_from_default_button)
+                            }
+                        })
+                    },
+                ),
         )
     }
 
-    fn render_footer(
+    fn render_header(
         &self,
         _window: &mut Window,
-        cx: &mut Context<Picker<Self>>,
+        _cx: &mut Context<Picker<Self>>,
     ) -> Option<AnyElement> {
+        matches!(self.state, PickerState::List).then(|| {
+            let label = match self.branch_filter {
+                BranchFilter::All => "Branches",
+                BranchFilter::Remote => "Remotes",
+            };
+
+            ListHeader::new(label).inset(true).into_any_element()
+        })
+    }
+
+    fn render_footer(&self, _: &mut Window, cx: &mut Context<Picker<Self>>) -> Option<AnyElement> {
+        if self.editor_position() == PickerEditorPosition::End {
+            return None;
+        }
         let focus_handle = self.focus_handle.clone();
 
-        Some(
+        let footer_container = || {
             h_flex()
                 .w_full()
                 .p_1p5()
-                .gap_0p5()
-                .justify_end()
                 .border_t_1()
                 .border_color(cx.theme().colors().border_variant)
-                .child(
-                    Button::new("delete-branch", "Delete")
-                        .key_binding(
-                            KeyBinding::for_action_in(
-                                &branch_picker::DeleteBranch,
-                                &focus_handle,
-                                cx,
+        };
+
+        match self.state {
+            PickerState::List => {
+                let selected_entry = self.matches.get(self.selected_index);
+
+                let branch_from_default_button = self
+                    .default_branch
+                    .as_ref()
+                    .filter(|_| matches!(selected_entry, Some(Entry::NewBranch { .. })))
+                    .map(|default_branch| {
+                        let button_label = format!("Create New From: {default_branch}");
+
+                        Button::new("branch-from-default", button_label)
+                            .key_binding(
+                                KeyBinding::for_action_in(
+                                    &menu::SecondaryConfirm,
+                                    &focus_handle,
+                                    cx,
+                                )
+                                .map(|kb| kb.size(rems_from_px(12.))),
+                            )
+                            .on_click(cx.listener(|this, _, window, cx| {
+                                this.delegate.confirm(true, window, cx);
+                            }))
+                    });
+
+                let delete_and_select_btns = h_flex()
+                    .gap_1()
+                    .child(
+                        Button::new("delete-branch", "Delete")
+                            .key_binding(
+                                KeyBinding::for_action_in(
+                                    &branch_picker::DeleteBranch,
+                                    &focus_handle,
+                                    cx,
+                                )
+                                .map(|kb| kb.size(rems_from_px(12.))),
+                            )
+                            .on_click(|_, window, cx| {
+                                window
+                                    .dispatch_action(branch_picker::DeleteBranch.boxed_clone(), cx);
+                            }),
+                    )
+                    .child(
+                        Button::new("select_branch", "Select")
+                            .key_binding(
+                                KeyBinding::for_action_in(&menu::Confirm, &focus_handle, cx)
+                                    .map(|kb| kb.size(rems_from_px(12.))),
                             )
-                            .map(|kb| kb.size(rems_from_px(12.))),
+                            .on_click(cx.listener(|this, _, window, cx| {
+                                this.delegate.confirm(false, window, cx);
+                            })),
+                    );
+
+                Some(
+                    footer_container()
+                        .map(|this| {
+                            if branch_from_default_button.is_some() {
+                                this.justify_end().when_some(
+                                    branch_from_default_button,
+                                    |this, button| {
+                                        this.child(button).child(
+                                            Button::new("create", "Create")
+                                                .key_binding(
+                                                    KeyBinding::for_action_in(
+                                                        &menu::Confirm,
+                                                        &focus_handle,
+                                                        cx,
+                                                    )
+                                                    .map(|kb| kb.size(rems_from_px(12.))),
+                                                )
+                                                .on_click(cx.listener(|this, _, window, cx| {
+                                                    this.delegate.confirm(false, window, cx);
+                                                })),
+                                        )
+                                    },
+                                )
+                            } else {
+                                this.justify_between()
+                                    .child({
+                                        let focus_handle = focus_handle.clone();
+                                        Button::new("filter-remotes", "Filter Remotes")
+                                            .toggle_state(matches!(
+                                                self.branch_filter,
+                                                BranchFilter::Remote
+                                            ))
+                                            .key_binding(
+                                                KeyBinding::for_action_in(
+                                                    &branch_picker::FilterRemotes,
+                                                    &focus_handle,
+                                                    cx,
+                                                )
+                                                .map(|kb| kb.size(rems_from_px(12.))),
+                                            )
+                                            .on_click(|_click, window, cx| {
+                                                window.dispatch_action(
+                                                    branch_picker::FilterRemotes.boxed_clone(),
+                                                    cx,
+                                                );
+                                            })
+                                    })
+                                    .child(delete_and_select_btns)
+                            }
+                        })
+                        .into_any_element(),
+                )
+            }
+            PickerState::NewBranch => {
+                let branch_from_default_button =
+                    self.default_branch.as_ref().map(|default_branch| {
+                        let button_label = format!("Create New From: {default_branch}");
+
+                        Button::new("branch-from-default", button_label)
+                            .key_binding(
+                                KeyBinding::for_action_in(
+                                    &menu::SecondaryConfirm,
+                                    &focus_handle,
+                                    cx,
+                                )
+                                .map(|kb| kb.size(rems_from_px(12.))),
+                            )
+                            .on_click(cx.listener(|this, _, window, cx| {
+                                this.delegate.confirm(true, window, cx);
+                            }))
+                    });
+
+                Some(
+                    footer_container()
+                        .gap_1()
+                        .justify_end()
+                        .when_some(branch_from_default_button, |this, button| {
+                            this.child(button)
+                        })
+                        .child(
+                            Button::new("branch-from-default", "Create")
+                                .key_binding(
+                                    KeyBinding::for_action_in(&menu::Confirm, &focus_handle, cx)
+                                        .map(|kb| kb.size(rems_from_px(12.))),
+                                )
+                                .on_click(cx.listener(|this, _, window, cx| {
+                                    this.delegate.confirm(false, window, cx);
+                                })),
                         )
-                        .on_click(|_, window, cx| {
-                            window.dispatch_action(branch_picker::DeleteBranch.boxed_clone(), cx);
-                        }),
+                        .into_any_element(),
                 )
-                .into_any(),
+            }
+            PickerState::CreateRemote(_) => Some(
+                footer_container()
+                    .justify_end()
+                    .child(
+                        Button::new("branch-from-default", "Confirm")
+                            .key_binding(
+                                KeyBinding::for_action_in(&menu::Confirm, &focus_handle, cx)
+                                    .map(|kb| kb.size(rems_from_px(12.))),
+                            )
+                            .on_click(cx.listener(|this, _, window, cx| {
+                                this.delegate.confirm(false, window, cx);
+                            }))
+                            .disabled(self.last_query.is_empty()),
+                    )
+                    .into_any_element(),
+            ),
+            PickerState::NewRemote => None,
+        }
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use std::collections::HashSet;
+
+    use super::*;
+    use git::repository::{CommitSummary, Remote};
+    use gpui::{AppContext, TestAppContext, VisualTestContext};
+    use project::{FakeFs, Project};
+    use rand::{Rng, rngs::StdRng};
+    use serde_json::json;
+    use settings::SettingsStore;
+    use util::path;
+
+    fn init_test(cx: &mut TestAppContext) {
+        cx.update(|cx| {
+            let settings_store = SettingsStore::test(cx);
+            cx.set_global(settings_store);
+            theme::init(theme::LoadThemes::JustBase, cx);
+        });
+    }
+
+    fn create_test_branch(
+        name: &str,
+        is_head: bool,
+        remote_name: Option<&str>,
+        timestamp: Option<i64>,
+    ) -> Branch {
+        let ref_name = match remote_name {
+            Some(remote_name) => format!("refs/remotes/{remote_name}/{name}"),
+            None => format!("refs/heads/{name}"),
+        };
+
+        Branch {
+            is_head,
+            ref_name: ref_name.into(),
+            upstream: None,
+            most_recent_commit: timestamp.map(|ts| CommitSummary {
+                sha: "abc123".into(),
+                commit_timestamp: ts,
+                author_name: "Test Author".into(),
+                subject: "Test commit".into(),
+                has_parent: true,
+            }),
+        }
+    }
+
+    fn create_test_branches() -> Vec<Branch> {
+        vec![
+            create_test_branch("main", true, None, Some(1000)),
+            create_test_branch("feature-auth", false, None, Some(900)),
+            create_test_branch("feature-ui", false, None, Some(800)),
+            create_test_branch("develop", false, None, Some(700)),
+        ]
+    }
+
+    async fn init_branch_list_test(
+        repository: Option<Entity<Repository>>,
+        branches: Vec<Branch>,
+        cx: &mut TestAppContext,
+    ) -> (Entity<BranchList>, VisualTestContext) {
+        let fs = FakeFs::new(cx.executor());
+        let project = Project::test(fs, [], cx).await;
+
+        let workspace = cx.add_window(|window, cx| Workspace::test_new(project, window, cx));
+
+        let branch_list = workspace
+            .update(cx, |workspace, window, cx| {
+                cx.new(|cx| {
+                    let mut delegate = BranchListDelegate::new(
+                        workspace.weak_handle(),
+                        repository,
+                        BranchListStyle::Modal,
+                        cx,
+                    );
+                    delegate.all_branches = Some(branches);
+                    let picker = cx.new(|cx| Picker::uniform_list(delegate, window, cx));
+                    let picker_focus_handle = picker.focus_handle(cx);
+                    picker.update(cx, |picker, _| {
+                        picker.delegate.focus_handle = picker_focus_handle.clone();
+                    });
+
+                    let _subscription = cx.subscribe(&picker, |_, _, _, cx| {
+                        cx.emit(DismissEvent);
+                    });
+
+                    BranchList {
+                        picker,
+                        picker_focus_handle,
+                        width: rems(34.),
+                        _subscription,
+                    }
+                })
+            })
+            .unwrap();
+
+        let cx = VisualTestContext::from_window(*workspace, cx);
+
+        (branch_list, cx)
+    }
+
+    async fn init_fake_repository(cx: &mut TestAppContext) -> Entity<Repository> {
+        let fs = FakeFs::new(cx.executor());
+        fs.insert_tree(
+            path!("/dir"),
+            json!({
+                ".git": {},
+                "file.txt": "buffer_text".to_string()
+            }),
         )
+        .await;
+        fs.set_head_for_repo(
+            path!("/dir/.git").as_ref(),
+            &[("file.txt", "test".to_string())],
+            "deadbeef",
+        );
+        fs.set_index_for_repo(
+            path!("/dir/.git").as_ref(),
+            &[("file.txt", "index_text".to_string())],
+        );
+
+        let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
+        let repository = cx.read(|cx| project.read(cx).active_repository(cx));
+
+        repository.unwrap()
     }
 
-    fn no_matches_text(&self, _window: &mut Window, _cx: &mut App) -> Option<SharedString> {
-        None
+    #[gpui::test]
+    async fn test_update_branch_matches_with_query(cx: &mut TestAppContext) {
+        init_test(cx);
+
+        let branches = create_test_branches();
+        let (branch_list, mut ctx) = init_branch_list_test(None, branches, cx).await;
+        let cx = &mut ctx;
+
+        branch_list
+            .update_in(cx, |branch_list, window, cx| {
+                let query = "feature".to_string();
+                branch_list.picker.update(cx, |picker, cx| {
+                    picker.delegate.update_matches(query, window, cx)
+                })
+            })
+            .await;
+        cx.run_until_parked();
+
+        branch_list.update(cx, |branch_list, cx| {
+            branch_list.picker.update(cx, |picker, _cx| {
+                // Should have 2 existing branches + 1 "create new branch" entry = 3 total
+                assert_eq!(picker.delegate.matches.len(), 3);
+                assert!(
+                    picker
+                        .delegate
+                        .matches
+                        .iter()
+                        .any(|m| m.name() == "feature-auth")
+                );
+                assert!(
+                    picker
+                        .delegate
+                        .matches
+                        .iter()
+                        .any(|m| m.name() == "feature-ui")
+                );
+                // Verify the last entry is the "create new branch" option
+                let last_match = picker.delegate.matches.last().unwrap();
+                assert!(last_match.is_new_branch());
+            })
+        });
+    }
+
+    async fn update_branch_list_matches_with_empty_query(
+        branch_list: &Entity<BranchList>,
+        cx: &mut VisualTestContext,
+    ) {
+        branch_list
+            .update_in(cx, |branch_list, window, cx| {
+                branch_list.picker.update(cx, |picker, cx| {
+                    picker.delegate.update_matches(String::new(), window, cx)
+                })
+            })
+            .await;
+        cx.run_until_parked();
+    }
+
+    #[gpui::test]
+    async fn test_delete_branch(cx: &mut TestAppContext) {
+        init_test(cx);
+        let repository = init_fake_repository(cx).await;
+
+        let branches = create_test_branches();
+
+        let branch_names = branches
+            .iter()
+            .map(|branch| branch.name().to_string())
+            .collect::<Vec<String>>();
+        let repo = repository.clone();
+        cx.spawn(async move |mut cx| {
+            for branch in branch_names {
+                repo.update(&mut cx, |repo, _| repo.create_branch(branch, None))
+                    .unwrap()
+                    .await
+                    .unwrap()
+                    .unwrap();
+            }
+        })
+        .await;
+        cx.run_until_parked();
+
+        let (branch_list, mut ctx) = init_branch_list_test(repository.into(), branches, cx).await;
+        let cx = &mut ctx;
+
+        update_branch_list_matches_with_empty_query(&branch_list, cx).await;
+
+        let branch_to_delete = branch_list.update_in(cx, |branch_list, window, cx| {
+            branch_list.picker.update(cx, |picker, cx| {
+                assert_eq!(picker.delegate.matches.len(), 4);
+                let branch_to_delete = picker.delegate.matches.get(1).unwrap().name().to_string();
+                picker.delegate.delete_at(1, window, cx);
+                branch_to_delete
+            })
+        });
+        cx.run_until_parked();
+
+        branch_list.update(cx, move |branch_list, cx| {
+            branch_list.picker.update(cx, move |picker, _cx| {
+                assert_eq!(picker.delegate.matches.len(), 3);
+                let branches = picker
+                    .delegate
+                    .matches
+                    .iter()
+                    .map(|be| be.name())
+                    .collect::<HashSet<_>>();
+                assert_eq!(
+                    branches,
+                    ["main", "feature-auth", "feature-ui", "develop"]
+                        .into_iter()
+                        .filter(|name| name != &branch_to_delete)
+                        .collect::<HashSet<_>>()
+                );
+            })
+        });
+    }
+
+    #[gpui::test]
+    async fn test_delete_remote(cx: &mut TestAppContext) {
+        init_test(cx);
+        let repository = init_fake_repository(cx).await;
+        let branches = vec![
+            create_test_branch("main", true, Some("origin"), Some(1000)),
+            create_test_branch("feature-auth", false, Some("origin"), Some(900)),
+            create_test_branch("feature-ui", false, Some("fork"), Some(800)),
+            create_test_branch("develop", false, Some("private"), Some(700)),
+        ];
+
+        let remote_names = branches
+            .iter()
+            .filter_map(|branch| branch.remote_name().map(|r| r.to_string()))
+            .collect::<Vec<String>>();
+        let repo = repository.clone();
+        cx.spawn(async move |mut cx| {
+            for branch in remote_names {
+                repo.update(&mut cx, |repo, _| {
+                    repo.create_remote(branch, String::from("test"))
+                })
+                .unwrap()
+                .await
+                .unwrap()
+                .unwrap();
+            }
+        })
+        .await;
+        cx.run_until_parked();
+
+        let (branch_list, mut ctx) = init_branch_list_test(repository.into(), branches, cx).await;
+        let cx = &mut ctx;
+        // Enable remote filter
+        branch_list.update(cx, |branch_list, cx| {
+            branch_list.picker.update(cx, |picker, _cx| {
+                picker.delegate.branch_filter = BranchFilter::Remote;
+            });
+        });
+        update_branch_list_matches_with_empty_query(&branch_list, cx).await;
+
+        // Check matches, it should match all existing branches and no option to create new branch
+        let branch_to_delete = branch_list.update_in(cx, |branch_list, window, cx| {
+            branch_list.picker.update(cx, |picker, cx| {
+                assert_eq!(picker.delegate.matches.len(), 4);
+                let branch_to_delete = picker.delegate.matches.get(1).unwrap().name().to_string();
+                picker.delegate.delete_at(1, window, cx);
+                branch_to_delete
+            })
+        });
+        cx.run_until_parked();
+
+        // Check matches, it should match one less branch than before
+        branch_list.update(cx, move |branch_list, cx| {
+            branch_list.picker.update(cx, move |picker, _cx| {
+                assert_eq!(picker.delegate.matches.len(), 3);
+                let branches = picker
+                    .delegate
+                    .matches
+                    .iter()
+                    .map(|be| be.name())
+                    .collect::<HashSet<_>>();
+                assert_eq!(
+                    branches,
+                    [
+                        "origin/main",
+                        "origin/feature-auth",
+                        "fork/feature-ui",
+                        "private/develop"
+                    ]
+                    .into_iter()
+                    .filter(|name| name != &branch_to_delete)
+                    .collect::<HashSet<_>>()
+                );
+            })
+        });
+    }
+
+    #[gpui::test]
+    async fn test_branch_filter_shows_all_then_remotes_and_applies_query(cx: &mut TestAppContext) {
+        init_test(cx);
+
+        let branches = vec![
+            create_test_branch("main", true, Some("origin"), Some(1000)),
+            create_test_branch("feature-auth", false, Some("fork"), Some(900)),
+            create_test_branch("feature-ui", false, None, Some(800)),
+            create_test_branch("develop", false, None, Some(700)),
+        ];
+
+        let (branch_list, mut ctx) = init_branch_list_test(None, branches, cx).await;
+        let cx = &mut ctx;
+
+        update_branch_list_matches_with_empty_query(&branch_list, cx).await;
+
+        branch_list.update(cx, |branch_list, cx| {
+            branch_list.picker.update(cx, |picker, _cx| {
+                assert_eq!(picker.delegate.matches.len(), 4);
+
+                let branches = picker
+                    .delegate
+                    .matches
+                    .iter()
+                    .map(|be| be.name())
+                    .collect::<HashSet<_>>();
+                assert_eq!(
+                    branches,
+                    ["origin/main", "fork/feature-auth", "feature-ui", "develop"]
+                        .into_iter()
+                        .collect::<HashSet<_>>()
+                );
+
+                // Locals should be listed before remotes.
+                let ordered = picker
+                    .delegate
+                    .matches
+                    .iter()
+                    .map(|be| be.name())
+                    .collect::<Vec<_>>();
+                assert_eq!(
+                    ordered,
+                    vec!["feature-ui", "develop", "origin/main", "fork/feature-auth"]
+                );
+
+                // Verify the last entry is NOT the "create new branch" option
+                let last_match = picker.delegate.matches.last().unwrap();
+                assert!(!last_match.is_new_branch());
+                assert!(!last_match.is_new_url());
+            })
+        });
+
+        branch_list.update(cx, |branch_list, cx| {
+            branch_list.picker.update(cx, |picker, _cx| {
+                picker.delegate.branch_filter = BranchFilter::Remote;
+            })
+        });
+
+        update_branch_list_matches_with_empty_query(&branch_list, cx).await;
+
+        branch_list
+            .update_in(cx, |branch_list, window, cx| {
+                branch_list.picker.update(cx, |picker, cx| {
+                    assert_eq!(picker.delegate.matches.len(), 2);
+                    let branches = picker
+                        .delegate
+                        .matches
+                        .iter()
+                        .map(|be| be.name())
+                        .collect::<HashSet<_>>();
+                    assert_eq!(
+                        branches,
+                        ["origin/main", "fork/feature-auth"]
+                            .into_iter()
+                            .collect::<HashSet<_>>()
+                    );
+
+                    // Verify the last entry is NOT the "create new branch" option
+                    let last_match = picker.delegate.matches.last().unwrap();
+                    assert!(!last_match.is_new_url());
+                    picker.delegate.branch_filter = BranchFilter::Remote;
+                    picker
+                        .delegate
+                        .update_matches(String::from("fork"), window, cx)
+                })
+            })
+            .await;
+        cx.run_until_parked();
+
+        branch_list.update(cx, |branch_list, cx| {
+            branch_list.picker.update(cx, |picker, _cx| {
+                // Should have 1 existing branch + 1 "create new branch" entry = 2 total
+                assert_eq!(picker.delegate.matches.len(), 2);
+                assert!(
+                    picker
+                        .delegate
+                        .matches
+                        .iter()
+                        .any(|m| m.name() == "fork/feature-auth")
+                );
+                // Verify the last entry is the "create new branch" option
+                let last_match = picker.delegate.matches.last().unwrap();
+                assert!(last_match.is_new_branch());
+            })
+        });
+    }
+
+    #[gpui::test]
+    async fn test_new_branch_creation_with_query(test_cx: &mut TestAppContext) {
+        const MAIN_BRANCH: &str = "main";
+        const FEATURE_BRANCH: &str = "feature";
+        const NEW_BRANCH: &str = "new-feature-branch";
+
+        init_test(test_cx);
+        let repository = init_fake_repository(test_cx).await;
+
+        let branches = vec![
+            create_test_branch(MAIN_BRANCH, true, None, Some(1000)),
+            create_test_branch(FEATURE_BRANCH, false, None, Some(900)),
+        ];
+
+        let (branch_list, mut ctx) =
+            init_branch_list_test(repository.into(), branches, test_cx).await;
+        let cx = &mut ctx;
+
+        branch_list
+            .update_in(cx, |branch_list, window, cx| {
+                branch_list.picker.update(cx, |picker, cx| {
+                    picker
+                        .delegate
+                        .update_matches(NEW_BRANCH.to_string(), window, cx)
+                })
+            })
+            .await;
+
+        cx.run_until_parked();
+
+        branch_list.update_in(cx, |branch_list, window, cx| {
+            branch_list.picker.update(cx, |picker, cx| {
+                let last_match = picker.delegate.matches.last().unwrap();
+                assert!(last_match.is_new_branch());
+                assert_eq!(last_match.name(), NEW_BRANCH);
+                // State is NewBranch because no existing branches fuzzy-match the query
+                assert!(matches!(picker.delegate.state, PickerState::NewBranch));
+                picker.delegate.confirm(false, window, cx);
+            })
+        });
+        cx.run_until_parked();
+
+        let branches = branch_list
+            .update(cx, |branch_list, cx| {
+                branch_list.picker.update(cx, |picker, cx| {
+                    picker
+                        .delegate
+                        .repo
+                        .as_ref()
+                        .unwrap()
+                        .update(cx, |repo, _cx| repo.branches())
+                })
+            })
+            .await
+            .unwrap()
+            .unwrap();
+
+        let new_branch = branches
+            .into_iter()
+            .find(|branch| branch.name() == NEW_BRANCH)
+            .expect("new-feature-branch should exist");
+        assert_eq!(
+            new_branch.ref_name.as_ref(),
+            &format!("refs/heads/{NEW_BRANCH}"),
+            "branch ref_name should not have duplicate refs/heads/ prefix"
+        );
+    }
+
+    #[gpui::test]
+    async fn test_remote_url_detection_https(cx: &mut TestAppContext) {
+        init_test(cx);
+        let repository = init_fake_repository(cx).await;
+        let branches = vec![create_test_branch("main", true, None, Some(1000))];
+
+        let (branch_list, mut ctx) = init_branch_list_test(repository.into(), branches, cx).await;
+        let cx = &mut ctx;
+
+        branch_list
+            .update_in(cx, |branch_list, window, cx| {
+                branch_list.picker.update(cx, |picker, cx| {
+                    let query = "https://github.com/user/repo.git".to_string();
+                    picker.delegate.update_matches(query, window, cx)
+                })
+            })
+            .await;
+
+        cx.run_until_parked();
+
+        branch_list
+            .update_in(cx, |branch_list, window, cx| {
+                branch_list.picker.update(cx, |picker, cx| {
+                    let last_match = picker.delegate.matches.last().unwrap();
+                    assert!(last_match.is_new_url());
+                    assert!(matches!(picker.delegate.state, PickerState::NewRemote));
+                    picker.delegate.confirm(false, window, cx);
+                    assert_eq!(picker.delegate.matches.len(), 0);
+                    if let PickerState::CreateRemote(remote_url) = &picker.delegate.state
+                        && remote_url.as_ref() == "https://github.com/user/repo.git"
+                    {
+                    } else {
+                        panic!("wrong picker state");
+                    }
+                    picker
+                        .delegate
+                        .update_matches("my_new_remote".to_string(), window, cx)
+                })
+            })
+            .await;
+
+        cx.run_until_parked();
+
+        branch_list.update_in(cx, |branch_list, window, cx| {
+            branch_list.picker.update(cx, |picker, cx| {
+                assert_eq!(picker.delegate.matches.len(), 1);
+                assert!(matches!(
+                    picker.delegate.matches.first(),
+                    Some(Entry::NewRemoteName { name, url })
+                        if name == "my_new_remote" && url.as_ref() == "https://github.com/user/repo.git"
+                ));
+                picker.delegate.confirm(false, window, cx);
+            })
+        });
+        cx.run_until_parked();
+
+        // List remotes
+        let remotes = branch_list
+            .update(cx, |branch_list, cx| {
+                branch_list.picker.update(cx, |picker, cx| {
+                    picker
+                        .delegate
+                        .repo
+                        .as_ref()
+                        .unwrap()
+                        .update(cx, |repo, _cx| repo.get_remotes(None, false))
+                })
+            })
+            .await
+            .unwrap()
+            .unwrap();
+        assert_eq!(
+            remotes,
+            vec![Remote {
+                name: SharedString::from("my_new_remote".to_string())
+            }]
+        );
+    }
+
+    #[gpui::test]
+    async fn test_confirm_remote_url_transitions(cx: &mut TestAppContext) {
+        init_test(cx);
+
+        let branches = vec![create_test_branch("main_branch", true, None, Some(1000))];
+        let (branch_list, mut ctx) = init_branch_list_test(None, branches, cx).await;
+        let cx = &mut ctx;
+
+        branch_list
+            .update_in(cx, |branch_list, window, cx| {
+                branch_list.picker.update(cx, |picker, cx| {
+                    let query = "https://github.com/user/repo.git".to_string();
+                    picker.delegate.update_matches(query, window, cx)
+                })
+            })
+            .await;
+        cx.run_until_parked();
+
+        // Try to create a new remote but cancel in the middle of the process
+        branch_list
+            .update_in(cx, |branch_list, window, cx| {
+                branch_list.picker.update(cx, |picker, cx| {
+                    picker.delegate.selected_index = picker.delegate.matches.len() - 1;
+                    picker.delegate.confirm(false, window, cx);
+
+                    assert!(matches!(
+                        picker.delegate.state,
+                        PickerState::CreateRemote(_)
+                    ));
+                    if let PickerState::CreateRemote(ref url) = picker.delegate.state {
+                        assert_eq!(url.as_ref(), "https://github.com/user/repo.git");
+                    }
+                    assert_eq!(picker.delegate.matches.len(), 0);
+                    picker.delegate.dismissed(window, cx);
+                    assert!(matches!(picker.delegate.state, PickerState::List));
+                    let query = "main".to_string();
+                    picker.delegate.update_matches(query, window, cx)
+                })
+            })
+            .await;
+        cx.run_until_parked();
+
+        // Try to search a branch again to see if the state is restored properly
+        branch_list.update(cx, |branch_list, cx| {
+            branch_list.picker.update(cx, |picker, _cx| {
+                // Should have 1 existing branch + 1 "create new branch" entry = 2 total
+                assert_eq!(picker.delegate.matches.len(), 2);
+                assert!(
+                    picker
+                        .delegate
+                        .matches
+                        .iter()
+                        .any(|m| m.name() == "main_branch")
+                );
+                // Verify the last entry is the "create new branch" option
+                let last_match = picker.delegate.matches.last().unwrap();
+                assert!(last_match.is_new_branch());
+            })
+        });
+    }
+
+    #[gpui::test]
+    async fn test_confirm_remote_url_does_not_dismiss(cx: &mut TestAppContext) {
+        const REMOTE_URL: &str = "https://github.com/user/repo.git";
+
+        init_test(cx);
+        let branches = vec![create_test_branch("main", true, None, Some(1000))];
+
+        let (branch_list, mut ctx) = init_branch_list_test(None, branches, cx).await;
+        let cx = &mut ctx;
+
+        let subscription = cx.update(|_, cx| {
+            cx.subscribe(&branch_list, |_, _: &DismissEvent, _| {
+                panic!("DismissEvent should not be emitted when confirming a remote URL");
+            })
+        });
+
+        branch_list
+            .update_in(cx, |branch_list, window, cx| {
+                window.focus(&branch_list.picker_focus_handle, cx);
+                assert!(
+                    branch_list.picker_focus_handle.is_focused(window),
+                    "Branch picker should be focused when selecting an entry"
+                );
+
+                branch_list.picker.update(cx, |picker, cx| {
+                    picker
+                        .delegate
+                        .update_matches(REMOTE_URL.to_string(), window, cx)
+                })
+            })
+            .await;
+
+        cx.run_until_parked();
+
+        branch_list.update_in(cx, |branch_list, window, cx| {
+            // Re-focus the picker since workspace initialization during run_until_parked
+            window.focus(&branch_list.picker_focus_handle, cx);
+
+            branch_list.picker.update(cx, |picker, cx| {
+                let last_match = picker.delegate.matches.last().unwrap();
+                assert!(last_match.is_new_url());
+                assert!(matches!(picker.delegate.state, PickerState::NewRemote));
+
+                picker.delegate.confirm(false, window, cx);
+
+                assert!(
+                    matches!(picker.delegate.state, PickerState::CreateRemote(ref url) if url.as_ref() == REMOTE_URL),
+                    "State should transition to CreateRemote with the URL"
+                );
+            });
+
+            assert!(
+                branch_list.picker_focus_handle.is_focused(window),
+                "Branch list picker should still be focused after confirming remote URL"
+            );
+        });
+
+        cx.run_until_parked();
+
+        drop(subscription);
+    }
+
+    #[gpui::test(iterations = 10)]
+    async fn test_empty_query_displays_all_branches(mut rng: StdRng, cx: &mut TestAppContext) {
+        init_test(cx);
+        let branch_count = rng.random_range(13..540);
+
+        let branches: Vec<Branch> = (0..branch_count)
+            .map(|i| create_test_branch(&format!("branch-{:02}", i), i == 0, None, Some(i * 100)))
+            .collect();
+
+        let (branch_list, mut ctx) = init_branch_list_test(None, branches, cx).await;
+        let cx = &mut ctx;
+
+        update_branch_list_matches_with_empty_query(&branch_list, cx).await;
+
+        branch_list.update(cx, |branch_list, cx| {
+            branch_list.picker.update(cx, |picker, _cx| {
+                assert_eq!(picker.delegate.matches.len(), branch_count as usize);
+            })
+        });
     }
 }

crates/git_ui/src/clone.rs 🔗

@@ -0,0 +1,155 @@
+use gpui::{App, Context, WeakEntity, Window};
+use notifications::status_toast::{StatusToast, ToastIcon};
+use std::sync::Arc;
+use ui::{Color, IconName, SharedString};
+use util::ResultExt;
+use workspace::{self, Workspace};
+
+pub fn clone_and_open(
+    repo_url: SharedString,
+    workspace: WeakEntity<Workspace>,
+    window: &mut Window,
+    cx: &mut App,
+    on_success: Arc<
+        dyn Fn(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send + Sync + 'static,
+    >,
+) {
+    let destination_prompt = cx.prompt_for_paths(gpui::PathPromptOptions {
+        files: false,
+        directories: true,
+        multiple: false,
+        prompt: Some("Select as Repository Destination".into()),
+    });
+
+    window
+        .spawn(cx, async move |cx| {
+            let mut paths = destination_prompt.await.ok()?.ok()??;
+            let mut destination_dir = paths.pop()?;
+
+            let repo_name = repo_url
+                .split('/')
+                .next_back()
+                .map(|name| name.strip_suffix(".git").unwrap_or(name))
+                .unwrap_or("repository")
+                .to_owned();
+
+            let clone_task = workspace
+                .update(cx, |workspace, cx| {
+                    let fs = workspace.app_state().fs.clone();
+                    let destination_dir = destination_dir.clone();
+                    let repo_url = repo_url.clone();
+                    cx.spawn(async move |_workspace, _cx| {
+                        fs.git_clone(&repo_url, destination_dir.as_path()).await
+                    })
+                })
+                .ok()?;
+
+            if let Err(error) = clone_task.await {
+                workspace
+                    .update(cx, |workspace, cx| {
+                        let toast = StatusToast::new(error.to_string(), cx, |this, _| {
+                            this.icon(ToastIcon::new(IconName::XCircle).color(Color::Error))
+                                .dismiss_button(true)
+                        });
+                        workspace.toggle_status_toast(toast, cx);
+                    })
+                    .log_err();
+                return None;
+            }
+
+            let has_worktrees = workspace
+                .read_with(cx, |workspace, cx| {
+                    workspace.project().read(cx).worktrees(cx).next().is_some()
+                })
+                .ok()?;
+
+            let prompt_answer = if has_worktrees {
+                cx.update(|window, cx| {
+                    window.prompt(
+                        gpui::PromptLevel::Info,
+                        &format!("Git Clone: {}", repo_name),
+                        None,
+                        &["Add repo to project", "Open repo in new project"],
+                        cx,
+                    )
+                })
+                .ok()?
+                .await
+                .ok()?
+            } else {
+                // Don't ask if project is empty
+                0
+            };
+
+            destination_dir.push(&repo_name);
+
+            match prompt_answer {
+                0 => {
+                    workspace
+                        .update_in(cx, |workspace, window, cx| {
+                            let create_task = workspace.project().update(cx, |project, cx| {
+                                project.create_worktree(destination_dir.as_path(), true, cx)
+                            });
+
+                            let workspace_weak = cx.weak_entity();
+                            let on_success = on_success.clone();
+                            cx.spawn_in(window, async move |_window, cx| {
+                                if create_task.await.log_err().is_some() {
+                                    workspace_weak
+                                        .update_in(cx, |workspace, window, cx| {
+                                            (on_success)(workspace, window, cx);
+                                        })
+                                        .ok();
+                                }
+                            })
+                            .detach();
+                        })
+                        .ok()?;
+                }
+                1 => {
+                    workspace
+                        .update(cx, move |workspace, cx| {
+                            let app_state = workspace.app_state().clone();
+                            let destination_path = destination_dir.clone();
+                            let on_success = on_success.clone();
+
+                            workspace::open_new(
+                                Default::default(),
+                                app_state,
+                                cx,
+                                move |workspace, window, cx| {
+                                    cx.activate(true);
+
+                                    let create_task =
+                                        workspace.project().update(cx, |project, cx| {
+                                            project.create_worktree(
+                                                destination_path.as_path(),
+                                                true,
+                                                cx,
+                                            )
+                                        });
+
+                                    let workspace_weak = cx.weak_entity();
+                                    cx.spawn_in(window, async move |_window, cx| {
+                                        if create_task.await.log_err().is_some() {
+                                            workspace_weak
+                                                .update_in(cx, |workspace, window, cx| {
+                                                    (on_success)(workspace, window, cx);
+                                                })
+                                                .ok();
+                                        }
+                                    })
+                                    .detach();
+                                },
+                            )
+                            .detach();
+                        })
+                        .ok();
+                }
+                _ => {}
+            }
+
+            Some(())
+        })
+        .detach();
+}

crates/git_ui/src/commit_modal.rs 🔗

@@ -139,7 +139,7 @@ impl CommitModal {
                             && !git_panel.amend_pending()
                         {
                             git_panel.set_amend_pending(true, cx);
-                            git_panel.load_last_commit_message_if_empty(cx);
+                            git_panel.load_last_commit_message(cx);
                         }
                     }
                     ForceMode::Commit => {
@@ -337,6 +337,7 @@ impl CommitModal {
             active_repo,
             is_amend_pending,
             is_signoff_enabled,
+            workspace,
         ) = self.git_panel.update(cx, |git_panel, cx| {
             let (can_commit, tooltip) = git_panel.configure_commit_button(cx);
             let title = git_panel.commit_button_title();
@@ -354,6 +355,7 @@ impl CommitModal {
                 active_repo,
                 is_amend_pending,
                 is_signoff_enabled,
+                git_panel.workspace.clone(),
             )
         });
 
@@ -375,7 +377,14 @@ impl CommitModal {
             .style(ButtonStyle::Transparent);
 
         let branch_picker = PopoverMenu::new("popover-button")
-            .menu(move |window, cx| Some(branch_picker::popover(active_repo.clone(), window, cx)))
+            .menu(move |window, cx| {
+                Some(branch_picker::popover(
+                    workspace.clone(),
+                    active_repo.clone(),
+                    window,
+                    cx,
+                ))
+            })
             .with_handle(self.branch_list_handle.clone())
             .trigger_with_tooltip(
                 branch_picker_button,
@@ -492,60 +501,27 @@ impl CommitModal {
         }
     }
 
-    fn commit(&mut self, _: &git::Commit, window: &mut Window, cx: &mut Context<Self>) {
-        if self.git_panel.read(cx).amend_pending() {
-            return;
+    fn on_commit(&mut self, _: &git::Commit, window: &mut Window, cx: &mut Context<Self>) {
+        if self.git_panel.update(cx, |git_panel, cx| {
+            git_panel.commit(&self.commit_editor.focus_handle(cx), window, cx)
+        }) {
+            telemetry::event!("Git Committed", source = "Git Modal");
+            cx.emit(DismissEvent);
         }
-        telemetry::event!("Git Committed", source = "Git Modal");
-        self.git_panel.update(cx, |git_panel, cx| {
-            git_panel.commit_changes(
-                CommitOptions {
-                    amend: false,
-                    signoff: git_panel.signoff_enabled(),
-                },
-                window,
-                cx,
-            )
-        });
-        cx.emit(DismissEvent);
     }
 
-    fn amend(&mut self, _: &git::Amend, window: &mut Window, cx: &mut Context<Self>) {
-        if self
-            .git_panel
-            .read(cx)
-            .active_repository
-            .as_ref()
-            .and_then(|repo| repo.read(cx).head_commit.as_ref())
-            .is_none()
-        {
-            return;
-        }
-        if !self.git_panel.read(cx).amend_pending() {
-            self.git_panel.update(cx, |git_panel, cx| {
-                git_panel.set_amend_pending(true, cx);
-                git_panel.load_last_commit_message_if_empty(cx);
-            });
-        } else {
+    fn on_amend(&mut self, _: &git::Amend, window: &mut Window, cx: &mut Context<Self>) {
+        if self.git_panel.update(cx, |git_panel, cx| {
+            git_panel.amend(&self.commit_editor.focus_handle(cx), window, cx)
+        }) {
             telemetry::event!("Git Amended", source = "Git Modal");
-            self.git_panel.update(cx, |git_panel, cx| {
-                git_panel.set_amend_pending(false, cx);
-                git_panel.commit_changes(
-                    CommitOptions {
-                        amend: true,
-                        signoff: git_panel.signoff_enabled(),
-                    },
-                    window,
-                    cx,
-                );
-            });
             cx.emit(DismissEvent);
         }
     }
 
     fn toggle_branch_selector(&mut self, window: &mut Window, cx: &mut Context<Self>) {
         if self.branch_list_handle.is_focused(window, cx) {
-            self.focus_handle(cx).focus(window)
+            self.focus_handle(cx).focus(window, cx)
         } else {
             self.branch_list_handle.toggle(window, cx);
         }
@@ -564,8 +540,8 @@ impl Render for CommitModal {
             .id("commit-modal")
             .key_context("GitCommit")
             .on_action(cx.listener(Self::dismiss))
-            .on_action(cx.listener(Self::commit))
-            .on_action(cx.listener(Self::amend))
+            .on_action(cx.listener(Self::on_commit))
+            .on_action(cx.listener(Self::on_amend))
             .when(!DisableAiSettings::get_global(cx).disable_ai, |this| {
                 this.on_action(cx.listener(|this, _: &GenerateCommitMessage, _, cx| {
                     this.git_panel.update(cx, |panel, cx| {
@@ -611,8 +587,8 @@ impl Render for CommitModal {
                     .bg(cx.theme().colors().editor_background)
                     .border_1()
                     .border_color(cx.theme().colors().border_variant)
-                    .on_click(cx.listener(move |_, _: &ClickEvent, window, _cx| {
-                        window.focus(&editor_focus_handle);
+                    .on_click(cx.listener(move |_, _: &ClickEvent, window, cx| {
+                        window.focus(&editor_focus_handle, cx);
                     }))
                     .child(
                         div()

crates/git_ui/src/commit_tooltip.rs 🔗

@@ -3,7 +3,7 @@ use editor::hover_markdown_style;
 use futures::Future;
 use git::blame::BlameEntry;
 use git::repository::CommitSummary;
-use git::{GitRemote, blame::ParsedCommitMessage};
+use git::{GitRemote, commit::ParsedCommitMessage};
 use gpui::{
     App, Asset, ClipboardItem, Element, Entity, MouseButton, ParentElement, Render, ScrollHandle,
     StatefulInteractiveElement, WeakEntity, prelude::*,
@@ -29,11 +29,16 @@ pub struct CommitDetails {
 pub struct CommitAvatar<'a> {
     sha: &'a SharedString,
     remote: Option<&'a GitRemote>,
+    size: Option<IconSize>,
 }
 
 impl<'a> CommitAvatar<'a> {
     pub fn new(sha: &'a SharedString, remote: Option<&'a GitRemote>) -> Self {
-        Self { sha, remote }
+        Self {
+            sha,
+            remote,
+            size: None,
+        }
     }
 
     pub fn from_commit_details(details: &'a CommitDetails) -> Self {
@@ -43,28 +48,37 @@ impl<'a> CommitAvatar<'a> {
                 .message
                 .as_ref()
                 .and_then(|details| details.remote.as_ref()),
+            size: None,
         }
     }
-}
 
-impl<'a> CommitAvatar<'a> {
-    pub fn render(&'a self, window: &mut Window, cx: &mut App) -> Option<impl IntoElement + use<>> {
+    pub fn size(mut self, size: IconSize) -> Self {
+        self.size = Some(size);
+        self
+    }
+
+    pub fn render(&'a self, window: &mut Window, cx: &mut App) -> AnyElement {
+        match self.avatar(window, cx) {
+            // Loading or no avatar found
+            None => Icon::new(IconName::Person)
+                .color(Color::Muted)
+                .when_some(self.size, |this, size| this.size(size))
+                .into_any_element(),
+            // Found
+            Some(avatar) => avatar
+                .when_some(self.size, |this, size| this.size(size.rems()))
+                .into_any_element(),
+        }
+    }
+
+    pub fn avatar(&'a self, window: &mut Window, cx: &mut App) -> Option<Avatar> {
         let remote = self
             .remote
             .filter(|remote| remote.host_supports_avatars())?;
-
         let avatar_url = CommitAvatarAsset::new(remote.clone(), self.sha.clone());
 
-        let element = match window.use_asset::<CommitAvatarAsset>(&avatar_url, cx) {
-            // Loading or no avatar found
-            None | Some(None) => Icon::new(IconName::Person)
-                .color(Color::Muted)
-                .into_element()
-                .into_any(),
-            // Found
-            Some(Some(url)) => Avatar::new(url.to_string()).into_element().into_any(),
-        };
-        Some(element)
+        let url = window.use_asset::<CommitAvatarAsset>(&avatar_url, cx)??;
+        Some(Avatar::new(url.to_string()))
     }
 }
 
@@ -197,10 +211,7 @@ impl Render for CommitTooltip {
             time_format::TimestampFormat::MediumAbsolute,
         );
         let markdown_style = {
-            let mut style = hover_markdown_style(window, cx);
-            if let Some(code_block) = &style.code_block.text {
-                style.base_text_style.refine(code_block);
-            }
+            let style = hover_markdown_style(window, cx);
             style
         };
 
@@ -256,7 +267,7 @@ impl Render for CommitTooltip {
                                 .gap_x_2()
                                 .overflow_x_hidden()
                                 .flex_wrap()
-                                .children(avatar)
+                                .child(avatar)
                                 .child(author)
                                 .when(!author_email.is_empty(), |this| {
                                     this.child(

crates/git_ui/src/commit_view.rs 🔗

@@ -1,20 +1,21 @@
 use anyhow::{Context as _, Result};
 use buffer_diff::BufferDiff;
-use editor::{Addon, Editor, EditorEvent, MultiBuffer};
+use editor::display_map::{BlockPlacement, BlockProperties, BlockStyle};
+use editor::{Editor, EditorEvent, ExcerptRange, MultiBuffer, multibuffer_context_lines};
 use git::repository::{CommitDetails, CommitDiff, RepoPath};
-use git::{GitHostingProviderRegistry, GitRemote, parse_git_remote_url};
+use git::{
+    BuildCommitPermalinkParams, GitHostingProviderRegistry, GitRemote, ParsedGitRemote,
+    parse_git_remote_url,
+};
 use gpui::{
-    AnyElement, App, AppContext as _, Asset, AsyncApp, AsyncWindowContext, Context, Element,
-    Entity, EventEmitter, FocusHandle, Focusable, InteractiveElement, IntoElement, ParentElement,
-    PromptLevel, Render, Styled, Task, TextStyleRefinement, UnderlineStyle, WeakEntity, Window,
-    actions, px,
+    AnyElement, App, AppContext as _, AsyncApp, AsyncWindowContext, ClipboardItem, Context,
+    Element, Entity, EventEmitter, FocusHandle, Focusable, InteractiveElement, IntoElement,
+    ParentElement, PromptLevel, Render, Styled, Task, WeakEntity, Window, actions,
 };
 use language::{
-    Buffer, Capability, DiskState, File, LanguageRegistry, LineEnding, ReplicaId, Rope, TextBuffer,
-    ToPoint,
+    Anchor, Buffer, Capability, DiskState, File, LanguageRegistry, LineEnding, OffsetRangeExt as _,
+    Point, ReplicaId, Rope, TextBuffer,
 };
-use markdown::{Markdown, MarkdownElement, MarkdownStyle};
-use multi_buffer::ExcerptInfo;
 use multi_buffer::PathKey;
 use project::{Project, WorktreeId, git_store::Repository};
 use std::{
@@ -23,11 +24,9 @@ use std::{
     sync::Arc,
 };
 use theme::ActiveTheme;
-use ui::{
-    Avatar, Button, ButtonCommon, Clickable, Color, Icon, IconName, IconSize, Label,
-    LabelCommon as _, LabelSize, SharedString, div, h_flex, v_flex,
-};
+use ui::{ButtonLike, DiffStat, Tooltip, prelude::*};
 use util::{ResultExt, paths::PathStyle, rel_path::RelPath, truncate_and_trailoff};
+use workspace::item::TabTooltipContent;
 use workspace::{
     Item, ItemHandle, ItemNavHistory, ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView,
     Workspace,
@@ -37,6 +36,7 @@ use workspace::{
     searchable::SearchableItemHandle,
 };
 
+use crate::commit_tooltip::CommitAvatar;
 use crate::git_panel::GitPanel;
 
 actions!(git, [ApplyCurrentStash, PopCurrentStash, DropCurrentStash,]);
@@ -63,15 +63,16 @@ pub struct CommitView {
     multibuffer: Entity<MultiBuffer>,
     repository: Entity<Repository>,
     remote: Option<GitRemote>,
-    markdown: Entity<Markdown>,
 }
 
 struct GitBlob {
     path: RepoPath,
     worktree_id: WorktreeId,
     is_deleted: bool,
+    display_name: String,
 }
 
+const COMMIT_MESSAGE_SORT_PREFIX: u64 = 0;
 const FILE_NAMESPACE_SORT_PREFIX: u64 = 1;
 
 impl CommitView {
@@ -149,17 +150,73 @@ impl CommitView {
     ) -> Self {
         let language_registry = project.read(cx).languages().clone();
         let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadOnly));
+
+        let message_buffer = cx.new(|cx| {
+            let mut buffer = Buffer::local(commit.message.clone(), cx);
+            buffer.set_capability(Capability::ReadOnly, cx);
+            buffer
+        });
+
+        multibuffer.update(cx, |multibuffer, cx| {
+            let snapshot = message_buffer.read(cx).snapshot();
+            let full_range = Point::zero()..snapshot.max_point();
+            let range = ExcerptRange {
+                context: full_range.clone(),
+                primary: full_range,
+            };
+            multibuffer.set_excerpt_ranges_for_path(
+                PathKey::with_sort_prefix(
+                    COMMIT_MESSAGE_SORT_PREFIX,
+                    RelPath::unix("commit message").unwrap().into(),
+                ),
+                message_buffer.clone(),
+                &snapshot,
+                vec![range],
+                cx,
+            )
+        });
+
         let editor = cx.new(|cx| {
             let mut editor =
                 Editor::for_multibuffer(multibuffer.clone(), Some(project.clone()), window, cx);
+
             editor.disable_inline_diagnostics();
+            editor.set_show_breakpoints(false, cx);
             editor.set_expand_all_diff_hunks(cx);
-            editor.register_addon(CommitViewAddon {
-                multibuffer: multibuffer.downgrade(),
-            });
+            editor.disable_header_for_buffer(message_buffer.read(cx).remote_id(), cx);
+            editor.disable_indent_guides_for_buffer(message_buffer.read(cx).remote_id(), cx);
+
+            editor.insert_blocks(
+                [BlockProperties {
+                    placement: BlockPlacement::Above(editor::Anchor::min()),
+                    height: Some(1),
+                    style: BlockStyle::Sticky,
+                    render: Arc::new(|_| gpui::Empty.into_any_element()),
+                    priority: 0,
+                }]
+                .into_iter()
+                .chain(
+                    editor
+                        .buffer()
+                        .read(cx)
+                        .buffer_anchor_to_anchor(&message_buffer, Anchor::MAX, cx)
+                        .map(|anchor| BlockProperties {
+                            placement: BlockPlacement::Below(anchor),
+                            height: Some(1),
+                            style: BlockStyle::Sticky,
+                            render: Arc::new(|_| gpui::Empty.into_any_element()),
+                            priority: 0,
+                        }),
+                ),
+                None,
+                cx,
+            );
+
             editor
         });
 
+        let commit_sha = Arc::<str>::from(commit.sha.as_ref());
+
         let first_worktree_id = project
             .read(cx)
             .worktrees(cx)
@@ -167,6 +224,7 @@ impl CommitView {
             .map(|worktree| worktree.read(cx).id());
 
         let repository_clone = repository.clone();
+
         cx.spawn(async move |this, cx| {
             for file in commit_diff.files {
                 let is_deleted = file.new_text.is_none();
@@ -180,10 +238,19 @@ impl CommitView {
                             .or(first_worktree_id)
                     })?
                     .context("project has no worktrees")?;
+                let short_sha = commit_sha.get(0..7).unwrap_or(&commit_sha);
+                let file_name = file
+                    .path
+                    .file_name()
+                    .map(|name| name.to_string())
+                    .unwrap_or_else(|| file.path.display(PathStyle::local()).to_string());
+                let display_name = format!("{short_sha} - {file_name}");
+
                 let file = Arc::new(GitBlob {
                     path: file.path.clone(),
                     is_deleted,
                     worktree_id,
+                    display_name,
                 }) as Arc<dyn language::File>;
 
                 let buffer = build_buffer(new_text, file, &language_registry, cx).await?;
@@ -194,40 +261,30 @@ impl CommitView {
                     this.multibuffer.update(cx, |multibuffer, cx| {
                         let snapshot = buffer.read(cx).snapshot();
                         let path = snapshot.file().unwrap().path().clone();
-
-                        let hunks: Vec<_> =
-                            buffer_diff.read(cx).snapshot(cx).hunks(&snapshot).collect();
-
-                        let excerpt_ranges = if hunks.is_empty() {
-                            vec![language::Point::zero()..snapshot.max_point()]
-                        } else {
-                            hunks
-                                .into_iter()
-                                .map(|hunk| {
-                                    let start = hunk.range.start.max(language::Point::new(
-                                        hunk.range.start.row.saturating_sub(3),
-                                        0,
-                                    ));
-                                    let end_row =
-                                        (hunk.range.end.row + 3).min(snapshot.max_point().row);
-                                    let end =
-                                        language::Point::new(end_row, snapshot.line_len(end_row));
-                                    start..end
-                                })
-                                .collect()
+                        let excerpt_ranges = {
+                            let diff_snapshot = buffer_diff.read(cx).snapshot(cx);
+                            let mut hunks = diff_snapshot.hunks(&snapshot).peekable();
+                            if hunks.peek().is_none() {
+                                vec![language::Point::zero()..snapshot.max_point()]
+                            } else {
+                                hunks
+                                    .map(|hunk| hunk.buffer_range.to_point(&snapshot))
+                                    .collect::<Vec<_>>()
+                            }
                         };
 
                         let _is_newly_added = multibuffer.set_excerpts_for_path(
                             PathKey::with_sort_prefix(FILE_NAMESPACE_SORT_PREFIX, path),
                             buffer,
                             excerpt_ranges,
-                            0,
+                            multibuffer_context_lines(cx),
                             cx,
                         );
                         multibuffer.add_diff(buffer_diff, cx);
                     });
                 })?;
             }
+
             anyhow::Ok(())
         })
         .detach();
@@ -247,14 +304,6 @@ impl CommitView {
             })
         });
 
-        let processed_message = if let Some(ref remote) = remote {
-            Self::process_github_issues(&commit.message, remote)
-        } else {
-            commit.message.to_string()
-        };
-
-        let markdown = cx.new(|cx| Markdown::new(processed_message.into(), None, None, cx));
-
         Self {
             commit,
             editor,
@@ -262,18 +311,9 @@ impl CommitView {
             stash,
             repository,
             remote,
-            markdown,
         }
     }
 
-    fn fallback_commit_avatar() -> AnyElement {
-        Icon::new(IconName::Person)
-            .color(Color::Muted)
-            .size(IconSize::Medium)
-            .into_element()
-            .into_any()
-    }
-
     fn render_commit_avatar(
         &self,
         sha: &SharedString,
@@ -281,26 +321,70 @@ impl CommitView {
         window: &mut Window,
         cx: &mut App,
     ) -> AnyElement {
-        let remote = self.remote.as_ref().filter(|r| r.host_supports_avatars());
-
-        if let Some(remote) = remote {
-            let avatar_asset = CommitAvatarAsset::new(remote.clone(), sha.clone());
-            if let Some(Some(url)) = window.use_asset::<CommitAvatarAsset>(&avatar_asset, cx) {
-                Avatar::new(url.to_string())
-                    .size(size)
-                    .into_element()
-                    .into_any()
-            } else {
-                Self::fallback_commit_avatar()
+        let size = size.into();
+        let avatar = CommitAvatar::new(sha, self.remote.as_ref());
+
+        v_flex()
+            .w(size)
+            .h(size)
+            .border_1()
+            .border_color(cx.theme().colors().border)
+            .rounded_full()
+            .justify_center()
+            .items_center()
+            .child(
+                avatar
+                    .avatar(window, cx)
+                    .map(|a| a.size(size).into_any_element())
+                    .unwrap_or_else(|| {
+                        Icon::new(IconName::Person)
+                            .color(Color::Muted)
+                            .size(IconSize::Medium)
+                            .into_any_element()
+                    }),
+            )
+            .into_any()
+    }
+
+    fn calculate_changed_lines(&self, cx: &App) -> (u32, u32) {
+        let snapshot = self.multibuffer.read(cx).snapshot(cx);
+        let mut total_additions = 0u32;
+        let mut total_deletions = 0u32;
+
+        let mut seen_buffers = std::collections::HashSet::new();
+        for (_, buffer, _) in snapshot.excerpts() {
+            let buffer_id = buffer.remote_id();
+            if !seen_buffers.insert(buffer_id) {
+                continue;
+            }
+
+            let Some(diff) = snapshot.diff_for_buffer_id(buffer_id) else {
+                continue;
+            };
+
+            let base_text = diff.base_text();
+
+            for hunk in diff.hunks_intersecting_range(Anchor::MIN..Anchor::MAX, buffer) {
+                let added_rows = hunk.range.end.row.saturating_sub(hunk.range.start.row);
+                total_additions += added_rows;
+
+                let base_start = base_text
+                    .offset_to_point(hunk.diff_base_byte_range.start)
+                    .row;
+                let base_end = base_text.offset_to_point(hunk.diff_base_byte_range.end).row;
+                let deleted_rows = base_end.saturating_sub(base_start);
+
+                total_deletions += deleted_rows;
             }
-        } else {
-            Self::fallback_commit_avatar()
         }
+
+        (total_additions, total_deletions)
     }
 
     fn render_header(&self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
         let commit = &self.commit;
         let author_name = commit.author_name.clone();
+        let commit_sha = commit.sha.clone();
         let commit_date = time::OffsetDateTime::from_unix_timestamp(commit.commit_timestamp)
             .unwrap_or_else(|_| time::OffsetDateTime::now_utc());
         let local_offset = time::UtcOffset::current_local_offset().unwrap_or(time::UtcOffset::UTC);
@@ -311,109 +395,152 @@ impl CommitView {
             time_format::TimestampFormat::MediumAbsolute,
         );
 
-        let github_url = self.remote.as_ref().map(|remote| {
-            format!(
-                "{}/{}/{}/commit/{}",
-                remote.host.base_url(),
-                remote.owner,
-                remote.repo,
-                commit.sha
-            )
+        let remote_info = self.remote.as_ref().map(|remote| {
+            let provider = remote.host.name();
+            let parsed_remote = ParsedGitRemote {
+                owner: remote.owner.as_ref().into(),
+                repo: remote.repo.as_ref().into(),
+            };
+            let params = BuildCommitPermalinkParams { sha: &commit.sha };
+            let url = remote
+                .host
+                .build_commit_permalink(&parsed_remote, params)
+                .to_string();
+            (provider, url)
         });
 
-        v_flex()
-            .p_4()
-            .gap_4()
+        let (additions, deletions) = self.calculate_changed_lines(cx);
+
+        let commit_diff_stat = if additions > 0 || deletions > 0 {
+            Some(DiffStat::new(
+                "commit-diff-stat",
+                additions as usize,
+                deletions as usize,
+            ))
+        } else {
+            None
+        };
+
+        let gutter_width = self.editor.update(cx, |editor, cx| {
+            let snapshot = editor.snapshot(window, cx);
+            let style = editor.style(cx);
+            let font_id = window.text_system().resolve_font(&style.text.font());
+            let font_size = style.text.font_size.to_pixels(window.rem_size());
+            snapshot
+                .gutter_dimensions(font_id, font_size, style, window, cx)
+                .full_width()
+        });
+
+        let clipboard_has_link = cx
+            .read_from_clipboard()
+            .and_then(|entry| entry.text())
+            .map_or(false, |clipboard_text| {
+                clipboard_text.trim() == commit_sha.as_ref()
+            });
+
+        let (copy_icon, copy_icon_color) = if clipboard_has_link {
+            (IconName::Check, Color::Success)
+        } else {
+            (IconName::Copy, Color::Muted)
+        };
+
+        h_flex()
             .border_b_1()
-            .border_color(cx.theme().colors().border)
+            .border_color(cx.theme().colors().border_variant)
+            .w_full()
             .child(
                 h_flex()
+                    .w(gutter_width)
+                    .justify_center()
+                    .child(self.render_commit_avatar(&commit.sha, rems_from_px(48.), window, cx)),
+            )
+            .child(
+                h_flex()
+                    .py_4()
+                    .pl_1()
+                    .pr_4()
+                    .w_full()
                     .items_start()
-                    .gap_3()
-                    .child(self.render_commit_avatar(&commit.sha, gpui::rems(3.0), window, cx))
+                    .justify_between()
+                    .flex_wrap()
                     .child(
                         v_flex()
-                            .gap_1()
                             .child(
                                 h_flex()
-                                    .gap_3()
-                                    .items_baseline()
+                                    .gap_1()
                                     .child(Label::new(author_name).color(Color::Default))
-                                    .child(
-                                        Label::new(format!("commit {}", commit.sha))
-                                            .color(Color::Muted),
-                                    ),
+                                    .child({
+                                        ButtonLike::new("sha")
+                                            .child(
+                                                h_flex()
+                                                    .group("sha_btn")
+                                                    .size_full()
+                                                    .max_w_32()
+                                                    .gap_0p5()
+                                                    .child(
+                                                        Label::new(commit_sha.clone())
+                                                            .color(Color::Muted)
+                                                            .size(LabelSize::Small)
+                                                            .truncate()
+                                                            .buffer_font(cx),
+                                                    )
+                                                    .child(
+                                                        div().visible_on_hover("sha_btn").child(
+                                                            Icon::new(copy_icon)
+                                                                .color(copy_icon_color)
+                                                                .size(IconSize::Small),
+                                                        ),
+                                                    ),
+                                            )
+                                            .tooltip({
+                                                let commit_sha = commit_sha.clone();
+                                                move |_, cx| {
+                                                    Tooltip::with_meta(
+                                                        "Copy Commit SHA",
+                                                        None,
+                                                        commit_sha.clone(),
+                                                        cx,
+                                                    )
+                                                }
+                                            })
+                                            .on_click(move |_, _, cx| {
+                                                cx.stop_propagation();
+                                                cx.write_to_clipboard(ClipboardItem::new_string(
+                                                    commit_sha.to_string(),
+                                                ));
+                                            })
+                                    }),
                             )
-                            .child(Label::new(date_string).color(Color::Muted)),
+                            .child(
+                                h_flex()
+                                    .gap_1p5()
+                                    .child(
+                                        Label::new(date_string)
+                                            .color(Color::Muted)
+                                            .size(LabelSize::Small),
+                                    )
+                                    .child(
+                                        Label::new("•")
+                                            .color(Color::Ignored)
+                                            .size(LabelSize::Small),
+                                    )
+                                    .children(commit_diff_stat),
+                            ),
                     )
-                    .child(div().flex_grow())
-                    .children(github_url.map(|url| {
-                        Button::new("view_on_github", "View on GitHub")
-                            .icon(IconName::Github)
-                            .style(ui::ButtonStyle::Subtle)
+                    .children(remote_info.map(|(provider_name, url)| {
+                        let icon = match provider_name.as_str() {
+                            "GitHub" => IconName::Github,
+                            _ => IconName::Link,
+                        };
+
+                        Button::new("view_on_provider", format!("View on {}", provider_name))
+                            .icon(icon)
+                            .icon_color(Color::Muted)
+                            .icon_size(IconSize::Small)
+                            .icon_position(IconPosition::Start)
                             .on_click(move |_, _, cx| cx.open_url(&url))
                     })),
             )
-            .child(self.render_commit_message(window, cx))
-    }
-
-    fn process_github_issues(message: &str, remote: &GitRemote) -> String {
-        let mut result = String::new();
-        let chars: Vec<char> = message.chars().collect();
-        let mut i = 0;
-
-        while i < chars.len() {
-            if chars[i] == '#' && i + 1 < chars.len() && chars[i + 1].is_ascii_digit() {
-                let mut j = i + 1;
-                while j < chars.len() && chars[j].is_ascii_digit() {
-                    j += 1;
-                }
-                let issue_number = &message[i + 1..i + (j - i)];
-                let url = format!(
-                    "{}/{}/{}/issues/{}",
-                    remote.host.base_url().as_str().trim_end_matches('/'),
-                    remote.owner,
-                    remote.repo,
-                    issue_number
-                );
-                result.push_str(&format!("[#{}]({})", issue_number, url));
-                i = j;
-            } else if i + 3 < chars.len()
-                && chars[i] == 'G'
-                && chars[i + 1] == 'H'
-                && chars[i + 2] == '-'
-                && chars[i + 3].is_ascii_digit()
-            {
-                let mut j = i + 3;
-                while j < chars.len() && chars[j].is_ascii_digit() {
-                    j += 1;
-                }
-                let issue_number = &message[i + 3..i + (j - i)];
-                let url = format!(
-                    "{}/{}/{}/issues/{}",
-                    remote.host.base_url().as_str().trim_end_matches('/'),
-                    remote.owner,
-                    remote.repo,
-                    issue_number
-                );
-                result.push_str(&format!("[GH-{}]({})", issue_number, url));
-                i = j;
-            } else {
-                result.push(chars[i]);
-                i += 1;
-            }
-        }
-
-        result
-    }
-
-    fn render_commit_message(
-        &self,
-        window: &mut Window,
-        cx: &mut Context<Self>,
-    ) -> impl IntoElement {
-        let style = hover_markdown_style(window, cx);
-        MarkdownElement::new(self.markdown.clone(), style)
     }
 
     fn apply_stash(workspace: &mut Workspace, window: &mut Window, cx: &mut App) {
@@ -576,69 +703,19 @@ impl CommitView {
     }
 }
 
-#[derive(Clone, Debug)]
-struct CommitAvatarAsset {
-    sha: SharedString,
-    remote: GitRemote,
-}
-
-impl std::hash::Hash for CommitAvatarAsset {
-    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
-        self.sha.hash(state);
-        self.remote.host.name().hash(state);
-    }
-}
-
-impl CommitAvatarAsset {
-    fn new(remote: GitRemote, sha: SharedString) -> Self {
-        Self { remote, sha }
-    }
-}
-
-impl Asset for CommitAvatarAsset {
-    type Source = Self;
-    type Output = Option<SharedString>;
-
-    fn load(
-        source: Self::Source,
-        cx: &mut App,
-    ) -> impl Future<Output = Self::Output> + Send + 'static {
-        let client = cx.http_client();
-        async move {
-            match source
-                .remote
-                .host
-                .commit_author_avatar_url(
-                    &source.remote.owner,
-                    &source.remote.repo,
-                    source.sha.clone(),
-                    client,
-                )
-                .await
-            {
-                Ok(Some(url)) => Some(SharedString::from(url.to_string())),
-                Ok(None) => None,
-                Err(_) => None,
-            }
-        }
-    }
-}
-
 impl language::File for GitBlob {
     fn as_local(&self) -> Option<&dyn language::LocalFile> {
         None
     }
 
     fn disk_state(&self) -> DiskState {
-        if self.is_deleted {
-            DiskState::Deleted
-        } else {
-            DiskState::New
+        DiskState::Historic {
+            was_deleted: self.is_deleted,
         }
     }
 
     fn path_style(&self, _: &App) -> PathStyle {
-        PathStyle::Posix
+        PathStyle::local()
     }
 
     fn path(&self) -> &Arc<RelPath> {
@@ -650,7 +727,7 @@ impl language::File for GitBlob {
     }
 
     fn file_name<'a>(&'a self, _: &'a App) -> &'a str {
-        self.path.file_name().unwrap()
+        self.display_name.as_ref()
     }
 
     fn worktree_id(&self, _: &App) -> WorktreeId {
@@ -666,94 +743,6 @@ impl language::File for GitBlob {
     }
 }
 
-// No longer needed since metadata buffer is not created
-// impl language::File for CommitMetadataFile {
-//     fn as_local(&self) -> Option<&dyn language::LocalFile> {
-//         None
-//     }
-//
-//     fn disk_state(&self) -> DiskState {
-//         DiskState::New
-//     }
-//
-//     fn path_style(&self, _: &App) -> PathStyle {
-//         PathStyle::Posix
-//     }
-//
-//     fn path(&self) -> &Arc<RelPath> {
-//         &self.title
-//     }
-//
-//     fn full_path(&self, _: &App) -> PathBuf {
-//         self.title.as_std_path().to_path_buf()
-//     }
-//
-//     fn file_name<'a>(&'a self, _: &'a App) -> &'a str {
-//         self.title.file_name().unwrap_or("commit")
-//     }
-//
-//     fn worktree_id(&self, _: &App) -> WorktreeId {
-//         self.worktree_id
-//     }
-//
-//     fn to_proto(&self, _cx: &App) -> language::proto::File {
-//         unimplemented!()
-//     }
-//
-//     fn is_private(&self) -> bool {
-//         false
-//     }
-// }
-
-struct CommitViewAddon {
-    multibuffer: WeakEntity<MultiBuffer>,
-}
-
-impl Addon for CommitViewAddon {
-    fn render_buffer_header_controls(
-        &self,
-        excerpt: &ExcerptInfo,
-        _window: &Window,
-        cx: &App,
-    ) -> Option<AnyElement> {
-        let multibuffer = self.multibuffer.upgrade()?;
-        let snapshot = multibuffer.read(cx).snapshot(cx);
-        let excerpts = snapshot.excerpts().collect::<Vec<_>>();
-        let current_idx = excerpts.iter().position(|(id, _, _)| *id == excerpt.id)?;
-        let (_, _, current_range) = &excerpts[current_idx];
-
-        let start_row = current_range.context.start.to_point(&excerpt.buffer).row;
-
-        let prev_end_row = if current_idx > 0 {
-            let (_, prev_buffer, prev_range) = &excerpts[current_idx - 1];
-            if prev_buffer.remote_id() == excerpt.buffer_id {
-                prev_range.context.end.to_point(&excerpt.buffer).row
-            } else {
-                0
-            }
-        } else {
-            0
-        };
-
-        let skipped_lines = start_row.saturating_sub(prev_end_row);
-
-        if skipped_lines > 0 {
-            Some(
-                Label::new(format!("{} unchanged lines", skipped_lines))
-                    .color(Color::Muted)
-                    .size(LabelSize::Small)
-                    .into_any_element(),
-            )
-        } else {
-            None
-        }
-    }
-
-    fn to_any(&self) -> &dyn Any {
-        self
-    }
-}
-
 async fn build_buffer(
     mut text: String,
     blob: Arc<dyn File>,
@@ -851,13 +840,28 @@ impl Item for CommitView {
     fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
         let short_sha = self.commit.sha.get(0..7).unwrap_or(&*self.commit.sha);
         let subject = truncate_and_trailoff(self.commit.message.split('\n').next().unwrap(), 20);
-        format!("{short_sha} - {subject}").into()
+        format!("{short_sha} — {subject}").into()
     }
 
-    fn tab_tooltip_text(&self, _: &App) -> Option<ui::SharedString> {
+    fn tab_tooltip_content(&self, _: &App) -> Option<TabTooltipContent> {
         let short_sha = self.commit.sha.get(0..16).unwrap_or(&*self.commit.sha);
         let subject = self.commit.message.split('\n').next().unwrap();
-        Some(format!("{short_sha} - {subject}").into())
+
+        Some(TabTooltipContent::Custom(Box::new(Tooltip::element({
+            let subject = subject.to_string();
+            let short_sha = short_sha.to_string();
+
+            move |_, _| {
+                v_flex()
+                    .child(Label::new(subject.clone()))
+                    .child(
+                        Label::new(short_sha.clone())
+                            .color(Color::Muted)
+                            .size(LabelSize::Small),
+                    )
+                    .into_any_element()
+            }
+        }))))
     }
 
     fn to_item_events(event: &EditorEvent, f: impl FnMut(ItemEvent)) {
@@ -959,12 +963,6 @@ impl Item for CommitView {
                     .update(cx, |editor, cx| editor.clone(window, cx))
             });
             let multibuffer = editor.read(cx).buffer().clone();
-            let processed_message = if let Some(ref remote) = self.remote {
-                Self::process_github_issues(&self.commit.message, remote)
-            } else {
-                self.commit.message.to_string()
-            };
-            let markdown = cx.new(|cx| Markdown::new(processed_message.into(), None, None, cx));
             Self {
                 editor,
                 multibuffer,
@@ -972,7 +970,6 @@ impl Item for CommitView {
                 stash: self.stash,
                 repository: self.repository.clone(),
                 remote: self.remote.clone(),
-                markdown,
             }
         })))
     }
@@ -981,14 +978,15 @@ impl Item for CommitView {
 impl Render for CommitView {
     fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
         let is_stash = self.stash.is_some();
-        div()
+
+        v_flex()
             .key_context(if is_stash { "StashDiff" } else { "CommitDiff" })
-            .bg(cx.theme().colors().editor_background)
-            .flex()
-            .flex_col()
             .size_full()
+            .bg(cx.theme().colors().editor_background)
             .child(self.render_header(window, cx))
-            .child(div().flex_grow().child(self.editor.clone()))
+            .when(!self.editor.read(cx).is_empty(cx), |this| {
+                this.child(div().flex_grow().child(self.editor.clone()))
+            })
     }
 }
 
@@ -1006,7 +1004,7 @@ impl EventEmitter<ToolbarItemEvent> for CommitViewToolbar {}
 
 impl Render for CommitViewToolbar {
     fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
-        div()
+        div().hidden()
     }
 }
 
@@ -1042,117 +1040,3 @@ fn stash_matches_index(sha: &str, stash_index: usize, repo: &Repository) -> bool
         .map(|entry| entry.oid.to_string() == sha)
         .unwrap_or(false)
 }
-
-fn hover_markdown_style(window: &Window, cx: &App) -> MarkdownStyle {
-    let colors = cx.theme().colors();
-    let mut style = MarkdownStyle::default();
-    style.base_text_style = window.text_style();
-    style.syntax = cx.theme().syntax().clone();
-    style.selection_background_color = colors.element_selection_background;
-    style.link = TextStyleRefinement {
-        color: Some(colors.text_accent),
-        underline: Some(UnderlineStyle {
-            thickness: px(1.0),
-            color: Some(colors.text_accent),
-            wavy: false,
-        }),
-        ..Default::default()
-    };
-    style
-}
-
-#[cfg(test)]
-mod tests {
-    use super::*;
-    use git_hosting_providers::Github;
-
-    fn create_test_remote() -> GitRemote {
-        GitRemote {
-            host: Arc::new(Github::public_instance()),
-            owner: "zed-industries".into(),
-            repo: "zed".into(),
-        }
-    }
-
-    #[test]
-    fn test_process_github_issues_simple_issue_number() {
-        let remote = create_test_remote();
-        let message = "Fix bug #123";
-        let result = CommitView::process_github_issues(message, &remote);
-        assert_eq!(
-            result,
-            "Fix bug [#123](https://github.com/zed-industries/zed/issues/123)"
-        );
-    }
-
-    #[test]
-    fn test_process_github_issues_multiple_issue_numbers() {
-        let remote = create_test_remote();
-        let message = "Fix #123 and #456";
-        let result = CommitView::process_github_issues(message, &remote);
-        assert_eq!(
-            result,
-            "Fix [#123](https://github.com/zed-industries/zed/issues/123) and [#456](https://github.com/zed-industries/zed/issues/456)"
-        );
-    }
-
-    #[test]
-    fn test_process_github_issues_gh_format() {
-        let remote = create_test_remote();
-        let message = "Fix GH-789";
-        let result = CommitView::process_github_issues(message, &remote);
-        assert_eq!(
-            result,
-            "Fix [GH-789](https://github.com/zed-industries/zed/issues/789)"
-        );
-    }
-
-    #[test]
-    fn test_process_github_issues_mixed_formats() {
-        let remote = create_test_remote();
-        let message = "Fix #123 and GH-456";
-        let result = CommitView::process_github_issues(message, &remote);
-        assert_eq!(
-            result,
-            "Fix [#123](https://github.com/zed-industries/zed/issues/123) and [GH-456](https://github.com/zed-industries/zed/issues/456)"
-        );
-    }
-
-    #[test]
-    fn test_process_github_issues_no_issues() {
-        let remote = create_test_remote();
-        let message = "This is a commit message without any issues";
-        let result = CommitView::process_github_issues(message, &remote);
-        assert_eq!(result, message);
-    }
-
-    #[test]
-    fn test_process_github_issues_hash_without_number() {
-        let remote = create_test_remote();
-        let message = "Use # for comments";
-        let result = CommitView::process_github_issues(message, &remote);
-        assert_eq!(result, message);
-    }
-
-    #[test]
-    fn test_process_github_issues_consecutive_issues() {
-        let remote = create_test_remote();
-        let message = "#123#456";
-        let result = CommitView::process_github_issues(message, &remote);
-        assert_eq!(
-            result,
-            "[#123](https://github.com/zed-industries/zed/issues/123)[#456](https://github.com/zed-industries/zed/issues/456)"
-        );
-    }
-
-    #[test]
-    fn test_process_github_issues_multiline() {
-        let remote = create_test_remote();
-        let message = "Fix #123\n\nThis also fixes #456";
-        let result = CommitView::process_github_issues(message, &remote);
-        assert_eq!(
-            result,
-            "Fix [#123](https://github.com/zed-industries/zed/issues/123)\n\nThis also fixes [#456](https://github.com/zed-industries/zed/issues/456)"
-        );
-    }
-}

crates/git_ui/src/conflict_view.rs 🔗

@@ -111,6 +111,7 @@ fn excerpt_for_buffer_updated(
     );
 }
 
+#[ztracing::instrument(skip_all)]
 fn buffer_added(editor: &mut Editor, buffer: Entity<Buffer>, cx: &mut Context<Editor>) {
     let Some(project) = editor.project() else {
         return;
@@ -166,6 +167,7 @@ fn buffers_removed(editor: &mut Editor, removed_buffer_ids: &[BufferId], cx: &mu
     editor.remove_blocks(removed_block_ids, None, cx);
 }
 
+#[ztracing::instrument(skip_all)]
 fn conflicts_updated(
     editor: &mut Editor,
     conflict_set: Entity<ConflictSet>,
@@ -311,6 +313,7 @@ fn conflicts_updated(
     }
 }
 
+#[ztracing::instrument(skip_all)]
 fn update_conflict_highlighting(
     editor: &mut Editor,
     conflict: &ConflictRegion,
@@ -372,7 +375,7 @@ fn render_conflict_buttons(
         .gap_1()
         .bg(cx.theme().colors().editor_background)
         .child(
-            Button::new("head", "Use HEAD")
+            Button::new("head", format!("Use {}", conflict.ours_branch_name))
                 .label_size(LabelSize::Small)
                 .on_click({
                     let editor = editor.clone();
@@ -392,7 +395,7 @@ fn render_conflict_buttons(
                 }),
         )
         .child(
-            Button::new("origin", "Use Origin")
+            Button::new("origin", format!("Use {}", conflict.theirs_branch_name))
                 .label_size(LabelSize::Small)
                 .on_click({
                     let editor = editor.clone();

crates/git_ui/src/file_diff_view.rs 🔗

@@ -109,7 +109,7 @@ impl FileDiffView {
         for buffer in [&old_buffer, &new_buffer] {
             cx.subscribe(buffer, move |this, _, event, _| match event {
                 language::BufferEvent::Edited
-                | language::BufferEvent::LanguageChanged
+                | language::BufferEvent::LanguageChanged(_)
                 | language::BufferEvent::Reparsed => {
                     this.buffer_changes_tx.send(()).ok();
                 }

crates/git_ui/src/file_history_view.rs 🔗

@@ -4,7 +4,8 @@ use git::repository::{FileHistory, FileHistoryEntry, RepoPath};
 use git::{GitHostingProviderRegistry, GitRemote, parse_git_remote_url};
 use gpui::{
     AnyElement, AnyEntity, App, Asset, Context, Entity, EventEmitter, FocusHandle, Focusable,
-    IntoElement, Render, Task, UniformListScrollHandle, WeakEntity, Window, actions, uniform_list,
+    IntoElement, Render, ScrollStrategy, Task, UniformListScrollHandle, WeakEntity, Window,
+    actions, uniform_list,
 };
 use project::{
     Project, ProjectPath,
@@ -191,6 +192,93 @@ impl FileHistoryView {
         task.detach();
     }
 
+    fn select_next(&mut self, _: &menu::SelectNext, _: &mut Window, cx: &mut Context<Self>) {
+        let entry_count = self.history.entries.len();
+        let ix = match self.selected_entry {
+            _ if entry_count == 0 => None,
+            None => Some(0),
+            Some(ix) => {
+                if ix == entry_count - 1 {
+                    Some(0)
+                } else {
+                    Some(ix + 1)
+                }
+            }
+        };
+        self.select_ix(ix, cx);
+    }
+
+    fn select_previous(
+        &mut self,
+        _: &menu::SelectPrevious,
+        _: &mut Window,
+        cx: &mut Context<Self>,
+    ) {
+        let entry_count = self.history.entries.len();
+        let ix = match self.selected_entry {
+            _ if entry_count == 0 => None,
+            None => Some(entry_count - 1),
+            Some(ix) => {
+                if ix == 0 {
+                    Some(entry_count - 1)
+                } else {
+                    Some(ix - 1)
+                }
+            }
+        };
+        self.select_ix(ix, cx);
+    }
+
+    fn select_first(&mut self, _: &menu::SelectFirst, _: &mut Window, cx: &mut Context<Self>) {
+        let entry_count = self.history.entries.len();
+        let ix = if entry_count != 0 { Some(0) } else { None };
+        self.select_ix(ix, cx);
+    }
+
+    fn select_last(&mut self, _: &menu::SelectLast, _: &mut Window, cx: &mut Context<Self>) {
+        let entry_count = self.history.entries.len();
+        let ix = if entry_count != 0 {
+            Some(entry_count - 1)
+        } else {
+            None
+        };
+        self.select_ix(ix, cx);
+    }
+
+    fn select_ix(&mut self, ix: Option<usize>, cx: &mut Context<Self>) {
+        self.selected_entry = ix;
+        if let Some(ix) = ix {
+            self.scroll_handle.scroll_to_item(ix, ScrollStrategy::Top);
+        }
+        cx.notify();
+    }
+
+    fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
+        self.open_commit_view(window, cx);
+    }
+
+    fn open_commit_view(&mut self, window: &mut Window, cx: &mut Context<Self>) {
+        let Some(entry) = self
+            .selected_entry
+            .and_then(|ix| self.history.entries.get(ix))
+        else {
+            return;
+        };
+
+        if let Some(repo) = self.repository.upgrade() {
+            let sha_str = entry.sha.to_string();
+            CommitView::open(
+                sha_str,
+                repo.downgrade(),
+                self.workspace.clone(),
+                None,
+                Some(self.history.path.clone()),
+                window,
+                cx,
+            );
+        }
+    }
+
     fn render_commit_avatar(
         &self,
         sha: &SharedString,
@@ -245,12 +333,8 @@ impl FileHistoryView {
             time_format::TimestampFormat::Relative,
         );
 
-        let sha = entry.sha.clone();
-        let repo = self.repository.clone();
-        let workspace = self.workspace.clone();
-        let file_path = self.history.path.clone();
-
         ListItem::new(("commit", ix))
+            .toggle_state(Some(ix) == self.selected_entry)
             .child(
                 h_flex()
                     .h_8()
@@ -267,15 +351,19 @@ impl FileHistoryView {
                     .child(self.render_commit_avatar(&entry.sha, window, cx))
                     .child(
                         h_flex()
+                            .min_w_0()
                             .w_full()
                             .justify_between()
                             .child(
                                 h_flex()
+                                    .min_w_0()
+                                    .w_full()
                                     .gap_1()
                                     .child(
                                         Label::new(entry.author_name.clone())
                                             .size(LabelSize::Small)
-                                            .color(Color::Default),
+                                            .color(Color::Default)
+                                            .truncate(),
                                     )
                                     .child(
                                         Label::new(&entry.subject)
@@ -285,9 +373,11 @@ impl FileHistoryView {
                                     ),
                             )
                             .child(
-                                Label::new(relative_timestamp)
-                                    .size(LabelSize::Small)
-                                    .color(Color::Muted),
+                                h_flex().flex_none().child(
+                                    Label::new(relative_timestamp)
+                                        .size(LabelSize::Small)
+                                        .color(Color::Muted),
+                                ),
                             ),
                     ),
             )
@@ -295,18 +385,7 @@ impl FileHistoryView {
                 this.selected_entry = Some(ix);
                 cx.notify();
 
-                if let Some(repo) = repo.upgrade() {
-                    let sha_str = sha.to_string();
-                    CommitView::open(
-                        sha_str,
-                        repo.downgrade(),
-                        workspace.clone(),
-                        None,
-                        Some(file_path.clone()),
-                        window,
-                        cx,
-                    );
-                }
+                this.open_commit_view(window, cx);
             }))
             .into_any_element()
     }
@@ -374,6 +453,14 @@ impl Render for FileHistoryView {
         let entry_count = self.history.entries.len();
 
         v_flex()
+            .id("file_history_view")
+            .key_context("FileHistoryView")
+            .track_focus(&self.focus_handle)
+            .on_action(cx.listener(Self::select_next))
+            .on_action(cx.listener(Self::select_previous))
+            .on_action(cx.listener(Self::select_first))
+            .on_action(cx.listener(Self::select_last))
+            .on_action(cx.listener(Self::confirm))
             .size_full()
             .bg(cx.theme().colors().editor_background)
             .child(
@@ -546,9 +633,9 @@ impl Item for FileHistoryView {
         &mut self,
         _workspace: &mut Workspace,
         window: &mut Window,
-        _cx: &mut Context<Self>,
+        cx: &mut Context<Self>,
     ) {
-        window.focus(&self.focus_handle);
+        window.focus(&self.focus_handle, cx);
     }
 
     fn show_toolbar(&self) -> bool {

crates/git_ui/src/git_panel.rs 🔗

@@ -6,19 +6,22 @@ use crate::project_diff::{self, Diff, ProjectDiff};
 use crate::remote_output::{self, RemoteAction, SuccessMessage};
 use crate::{branch_picker, picker_prompt, render_remote_button};
 use crate::{
-    git_panel_settings::GitPanelSettings, git_status_icon, repository_selector::RepositorySelector,
+    file_history_view::FileHistoryView, git_panel_settings::GitPanelSettings, git_status_icon,
+    repository_selector::RepositorySelector,
 };
 use agent_settings::AgentSettings;
 use anyhow::Context as _;
 use askpass::AskPassDelegate;
 use cloud_llm_client::CompletionIntent;
+use collections::{BTreeMap, HashMap, HashSet};
 use db::kvp::KEY_VALUE_STORE;
+use editor::RewrapOptions;
 use editor::{
     Direction, Editor, EditorElement, EditorMode, MultiBuffer, MultiBufferOffset,
     actions::ExpandAllDiffHunks,
 };
 use futures::StreamExt as _;
-use git::blame::ParsedCommitMessage;
+use git::commit::ParsedCommitMessage;
 use git::repository::{
     Branch, CommitDetails, CommitOptions, CommitSummary, DiffType, FetchOptions, GitCommitter,
     PushOptions, Remote, RemoteCommandOutput, ResetMode, Upstream, UpstreamTracking,
@@ -28,21 +31,22 @@ use git::stash::GitStash;
 use git::status::StageStatus;
 use git::{Amend, Signoff, ToggleStaged, repository::RepoPath, status::FileStatus};
 use git::{
-    ExpandCommitEditor, RestoreTrackedFiles, StageAll, StashAll, StashApply, StashPop,
-    TrashUntrackedFiles, UnstageAll,
+    ExpandCommitEditor, GitHostingProviderRegistry, RestoreTrackedFiles, StageAll, StashAll,
+    StashApply, StashPop, TrashUntrackedFiles, UnstageAll,
 };
 use gpui::{
-    Action, AsyncApp, AsyncWindowContext, ClickEvent, Corner, DismissEvent, Entity, EventEmitter,
-    FocusHandle, Focusable, KeyContext, ListHorizontalSizingBehavior, ListSizingBehavior,
-    MouseButton, MouseDownEvent, Point, PromptLevel, ScrollStrategy, Subscription, Task,
-    UniformListScrollHandle, WeakEntity, actions, anchored, deferred, uniform_list,
+    Action, AsyncApp, AsyncWindowContext, Bounds, ClickEvent, Corner, DismissEvent, Entity,
+    EventEmitter, FocusHandle, Focusable, KeyContext, MouseButton, MouseDownEvent, Point,
+    PromptLevel, ScrollStrategy, Subscription, Task, UniformListScrollHandle, WeakEntity, actions,
+    anchored, deferred, point, size, uniform_list,
 };
 use itertools::Itertools;
 use language::{Buffer, File};
 use language_model::{
-    ConfiguredModel, LanguageModelRegistry, LanguageModelRequest, LanguageModelRequestMessage, Role,
+    ConfiguredModel, LanguageModelRegistry, LanguageModelRequest, LanguageModelRequestMessage,
+    Role, ZED_CLOUD_PROVIDER_ID,
 };
-use menu::{Confirm, SecondaryConfirm, SelectFirst, SelectLast, SelectNext, SelectPrevious};
+use menu;
 use multi_buffer::ExcerptInfo;
 use notifications::status_toast::{StatusToast, ToastIcon};
 use panel::{
@@ -54,20 +58,22 @@ use project::{
     git_store::{GitStoreEvent, Repository, RepositoryEvent, RepositoryId, pending_op},
     project_settings::{GitPathStyle, ProjectSettings},
 };
+use prompt_store::{BuiltInPrompt, PromptId, PromptStore, RULES_FILE_NAMES};
 use serde::{Deserialize, Serialize};
 use settings::{Settings, SettingsStore, StatusStyle};
 use std::future::Future;
 use std::ops::Range;
 use std::path::Path;
-use std::{collections::HashSet, sync::Arc, time::Duration, usize};
+use std::{sync::Arc, time::Duration, usize};
 use strum::{IntoEnumIterator, VariantNames};
 use time::OffsetDateTime;
 use ui::{
-    ButtonLike, Checkbox, CommonAnimationExt, ContextMenu, ElevationIndex, PopoverMenu, ScrollAxes,
-    Scrollbars, SplitButton, Tooltip, WithScrollbar, prelude::*,
+    ButtonLike, Checkbox, CommonAnimationExt, ContextMenu, ElevationIndex, IndentGuideColors,
+    PopoverMenu, RenderedIndentGuide, ScrollAxes, Scrollbars, SplitButton, Tooltip, WithScrollbar,
+    prelude::*,
 };
 use util::paths::PathStyle;
-use util::{ResultExt, TryFutureExt, maybe};
+use util::{ResultExt, TryFutureExt, maybe, rel_path::RelPath};
 use workspace::SERIALIZATION_THROTTLE_TIME;
 use workspace::{
     Workspace,
@@ -87,10 +93,24 @@ actions!(
         FocusEditor,
         /// Focuses on the changes list.
         FocusChanges,
+        /// Select next git panel menu item, and show it in the diff view
+        NextEntry,
+        /// Select previous git panel menu item, and show it in the diff view
+        PreviousEntry,
+        /// Select first git panel menu item, and show it in the diff view
+        FirstEntry,
+        /// Select last git panel menu item, and show it in the diff view
+        LastEntry,
         /// Toggles automatic co-author suggestions.
         ToggleFillCoAuthors,
         /// Toggles sorting entries by path vs status.
         ToggleSortByPath,
+        /// Toggles showing entries in tree vs flat view.
+        ToggleTreeView,
+        /// Expands the selected entry to show its children.
+        ExpandSelectedEntry,
+        /// Collapses the selected entry to hide its children.
+        CollapseSelectedEntry,
     ]
 );
 
@@ -121,6 +141,7 @@ struct GitMenuState {
     has_new_changes: bool,
     sort_by_path: bool,
     has_stash_items: bool,
+    tree_view: bool,
 }
 
 fn git_panel_context_menu(
@@ -165,20 +186,33 @@ fn git_panel_context_menu(
             )
             .separator()
             .entry(
-                if state.sort_by_path {
-                    "Sort by Status"
+                if state.tree_view {
+                    "Flat View"
                 } else {
-                    "Sort by Path"
+                    "Tree View"
                 },
-                Some(Box::new(ToggleSortByPath)),
-                move |window, cx| window.dispatch_action(Box::new(ToggleSortByPath), cx),
+                Some(Box::new(ToggleTreeView)),
+                move |window, cx| window.dispatch_action(Box::new(ToggleTreeView), cx),
             )
+            .when(!state.tree_view, |this| {
+                this.entry(
+                    if state.sort_by_path {
+                        "Sort by Status"
+                    } else {
+                        "Sort by Path"
+                    },
+                    Some(Box::new(ToggleSortByPath)),
+                    move |window, cx| window.dispatch_action(Box::new(ToggleSortByPath), cx),
+                )
+            })
     })
 }
 
 const GIT_PANEL_KEY: &str = "GitPanel";
 
 const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
+// TODO: We should revise this part. It seems the indentation width is not aligned with the one in project panel
+const TREE_INDENT: f32 = 16.0;
 
 pub fn register(workspace: &mut Workspace) {
     workspace.register_action(|workspace, _: &ToggleFocus, window, cx| {
@@ -203,7 +237,7 @@ struct SerializedGitPanel {
     signoff_enabled: bool,
 }
 
-#[derive(Debug, PartialEq, Eq, Clone, Copy)]
+#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)]
 enum Section {
     Conflict,
     Tracked,
@@ -239,6 +273,8 @@ impl GitHeaderEntry {
 #[derive(Debug, PartialEq, Eq, Clone)]
 enum GitListEntry {
     Status(GitStatusEntry),
+    TreeStatus(GitTreeStatusEntry),
+    Directory(GitTreeDirEntry),
     Header(GitHeaderEntry),
 }
 
@@ -246,9 +282,213 @@ impl GitListEntry {
     fn status_entry(&self) -> Option<&GitStatusEntry> {
         match self {
             GitListEntry::Status(entry) => Some(entry),
+            GitListEntry::TreeStatus(entry) => Some(&entry.entry),
             _ => None,
         }
     }
+
+    fn directory_entry(&self) -> Option<&GitTreeDirEntry> {
+        match self {
+            GitListEntry::Directory(entry) => Some(entry),
+            _ => None,
+        }
+    }
+}
+
+enum GitPanelViewMode {
+    Flat,
+    Tree(TreeViewState),
+}
+
+impl GitPanelViewMode {
+    fn from_settings(cx: &App) -> Self {
+        if GitPanelSettings::get_global(cx).tree_view {
+            GitPanelViewMode::Tree(TreeViewState::default())
+        } else {
+            GitPanelViewMode::Flat
+        }
+    }
+
+    fn tree_state(&self) -> Option<&TreeViewState> {
+        match self {
+            GitPanelViewMode::Tree(state) => Some(state),
+            GitPanelViewMode::Flat => None,
+        }
+    }
+
+    fn tree_state_mut(&mut self) -> Option<&mut TreeViewState> {
+        match self {
+            GitPanelViewMode::Tree(state) => Some(state),
+            GitPanelViewMode::Flat => None,
+        }
+    }
+}
+
+#[derive(Default)]
+struct TreeViewState {
+    // Maps visible index to actual entry index.
+    // Length equals the number of visible entries.
+    // This is needed because some entries (like collapsed directories) may be hidden.
+    logical_indices: Vec<usize>,
+    expanded_dirs: HashMap<TreeKey, bool>,
+    directory_descendants: HashMap<TreeKey, Vec<GitStatusEntry>>,
+}
+
+impl TreeViewState {
+    fn build_tree_entries(
+        &mut self,
+        section: Section,
+        mut entries: Vec<GitStatusEntry>,
+        seen_directories: &mut HashSet<TreeKey>,
+    ) -> Vec<(GitListEntry, bool)> {
+        if entries.is_empty() {
+            return Vec::new();
+        }
+
+        entries.sort_by(|a, b| a.repo_path.cmp(&b.repo_path));
+
+        let mut root = TreeNode::default();
+        for entry in entries {
+            let components: Vec<&str> = entry.repo_path.components().collect();
+            if components.is_empty() {
+                root.files.push(entry);
+                continue;
+            }
+
+            let mut current = &mut root;
+            let mut current_path = String::new();
+
+            for (ix, component) in components.iter().enumerate() {
+                if ix == components.len() - 1 {
+                    current.files.push(entry.clone());
+                } else {
+                    if !current_path.is_empty() {
+                        current_path.push('/');
+                    }
+                    current_path.push_str(component);
+                    let dir_path = RepoPath::new(&current_path)
+                        .expect("repo path from status entry component");
+
+                    let component = SharedString::from(component.to_string());
+
+                    current = current
+                        .children
+                        .entry(component.clone())
+                        .or_insert_with(|| TreeNode {
+                            name: component,
+                            path: Some(dir_path),
+                            ..Default::default()
+                        });
+                }
+            }
+        }
+
+        let (flattened, _) = self.flatten_tree(&root, section, 0, seen_directories);
+        flattened
+    }
+
+    fn flatten_tree(
+        &mut self,
+        node: &TreeNode,
+        section: Section,
+        depth: usize,
+        seen_directories: &mut HashSet<TreeKey>,
+    ) -> (Vec<(GitListEntry, bool)>, Vec<GitStatusEntry>) {
+        let mut all_statuses = Vec::new();
+        let mut flattened = Vec::new();
+
+        for child in node.children.values() {
+            let (terminal, name) = Self::compact_directory_chain(child);
+            let Some(path) = terminal.path.clone().or_else(|| child.path.clone()) else {
+                continue;
+            };
+            let (child_flattened, mut child_statuses) =
+                self.flatten_tree(terminal, section, depth + 1, seen_directories);
+            let key = TreeKey { section, path };
+            let expanded = *self.expanded_dirs.get(&key).unwrap_or(&true);
+            self.expanded_dirs.entry(key.clone()).or_insert(true);
+            seen_directories.insert(key.clone());
+
+            self.directory_descendants
+                .insert(key.clone(), child_statuses.clone());
+
+            flattened.push((
+                GitListEntry::Directory(GitTreeDirEntry {
+                    key,
+                    name,
+                    depth,
+                    expanded,
+                }),
+                true,
+            ));
+
+            if expanded {
+                flattened.extend(child_flattened);
+            } else {
+                flattened.extend(child_flattened.into_iter().map(|(child, _)| (child, false)));
+            }
+
+            all_statuses.append(&mut child_statuses);
+        }
+
+        for file in &node.files {
+            all_statuses.push(file.clone());
+            flattened.push((
+                GitListEntry::TreeStatus(GitTreeStatusEntry {
+                    entry: file.clone(),
+                    depth,
+                }),
+                true,
+            ));
+        }
+
+        (flattened, all_statuses)
+    }
+
+    fn compact_directory_chain(mut node: &TreeNode) -> (&TreeNode, SharedString) {
+        let mut parts = vec![node.name.clone()];
+        while node.files.is_empty() && node.children.len() == 1 {
+            let Some(child) = node.children.values().next() else {
+                continue;
+            };
+            if child.path.is_none() {
+                break;
+            }
+            parts.push(child.name.clone());
+            node = child;
+        }
+        let name = parts.join("/");
+        (node, SharedString::from(name))
+    }
+}
+
+#[derive(Debug, PartialEq, Eq, Clone)]
+struct GitTreeStatusEntry {
+    entry: GitStatusEntry,
+    depth: usize,
+}
+
+#[derive(Debug, PartialEq, Eq, Clone, Hash)]
+struct TreeKey {
+    section: Section,
+    path: RepoPath,
+}
+
+#[derive(Debug, PartialEq, Eq, Clone)]
+struct GitTreeDirEntry {
+    key: TreeKey,
+    name: SharedString,
+    depth: usize,
+    // staged_state: ToggleState,
+    expanded: bool,
+}
+
+#[derive(Default)]
+struct TreeNode {
+    name: SharedString,
+    path: Option<RepoPath>,
+    children: BTreeMap<SharedString, TreeNode>,
+    files: Vec<GitStatusEntry>,
 }
 
 #[derive(Debug, PartialEq, Eq, Clone)]
@@ -344,12 +584,15 @@ pub struct GitPanel {
     add_coauthors: bool,
     generate_commit_message_task: Option<Task<Option<()>>>,
     entries: Vec<GitListEntry>,
+    view_mode: GitPanelViewMode,
+    entries_indices: HashMap<RepoPath, usize>,
     single_staged_entry: Option<GitStatusEntry>,
     single_tracked_entry: Option<GitStatusEntry>,
     focus_handle: FocusHandle,
     fs: Arc<dyn Fs>,
     new_count: usize,
     entry_count: usize,
+    changes_count: usize,
     new_staged_count: usize,
     pending_commit: Option<Task<()>>,
     amend_pending: bool,
@@ -365,7 +608,7 @@ pub struct GitPanel {
     tracked_staged_count: usize,
     update_visible_entries_task: Task<()>,
     width: Option<Pixels>,
-    workspace: WeakEntity<Workspace>,
+    pub(crate) workspace: WeakEntity<Workspace>,
     context_menu: Option<(Entity<ContextMenu>, Point<Pixels>, Subscription)>,
     modal_open: bool,
     show_placeholders: bool,
@@ -432,14 +675,19 @@ impl GitPanel {
             cx.on_focus(&focus_handle, window, Self::focus_in).detach();
 
             let mut was_sort_by_path = GitPanelSettings::get_global(cx).sort_by_path;
+            let mut was_tree_view = GitPanelSettings::get_global(cx).tree_view;
             cx.observe_global_in::<SettingsStore>(window, move |this, window, cx| {
-                let is_sort_by_path = GitPanelSettings::get_global(cx).sort_by_path;
-                if is_sort_by_path != was_sort_by_path {
-                    this.entries.clear();
+                let sort_by_path = GitPanelSettings::get_global(cx).sort_by_path;
+                let tree_view = GitPanelSettings::get_global(cx).tree_view;
+                if tree_view != was_tree_view {
+                    this.view_mode = GitPanelViewMode::from_settings(cx);
+                }
+                if sort_by_path != was_sort_by_path || tree_view != was_tree_view {
                     this.bulk_staging.take();
                     this.update_visible_entries(window, cx);
                 }
-                was_sort_by_path = is_sort_by_path
+                was_sort_by_path = sort_by_path;
+                was_tree_view = tree_view;
             })
             .detach();
 
@@ -505,10 +753,13 @@ impl GitPanel {
                 add_coauthors: true,
                 generate_commit_message_task: None,
                 entries: Vec::new(),
+                view_mode: GitPanelViewMode::from_settings(cx),
+                entries_indices: HashMap::default(),
                 focus_handle: cx.focus_handle(),
                 fs,
                 new_count: 0,
                 new_staged_count: 0,
+                changes_count: 0,
                 pending_commit: None,
                 amend_pending: false,
                 original_commit_message: None,
@@ -542,70 +793,70 @@ impl GitPanel {
         })
     }
 
-    pub fn entry_by_path(&self, path: &RepoPath, cx: &App) -> Option<usize> {
-        if GitPanelSettings::get_global(cx).sort_by_path {
-            return self
-                .entries
-                .binary_search_by(|entry| entry.status_entry().unwrap().repo_path.cmp(path))
-                .ok();
-        }
-
-        if self.conflicted_count > 0 {
-            let conflicted_start = 1;
-            if let Ok(ix) = self.entries[conflicted_start..conflicted_start + self.conflicted_count]
-                .binary_search_by(|entry| entry.status_entry().unwrap().repo_path.cmp(path))
-            {
-                return Some(conflicted_start + ix);
-            }
-        }
-        if self.tracked_count > 0 {
-            let tracked_start = if self.conflicted_count > 0 {
-                1 + self.conflicted_count
-            } else {
-                0
-            } + 1;
-            if let Ok(ix) = self.entries[tracked_start..tracked_start + self.tracked_count]
-                .binary_search_by(|entry| entry.status_entry().unwrap().repo_path.cmp(path))
-            {
-                return Some(tracked_start + ix);
-            }
-        }
-        if self.new_count > 0 {
-            let untracked_start = if self.conflicted_count > 0 {
-                1 + self.conflicted_count
-            } else {
-                0
-            } + if self.tracked_count > 0 {
-                1 + self.tracked_count
-            } else {
-                0
-            } + 1;
-            if let Ok(ix) = self.entries[untracked_start..untracked_start + self.new_count]
-                .binary_search_by(|entry| entry.status_entry().unwrap().repo_path.cmp(path))
-            {
-                return Some(untracked_start + ix);
-            }
-        }
-        None
+    pub fn entry_by_path(&self, path: &RepoPath) -> Option<usize> {
+        self.entries_indices.get(path).copied()
     }
 
     pub fn select_entry_by_path(
         &mut self,
         path: ProjectPath,
-        _: &mut Window,
+        window: &mut Window,
         cx: &mut Context<Self>,
     ) {
         let Some(git_repo) = self.active_repository.as_ref() else {
             return;
         };
-        let Some(repo_path) = git_repo.read(cx).project_path_to_repo_path(&path, cx) else {
-            return;
+
+        let (repo_path, section) = {
+            let repo = git_repo.read(cx);
+            let Some(repo_path) = repo.project_path_to_repo_path(&path, cx) else {
+                return;
+            };
+
+            let section = repo
+                .status_for_path(&repo_path)
+                .map(|status| status.status)
+                .map(|status| {
+                    if repo.had_conflict_on_last_merge_head_change(&repo_path) {
+                        Section::Conflict
+                    } else if status.is_created() {
+                        Section::New
+                    } else {
+                        Section::Tracked
+                    }
+                });
+
+            (repo_path, section)
         };
-        let Some(ix) = self.entry_by_path(&repo_path, cx) else {
+
+        let mut needs_rebuild = false;
+        if let (Some(section), Some(tree_state)) = (section, self.view_mode.tree_state_mut()) {
+            let mut current_dir = repo_path.parent();
+            while let Some(dir) = current_dir {
+                let key = TreeKey {
+                    section,
+                    path: RepoPath::from_rel_path(dir),
+                };
+
+                if tree_state.expanded_dirs.get(&key) == Some(&false) {
+                    tree_state.expanded_dirs.insert(key, true);
+                    needs_rebuild = true;
+                }
+
+                current_dir = dir.parent();
+            }
+        }
+
+        if needs_rebuild {
+            self.update_visible_entries(window, cx);
+        }
+
+        let Some(ix) = self.entry_by_path(&repo_path) else {
             return;
         };
+
         self.selected_entry = Some(ix);
-        cx.notify();
+        self.scroll_to_selected_entry(cx);
     }
 
     fn serialization_key(workspace: &Workspace) -> Option<String> {
@@ -693,24 +944,98 @@ impl GitPanel {
     }
 
     fn scroll_to_selected_entry(&mut self, cx: &mut Context<Self>) {
-        if let Some(selected_entry) = self.selected_entry {
+        let Some(selected_entry) = self.selected_entry else {
+            cx.notify();
+            return;
+        };
+
+        let visible_index = match &self.view_mode {
+            GitPanelViewMode::Flat => Some(selected_entry),
+            GitPanelViewMode::Tree(state) => state
+                .logical_indices
+                .iter()
+                .position(|&ix| ix == selected_entry),
+        };
+
+        if let Some(visible_index) = visible_index {
             self.scroll_handle
-                .scroll_to_item(selected_entry, ScrollStrategy::Center);
+                .scroll_to_item(visible_index, ScrollStrategy::Center);
         }
 
         cx.notify();
     }
 
-    fn select_first(&mut self, _: &SelectFirst, _window: &mut Window, cx: &mut Context<Self>) {
-        if !self.entries.is_empty() {
-            self.selected_entry = Some(1);
+    fn expand_selected_entry(
+        &mut self,
+        _: &ExpandSelectedEntry,
+        window: &mut Window,
+        cx: &mut Context<Self>,
+    ) {
+        let Some(entry) = self.get_selected_entry().cloned() else {
+            return;
+        };
+
+        if let GitListEntry::Directory(dir_entry) = entry {
+            if dir_entry.expanded {
+                self.select_next(&menu::SelectNext, window, cx);
+            } else {
+                self.toggle_directory(&dir_entry.key, window, cx);
+            }
+        } else {
+            self.select_next(&menu::SelectNext, window, cx);
+        }
+    }
+
+    fn collapse_selected_entry(
+        &mut self,
+        _: &CollapseSelectedEntry,
+        window: &mut Window,
+        cx: &mut Context<Self>,
+    ) {
+        let Some(entry) = self.get_selected_entry().cloned() else {
+            return;
+        };
+
+        if let GitListEntry::Directory(dir_entry) = entry {
+            if dir_entry.expanded {
+                self.toggle_directory(&dir_entry.key, window, cx);
+            } else {
+                self.select_previous(&menu::SelectPrevious, window, cx);
+            }
+        } else {
+            self.select_previous(&menu::SelectPrevious, window, cx);
+        }
+    }
+
+    fn select_first(
+        &mut self,
+        _: &menu::SelectFirst,
+        _window: &mut Window,
+        cx: &mut Context<Self>,
+    ) {
+        let first_entry = match &self.view_mode {
+            GitPanelViewMode::Flat => self
+                .entries
+                .iter()
+                .position(|entry| entry.status_entry().is_some()),
+            GitPanelViewMode::Tree(state) => {
+                let index = self.entries.iter().position(|entry| {
+                    entry.status_entry().is_some() || entry.directory_entry().is_some()
+                });
+
+                index.map(|index| state.logical_indices[index])
+            }
+        };
+
+        if let Some(first_entry) = first_entry {
+            self.selected_entry = Some(first_entry);
             self.scroll_to_selected_entry(cx);
         }
     }
 
     fn select_previous(
         &mut self,
-        _: &SelectPrevious,
+        _: &menu::SelectPrevious,
         _window: &mut Window,
         cx: &mut Context<Self>,
     ) {
@@ -719,80 +1044,142 @@ impl GitPanel {
             return;
         }
 
-        if let Some(selected_entry) = self.selected_entry {
-            let new_selected_entry = if selected_entry > 0 {
-                selected_entry - 1
-            } else {
-                selected_entry
-            };
+        let Some(selected_entry) = self.selected_entry else {
+            return;
+        };
 
-            if matches!(
-                self.entries.get(new_selected_entry),
-                Some(GitListEntry::Header(..))
-            ) {
-                if new_selected_entry > 0 {
-                    self.selected_entry = Some(new_selected_entry - 1)
-                }
-            } else {
-                self.selected_entry = Some(new_selected_entry);
+        let new_index = match &self.view_mode {
+            GitPanelViewMode::Flat => selected_entry.saturating_sub(1),
+            GitPanelViewMode::Tree(state) => {
+                let Some(current_logical_index) = state
+                    .logical_indices
+                    .iter()
+                    .position(|&i| i == selected_entry)
+                else {
+                    return;
+                };
+
+                state.logical_indices[current_logical_index.saturating_sub(1)]
             }
+        };
 
-            self.scroll_to_selected_entry(cx);
+        if selected_entry == 0 && new_index == 0 {
+            return;
         }
 
-        cx.notify();
+        if matches!(
+            self.entries.get(new_index.saturating_sub(1)),
+            Some(GitListEntry::Header(..))
+        ) && new_index == 0
+        {
+            return;
+        }
+
+        if matches!(self.entries.get(new_index), Some(GitListEntry::Header(..))) {
+            self.selected_entry = Some(new_index.saturating_sub(1));
+        } else {
+            self.selected_entry = Some(new_index);
+        }
+
+        self.scroll_to_selected_entry(cx);
     }
 
-    fn select_next(&mut self, _: &SelectNext, _window: &mut Window, cx: &mut Context<Self>) {
+    fn select_next(&mut self, _: &menu::SelectNext, _window: &mut Window, cx: &mut Context<Self>) {
         let item_count = self.entries.len();
         if item_count == 0 {
             return;
         }
 
-        if let Some(selected_entry) = self.selected_entry {
-            let new_selected_entry = if selected_entry < item_count - 1 {
-                selected_entry + 1
-            } else {
-                selected_entry
-            };
-            if matches!(
-                self.entries.get(new_selected_entry),
-                Some(GitListEntry::Header(..))
-            ) {
-                self.selected_entry = Some(new_selected_entry + 1);
-            } else {
-                self.selected_entry = Some(new_selected_entry);
+        let Some(selected_entry) = self.selected_entry else {
+            return;
+        };
+
+        if selected_entry == item_count - 1 {
+            return;
+        }
+
+        let new_index = match &self.view_mode {
+            GitPanelViewMode::Flat => selected_entry.saturating_add(1),
+            GitPanelViewMode::Tree(state) => {
+                let Some(current_logical_index) = state
+                    .logical_indices
+                    .iter()
+                    .position(|&i| i == selected_entry)
+                else {
+                    return;
+                };
+
+                state.logical_indices[current_logical_index.saturating_add(1)]
             }
+        };
 
-            self.scroll_to_selected_entry(cx);
+        if matches!(self.entries.get(new_index), Some(GitListEntry::Header(..))) {
+            self.selected_entry = Some(new_index.saturating_add(1));
+        } else {
+            self.selected_entry = Some(new_index);
         }
 
-        cx.notify();
+        self.scroll_to_selected_entry(cx);
     }
 
-    fn select_last(&mut self, _: &SelectLast, _window: &mut Window, cx: &mut Context<Self>) {
+    fn select_last(&mut self, _: &menu::SelectLast, _window: &mut Window, cx: &mut Context<Self>) {
         if self.entries.last().is_some() {
             self.selected_entry = Some(self.entries.len() - 1);
             self.scroll_to_selected_entry(cx);
         }
     }
 
+    /// Show diff view at selected entry, only if the diff view is open
+    fn move_diff_to_entry(&mut self, window: &mut Window, cx: &mut Context<Self>) {
+        maybe!({
+            let workspace = self.workspace.upgrade()?;
+
+            if let Some(project_diff) = workspace.read(cx).item_of_type::<ProjectDiff>(cx) {
+                let entry = self.entries.get(self.selected_entry?)?.status_entry()?;
+
+                project_diff.update(cx, |project_diff, cx| {
+                    project_diff.move_to_entry(entry.clone(), window, cx);
+                });
+            }
+
+            Some(())
+        });
+    }
+
+    fn first_entry(&mut self, _: &FirstEntry, window: &mut Window, cx: &mut Context<Self>) {
+        self.select_first(&menu::SelectFirst, window, cx);
+        self.move_diff_to_entry(window, cx);
+    }
+
+    fn last_entry(&mut self, _: &LastEntry, window: &mut Window, cx: &mut Context<Self>) {
+        self.select_last(&menu::SelectLast, window, cx);
+        self.move_diff_to_entry(window, cx);
+    }
+
+    fn next_entry(&mut self, _: &NextEntry, window: &mut Window, cx: &mut Context<Self>) {
+        self.select_next(&menu::SelectNext, window, cx);
+        self.move_diff_to_entry(window, cx);
+    }
+
+    fn previous_entry(&mut self, _: &PreviousEntry, window: &mut Window, cx: &mut Context<Self>) {
+        self.select_previous(&menu::SelectPrevious, window, cx);
+        self.move_diff_to_entry(window, cx);
+    }
+
     fn focus_editor(&mut self, _: &FocusEditor, window: &mut Window, cx: &mut Context<Self>) {
         self.commit_editor.update(cx, |editor, cx| {
-            window.focus(&editor.focus_handle(cx));
+            window.focus(&editor.focus_handle(cx), cx);
         });
         cx.notify();
     }
 
-    fn select_first_entry_if_none(&mut self, cx: &mut Context<Self>) {
+    fn select_first_entry_if_none(&mut self, window: &mut Window, cx: &mut Context<Self>) {
         let have_entries = self
             .active_repository
             .as_ref()
             .is_some_and(|active_repository| active_repository.read(cx).status_summary().count > 0);
         if have_entries && self.selected_entry.is_none() {
-            self.selected_entry = Some(1);
-            self.scroll_to_selected_entry(cx);
-            cx.notify();
+            self.select_first(&menu::SelectFirst, window, cx);
         }
     }
 
@@ -802,10 +1189,8 @@ impl GitPanel {
         window: &mut Window,
         cx: &mut Context<Self>,
     ) {
-        self.select_first_entry_if_none(cx);
-
-        self.focus_handle.focus(window);
-        cx.notify();
+        self.focus_handle.focus(window, cx);
+        self.select_first_entry_if_none(window, cx);
     }
 
     fn get_selected_entry(&self) -> Option<&GitListEntry> {
@@ -826,7 +1211,7 @@ impl GitPanel {
                         .project_path_to_repo_path(&project_path, cx)
                         .as_ref()
             {
-                project_diff.focus_handle(cx).focus(window);
+                project_diff.focus_handle(cx).focus(window, cx);
                 project_diff.update(cx, |project_diff, cx| project_diff.autoscroll(cx));
                 return None;
             };
@@ -836,7 +1221,27 @@ impl GitPanel {
                     ProjectDiff::deploy_at(workspace, Some(entry.clone()), window, cx);
                 })
                 .ok();
-            self.focus_handle.focus(window);
+            self.focus_handle.focus(window, cx);
+
+            Some(())
+        });
+    }
+
+    fn file_history(&mut self, _: &git::FileHistory, window: &mut Window, cx: &mut Context<Self>) {
+        maybe!({
+            let entry = self.entries.get(self.selected_entry?)?.status_entry()?;
+            let active_repo = self.active_repository.as_ref()?;
+            let repo_path = entry.repo_path.clone();
+            let git_store = self.project.read(cx).git_store();
+
+            FileHistoryView::open(
+                repo_path,
+                git_store.downgrade(),
+                active_repo.downgrade(),
+                self.workspace.clone(),
+                window,
+                cx,
+            );
 
             Some(())
         });
@@ -919,14 +1324,14 @@ impl GitPanel {
                 let prompt = window.prompt(
                     PromptLevel::Warning,
                     &format!(
-                        "Are you sure you want to restore {}?",
+                        "Are you sure you want to discard changes to {}?",
                         entry
                             .repo_path
                             .file_name()
                             .unwrap_or(entry.repo_path.display(path_style).as_ref()),
                     ),
                     None,
-                    &["Restore", "Cancel"],
+                    &["Discard Changes", "Cancel"],
                     cx,
                 );
                 cx.background_spawn(prompt)
@@ -1297,6 +1702,71 @@ impl GitPanel {
         .detach();
     }
 
+    fn stage_status_for_entry(entry: &GitStatusEntry, repo: &Repository) -> StageStatus {
+        // Checking for current staged/unstaged file status is a chained operation:
+        // 1. first, we check for any pending operation recorded in repository
+        // 2. if there are no pending ops either running or finished, we then ask the repository
+        //    for the most up-to-date file status read from disk - we do this since `entry` arg to this function `render_entry`
+        //    is likely to be staled, and may lead to weird artifacts in the form of subsecond auto-uncheck/check on
+        //    the checkbox's state (or flickering) which is undesirable.
+        // 3. finally, if there is no info about this `entry` in the repo, we fall back to whatever status is encoded
+        //    in `entry` arg.
+        repo.pending_ops_for_path(&entry.repo_path)
+            .map(|ops| {
+                if ops.staging() || ops.staged() {
+                    StageStatus::Staged
+                } else {
+                    StageStatus::Unstaged
+                }
+            })
+            .or_else(|| {
+                repo.status_for_path(&entry.repo_path)
+                    .map(|status| status.status.staging())
+            })
+            .unwrap_or(entry.staging)
+    }
+
+    fn stage_status_for_directory(
+        &self,
+        entry: &GitTreeDirEntry,
+        repo: &Repository,
+    ) -> StageStatus {
+        let GitPanelViewMode::Tree(tree_state) = &self.view_mode else {
+            util::debug_panic!("We should never render a directory entry while in flat view mode");
+            return StageStatus::Unstaged;
+        };
+
+        let Some(descendants) = tree_state.directory_descendants.get(&entry.key) else {
+            return StageStatus::Unstaged;
+        };
+
+        let mut fully_staged_count = 0usize;
+        let mut any_staged_or_partially_staged = false;
+
+        for descendant in descendants {
+            match GitPanel::stage_status_for_entry(descendant, repo) {
+                StageStatus::Staged => {
+                    fully_staged_count += 1;
+                    any_staged_or_partially_staged = true;
+                }
+                StageStatus::PartiallyStaged => {
+                    any_staged_or_partially_staged = true;
+                }
+                StageStatus::Unstaged => {}
+            }
+        }
+
+        if descendants.is_empty() {
+            StageStatus::Unstaged
+        } else if fully_staged_count == descendants.len() {
+            StageStatus::Staged
+        } else if any_staged_or_partially_staged {
+            StageStatus::PartiallyStaged
+        } else {
+            StageStatus::Unstaged
+        }
+    }
+
     pub fn stage_all(&mut self, _: &StageAll, _window: &mut Window, cx: &mut Context<Self>) {
         self.change_all_files_stage(true, cx);
     }
@@ -1311,50 +1781,101 @@ impl GitPanel {
         _window: &mut Window,
         cx: &mut Context<Self>,
     ) {
-        let Some(active_repository) = self.active_repository.as_ref() else {
+        let Some(active_repository) = self.active_repository.clone() else {
             return;
         };
-        let repo = active_repository.read(cx);
-        let (stage, repo_paths) = match entry {
-            GitListEntry::Status(status_entry) => {
-                let repo_paths = vec![status_entry.clone()];
-                let stage = if repo
-                    .pending_ops_for_path(&status_entry.repo_path)
-                    .map(|ops| ops.staging() || ops.staged())
-                    .or_else(|| {
-                        repo.status_for_path(&status_entry.repo_path)
-                            .map(|status| status.status.staging().has_staged())
-                    })
-                    .unwrap_or(status_entry.staging.has_staged())
-                {
-                    if let Some(op) = self.bulk_staging.clone()
-                        && op.anchor == status_entry.repo_path
-                    {
-                        self.bulk_staging = None;
-                    }
-                    false
-                } else {
-                    self.set_bulk_staging_anchor(status_entry.repo_path.clone(), cx);
-                    true
-                };
-                (stage, repo_paths)
-            }
-            GitListEntry::Header(section) => {
-                let goal_staged_state = !self.header_state(section.header).selected();
-                let entries = self
-                    .entries
-                    .iter()
-                    .filter_map(|entry| entry.status_entry())
-                    .filter(|status_entry| {
-                        section.contains(status_entry, repo)
-                            && status_entry.staging.as_bool() != Some(goal_staged_state)
-                    })
-                    .cloned()
-                    .collect::<Vec<_>>();
+        let mut set_anchor: Option<RepoPath> = None;
+        let mut clear_anchor = None;
+
+        let (stage, repo_paths) = {
+            let repo = active_repository.read(cx);
+            match entry {
+                GitListEntry::Status(status_entry) => {
+                    let repo_paths = vec![status_entry.clone()];
+                    let stage = match GitPanel::stage_status_for_entry(status_entry, &repo) {
+                        StageStatus::Staged => {
+                            if let Some(op) = self.bulk_staging.clone()
+                                && op.anchor == status_entry.repo_path
+                            {
+                                clear_anchor = Some(op.anchor);
+                            }
+                            false
+                        }
+                        StageStatus::Unstaged | StageStatus::PartiallyStaged => {
+                            set_anchor = Some(status_entry.repo_path.clone());
+                            true
+                        }
+                    };
+                    (stage, repo_paths)
+                }
+                GitListEntry::TreeStatus(status_entry) => {
+                    let repo_paths = vec![status_entry.entry.clone()];
+                    let stage = match GitPanel::stage_status_for_entry(&status_entry.entry, &repo) {
+                        StageStatus::Staged => {
+                            if let Some(op) = self.bulk_staging.clone()
+                                && op.anchor == status_entry.entry.repo_path
+                            {
+                                clear_anchor = Some(op.anchor);
+                            }
+                            false
+                        }
+                        StageStatus::Unstaged | StageStatus::PartiallyStaged => {
+                            set_anchor = Some(status_entry.entry.repo_path.clone());
+                            true
+                        }
+                    };
+                    (stage, repo_paths)
+                }
+                GitListEntry::Header(section) => {
+                    let goal_staged_state = !self.header_state(section.header).selected();
+                    let entries = self
+                        .entries
+                        .iter()
+                        .filter_map(|entry| entry.status_entry())
+                        .filter(|status_entry| {
+                            section.contains(status_entry, &repo)
+                                && GitPanel::stage_status_for_entry(status_entry, &repo).as_bool()
+                                    != Some(goal_staged_state)
+                        })
+                        .cloned()
+                        .collect::<Vec<_>>();
 
-                (goal_staged_state, entries)
+                    (goal_staged_state, entries)
+                }
+                GitListEntry::Directory(entry) => {
+                    let goal_staged_state = match self.stage_status_for_directory(entry, repo) {
+                        StageStatus::Staged => StageStatus::Unstaged,
+                        StageStatus::Unstaged | StageStatus::PartiallyStaged => StageStatus::Staged,
+                    };
+                    let goal_stage = goal_staged_state == StageStatus::Staged;
+
+                    let entries = self
+                        .view_mode
+                        .tree_state()
+                        .and_then(|state| state.directory_descendants.get(&entry.key))
+                        .cloned()
+                        .unwrap_or_default()
+                        .into_iter()
+                        .filter(|status_entry| {
+                            GitPanel::stage_status_for_entry(status_entry, &repo)
+                                != goal_staged_state
+                        })
+                        .collect::<Vec<_>>();
+                    (goal_stage, entries)
+                }
             }
         };
+        if let Some(anchor) = clear_anchor {
+            if let Some(op) = self.bulk_staging.clone()
+                && op.anchor == anchor
+            {
+                self.bulk_staging = None;
+            }
+        }
+        if let Some(anchor) = set_anchor {
+            self.set_bulk_staging_anchor(anchor, cx);
+        }
+
         self.change_file_stage(stage, repo_paths, cx);
     }
 

crates/git_ui/src/git_panel_settings.rs 🔗

@@ -24,6 +24,7 @@ pub struct GitPanelSettings {
     pub fallback_branch_name: String,
     pub sort_by_path: bool,
     pub collapse_untracked_diff: bool,
+    pub tree_view: bool,
 }
 
 impl ScrollbarVisibility for GitPanelSettings {
@@ -56,6 +57,7 @@ impl Settings for GitPanelSettings {
             fallback_branch_name: git_panel.fallback_branch_name.unwrap(),
             sort_by_path: git_panel.sort_by_path.unwrap(),
             collapse_untracked_diff: git_panel.collapse_untracked_diff.unwrap(),
+            tree_view: git_panel.tree_view.unwrap(),
         }
     }
 }

crates/git_ui/src/git_ui.rs 🔗

@@ -10,6 +10,7 @@ use ui::{
 };
 
 mod blame_ui;
+pub mod clone;
 
 use git::{
     repository::{Branch, Upstream, UpstreamTracking, UpstreamTrackingStatus},
@@ -817,7 +818,7 @@ impl GitCloneModal {
         });
         let focus_handle = repo_input.focus_handle(cx);
 
-        window.focus(&focus_handle);
+        window.focus(&focus_handle, cx);
 
         Self {
             panel,

crates/git_ui/src/onboarding.rs 🔗

@@ -85,8 +85,8 @@ impl Render for GitOnboardingModal {
                 git_onboarding_event!("Cancelled", trigger = "Action");
                 cx.emit(DismissEvent);
             }))
-            .on_any_mouse_down(cx.listener(|this, _: &MouseDownEvent, window, _cx| {
-                this.focus_handle.focus(window);
+            .on_any_mouse_down(cx.listener(|this, _: &MouseDownEvent, window, cx| {
+                this.focus_handle.focus(window, cx);
             }))
             .child(
                 div().p_1p5().absolute().inset_0().h(px(160.)).child(

crates/git_ui/src/picker_prompt.rs 🔗

@@ -220,7 +220,7 @@ impl PickerDelegate for PickerPromptDelegate {
         let shortened_option = util::truncate_and_trailoff(&hit.string, self.max_match_length);
 
         Some(
-            ListItem::new(SharedString::from(format!("picker-prompt-menu-{ix}")))
+            ListItem::new(format!("picker-prompt-menu-{ix}"))
                 .inset(true)
                 .spacing(ListItemSpacing::Sparse)
                 .toggle_state(selected)

crates/git_ui/src/project_diff.rs 🔗

@@ -34,7 +34,6 @@ use project::{
 use settings::{Settings, SettingsStore};
 use smol::future::yield_now;
 use std::any::{Any, TypeId};
-use std::ops::Range;
 use std::sync::Arc;
 use theme::ActiveTheme;
 use ui::{KeyBinding, Tooltip, prelude::*, vertical_divider};
@@ -46,6 +45,7 @@ use workspace::{
     notifications::NotifyTaskExt,
     searchable::SearchableItemHandle,
 };
+use ztracing::instrument;
 
 actions!(
     git,
@@ -74,6 +74,13 @@ pub struct ProjectDiff {
     _subscription: Subscription,
 }
 
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum RefreshReason {
+    DiffChanged,
+    StatusesChanged,
+    EditorSaved,
+}
+
 const CONFLICT_SORT_PREFIX: u64 = 1;
 const TRACKED_SORT_PREFIX: u64 = 2;
 const NEW_SORT_PREFIX: u64 = 3;
@@ -149,6 +156,10 @@ impl ProjectDiff {
             .items_of_type::<Self>(cx)
             .find(|item| matches!(item.read(cx).diff_base(cx), DiffBase::Head));
         let project_diff = if let Some(existing) = existing {
+            existing.update(cx, |project_diff, cx| {
+                project_diff.move_to_beginning(window, cx);
+            });
+
             workspace.activate_item(&existing, true, true, window, cx);
             existing
         } else {
@@ -278,7 +289,7 @@ impl ProjectDiff {
                 BranchDiffEvent::FileListChanged => {
                     this._task = window.spawn(cx, {
                         let this = cx.weak_entity();
-                        async |cx| Self::refresh(this, cx).await
+                        async |cx| Self::refresh(this, RefreshReason::StatusesChanged, cx).await
                     })
                 }
             },
@@ -297,7 +308,7 @@ impl ProjectDiff {
                 this._task = {
                     window.spawn(cx, {
                         let this = cx.weak_entity();
-                        async |cx| Self::refresh(this, cx).await
+                        async |cx| Self::refresh(this, RefreshReason::StatusesChanged, cx).await
                     })
                 }
             }
@@ -308,7 +319,7 @@ impl ProjectDiff {
 
         let task = window.spawn(cx, {
             let this = cx.weak_entity();
-            async |cx| Self::refresh(this, cx).await
+            async |cx| Self::refresh(this, RefreshReason::StatusesChanged, cx).await
         });
 
         Self {
@@ -358,6 +369,14 @@ impl ProjectDiff {
         })
     }
 
+    fn move_to_beginning(&mut self, window: &mut Window, cx: &mut Context<Self>) {
+        self.editor.update(cx, |editor, cx| {
+            editor.primary_editor().update(cx, |editor, cx| {
+                editor.move_to_beginning(&Default::default(), window, cx);
+            });
+        });
+    }
+
     fn move_to_path(&mut self, path_key: PathKey, window: &mut Window, cx: &mut Context<Self>) {
         if let Some(position) = self.multibuffer.read(cx).location_for_path(&path_key, cx) {
             self.editor.update(cx, |editor, cx| {
@@ -448,27 +467,36 @@ impl ProjectDiff {
         window: &mut Window,
         cx: &mut Context<Self>,
     ) {
-        if let EditorEvent::SelectionsChanged { local: true } = event {
-            let Some(project_path) = self.active_path(cx) else {
-                return;
-            };
-            self.workspace
-                .update(cx, |workspace, cx| {
-                    if let Some(git_panel) = workspace.panel::<GitPanel>(cx) {
-                        git_panel.update(cx, |git_panel, cx| {
-                            git_panel.select_entry_by_path(project_path, window, cx)
-                        })
-                    }
-                })
-                .ok();
+        match event {
+            EditorEvent::SelectionsChanged { local: true } => {
+                let Some(project_path) = self.active_path(cx) else {
+                    return;
+                };
+                self.workspace
+                    .update(cx, |workspace, cx| {
+                        if let Some(git_panel) = workspace.panel::<GitPanel>(cx) {
+                            git_panel.update(cx, |git_panel, cx| {
+                                git_panel.select_entry_by_path(project_path, window, cx)
+                            })
+                        }
+                    })
+                    .ok();
+            }
+            EditorEvent::Saved => {
+                self._task = cx.spawn_in(window, async move |this, cx| {
+                    Self::refresh(this, RefreshReason::EditorSaved, cx).await
+                });
+            }
+            _ => {}
         }
         if editor.focus_handle(cx).contains_focused(window, cx)
             && self.multibuffer.read(cx).is_empty()
         {
-            self.focus_handle.focus(window)
+            self.focus_handle.focus(window, cx)
         }
     }
 
+    #[instrument(skip_all)]
     fn register_buffer(
         &mut self,
         path_key: PathKey,
@@ -481,7 +509,7 @@ impl ProjectDiff {
         let subscription = cx.subscribe_in(&diff, window, move |this, _, _, window, cx| {
             this._task = window.spawn(cx, {
                 let this = cx.weak_entity();
-                async |cx| Self::refresh(this, cx).await
+                async |cx| Self::refresh(this, RefreshReason::DiffChanged, cx).await
             })
         });
         self.buffer_diff_subscriptions
@@ -497,24 +525,30 @@ impl ProjectDiff {
             .expect("project diff editor should have a conflict addon");
 
         let snapshot = buffer.read(cx).snapshot();
-        let diff_read = diff.read(cx);
-        let diff_snapshot = diff_read.snapshot(cx);
-        let diff_hunk_ranges = diff_snapshot
-            .hunks_intersecting_range(
-                Anchor::min_max_range_for_buffer(diff_read.buffer_id),
-                &snapshot,
-            )
-            .map(|diff_hunk| diff_hunk.buffer_range);
-        let conflicts = conflict_addon
-            .conflict_set(snapshot.remote_id())
-            .map(|conflict_set| conflict_set.read(cx).snapshot().conflicts)
-            .unwrap_or_default();
-        let conflicts = conflicts.iter().map(|conflict| conflict.range.clone());
-
-        let excerpt_ranges =
-            merge_anchor_ranges(diff_hunk_ranges.into_iter(), conflicts, &snapshot)
-                .map(|range| range.to_point(&snapshot))
-                .collect::<Vec<_>>();
+        let diff_snapshot = diff.read(cx).snapshot(cx);
+
+        let excerpt_ranges = {
+            let diff_hunk_ranges = diff_snapshot
+                .hunks_intersecting_range(
+                    Anchor::min_max_range_for_buffer(snapshot.remote_id()),
+                    &snapshot,
+                )
+                .map(|diff_hunk| diff_hunk.buffer_range.to_point(&snapshot));
+            let conflicts = conflict_addon
+                .conflict_set(snapshot.remote_id())
+                .map(|conflict_set| conflict_set.read(cx).snapshot().conflicts)
+                .unwrap_or_default();
+            let mut conflicts = conflicts
+                .iter()
+                .map(|conflict| conflict.range.to_point(&snapshot))
+                .peekable();
+
+            if conflicts.peek().is_some() {
+                conflicts.collect::<Vec<_>>()
+            } else {
+                diff_hunk_ranges.collect()
+            }
+        };
 
         let (was_empty, is_excerpt_newly_added) = self.editor.update(cx, |editor, cx| {
             let was_empty = editor
@@ -565,10 +599,10 @@ impl ProjectDiff {
                 .focus_handle(cx)
                 .contains_focused(window, cx)
         {
-            self.focus_handle.focus(window);
+            self.focus_handle.focus(window, cx);
         } else if self.focus_handle.is_focused(window) && !self.multibuffer.read(cx).is_empty() {
             self.editor.update(cx, |editor, cx| {
-                editor.focus_handle(cx).focus(window);
+                editor.focus_handle(cx).focus(window, cx);
             });
         }
         if self.pending_scroll.as_ref() == Some(&path_key) {
@@ -576,14 +610,23 @@ impl ProjectDiff {
         }
     }
 
-    pub async fn refresh(this: WeakEntity<Self>, cx: &mut AsyncWindowContext) -> Result<()> {
+    pub async fn refresh(
+        this: WeakEntity<Self>,
+        reason: RefreshReason,
+        cx: &mut AsyncWindowContext,
+    ) -> Result<()> {
         let mut path_keys = Vec::new();
         let buffers_to_load = this.update(cx, |this, cx| {
             let (repo, buffers_to_load) = this.branch_diff.update(cx, |branch_diff, cx| {
                 let load_buffers = branch_diff.load_buffers(cx);
                 (branch_diff.repo().cloned(), load_buffers)
             });
-            let mut previous_paths = this.multibuffer.read(cx).paths().collect::<HashSet<_>>();
+            let mut previous_paths = this
+                .multibuffer
+                .read(cx)
+                .paths()
+                .cloned()
+                .collect::<HashSet<_>>();
 
             if let Some(repo) = repo {
                 let repo = repo.read(cx);
@@ -600,6 +643,18 @@ impl ProjectDiff {
 
             this.editor.update(cx, |editor, cx| {
                 for path in previous_paths {
+                    if let Some(buffer) = this.multibuffer.read(cx).buffer_for_path(&path, cx) {
+                        let skip = match reason {
+                            RefreshReason::DiffChanged | RefreshReason::EditorSaved => {
+                                buffer.read(cx).is_dirty()
+                            }
+                            RefreshReason::StatusesChanged => false,
+                        };
+                        if skip {
+                            continue;
+                        }
+                    }
+
                     this.buffer_diff_subscriptions.remove(&path.path);
                     editor.remove_excerpts_for_path(path, cx);
                 }
@@ -614,7 +669,27 @@ impl ProjectDiff {
                 yield_now().await;
                 cx.update(|window, cx| {
                     this.update(cx, |this, cx| {
-                        this.register_buffer(path_key, entry.file_status, buffer, diff, window, cx)
+                        let multibuffer = this.multibuffer.read(cx);
+                        let skip = multibuffer.buffer(buffer.read(cx).remote_id()).is_some()
+                            && multibuffer
+                                .diff_for(buffer.read(cx).remote_id())
+                                .is_some_and(|prev_diff| prev_diff.entity_id() == diff.entity_id())
+                            && match reason {
+                                RefreshReason::DiffChanged | RefreshReason::EditorSaved => {
+                                    buffer.read(cx).is_dirty()
+                                }
+                                RefreshReason::StatusesChanged => false,
+                            };
+                        if !skip {
+                            this.register_buffer(
+                                path_key,
+                                entry.file_status,
+                                buffer,
+                                diff,
+                                window,
+                                cx,
+                            )
+                        }
                     })
                     .ok();
                 })?;
@@ -632,14 +707,17 @@ impl ProjectDiff {
     pub fn excerpt_paths(&self, cx: &App) -> Vec<std::sync::Arc<util::rel_path::RelPath>> {
         self.multibuffer
             .read(cx)
-            .excerpt_paths()
+            .paths()
             .map(|key| key.path.clone())
             .collect()
     }
 }
 
 fn sort_prefix(repo: &Repository, repo_path: &RepoPath, status: FileStatus, cx: &App) -> u64 {
-    if GitPanelSettings::get_global(cx).sort_by_path {
+    let settings = GitPanelSettings::get_global(cx);
+
+    // Tree view can only sort by path
+    if settings.sort_by_path || settings.tree_view {
         TRACKED_SORT_PREFIX
     } else if repo.had_conflict_on_last_merge_head_change(repo_path) {
         CONFLICT_SORT_PREFIX
@@ -907,7 +985,7 @@ impl Render for ProjectDiff {
                                         cx,
                                     ))
                                     .on_click(move |_, window, cx| {
-                                        window.focus(&keybinding_focus_handle);
+                                        window.focus(&keybinding_focus_handle, cx);
                                         window.dispatch_action(
                                             Box::new(CloseActiveItem::default()),
                                             cx,
@@ -1077,7 +1155,7 @@ impl ProjectDiffToolbar {
 
     fn dispatch_action(&self, action: &dyn Action, window: &mut Window, cx: &mut Context<Self>) {
         if let Some(project_diff) = self.project_diff(cx) {
-            project_diff.focus_handle(cx).focus(window);
+            project_diff.focus_handle(cx).focus(window, cx);
         }
         let action = action.boxed_clone();
         cx.defer(move |cx| {
@@ -1545,53 +1623,6 @@ mod preview {
     }
 }
 
-fn merge_anchor_ranges<'a>(
-    left: impl 'a + Iterator<Item = Range<Anchor>>,
-    right: impl 'a + Iterator<Item = Range<Anchor>>,
-    snapshot: &'a language::BufferSnapshot,
-) -> impl 'a + Iterator<Item = Range<Anchor>> {
-    let mut left = left.fuse().peekable();
-    let mut right = right.fuse().peekable();
-
-    std::iter::from_fn(move || {
-        let Some(left_range) = left.peek() else {
-            return right.next();
-        };
-        let Some(right_range) = right.peek() else {
-            return left.next();
-        };
-
-        let mut next_range = if left_range.start.cmp(&right_range.start, snapshot).is_lt() {
-            left.next().unwrap()
-        } else {
-            right.next().unwrap()
-        };
-
-        // Extend the basic range while there's overlap with a range from either stream.
-        loop {
-            if let Some(left_range) = left
-                .peek()
-                .filter(|range| range.start.cmp(&next_range.end, snapshot).is_le())
-                .cloned()
-            {
-                left.next();
-                next_range.end = left_range.end;
-            } else if let Some(right_range) = right
-                .peek()
-                .filter(|range| range.start.cmp(&next_range.end, snapshot).is_le())
-                .cloned()
-            {
-                right.next();
-                next_range.end = right_range.end;
-            } else {
-                break;
-            }
-        }
-
-        Some(next_range)
-    })
-}
-
 struct BranchDiffAddon {
     branch_diff: Entity<branch_diff::BranchDiff>,
 }
@@ -1689,9 +1720,13 @@ mod tests {
             .unindent(),
         );
 
-        editor.update_in(cx, |editor, window, cx| {
-            editor.git_restore(&Default::default(), window, cx);
-        });
+        editor
+            .update_in(cx, |editor, window, cx| {
+                editor.git_restore(&Default::default(), window, cx);
+                editor.save(SaveOptions::default(), project.clone(), window, cx)
+            })
+            .await
+            .unwrap();
         cx.run_until_parked();
 
         assert_state_with_diff(&editor, cx, &"ˇ".unindent());
@@ -1880,8 +1915,8 @@ mod tests {
             cx,
             &"
                 - original
-                + ˇdifferent
-            "
+                + different
+                  ˇ"
             .unindent(),
         );
     }

crates/git_ui/src/remote_output.rs 🔗

@@ -1,4 +1,5 @@
 use anyhow::Context as _;
+
 use git::repository::{Remote, RemoteCommandOutput};
 use linkify::{LinkFinder, LinkKind};
 use ui::SharedString;

crates/git_ui/src/stash_picker.rs 🔗

@@ -464,7 +464,7 @@ impl PickerDelegate for StashListDelegate {
             );
 
         Some(
-            ListItem::new(SharedString::from(format!("stash-{ix}")))
+            ListItem::new(format!("stash-{ix}"))
                 .inset(true)
                 .spacing(ListItemSpacing::Sparse)
                 .toggle_state(selected)

crates/git_ui/src/text_diff_view.rs 🔗

@@ -170,7 +170,7 @@ impl TextDiffView {
 
         cx.subscribe(&source_buffer, move |this, _, event, _| match event {
             language::BufferEvent::Edited
-            | language::BufferEvent::LanguageChanged
+            | language::BufferEvent::LanguageChanged(_)
             | language::BufferEvent::Reparsed => {
                 this.buffer_changes_tx.send(()).ok();
             }

crates/git_ui/src/worktree_picker.rs 🔗

@@ -1,4 +1,5 @@
 use anyhow::Context as _;
+use collections::HashSet;
 use fuzzy::StringMatchCandidate;
 
 use git::repository::Worktree as GitWorktree;
@@ -9,7 +10,11 @@ use gpui::{
     actions, rems,
 };
 use picker::{Picker, PickerDelegate, PickerEditorPosition};
-use project::{DirectoryLister, git_store::Repository};
+use project::{
+    DirectoryLister,
+    git_store::Repository,
+    trusted_worktrees::{PathTrust, RemoteHostLocation, TrustedWorktrees},
+};
 use recent_projects::{RemoteConnectionModal, connect};
 use remote::{RemoteConnectionOptions, remote_client::ConnectionIdentifier};
 use std::{path::PathBuf, sync::Arc};
@@ -219,7 +224,6 @@ impl WorktreeListDelegate {
         window: &mut Window,
         cx: &mut Context<Picker<Self>>,
     ) {
-        let workspace = self.workspace.clone();
         let Some(repo) = self.repo.clone() else {
             return;
         };
@@ -247,6 +251,7 @@ impl WorktreeListDelegate {
 
         let branch = worktree_branch.to_string();
         let window_handle = window.window_handle();
+        let workspace = self.workspace.clone();
         cx.spawn_in(window, async move |_, cx| {
             let Some(paths) = worktree_path.await? else {
                 return anyhow::Ok(());
@@ -257,8 +262,32 @@ impl WorktreeListDelegate {
                 repo.create_worktree(branch.clone(), path.clone(), commit)
             })?
             .await??;
-
-            let final_path = path.join(branch);
+            let new_worktree_path = path.join(branch);
+
+            workspace.update(cx, |workspace, cx| {
+                if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
+                    let repo_path = &repo.read(cx).snapshot().work_directory_abs_path;
+                    let project = workspace.project();
+                    if let Some((parent_worktree, _)) =
+                        project.read(cx).find_worktree(repo_path, cx)
+                    {
+                        trusted_worktrees.update(cx, |trusted_worktrees, cx| {
+                            if trusted_worktrees.can_trust(parent_worktree.read(cx).id(), cx) {
+                                trusted_worktrees.trust(
+                                    HashSet::from_iter([PathTrust::AbsPath(
+                                        new_worktree_path.clone(),
+                                    )]),
+                                    project
+                                        .read(cx)
+                                        .remote_connection_options(cx)
+                                        .map(RemoteHostLocation::from),
+                                    cx,
+                                );
+                            }
+                        });
+                    }
+                }
+            })?;
 
             let (connection_options, app_state, is_local) =
                 workspace.update(cx, |workspace, cx| {
@@ -274,7 +303,7 @@ impl WorktreeListDelegate {
                     .update_in(cx, |workspace, window, cx| {
                         workspace.open_workspace_for_paths(
                             replace_current_window,
-                            vec![final_path],
+                            vec![new_worktree_path],
                             window,
                             cx,
                         )
@@ -283,7 +312,7 @@ impl WorktreeListDelegate {
             } else if let Some(connection_options) = connection_options {
                 open_remote_worktree(
                     connection_options,
-                    vec![final_path],
+                    vec![new_worktree_path],
                     app_state,
                     window_handle,
                     replace_current_window,
@@ -421,6 +450,7 @@ async fn open_remote_worktree(
             app_state.user_store.clone(),
             app_state.languages.clone(),
             app_state.fs.clone(),
+            true,
             cx,
         )
     })?;
@@ -665,7 +695,7 @@ impl PickerDelegate for WorktreeListDelegate {
         };
 
         Some(
-            ListItem::new(SharedString::from(format!("worktree-menu-{ix}")))
+            ListItem::new(format!("worktree-menu-{ix}"))
                 .inset(true)
                 .spacing(ListItemSpacing::Sparse)
                 .toggle_state(selected)

crates/go_to_line/src/go_to_line.rs 🔗

@@ -268,7 +268,7 @@ impl GoToLine {
                 cx,
                 |s| s.select_anchor_ranges([start..start]),
             );
-            editor.focus_handle(cx).focus(window);
+            editor.focus_handle(cx).focus(window, cx);
             cx.notify()
         });
         self.prev_scroll_position.take();

crates/google_ai/src/google_ai.rs 🔗

@@ -512,6 +512,8 @@ pub enum Model {
     Gemini25Pro,
     #[serde(rename = "gemini-3-pro-preview")]
     Gemini3Pro,
+    #[serde(rename = "gemini-3-flash-preview")]
+    Gemini3Flash,
     #[serde(rename = "custom")]
     Custom {
         name: String,
@@ -534,6 +536,7 @@ impl Model {
             Self::Gemini25Flash => "gemini-2.5-flash",
             Self::Gemini25Pro => "gemini-2.5-pro",
             Self::Gemini3Pro => "gemini-3-pro-preview",
+            Self::Gemini3Flash => "gemini-3-flash-preview",
             Self::Custom { name, .. } => name,
         }
     }
@@ -543,6 +546,7 @@ impl Model {
             Self::Gemini25Flash => "gemini-2.5-flash",
             Self::Gemini25Pro => "gemini-2.5-pro",
             Self::Gemini3Pro => "gemini-3-pro-preview",
+            Self::Gemini3Flash => "gemini-3-flash-preview",
             Self::Custom { name, .. } => name,
         }
     }
@@ -553,6 +557,7 @@ impl Model {
             Self::Gemini25Flash => "Gemini 2.5 Flash",
             Self::Gemini25Pro => "Gemini 2.5 Pro",
             Self::Gemini3Pro => "Gemini 3 Pro",
+            Self::Gemini3Flash => "Gemini 3 Flash",
             Self::Custom {
                 name, display_name, ..
             } => display_name.as_ref().unwrap_or(name),
@@ -561,20 +566,22 @@ impl Model {
 
     pub fn max_token_count(&self) -> u64 {
         match self {
-            Self::Gemini25FlashLite => 1_048_576,
-            Self::Gemini25Flash => 1_048_576,
-            Self::Gemini25Pro => 1_048_576,
-            Self::Gemini3Pro => 1_048_576,
+            Self::Gemini25FlashLite
+            | Self::Gemini25Flash
+            | Self::Gemini25Pro
+            | Self::Gemini3Pro
+            | Self::Gemini3Flash => 1_048_576,
             Self::Custom { max_tokens, .. } => *max_tokens,
         }
     }
 
     pub fn max_output_tokens(&self) -> Option<u64> {
         match self {
-            Model::Gemini25FlashLite => Some(65_536),
-            Model::Gemini25Flash => Some(65_536),
-            Model::Gemini25Pro => Some(65_536),
-            Model::Gemini3Pro => Some(65_536),
+            Model::Gemini25FlashLite
+            | Model::Gemini25Flash
+            | Model::Gemini25Pro
+            | Model::Gemini3Pro
+            | Model::Gemini3Flash => Some(65_536),
             Model::Custom { .. } => None,
         }
     }
@@ -599,6 +606,7 @@ impl Model {
                     budget_tokens: None,
                 }
             }
+            Self::Gemini3Flash => GoogleModelMode::Default,
             Self::Custom { mode, .. } => *mode,
         }
     }

crates/gpui/Cargo.toml 🔗

@@ -21,7 +21,6 @@ default = ["font-kit", "wayland", "x11", "windows-manifest"]
 test-support = [
     "leak-detection",
     "collections/test-support",
-    "rand",
     "util/test-support",
     "http_client/test-support",
     "wayland",
@@ -109,7 +108,7 @@ parking = "2.0.0"
 parking_lot.workspace = true
 postage.workspace = true
 profiling.workspace = true
-rand = { optional = true, workspace = true }
+rand.workspace = true
 raw-window-handle = "0.6"
 refineable.workspace = true
 resvg = { version = "0.45.0", default-features = false, features = [
@@ -158,8 +157,10 @@ media.workspace = true
 objc.workspace = true
 objc2 = { version = "0.6", optional = true }
 objc2-metal = { version = "0.3", optional = true }
+mach2.workspace = true
 #TODO: replace with "objc2"
 metal.workspace = true
+flume = "0.11"
 
 [target.'cfg(any(target_os = "linux", target_os = "freebsd", target_os = "macos"))'.dependencies]
 pathfinder_geometry = "0.5"
@@ -197,14 +198,14 @@ wayland-backend = { version = "0.3.3", features = [
     "client_system",
     "dlopen",
 ], optional = true }
-wayland-client = { version = "0.31.2", optional = true }
-wayland-cursor = { version = "0.31.1", optional = true }
-wayland-protocols = { version = "0.31.2", features = [
+wayland-client = { version = "0.31.11", optional = true }
+wayland-cursor = { version = "0.31.11", optional = true }
+wayland-protocols = { version = "0.32.9", features = [
     "client",
     "staging",
     "unstable",
 ], optional = true }
-wayland-protocols-plasma = { version = "0.2.0", features = [
+wayland-protocols-plasma = { version = "0.3.9", features = [
     "client",
 ], optional = true }
 wayland-protocols-wlr = { version = "0.3.9", features = [
@@ -329,3 +330,7 @@ path = "examples/window_shadow.rs"
 [[example]]
 name = "grid_layout"
 path = "examples/grid_layout.rs"
+
+[[example]]
+name = "mouse_pressure"
+path = "examples/mouse_pressure.rs"

crates/gpui/README.md 🔗

@@ -11,7 +11,7 @@ GPUI is still in active development as we work on the Zed code editor, and is st
 gpui = { version = "*" }
 ```
 
- - [Ownership and data flow](src/_ownership_and_data_flow.rs)
+ - [Ownership and data flow](_ownership_and_data_flow)
 
 Everything in GPUI starts with an `Application`. You can create one with `Application::new()`, and kick off your application by passing a callback to `Application::run()`. Inside this callback, you can create a new window with `App::open_window()`, and register your first root view. See [gpui.rs](https://www.gpui.rs/) for a complete example.
 

crates/gpui/build.rs 🔗

@@ -84,6 +84,8 @@ mod macos {
             .allowlist_var("_dispatch_main_q")
             .allowlist_var("_dispatch_source_type_data_add")
             .allowlist_var("DISPATCH_QUEUE_PRIORITY_HIGH")
+            .allowlist_var("DISPATCH_QUEUE_PRIORITY_DEFAULT")
+            .allowlist_var("DISPATCH_QUEUE_PRIORITY_LOW")
             .allowlist_var("DISPATCH_TIME_NOW")
             .allowlist_function("dispatch_get_global_queue")
             .allowlist_function("dispatch_async_f")

crates/gpui/examples/focus_visible.rs 🔗

@@ -29,7 +29,7 @@ impl Example {
         ];
 
         let focus_handle = cx.focus_handle();
-        window.focus(&focus_handle);
+        window.focus(&focus_handle, cx);
 
         Self {
             focus_handle,
@@ -40,13 +40,13 @@ impl Example {
         }
     }
 
-    fn on_tab(&mut self, _: &Tab, window: &mut Window, _: &mut Context<Self>) {
-        window.focus_next();
+    fn on_tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
+        window.focus_next(cx);
         self.message = SharedString::from("Pressed Tab - focus-visible border should appear!");
     }
 
-    fn on_tab_prev(&mut self, _: &TabPrev, window: &mut Window, _: &mut Context<Self>) {
-        window.focus_prev();
+    fn on_tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
+        window.focus_prev(cx);
         self.message =
             SharedString::from("Pressed Shift-Tab - focus-visible border should appear!");
     }

crates/gpui/examples/input.rs 🔗

@@ -546,8 +546,15 @@ impl Element for TextElement {
             window.paint_quad(selection)
         }
         let line = prepaint.line.take().unwrap();
-        line.paint(bounds.origin, window.line_height(), window, cx)
-            .unwrap();
+        line.paint(
+            bounds.origin,
+            window.line_height(),
+            gpui::TextAlign::Left,
+            None,
+            window,
+            cx,
+        )
+        .unwrap();
 
         if focus_handle.is_focused(window)
             && let Some(cursor) = prepaint.cursor.take()
@@ -736,7 +743,7 @@ fn main() {
 
         window
             .update(cx, |view, window, cx| {
-                window.focus(&view.text_input.focus_handle(cx));
+                window.focus(&view.text_input.focus_handle(cx), cx);
                 cx.activate(true);
             })
             .unwrap();

crates/gpui/examples/mouse_pressure.rs 🔗

@@ -0,0 +1,66 @@
+use gpui::{
+    App, Application, Bounds, Context, MousePressureEvent, PressureStage, Window, WindowBounds,
+    WindowOptions, div, prelude::*, px, rgb, size,
+};
+
+struct MousePressureExample {
+    pressure_stage: PressureStage,
+    pressure_amount: f32,
+}
+
+impl Render for MousePressureExample {
+    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
+        div()
+            .flex()
+            .flex_col()
+            .gap_3()
+            .bg(rgb(0x505050))
+            .size(px(500.0))
+            .justify_center()
+            .items_center()
+            .shadow_lg()
+            .border_1()
+            .border_color(rgb(0x0000ff))
+            .text_xl()
+            .text_color(rgb(0xffffff))
+            .child(format!("Pressure stage: {:?}", &self.pressure_stage))
+            .child(format!("Pressure amount: {:.2}", &self.pressure_amount))
+            .on_mouse_pressure(cx.listener(Self::on_mouse_pressure))
+    }
+}
+
+impl MousePressureExample {
+    fn on_mouse_pressure(
+        &mut self,
+        pressure_event: &MousePressureEvent,
+        _window: &mut Window,
+        cx: &mut Context<Self>,
+    ) {
+        self.pressure_amount = pressure_event.pressure;
+        self.pressure_stage = pressure_event.stage;
+
+        cx.notify();
+    }
+}
+
+fn main() {
+    Application::new().run(|cx: &mut App| {
+        let bounds = Bounds::centered(None, size(px(500.), px(500.0)), cx);
+
+        cx.open_window(
+            WindowOptions {
+                window_bounds: Some(WindowBounds::Windowed(bounds)),
+                ..Default::default()
+            },
+            |_, cx| {
+                cx.new(|_| MousePressureExample {
+                    pressure_stage: PressureStage::Zero,
+                    pressure_amount: 0.0,
+                })
+            },
+        )
+        .unwrap();
+
+        cx.activate(true);
+    });
+}

crates/gpui/examples/on_window_close_quit.rs 🔗

@@ -55,7 +55,7 @@ fn main() {
                 cx.activate(false);
                 cx.new(|cx| {
                     let focus_handle = cx.focus_handle();
-                    focus_handle.focus(window);
+                    focus_handle.focus(window, cx);
                     ExampleWindow { focus_handle }
                 })
             },
@@ -72,7 +72,7 @@ fn main() {
             |window, cx| {
                 cx.new(|cx| {
                     let focus_handle = cx.focus_handle();
-                    focus_handle.focus(window);
+                    focus_handle.focus(window, cx);
                     ExampleWindow { focus_handle }
                 })
             },

crates/gpui/examples/painting.rs 🔗

@@ -1,7 +1,7 @@
 use gpui::{
     Application, Background, Bounds, ColorSpace, Context, MouseDownEvent, Path, PathBuilder,
-    PathStyle, Pixels, Point, Render, SharedString, StrokeOptions, Window, WindowOptions, canvas,
-    div, linear_color_stop, linear_gradient, point, prelude::*, px, quad, rgb, size,
+    PathStyle, Pixels, Point, Render, StrokeOptions, Window, WindowOptions, canvas, div,
+    linear_color_stop, linear_gradient, point, prelude::*, px, quad, rgb, size,
 };
 
 struct PaintingViewer {
@@ -309,7 +309,7 @@ fn button(
     on_click: impl Fn(&mut PaintingViewer, &mut Context<PaintingViewer>) + 'static,
 ) -> impl IntoElement {
     div()
-        .id(SharedString::from(text.to_string()))
+        .id(text.to_string())
         .child(text.to_string())
         .bg(gpui::black())
         .text_color(gpui::white())

crates/gpui/examples/popover.rs 🔗

@@ -0,0 +1,174 @@
+use gpui::{
+    App, Application, Context, Corner, Div, Hsla, Stateful, Window, WindowOptions, anchored,
+    deferred, div, prelude::*, px,
+};
+
+/// An example show use deferred to create a floating layers.
+struct HelloWorld {
+    open: bool,
+    secondary_open: bool,
+}
+
+fn button(id: &'static str) -> Stateful<Div> {
+    div()
+        .id(id)
+        .bg(gpui::black())
+        .text_color(gpui::white())
+        .px_3()
+        .py_1()
+}
+
+fn popover() -> Div {
+    div()
+        .flex()
+        .flex_col()
+        .items_center()
+        .justify_center()
+        .shadow_lg()
+        .p_3()
+        .rounded_md()
+        .bg(gpui::white())
+        .text_color(gpui::black())
+        .border_1()
+        .text_sm()
+        .border_color(gpui::black().opacity(0.1))
+}
+
+fn line(color: Hsla) -> Div {
+    div().w(px(480.)).h_2().bg(color.opacity(0.25))
+}
+
+impl HelloWorld {
+    fn render_secondary_popover(
+        &mut self,
+        _window: &mut Window,
+        cx: &mut Context<Self>,
+    ) -> impl IntoElement {
+        button("secondary-btn")
+            .mt_2()
+            .child("Child Popover")
+            .on_click(cx.listener(|this, _, _, cx| {
+                this.secondary_open = true;
+                cx.notify();
+            }))
+            .when(self.secondary_open, |this| {
+                this.child(
+                    // GPUI can't support deferred here yet,
+                    // it was inside another deferred element.
+                    anchored()
+                        .anchor(Corner::TopLeft)
+                        .snap_to_window_with_margin(px(8.))
+                        .child(
+                            popover()
+                                .child("This is second level Popover")
+                                .bg(gpui::white())
+                                .border_color(gpui::blue())
+                                .on_mouse_down_out(cx.listener(|this, _, _, cx| {
+                                    this.secondary_open = false;
+                                    cx.notify();
+                                })),
+                        ),
+                )
+            })
+    }
+}
+
+impl Render for HelloWorld {
+    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
+        div()
+            .flex()
+            .flex_col()
+            .gap_3()
+            .size_full()
+            .bg(gpui::white())
+            .text_color(gpui::black())
+            .justify_center()
+            .items_center()
+            .child(
+                div()
+                    .flex()
+                    .flex_row()
+                    .gap_4()
+                    .child(
+                        button("popover0").child("Opened Popover").child(
+                            deferred(
+                                anchored()
+                                    .anchor(Corner::TopLeft)
+                                    .snap_to_window_with_margin(px(8.))
+                                    .child(popover().w_96().gap_3().child(
+                                        "This is a default opened Popover, \
+                                        we can use deferred to render it \
+                                        in a floating layer.",
+                                    )),
+                            )
+                            .priority(0),
+                        ),
+                    )
+                    .child(
+                        button("popover1")
+                            .child("Open Popover")
+                            .on_click(cx.listener(|this, _, _, cx| {
+                                this.open = true;
+                                cx.notify();
+                            }))
+                            .when(self.open, |this| {
+                                this.child(
+                                    deferred(
+                                        anchored()
+                                            .anchor(Corner::TopLeft)
+                                            .snap_to_window_with_margin(px(8.))
+                                            .child(
+                                                popover()
+                                                    .w_96()
+                                                    .gap_3()
+                                                    .child(
+                                                        "This is first level Popover, \
+                                                   we can use deferred to render it \
+                                                   in a floating layer.\n\
+                                                   Click outside to close.",
+                                                    )
+                                                    .when(!self.secondary_open, |this| {
+                                                        this.on_mouse_down_out(cx.listener(
+                                                            |this, _, _, cx| {
+                                                                this.open = false;
+                                                                cx.notify();
+                                                            },
+                                                        ))
+                                                    })
+                                                    // Here we need render popover after the content
+                                                    // to ensure it will be on top layer.
+                                                    .child(
+                                                        self.render_secondary_popover(window, cx),
+                                                    ),
+                                            ),
+                                    )
+                                    .priority(1),
+                                )
+                            }),
+                    ),
+            )
+            .child(
+                "Here is an example text rendered, \
+                to ensure the Popover will float above this contents.",
+            )
+            .children([
+                line(gpui::red()),
+                line(gpui::yellow()),
+                line(gpui::blue()),
+                line(gpui::green()),
+            ])
+    }
+}
+
+fn main() {
+    Application::new().run(|cx: &mut App| {
+        cx.open_window(WindowOptions::default(), |_, cx| {
+            cx.new(|_| HelloWorld {
+                open: false,
+                secondary_open: false,
+            })
+        })
+        .unwrap();
+        cx.activate(true);
+    });
+}

crates/gpui/examples/tab_stop.rs 🔗

@@ -22,7 +22,7 @@ impl Example {
         ];
 
         let focus_handle = cx.focus_handle();
-        window.focus(&focus_handle);
+        window.focus(&focus_handle, cx);
 
         Self {
             focus_handle,
@@ -31,13 +31,13 @@ impl Example {
         }
     }
 
-    fn on_tab(&mut self, _: &Tab, window: &mut Window, _: &mut Context<Self>) {
-        window.focus_next();
+    fn on_tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
+        window.focus_next(cx);
         self.message = SharedString::from("You have pressed `Tab`.");
     }
 
-    fn on_tab_prev(&mut self, _: &TabPrev, window: &mut Window, _: &mut Context<Self>) {
-        window.focus_prev();
+    fn on_tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
+        window.focus_prev(cx);
         self.message = SharedString::from("You have pressed `Shift-Tab`.");
     }
 }
@@ -130,6 +130,50 @@ impl Render for Example {
                             })),
                     ),
             )
+            .child(
+                div()
+                    .id("group-1")
+                    .tab_index(6)
+                    .tab_group()
+                    .tab_stop(false)
+                    .child(
+                        button("group-1-button-1")
+                            .tab_index(1)
+                            .child("Tab index [6, 1]"),
+                    )
+                    .child(
+                        button("group-1-button-2")
+                            .tab_index(2)
+                            .child("Tab index [6, 2]"),
+                    )
+                    .child(
+                        button("group-1-button-3")
+                            .tab_index(3)
+                            .child("Tab index [6, 3]"),
+                    ),
+            )
+            .child(
+                div()
+                    .id("group-2")
+                    .tab_index(7)
+                    .tab_group()
+                    .tab_stop(false)
+                    .child(
+                        button("group-2-button-1")
+                            .tab_index(1)
+                            .child("Tab index [7, 1]"),
+                    )
+                    .child(
+                        button("group-2-button-2")
+                            .tab_index(2)
+                            .child("Tab index [7, 2]"),
+                    )
+                    .child(
+                        button("group-2-button-3")
+                            .tab_index(3)
+                            .child("Tab index [7, 3]"),
+                    ),
+            )
     }
 }
 

crates/gpui/examples/window.rs 🔗

@@ -1,15 +1,16 @@
 use gpui::{
-    App, Application, Bounds, Context, KeyBinding, PromptButton, PromptLevel, SharedString, Timer,
-    Window, WindowBounds, WindowKind, WindowOptions, actions, div, prelude::*, px, rgb, size,
+    App, Application, Bounds, Context, KeyBinding, PromptButton, PromptLevel, Timer, Window,
+    WindowBounds, WindowKind, WindowOptions, actions, div, prelude::*, px, rgb, size,
 };
 
 struct SubWindow {
     custom_titlebar: bool,
+    is_dialog: bool,
 }
 
 fn button(text: &str, on_click: impl Fn(&mut Window, &mut App) + 'static) -> impl IntoElement {
     div()
-        .id(SharedString::from(text.to_string()))
+        .id(text.to_string())
         .flex_none()
         .px_2()
         .bg(rgb(0xf7f7f7))
@@ -23,7 +24,10 @@ fn button(text: &str, on_click: impl Fn(&mut Window, &mut App) + 'static) -> imp
 }
 
 impl Render for SubWindow {
-    fn render(&mut self, _window: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
+    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
+        let window_bounds =
+            WindowBounds::Windowed(Bounds::centered(None, size(px(250.0), px(200.0)), cx));
+
         div()
             .flex()
             .flex_col()
@@ -52,8 +56,28 @@ impl Render for SubWindow {
             .child(
                 div()
                     .p_8()
+                    .flex()
+                    .flex_col()
                     .gap_2()
                     .child("SubWindow")
+                    .when(self.is_dialog, |div| {
+                        div.child(button("Open Nested Dialog", move |_, cx| {
+                            cx.open_window(
+                                WindowOptions {
+                                    window_bounds: Some(window_bounds),
+                                    kind: WindowKind::Dialog,
+                                    ..Default::default()
+                                },
+                                |_, cx| {
+                                    cx.new(|_| SubWindow {
+                                        custom_titlebar: false,
+                                        is_dialog: true,
+                                    })
+                                },
+                            )
+                            .unwrap();
+                        }))
+                    })
                     .child(button("Close", |window, _| {
                         window.remove_window();
                     })),
@@ -86,6 +110,7 @@ impl Render for WindowDemo {
                     |_, cx| {
                         cx.new(|_| SubWindow {
                             custom_titlebar: false,
+                            is_dialog: false,
                         })
                     },
                 )
@@ -101,6 +126,39 @@ impl Render for WindowDemo {
                     |_, cx| {
                         cx.new(|_| SubWindow {
                             custom_titlebar: false,
+                            is_dialog: false,
+                        })
+                    },
+                )
+                .unwrap();
+            }))
+            .child(button("Floating", move |_, cx| {
+                cx.open_window(
+                    WindowOptions {
+                        window_bounds: Some(window_bounds),
+                        kind: WindowKind::Floating,
+                        ..Default::default()
+                    },
+                    |_, cx| {
+                        cx.new(|_| SubWindow {
+                            custom_titlebar: false,
+                            is_dialog: false,
+                        })
+                    },
+                )
+                .unwrap();
+            }))
+            .child(button("Dialog", move |_, cx| {
+                cx.open_window(
+                    WindowOptions {
+                        window_bounds: Some(window_bounds),
+                        kind: WindowKind::Dialog,
+                        ..Default::default()
+                    },
+                    |_, cx| {
+                        cx.new(|_| SubWindow {
+                            custom_titlebar: false,
+                            is_dialog: true,
                         })
                     },
                 )
@@ -116,6 +174,7 @@ impl Render for WindowDemo {
                     |_, cx| {
                         cx.new(|_| SubWindow {
                             custom_titlebar: true,
+                            is_dialog: false,
                         })
                     },
                 )
@@ -131,6 +190,7 @@ impl Render for WindowDemo {
                     |_, cx| {
                         cx.new(|_| SubWindow {
                             custom_titlebar: false,
+                            is_dialog: false,
                         })
                     },
                 )
@@ -147,6 +207,7 @@ impl Render for WindowDemo {
                     |_, cx| {
                         cx.new(|_| SubWindow {
                             custom_titlebar: false,
+                            is_dialog: false,
                         })
                     },
                 )
@@ -162,6 +223,7 @@ impl Render for WindowDemo {
                     |_, cx| {
                         cx.new(|_| SubWindow {
                             custom_titlebar: false,
+                            is_dialog: false,
                         })
                     },
                 )
@@ -177,6 +239,7 @@ impl Render for WindowDemo {
                     |_, cx| {
                         cx.new(|_| SubWindow {
                             custom_titlebar: false,
+                            is_dialog: false,
                         })
                     },
                 )

crates/gpui/src/app.rs 🔗

@@ -38,10 +38,11 @@ use crate::{
     AssetSource, BackgroundExecutor, Bounds, ClipboardItem, CursorStyle, DispatchPhase, DisplayId,
     EventEmitter, FocusHandle, FocusMap, ForegroundExecutor, Global, KeyBinding, KeyContext,
     Keymap, Keystroke, LayoutId, Menu, MenuItem, OwnedMenu, PathPromptOptions, Pixels, Platform,
-    PlatformDisplay, PlatformKeyboardLayout, PlatformKeyboardMapper, Point, PromptBuilder,
-    PromptButton, PromptHandle, PromptLevel, Render, RenderImage, RenderablePromptHandle,
-    Reservation, ScreenCaptureSource, SharedString, SubscriberSet, Subscription, SvgRenderer, Task,
-    TextSystem, Window, WindowAppearance, WindowHandle, WindowId, WindowInvalidator,
+    PlatformDisplay, PlatformKeyboardLayout, PlatformKeyboardMapper, Point, Priority,
+    PromptBuilder, PromptButton, PromptHandle, PromptLevel, Render, RenderImage,
+    RenderablePromptHandle, Reservation, ScreenCaptureSource, SharedString, SubscriberSet,
+    Subscription, SvgRenderer, Task, TextSystem, Window, WindowAppearance, WindowHandle, WindowId,
+    WindowInvalidator,
     colors::{Colors, GlobalColors},
     current_platform, hash, init_app_menus,
 };
@@ -315,6 +316,7 @@ impl SystemWindowTabController {
             .find_map(|(group, tabs)| tabs.iter().find(|tab| tab.id == id).map(|_| group));
 
         let current_group = current_group?;
+        // TODO: `.keys()` returns arbitrary order, what does "next" mean?
         let mut group_ids: Vec<_> = controller.tab_groups.keys().collect();
         let idx = group_ids.iter().position(|g| *g == current_group)?;
         let next_idx = (idx + 1) % group_ids.len();
@@ -339,6 +341,7 @@ impl SystemWindowTabController {
             .find_map(|(group, tabs)| tabs.iter().find(|tab| tab.id == id).map(|_| group));
 
         let current_group = current_group?;
+        // TODO: `.keys()` returns arbitrary order, what does "previous" mean?
         let mut group_ids: Vec<_> = controller.tab_groups.keys().collect();
         let idx = group_ids.iter().position(|g| *g == current_group)?;
         let prev_idx = if idx == 0 {
@@ -360,12 +363,9 @@ impl SystemWindowTabController {
 
     /// Get all tabs in the same window.
     pub fn tabs(&self, id: WindowId) -> Option<&Vec<SystemWindowTab>> {
-        let tab_group = self
-            .tab_groups
-            .iter()
-            .find_map(|(group, tabs)| tabs.iter().find(|tab| tab.id == id).map(|_| *group))?;
-
-        self.tab_groups.get(&tab_group)
+        self.tab_groups
+            .values()
+            .find(|tabs| tabs.iter().any(|tab| tab.id == id))
     }
 
     /// Initialize the visibility of the system window tab controller.
@@ -440,7 +440,7 @@ impl SystemWindowTabController {
     /// Insert a tab into a tab group.
     pub fn add_tab(cx: &mut App, id: WindowId, tabs: Vec<SystemWindowTab>) {
         let mut controller = cx.global_mut::<SystemWindowTabController>();
-        let Some(tab) = tabs.clone().into_iter().find(|tab| tab.id == id) else {
+        let Some(tab) = tabs.iter().find(|tab| tab.id == id).cloned() else {
             return;
         };
 
@@ -503,16 +503,14 @@ impl SystemWindowTabController {
             return;
         };
 
+        let initial_tabs_len = initial_tabs.len();
         let mut all_tabs = initial_tabs.clone();
-        for tabs in controller.tab_groups.values() {
-            all_tabs.extend(
-                tabs.iter()
-                    .filter(|tab| !initial_tabs.contains(tab))
-                    .cloned(),
-            );
+
+        for (_, mut tabs) in controller.tab_groups.drain() {
+            tabs.retain(|tab| !all_tabs[..initial_tabs_len].contains(tab));
+            all_tabs.extend(tabs);
         }
 
-        controller.tab_groups.clear();
         controller.tab_groups.insert(0, all_tabs);
     }
 
@@ -551,12 +549,39 @@ impl SystemWindowTabController {
     }
 }
 
+pub(crate) enum GpuiMode {
+    #[cfg(any(test, feature = "test-support"))]
+    Test {
+        skip_drawing: bool,
+    },
+    Production,
+}
+
+impl GpuiMode {
+    #[cfg(any(test, feature = "test-support"))]
+    pub fn test() -> Self {
+        GpuiMode::Test {
+            skip_drawing: false,
+        }
+    }
+
+    #[inline]
+    pub(crate) fn skip_drawing(&self) -> bool {
+        match self {
+            #[cfg(any(test, feature = "test-support"))]
+            GpuiMode::Test { skip_drawing } => *skip_drawing,
+            GpuiMode::Production => false,
+        }
+    }
+}
+
 /// Contains the state of the full application, and passed as a reference to a variety of callbacks.
 /// Other [Context] derefs to this type.
 /// You need a reference to an `App` to access the state of a [Entity].
 pub struct App {
     pub(crate) this: Weak<AppCell>,
     pub(crate) platform: Rc<dyn Platform>,
+    pub(crate) mode: GpuiMode,
     text_system: Arc<TextSystem>,
     flushing_effects: bool,
     pending_updates: usize,
@@ -635,6 +660,7 @@ impl App {
                 this: this.clone(),
                 platform: platform.clone(),
                 text_system,
+                mode: GpuiMode::Production,
                 actions: Rc::new(ActionRegistry::default()),
                 flushing_effects: false,
                 pending_updates: 0,
@@ -1051,11 +1077,9 @@ impl App {
         self.platform.window_appearance()
     }
 
-    /// Writes data to the primary selection buffer.
-    /// Only available on Linux.
-    #[cfg(any(target_os = "linux", target_os = "freebsd"))]
-    pub fn write_to_primary(&self, item: ClipboardItem) {
-        self.platform.write_to_primary(item)
+    /// Reads data from the platform clipboard.
+    pub fn read_from_clipboard(&self) -> Option<ClipboardItem> {
+        self.platform.read_from_clipboard()
     }
 
     /// Writes data to the platform clipboard.
@@ -1070,9 +1094,31 @@ impl App {
         self.platform.read_from_primary()
     }
 
-    /// Reads data from the platform clipboard.
-    pub fn read_from_clipboard(&self) -> Option<ClipboardItem> {
-        self.platform.read_from_clipboard()
+    /// Writes data to the primary selection buffer.
+    /// Only available on Linux.
+    #[cfg(any(target_os = "linux", target_os = "freebsd"))]
+    pub fn write_to_primary(&self, item: ClipboardItem) {
+        self.platform.write_to_primary(item)
+    }
+
+    /// Reads data from macOS's "Find" pasteboard.
+    ///
+    /// Used to share the current search string between apps.
+    ///
+    /// https://developer.apple.com/documentation/appkit/nspasteboard/name-swift.struct/find
+    #[cfg(target_os = "macos")]
+    pub fn read_from_find_pasteboard(&self) -> Option<ClipboardItem> {
+        self.platform.read_from_find_pasteboard()
+    }
+
+    /// Writes data to macOS's "Find" pasteboard.
+    ///
+    /// Used to share the current search string between apps.
+    ///
+    /// https://developer.apple.com/documentation/appkit/nspasteboard/name-swift.struct/find
+    #[cfg(target_os = "macos")]
+    pub fn write_to_find_pasteboard(&self, item: ClipboardItem) {
+        self.platform.write_to_find_pasteboard(item)
     }
 
     /// Writes credentials to the platform keychain.
@@ -1466,6 +1512,24 @@ impl App {
             .spawn(async move { f(&mut cx).await })
     }
 
+    /// Spawns the future returned by the given function on the main thread with
+    /// the given priority. The closure will be invoked with [AsyncApp], which
+    /// allows the application state to be accessed across await points.
+    pub fn spawn_with_priority<AsyncFn, R>(&self, priority: Priority, f: AsyncFn) -> Task<R>
+    where
+        AsyncFn: AsyncFnOnce(&mut AsyncApp) -> R + 'static,
+        R: 'static,
+    {
+        if self.quitting {
+            debug_panic!("Can't spawn on main thread after on_app_quit")
+        };
+
+        let mut cx = self.to_async();
+
+        self.foreground_executor
+            .spawn_with_priority(priority, async move { f(&mut cx).await })
+    }
+
     /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
     /// that are currently on the stack to be returned to the app.
     pub fn defer(&mut self, f: impl FnOnce(&mut App) + 'static) {
@@ -1730,7 +1794,10 @@ impl App {
     /// Register a global handler for actions invoked via the keyboard. These handlers are run at
     /// the end of the bubble phase for actions, and so will only be invoked if there are no other
     /// handlers or if they called `cx.propagate()`.
-    pub fn on_action<A: Action>(&mut self, listener: impl Fn(&A, &mut Self) + 'static) {
+    pub fn on_action<A: Action>(
+        &mut self,
+        listener: impl Fn(&A, &mut Self) + 'static,
+    ) -> &mut Self {
         self.global_action_listeners
             .entry(TypeId::of::<A>())
             .or_default()
@@ -1740,6 +1807,7 @@ impl App {
                     listener(action, cx)
                 }
             }));
+        self
     }
 
     /// Event handlers propagate events by default. Call this method to stop dispatching to
@@ -1849,8 +1917,11 @@ impl App {
     pub(crate) fn clear_pending_keystrokes(&mut self) {
         for window in self.windows() {
             window
-                .update(self, |_, window, _| {
-                    window.clear_pending_keystrokes();
+                .update(self, |_, window, cx| {
+                    if window.pending_input_keystrokes().is_some() {
+                        window.clear_pending_keystrokes();
+                        window.pending_input_changed(cx);
+                    }
                 })
                 .ok();
         }

crates/gpui/src/app/async_context.rs 🔗

@@ -487,7 +487,7 @@ impl VisualContext for AsyncWindowContext {
         V: Focusable,
     {
         self.app.update_window(self.window, |_, window, cx| {
-            view.read(cx).focus_handle(cx).focus(window);
+            view.read(cx).focus_handle(cx).focus(window, cx);
         })
     }
 }

crates/gpui/src/app/context.rs 🔗

@@ -1,7 +1,7 @@
 use crate::{
     AnyView, AnyWindowHandle, AppContext, AsyncApp, DispatchPhase, Effect, EntityId, EventEmitter,
-    FocusHandle, FocusOutEvent, Focusable, Global, KeystrokeObserver, Reservation, SubscriberSet,
-    Subscription, Task, WeakEntity, WeakFocusHandle, Window, WindowHandle,
+    FocusHandle, FocusOutEvent, Focusable, Global, KeystrokeObserver, Priority, Reservation,
+    SubscriberSet, Subscription, Task, WeakEntity, WeakFocusHandle, Window, WindowHandle,
 };
 use anyhow::Result;
 use futures::FutureExt;
@@ -285,7 +285,7 @@ impl<'a, T: 'static> Context<'a, T> {
 
     /// Focus the given view in the given window. View type is required to implement Focusable.
     pub fn focus_view<W: Focusable>(&mut self, view: &Entity<W>, window: &mut Window) {
-        window.focus(&view.focus_handle(self));
+        window.focus(&view.focus_handle(self), self);
     }
 
     /// Sets a given callback to be run on the next frame.
@@ -667,6 +667,25 @@ impl<'a, T: 'static> Context<'a, T> {
         window.spawn(self, async move |cx| f(view, cx).await)
     }
 
+    /// Schedule a future to be run asynchronously with the given priority.
+    /// The given callback is invoked with a [`WeakEntity<V>`] to avoid leaking the entity for a long-running process.
+    /// It's also given an [`AsyncWindowContext`], which can be used to access the state of the entity across await points.
+    /// The returned future will be polled on the main thread.
+    #[track_caller]
+    pub fn spawn_in_with_priority<AsyncFn, R>(
+        &self,
+        priority: Priority,
+        window: &Window,
+        f: AsyncFn,
+    ) -> Task<R>
+    where
+        R: 'static,
+        AsyncFn: AsyncFnOnce(WeakEntity<T>, &mut AsyncWindowContext) -> R + 'static,
+    {
+        let view = self.weak_entity();
+        window.spawn_with_priority(priority, self, async move |cx| f(view, cx).await)
+    }
+
     /// Register a callback to be invoked when the given global state changes.
     pub fn observe_global_in<G: Global>(
         &mut self,
@@ -713,7 +732,7 @@ impl<'a, T: 'static> Context<'a, T> {
     {
         let view = self.entity();
         window.defer(self, move |window, cx| {
-            view.read(cx).focus_handle(cx).focus(window)
+            view.read(cx).focus_handle(cx).focus(window, cx)
         })
     }
 }

crates/gpui/src/app/entity_map.rs 🔗

@@ -584,7 +584,33 @@ impl AnyWeakEntity {
         })
     }
 
-    /// Assert that entity referenced by this weak handle has been released.
+    /// Asserts that the entity referenced by this weak handle has been fully released.
+    ///
+    /// # Example
+    ///
+    /// ```ignore
+    /// let entity = cx.new(|_| MyEntity::new());
+    /// let weak = entity.downgrade();
+    /// drop(entity);
+    ///
+    /// // Verify the entity was released
+    /// weak.assert_released();
+    /// ```
+    ///
+    /// # Debugging Leaks
+    ///
+    /// If this method panics due to leaked handles, set the `LEAK_BACKTRACE` environment
+    /// variable to see where the leaked handles were allocated:
+    ///
+    /// ```bash
+    /// LEAK_BACKTRACE=1 cargo test my_test
+    /// ```
+    ///
+    /// # Panics
+    ///
+    /// - Panics if any strong handles to the entity are still alive.
+    /// - Panics if the entity was recently dropped but cleanup hasn't completed yet
+    ///   (resources are retained until the end of the effect cycle).
     #[cfg(any(test, feature = "leak-detection"))]
     pub fn assert_released(&self) {
         self.entity_ref_counts
@@ -814,16 +840,70 @@ impl<T: 'static> PartialOrd for WeakEntity<T> {
     }
 }
 
+/// Controls whether backtraces are captured when entity handles are created.
+///
+/// Set the `LEAK_BACKTRACE` environment variable to any non-empty value to enable
+/// backtrace capture. This helps identify where leaked handles were allocated.
 #[cfg(any(test, feature = "leak-detection"))]
 static LEAK_BACKTRACE: std::sync::LazyLock<bool> =
     std::sync::LazyLock::new(|| std::env::var("LEAK_BACKTRACE").is_ok_and(|b| !b.is_empty()));
 
+/// Unique identifier for a specific entity handle instance.
+///
+/// This is distinct from `EntityId` - while multiple handles can point to the same
+/// entity (same `EntityId`), each handle has its own unique `HandleId`.
 #[cfg(any(test, feature = "leak-detection"))]
 #[derive(Clone, Copy, Debug, Default, Hash, PartialEq, Eq)]
 pub(crate) struct HandleId {
-    id: u64, // id of the handle itself, not the pointed at object
+    id: u64,
 }
 
+/// Tracks entity handle allocations to detect leaks.
+///
+/// The leak detector is enabled in tests and when the `leak-detection` feature is active.
+/// It tracks every `Entity<T>` and `AnyEntity` handle that is created and released,
+/// allowing you to verify that all handles to an entity have been properly dropped.
+///
+/// # How do leaks happen?
+///
+/// Entities are reference-counted structures that can own other entities
+/// allowing to form cycles. If such a strong-reference counted cycle is
+/// created, all participating strong entities in this cycle will effectively
+/// leak as they cannot be released anymore.
+///
+/// # Usage
+///
+/// You can use `WeakEntity::assert_released` or `AnyWeakEntity::assert_released`
+/// to verify that an entity has been fully released:
+///
+/// ```ignore
+/// let entity = cx.new(|_| MyEntity::new());
+/// let weak = entity.downgrade();
+/// drop(entity);
+///
+/// // This will panic if any handles to the entity are still alive
+/// weak.assert_released();
+/// ```
+///
+/// # Debugging Leaks
+///
+/// When a leak is detected, the detector will panic with information about the leaked
+/// handles. To see where the leaked handles were allocated, set the `LEAK_BACKTRACE`
+/// environment variable:
+///
+/// ```bash
+/// LEAK_BACKTRACE=1 cargo test my_test
+/// ```
+///
+/// This will capture and display backtraces for each leaked handle, helping you
+/// identify where handles were created but not released.
+///
+/// # How It Works
+///
+/// - When an entity handle is created (via `Entity::new`, `Entity::clone`, or
+///   `WeakEntity::upgrade`), `handle_created` is called to register the handle.
+/// - When a handle is dropped, `handle_released` removes it from tracking.
+/// - `assert_released` verifies that no handles remain for a given entity.
 #[cfg(any(test, feature = "leak-detection"))]
 pub(crate) struct LeakDetector {
     next_handle_id: u64,
@@ -832,6 +912,11 @@ pub(crate) struct LeakDetector {
 
 #[cfg(any(test, feature = "leak-detection"))]
 impl LeakDetector {
+    /// Records that a new handle has been created for the given entity.
+    ///
+    /// Returns a unique `HandleId` that must be passed to `handle_released` when
+    /// the handle is dropped. If `LEAK_BACKTRACE` is set, captures a backtrace
+    /// at the allocation site.
     #[track_caller]
     pub fn handle_created(&mut self, entity_id: EntityId) -> HandleId {
         let id = util::post_inc(&mut self.next_handle_id);
@@ -844,23 +929,40 @@ impl LeakDetector {
         handle_id
     }
 
+    /// Records that a handle has been released (dropped).
+    ///
+    /// This removes the handle from tracking. The `handle_id` should be the same
+    /// one returned by `handle_created` when the handle was allocated.
     pub fn handle_released(&mut self, entity_id: EntityId, handle_id: HandleId) {
         let handles = self.entity_handles.entry(entity_id).or_default();
         handles.remove(&handle_id);
     }
 
+    /// Asserts that all handles to the given entity have been released.
+    ///
+    /// # Panics
+    ///
+    /// Panics if any handles to the entity are still alive. The panic message
+    /// includes backtraces for each leaked handle if `LEAK_BACKTRACE` is set,
+    /// otherwise it suggests setting the environment variable to get more info.
     pub fn assert_released(&mut self, entity_id: EntityId) {
+        use std::fmt::Write as _;
         let handles = self.entity_handles.entry(entity_id).or_default();
         if !handles.is_empty() {
+            let mut out = String::new();
             for backtrace in handles.values_mut() {
                 if let Some(mut backtrace) = backtrace.take() {
                     backtrace.resolve();
-                    eprintln!("Leaked handle: {:#?}", backtrace);
+                    writeln!(out, "Leaked handle:\n{:?}", backtrace).unwrap();
                 } else {
-                    eprintln!("Leaked handle: export LEAK_BACKTRACE to find allocation site");
+                    writeln!(
+                        out,
+                        "Leaked handle: (export LEAK_BACKTRACE to find allocation site)"
+                    )
+                    .unwrap();
                 }
             }
-            panic!();
+            panic!("{out}");
         }
     }
 }

crates/gpui/src/app/test_context.rs 🔗

@@ -5,7 +5,7 @@ use crate::{
     ModifiersChangedEvent, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, Pixels,
     Platform, Point, Render, Result, Size, Task, TestDispatcher, TestPlatform,
     TestScreenCaptureSource, TestWindow, TextSystem, VisualContext, Window, WindowBounds,
-    WindowHandle, WindowOptions,
+    WindowHandle, WindowOptions, app::GpuiMode,
 };
 use anyhow::{anyhow, bail};
 use futures::{Stream, StreamExt, channel::oneshot};
@@ -132,8 +132,11 @@ impl TestAppContext {
         let http_client = http_client::FakeHttpClient::with_404_response();
         let text_system = Arc::new(TextSystem::new(platform.text_system()));
 
+        let mut app = App::new_app(platform.clone(), asset_source, http_client);
+        app.borrow_mut().mode = GpuiMode::test();
+
         Self {
-            app: App::new_app(platform.clone(), asset_source, http_client),
+            app,
             background_executor,
             foreground_executor,
             dispatcher,
@@ -144,6 +147,11 @@ impl TestAppContext {
         }
     }
 
+    /// Skip all drawing operations for the duration of this test.
+    pub fn skip_drawing(&mut self) {
+        self.app.borrow_mut().mode = GpuiMode::Test { skip_drawing: true };
+    }
+
     /// Create a single TestAppContext, for non-multi-client tests
     pub fn single() -> Self {
         let dispatcher = TestDispatcher::new(StdRng::seed_from_u64(0));
@@ -1037,7 +1045,7 @@ impl VisualContext for VisualTestContext {
     fn focus<V: crate::Focusable>(&mut self, view: &Entity<V>) -> Self::Result<()> {
         self.window
             .update(&mut self.cx, |_, window, cx| {
-                view.read(cx).focus_handle(cx).focus(window)
+                view.read(cx).focus_handle(cx).focus(window, cx)
             })
             .unwrap()
     }

crates/gpui/src/bounds_tree.rs 🔗

@@ -5,14 +5,91 @@ use std::{
     ops::{Add, Sub},
 };
 
+/// Maximum children per internal node (R-tree style branching factor).
+/// Higher values = shorter tree = fewer cache misses, but more work per node.
+const MAX_CHILDREN: usize = 12;
+
+/// A spatial tree optimized for finding maximum ordering among intersecting bounds.
+///
+/// This is an R-tree variant specifically designed for the use case of assigning
+/// z-order to overlapping UI elements. Key optimizations:
+/// - Tracks the leaf with global max ordering for O(1) fast-path queries
+/// - Uses higher branching factor (4) for lower tree height
+/// - Aggressive pruning during search based on max_order metadata
 #[derive(Debug)]
 pub(crate) struct BoundsTree<U>
 where
     U: Clone + Debug + Default + PartialEq,
 {
-    root: Option<usize>,
+    /// All nodes stored contiguously for cache efficiency.
     nodes: Vec<Node<U>>,
-    stack: Vec<usize>,
+    /// Index of the root node, if any.
+    root: Option<usize>,
+    /// Index of the leaf with the highest ordering (for fast-path lookups).
+    max_leaf: Option<usize>,
+    /// Reusable stack for tree traversal during insertion.
+    insert_path: Vec<usize>,
+    /// Reusable stack for search operations.
+    search_stack: Vec<usize>,
+}
+
+/// A node in the bounds tree.
+#[derive(Debug, Clone)]
+struct Node<U>
+where
+    U: Clone + Debug + Default + PartialEq,
+{
+    /// Bounding box containing this node and all descendants.
+    bounds: Bounds<U>,
+    /// Maximum ordering value in this subtree.
+    max_order: u32,
+    /// Node-specific data.
+    kind: NodeKind,
+}
+
+#[derive(Debug, Clone)]
+enum NodeKind {
+    /// Leaf node containing actual bounds data.
+    Leaf {
+        /// The ordering assigned to this bounds.
+        order: u32,
+    },
+    /// Internal node with children.
+    Internal {
+        /// Indices of child nodes (2 to MAX_CHILDREN).
+        children: NodeChildren,
+    },
+}
+
+/// Fixed-size array for child indices, avoiding heap allocation.
+#[derive(Debug, Clone)]
+struct NodeChildren {
+    // Keeps an invariant where the max order child is always at the end
+    indices: [usize; MAX_CHILDREN],
+    len: u8,
+}
+
+impl NodeChildren {
+    fn new() -> Self {
+        Self {
+            indices: [0; MAX_CHILDREN],
+            len: 0,
+        }
+    }
+
+    fn push(&mut self, index: usize) {
+        debug_assert!((self.len as usize) < MAX_CHILDREN);
+        self.indices[self.len as usize] = index;
+        self.len += 1;
+    }
+
+    fn len(&self) -> usize {
+        self.len as usize
+    }
+
+    fn as_slice(&self) -> &[usize] {
+        &self.indices[..self.len as usize]
+    }
 }
 
 impl<U> BoundsTree<U>
@@ -26,158 +103,250 @@ where
         + Half
         + Default,
 {
+    /// Clears all nodes from the tree.
     pub fn clear(&mut self) {
-        self.root = None;
         self.nodes.clear();
-        self.stack.clear();
+        self.root = None;
+        self.max_leaf = None;
+        self.insert_path.clear();
+        self.search_stack.clear();
     }
 
+    /// Inserts bounds into the tree and returns its assigned ordering.
+    ///
+    /// The ordering is one greater than the maximum ordering of any
+    /// existing bounds that intersect with the new bounds.
     pub fn insert(&mut self, new_bounds: Bounds<U>) -> u32 {
-        // If the tree is empty, make the root the new leaf.
-        let Some(mut index) = self.root else {
-            let new_node = self.push_leaf(new_bounds, 1);
-            self.root = Some(new_node);
-            return 1;
+        // Find maximum ordering among intersecting bounds
+        let max_intersecting = self.find_max_ordering(&new_bounds);
+        let ordering = max_intersecting + 1;
+
+        // Insert the new leaf
+        let new_leaf_idx = self.insert_leaf(new_bounds, ordering);
+
+        // Update max_leaf tracking
+        self.max_leaf = match self.max_leaf {
+            None => Some(new_leaf_idx),
+            Some(old_idx) if self.nodes[old_idx].max_order < ordering => Some(new_leaf_idx),
+            some => some,
         };
 
-        // Search for the best place to add the new leaf based on heuristics.
-        let mut max_intersecting_ordering = 0;
-        while let Node::Internal {
-            left,
-            right,
-            bounds: node_bounds,
-            ..
-        } = &mut self.nodes[index]
-        {
-            let left = *left;
-            let right = *right;
-            *node_bounds = node_bounds.union(&new_bounds);
-            self.stack.push(index);
-
-            // Descend to the best-fit child, based on which one would increase
-            // the surface area the least. This attempts to keep the tree balanced
-            // in terms of surface area. If there is an intersection with the other child,
-            // add its keys to the intersections vector.
-            let left_cost = new_bounds.union(self.nodes[left].bounds()).half_perimeter();
-            let right_cost = new_bounds
-                .union(self.nodes[right].bounds())
-                .half_perimeter();
-            if left_cost < right_cost {
-                max_intersecting_ordering =
-                    self.find_max_ordering(right, &new_bounds, max_intersecting_ordering);
-                index = left;
-            } else {
-                max_intersecting_ordering =
-                    self.find_max_ordering(left, &new_bounds, max_intersecting_ordering);
-                index = right;
+        ordering
+    }
+
+    /// Finds the maximum ordering among all bounds that intersect with the query.
+    fn find_max_ordering(&mut self, query: &Bounds<U>) -> u32 {
+        let Some(root_idx) = self.root else {
+            return 0;
+        };
+
+        // Fast path: check if the max-ordering leaf intersects
+        if let Some(max_idx) = self.max_leaf {
+            let max_node = &self.nodes[max_idx];
+            if query.intersects(&max_node.bounds) {
+                return max_node.max_order;
             }
         }
 
-        // We've found a leaf ('index' now refers to a leaf node).
-        // We'll insert a new parent node above the leaf and attach our new leaf to it.
-        let sibling = index;
-
-        // Check for collision with the located leaf node
-        let Node::Leaf {
-            bounds: sibling_bounds,
-            order: sibling_ordering,
-            ..
-        } = &self.nodes[index]
-        else {
-            unreachable!();
-        };
-        if sibling_bounds.intersects(&new_bounds) {
-            max_intersecting_ordering = cmp::max(max_intersecting_ordering, *sibling_ordering);
+        // Slow path: search the tree
+        self.search_stack.clear();
+        self.search_stack.push(root_idx);
+
+        let mut max_found = 0u32;
+
+        while let Some(node_idx) = self.search_stack.pop() {
+            let node = &self.nodes[node_idx];
+
+            // Pruning: skip if this subtree can't improve our result
+            if node.max_order <= max_found {
+                continue;
+            }
+
+            // Spatial pruning: skip if bounds don't intersect
+            if !query.intersects(&node.bounds) {
+                continue;
+            }
+
+            match &node.kind {
+                NodeKind::Leaf { order } => {
+                    max_found = cmp::max(max_found, *order);
+                }
+                NodeKind::Internal { children } => {
+                    // Children are maintained with highest max_order at the end.
+                    // Push in forward order to highest (last) is popped first.
+                    for &child_idx in children.as_slice() {
+                        if self.nodes[child_idx].max_order > max_found {
+                            self.search_stack.push(child_idx);
+                        }
+                    }
+                }
+            }
         }
 
-        let ordering = max_intersecting_ordering + 1;
-        let new_node = self.push_leaf(new_bounds, ordering);
-        let new_parent = self.push_internal(sibling, new_node);
+        max_found
+    }
 
-        // If there was an old parent, we need to update its children indices.
-        if let Some(old_parent) = self.stack.last().copied() {
-            let Node::Internal { left, right, .. } = &mut self.nodes[old_parent] else {
-                unreachable!();
-            };
+    /// Inserts a leaf node with the given bounds and ordering.
+    /// Returns the index of the new leaf.
+    fn insert_leaf(&mut self, bounds: Bounds<U>, order: u32) -> usize {
+        let new_leaf_idx = self.nodes.len();
+        self.nodes.push(Node {
+            bounds: bounds.clone(),
+            max_order: order,
+            kind: NodeKind::Leaf { order },
+        });
 
-            if *left == sibling {
-                *left = new_parent;
+        let Some(root_idx) = self.root else {
+            // Tree is empty, new leaf becomes root
+            self.root = Some(new_leaf_idx);
+            return new_leaf_idx;
+        };
+
+        // If root is a leaf, create internal node with both
+        if matches!(self.nodes[root_idx].kind, NodeKind::Leaf { .. }) {
+            let root_bounds = self.nodes[root_idx].bounds.clone();
+            let root_order = self.nodes[root_idx].max_order;
+
+            let mut children = NodeChildren::new();
+            // Max end invariant
+            if order > root_order {
+                children.push(root_idx);
+                children.push(new_leaf_idx);
             } else {
-                *right = new_parent;
+                children.push(new_leaf_idx);
+                children.push(root_idx);
             }
-        } else {
-            // If the old parent was the root, the new parent is the new root.
-            self.root = Some(new_parent);
+
+            let new_root_idx = self.nodes.len();
+            self.nodes.push(Node {
+                bounds: root_bounds.union(&bounds),
+                max_order: cmp::max(root_order, order),
+                kind: NodeKind::Internal { children },
+            });
+            self.root = Some(new_root_idx);
+            return new_leaf_idx;
         }
 
-        for node_index in self.stack.drain(..).rev() {
-            let Node::Internal {
-                max_order: max_ordering,
-                ..
-            } = &mut self.nodes[node_index]
-            else {
-                unreachable!()
+        // Descend to find the best internal node to insert into
+        self.insert_path.clear();
+        let mut current_idx = root_idx;
+
+        loop {
+            let current = &self.nodes[current_idx];
+            let NodeKind::Internal { children } = &current.kind else {
+                unreachable!("Should only traverse internal nodes");
             };
-            if *max_ordering >= ordering {
-                break;
-            }
-            *max_ordering = ordering;
-        }
 
-        ordering
-    }
+            self.insert_path.push(current_idx);
+
+            // Find the best child to descend into
+            let mut best_child_idx = children.as_slice()[0];
+            let mut best_child_pos = 0;
+            let mut best_cost = bounds
+                .union(&self.nodes[best_child_idx].bounds)
+                .half_perimeter();
 
-    fn find_max_ordering(&self, index: usize, bounds: &Bounds<U>, mut max_ordering: u32) -> u32 {
-        match &self.nodes[index] {
-            Node::Leaf {
-                bounds: node_bounds,
-                order: ordering,
-                ..
-            } => {
-                if bounds.intersects(node_bounds) {
-                    max_ordering = cmp::max(*ordering, max_ordering);
+            for (pos, &child_idx) in children.as_slice().iter().enumerate().skip(1) {
+                let cost = bounds.union(&self.nodes[child_idx].bounds).half_perimeter();
+                if cost < best_cost {
+                    best_cost = cost;
+                    best_child_idx = child_idx;
+                    best_child_pos = pos;
                 }
             }
-            Node::Internal {
-                left,
-                right,
-                bounds: node_bounds,
-                max_order: node_max_ordering,
-                ..
-            } => {
-                if bounds.intersects(node_bounds) && max_ordering < *node_max_ordering {
-                    let left_max_ordering = self.nodes[*left].max_ordering();
-                    let right_max_ordering = self.nodes[*right].max_ordering();
-                    if left_max_ordering > right_max_ordering {
-                        max_ordering = self.find_max_ordering(*left, bounds, max_ordering);
-                        max_ordering = self.find_max_ordering(*right, bounds, max_ordering);
+
+            // Check if best child is a leaf or internal
+            if matches!(self.nodes[best_child_idx].kind, NodeKind::Leaf { .. }) {
+                // Best child is a leaf. Check if current node has room for another child.
+                if children.len() < MAX_CHILDREN {
+                    // Add new leaf directly to this node
+                    let node = &mut self.nodes[current_idx];
+
+                    if let NodeKind::Internal { children } = &mut node.kind {
+                        children.push(new_leaf_idx);
+                        // Swap new leaf only if it has the highest max_order
+                        if order <= node.max_order {
+                            let last = children.len() - 1;
+                            children.indices.swap(last - 1, last);
+                        }
+                    }
+
+                    node.bounds = node.bounds.union(&bounds);
+                    node.max_order = cmp::max(node.max_order, order);
+                    break;
+                } else {
+                    // Node is full, create new internal with [best_leaf, new_leaf]
+                    let sibling_bounds = self.nodes[best_child_idx].bounds.clone();
+                    let sibling_order = self.nodes[best_child_idx].max_order;
+
+                    let mut new_children = NodeChildren::new();
+                    // Max end invariant
+                    if order > sibling_order {
+                        new_children.push(best_child_idx);
+                        new_children.push(new_leaf_idx);
                     } else {
-                        max_ordering = self.find_max_ordering(*right, bounds, max_ordering);
-                        max_ordering = self.find_max_ordering(*left, bounds, max_ordering);
+                        new_children.push(new_leaf_idx);
+                        new_children.push(best_child_idx);
+                    }
+
+                    let new_internal_idx = self.nodes.len();
+                    let new_internal_max = cmp::max(sibling_order, order);
+                    self.nodes.push(Node {
+                        bounds: sibling_bounds.union(&bounds),
+                        max_order: new_internal_max,
+                        kind: NodeKind::Internal {
+                            children: new_children,
+                        },
+                    });
+
+                    // Replace the leaf with the new internal in parent
+                    let parent = &mut self.nodes[current_idx];
+                    if let NodeKind::Internal { children } = &mut parent.kind {
+                        let children_len = children.len();
+
+                        children.indices[best_child_pos] = new_internal_idx;
+
+                        // If new internal has highest max_order, swap it to the end
+                        // to maintain sorting invariant
+                        if new_internal_max > parent.max_order {
+                            children.indices.swap(best_child_pos, children_len - 1);
+                        }
                     }
+                    break;
                 }
+            } else {
+                // Best child is internal, continue descent
+                current_idx = best_child_idx;
             }
         }
-        max_ordering
-    }
 
-    fn push_leaf(&mut self, bounds: Bounds<U>, order: u32) -> usize {
-        self.nodes.push(Node::Leaf { bounds, order });
-        self.nodes.len() - 1
-    }
+        // Propagate bounds and max_order updates up the tree
+        let mut updated_child_idx = None;
+        for &node_idx in self.insert_path.iter().rev() {
+            let node = &mut self.nodes[node_idx];
+            node.bounds = node.bounds.union(&bounds);
 
-    fn push_internal(&mut self, left: usize, right: usize) -> usize {
-        let left_node = &self.nodes[left];
-        let right_node = &self.nodes[right];
-        let new_bounds = left_node.bounds().union(right_node.bounds());
-        let max_ordering = cmp::max(left_node.max_ordering(), right_node.max_ordering());
-        self.nodes.push(Node::Internal {
-            bounds: new_bounds,
-            left,
-            right,
-            max_order: max_ordering,
-        });
-        self.nodes.len() - 1
+            if node.max_order < order {
+                node.max_order = order;
+
+                // Swap updated child to end (skip first iteration since the invariant is already handled by previous cases)
+                if let Some(child_idx) = updated_child_idx {
+                    if let NodeKind::Internal { children } = &mut node.kind {
+                        if let Some(pos) = children.as_slice().iter().position(|&c| c == child_idx)
+                        {
+                            let last = children.len() - 1;
+                            if pos != last {
+                                children.indices.swap(pos, last);
+                            }
+                        }
+                    }
+                }
+            }
+
+            updated_child_idx = Some(node_idx);
+        }
+
+        new_leaf_idx
     }
 }
 
@@ -187,50 +356,11 @@ where
 {
     fn default() -> Self {
         BoundsTree {
-            root: None,
             nodes: Vec::new(),
-            stack: Vec::new(),
-        }
-    }
-}
-
-#[derive(Debug, Clone)]
-enum Node<U>
-where
-    U: Clone + Debug + Default + PartialEq,
-{
-    Leaf {
-        bounds: Bounds<U>,
-        order: u32,
-    },
-    Internal {
-        left: usize,
-        right: usize,
-        bounds: Bounds<U>,
-        max_order: u32,
-    },
-}
-
-impl<U> Node<U>
-where
-    U: Clone + Debug + Default + PartialEq,
-{
-    fn bounds(&self) -> &Bounds<U> {
-        match self {
-            Node::Leaf { bounds, .. } => bounds,
-            Node::Internal { bounds, .. } => bounds,
-        }
-    }
-
-    fn max_ordering(&self) -> u32 {
-        match self {
-            Node::Leaf {
-                order: ordering, ..
-            } => *ordering,
-            Node::Internal {
-                max_order: max_ordering,
-                ..
-            } => *max_ordering,
+            root: None,
+            max_leaf: None,
+            insert_path: Vec::new(),
+            search_stack: Vec::new(),
         }
     }
 }

crates/gpui/src/elements/div.rs 🔗

@@ -20,8 +20,8 @@ use crate::{
     DispatchPhase, Display, Element, ElementId, Entity, FocusHandle, Global, GlobalElementId,
     Hitbox, HitboxBehavior, HitboxId, InspectorElementId, IntoElement, IsZero, KeyContext,
     KeyDownEvent, KeyUpEvent, KeyboardButton, KeyboardClickEvent, LayoutId, ModifiersChangedEvent,
-    MouseButton, MouseClickEvent, MouseDownEvent, MouseMoveEvent, MouseUpEvent, Overflow,
-    ParentElement, Pixels, Point, Render, ScrollWheelEvent, SharedString, Size, Style,
+    MouseButton, MouseClickEvent, MouseDownEvent, MouseMoveEvent, MousePressureEvent, MouseUpEvent,
+    Overflow, ParentElement, Pixels, Point, Render, ScrollWheelEvent, SharedString, Size, Style,
     StyleRefinement, Styled, Task, TooltipId, Visibility, Window, WindowControlArea, point, px,
     size,
 };
@@ -166,6 +166,38 @@ impl Interactivity {
             }));
     }
 
+    /// Bind the given callback to the mouse pressure event, during the bubble phase
+    /// the imperative API equivalent to [`InteractiveElement::on_mouse_pressure`].
+    ///
+    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
+    pub fn on_mouse_pressure(
+        &mut self,
+        listener: impl Fn(&MousePressureEvent, &mut Window, &mut App) + 'static,
+    ) {
+        self.mouse_pressure_listeners
+            .push(Box::new(move |event, phase, hitbox, window, cx| {
+                if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
+                    (listener)(event, window, cx)
+                }
+            }));
+    }
+
+    /// Bind the given callback to the mouse pressure event, during the capture phase
+    /// the imperative API equivalent to [`InteractiveElement::on_mouse_pressure`].
+    ///
+    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
+    pub fn capture_mouse_pressure(
+        &mut self,
+        listener: impl Fn(&MousePressureEvent, &mut Window, &mut App) + 'static,
+    ) {
+        self.mouse_pressure_listeners
+            .push(Box::new(move |event, phase, hitbox, window, cx| {
+                if phase == DispatchPhase::Capture && hitbox.is_hovered(window) {
+                    (listener)(event, window, cx)
+                }
+            }));
+    }
+
     /// Bind the given callback to the mouse up event for the given button, during the bubble phase.
     /// The imperative API equivalent to [`InteractiveElement::on_mouse_up`].
     ///
@@ -622,7 +654,7 @@ pub trait InteractiveElement: Sized {
     /// Set whether this element is a tab stop.
     ///
     /// When false, the element remains in tab-index order but cannot be reached via keyboard navigation.
-    /// Useful for container elements: focus the container, then call `window.focus_next()` to focus
+    /// Useful for container elements: focus the container, then call `window.focus_next(cx)` to focus
     /// the first tab stop inside it while having the container element itself be unreachable via the keyboard.
     /// Should only be used with `tab_index`.
     fn tab_stop(mut self, tab_stop: bool) -> Self {
@@ -769,6 +801,30 @@ pub trait InteractiveElement: Sized {
         self
     }
 
+    /// Bind the given callback to the mouse pressure event, during the bubble phase
+    /// the fluent API equivalent to [`Interactivity::on_mouse_pressure`]
+    ///
+    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
+    fn on_mouse_pressure(
+        mut self,
+        listener: impl Fn(&MousePressureEvent, &mut Window, &mut App) + 'static,
+    ) -> Self {
+        self.interactivity().on_mouse_pressure(listener);
+        self
+    }
+
+    /// Bind the given callback to the mouse pressure event, during the capture phase
+    /// the fluent API equivalent to [`Interactivity::on_mouse_pressure`]
+    ///
+    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
+    fn capture_mouse_pressure(
+        mut self,
+        listener: impl Fn(&MousePressureEvent, &mut Window, &mut App) + 'static,
+    ) -> Self {
+        self.interactivity().capture_mouse_pressure(listener);
+        self
+    }
+
     /// Bind the given callback to the mouse down event, on any button, during the capture phase,
     /// when the mouse is outside of the bounds of this element.
     /// The fluent API equivalent to [`Interactivity::on_mouse_down_out`].
@@ -1197,7 +1253,8 @@ pub(crate) type MouseDownListener =
     Box<dyn Fn(&MouseDownEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
 pub(crate) type MouseUpListener =
     Box<dyn Fn(&MouseUpEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
-
+pub(crate) type MousePressureListener =
+    Box<dyn Fn(&MousePressureEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
 pub(crate) type MouseMoveListener =
     Box<dyn Fn(&MouseMoveEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
 
@@ -1521,6 +1578,7 @@ pub struct Interactivity {
     pub(crate) group_drag_over_styles: Vec<(TypeId, GroupStyle)>,
     pub(crate) mouse_down_listeners: Vec<MouseDownListener>,
     pub(crate) mouse_up_listeners: Vec<MouseUpListener>,
+    pub(crate) mouse_pressure_listeners: Vec<MousePressureListener>,
     pub(crate) mouse_move_listeners: Vec<MouseMoveListener>,
     pub(crate) scroll_wheel_listeners: Vec<ScrollWheelListener>,
     pub(crate) key_down_listeners: Vec<KeyDownListener>,
@@ -1672,6 +1730,11 @@ impl Interactivity {
                         let clicked_state = clicked_state.borrow();
                         self.active = Some(clicked_state.element);
                     }
+                    if self.hover_style.is_some() || self.group_hover_style.is_some() {
+                        element_state
+                            .hover_state
+                            .get_or_insert_with(Default::default);
+                    }
                     if let Some(active_tooltip) = element_state.active_tooltip.as_ref() {
                         if self.tooltip_builder.is_some() {
                             self.tooltip_id = set_tooltip_on_window(active_tooltip, window);
@@ -1714,6 +1777,7 @@ impl Interactivity {
             || self.group_hover_style.is_some()
             || self.hover_listener.is_some()
             || !self.mouse_up_listeners.is_empty()
+            || !self.mouse_pressure_listeners.is_empty()
             || !self.mouse_down_listeners.is_empty()
             || !self.mouse_move_listeners.is_empty()
             || !self.click_listeners.is_empty()
@@ -2037,12 +2101,12 @@ impl Interactivity {
         // This behavior can be suppressed by using `cx.prevent_default()`.
         if let Some(focus_handle) = self.tracked_focus_handle.clone() {
             let hitbox = hitbox.clone();
-            window.on_mouse_event(move |_: &MouseDownEvent, phase, window, _| {
+            window.on_mouse_event(move |_: &MouseDownEvent, phase, window, cx| {
                 if phase == DispatchPhase::Bubble
                     && hitbox.is_hovered(window)
                     && !window.default_prevented()
                 {
-                    window.focus(&focus_handle);
+                    window.focus(&focus_handle, cx);
                     // If there is a parent that is also focusable, prevent it
                     // from transferring focus because we already did so.
                     window.prevent_default();
@@ -2064,6 +2128,13 @@ impl Interactivity {
             })
         }
 
+        for listener in self.mouse_pressure_listeners.drain(..) {
+            let hitbox = hitbox.clone();
+            window.on_mouse_event(move |event: &MousePressureEvent, phase, window, cx| {
+                listener(event, phase, &hitbox, window, cx);
+            })
+        }
+
         for listener in self.mouse_move_listeners.drain(..) {
             let hitbox = hitbox.clone();
             window.on_mouse_event(move |event: &MouseMoveEvent, phase, window, cx| {
@@ -2083,15 +2154,51 @@ impl Interactivity {
             || cx.active_drag.is_some() && !self.drag_over_styles.is_empty()
         {
             let hitbox = hitbox.clone();
-            let was_hovered = hitbox.is_hovered(window);
+            let hover_state = self.hover_style.as_ref().and_then(|_| {
+                element_state
+                    .as_ref()
+                    .and_then(|state| state.hover_state.as_ref())
+                    .cloned()
+            });
             let current_view = window.current_view();
+
             window.on_mouse_event(move |_: &MouseMoveEvent, phase, window, cx| {
                 let hovered = hitbox.is_hovered(window);
+                let was_hovered = hover_state
+                    .as_ref()
+                    .is_some_and(|state| state.borrow().element);
                 if phase == DispatchPhase::Capture && hovered != was_hovered {
+                    if let Some(hover_state) = &hover_state {
+                        hover_state.borrow_mut().element = hovered;
+                    }
                     cx.notify(current_view);
                 }
             });
         }
+
+        if let Some(group_hover) = self.group_hover_style.as_ref() {
+            if let Some(group_hitbox_id) = GroupHitboxes::get(&group_hover.group, cx) {
+                let hover_state = element_state
+                    .as_ref()
+                    .and_then(|element| element.hover_state.as_ref())
+                    .cloned();
+                let current_view = window.current_view();
+
+                window.on_mouse_event(move |_: &MouseMoveEvent, phase, window, cx| {
+                    let group_hovered = group_hitbox_id.is_hovered(window);
+                    let was_group_hovered = hover_state
+                        .as_ref()
+                        .is_some_and(|state| state.borrow().group);
+                    if phase == DispatchPhase::Capture && group_hovered != was_group_hovered {
+                        if let Some(hover_state) = &hover_state {
+                            hover_state.borrow_mut().group = group_hovered;
+                        }
+                        cx.notify(current_view);
+                    }
+                });
+            }
+        }
+
         let drag_cursor_style = self.base_style.as_ref().mouse_cursor;
 
         let mut drag_listener = mem::take(&mut self.drag_listener);
@@ -2280,8 +2387,8 @@ impl Interactivity {
                         && hitbox.is_hovered(window);
                     let mut was_hovered = was_hovered.borrow_mut();
 
-                    if is_hovered != *was_hovered {
-                        *was_hovered = is_hovered;
+                    if is_hovered != was_hovered.element {
+                        was_hovered.element = is_hovered;
                         drop(was_hovered);
 
                         hover_listener(&is_hovered, window, cx);
@@ -2514,22 +2621,46 @@ impl Interactivity {
             }
         }
 
-        if let Some(hitbox) = hitbox {
-            if !cx.has_active_drag() {
-                if let Some(group_hover) = self.group_hover_style.as_ref()
-                    && let Some(group_hitbox_id) = GroupHitboxes::get(&group_hover.group, cx)
-                    && group_hitbox_id.is_hovered(window)
-                {
+        if !cx.has_active_drag() {
+            if let Some(group_hover) = self.group_hover_style.as_ref() {
+                let is_group_hovered =
+                    if let Some(group_hitbox_id) = GroupHitboxes::get(&group_hover.group, cx) {
+                        group_hitbox_id.is_hovered(window)
+                    } else if let Some(element_state) = element_state.as_ref() {
+                        element_state
+                            .hover_state
+                            .as_ref()
+                            .map(|state| state.borrow().group)
+                            .unwrap_or(false)
+                    } else {
+                        false
+                    };
+
+                if is_group_hovered {
                     style.refine(&group_hover.style);
                 }
+            }
 
-                if let Some(hover_style) = self.hover_style.as_ref()
-                    && hitbox.is_hovered(window)
-                {
+            if let Some(hover_style) = self.hover_style.as_ref() {
+                let is_hovered = if let Some(hitbox) = hitbox {
+                    hitbox.is_hovered(window)
+                } else if let Some(element_state) = element_state.as_ref() {
+                    element_state
+                        .hover_state
+                        .as_ref()
+                        .map(|state| state.borrow().element)
+                        .unwrap_or(false)
+                } else {
+                    false
+                };
+
+                if is_hovered {
                     style.refine(hover_style);
                 }
             }
+        }
 
+        if let Some(hitbox) = hitbox {
             if let Some(drag) = cx.active_drag.take() {
                 let mut can_drop = true;
                 if let Some(can_drop_predicate) = &self.can_drop_predicate {
@@ -2588,7 +2719,7 @@ impl Interactivity {
 pub struct InteractiveElementState {
     pub(crate) focus_handle: Option<FocusHandle>,
     pub(crate) clicked_state: Option<Rc<RefCell<ElementClickedState>>>,
-    pub(crate) hover_state: Option<Rc<RefCell<bool>>>,
+    pub(crate) hover_state: Option<Rc<RefCell<ElementHoverState>>>,
     pub(crate) pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
     pub(crate) scroll_offset: Option<Rc<RefCell<Point<Pixels>>>>,
     pub(crate) active_tooltip: Option<Rc<RefCell<Option<ActiveTooltip>>>>,
@@ -2610,6 +2741,16 @@ impl ElementClickedState {
     }
 }
 
+/// Whether or not the element or a group that contains it is hovered.
+#[derive(Copy, Clone, Default, Eq, PartialEq)]
+pub struct ElementHoverState {
+    /// True if this element's group is hovered, false otherwise
+    pub group: bool,
+
+    /// True if this element is hovered, false otherwise
+    pub element: bool,
+}
+
 pub(crate) enum ActiveTooltip {
     /// Currently delaying before showing the tooltip.
     WaitingForShow { _task: Task<()> },
@@ -3193,7 +3334,11 @@ impl ScrollHandle {
                 match active_item.strategy {
                     ScrollStrategy::FirstVisible => {
                         if state.overflow.y == Overflow::Scroll {
-                            if bounds.top() + scroll_offset.y < state.bounds.top() {
+                            let child_height = bounds.size.height;
+                            let viewport_height = state.bounds.size.height;
+                            if child_height > viewport_height {
+                                scroll_offset.y = state.bounds.top() - bounds.top();
+                            } else if bounds.top() + scroll_offset.y < state.bounds.top() {
                                 scroll_offset.y = state.bounds.top() - bounds.top();
                             } else if bounds.bottom() + scroll_offset.y > state.bounds.bottom() {
                                 scroll_offset.y = state.bounds.bottom() - bounds.bottom();
@@ -3206,7 +3351,11 @@ impl ScrollHandle {
                 }
 
                 if state.overflow.x == Overflow::Scroll {
-                    if bounds.left() + scroll_offset.x < state.bounds.left() {
+                    let child_width = bounds.size.width;
+                    let viewport_width = state.bounds.size.width;
+                    if child_width > viewport_width {
+                        scroll_offset.x = state.bounds.left() - bounds.left();
+                    } else if bounds.left() + scroll_offset.x < state.bounds.left() {
                         scroll_offset.x = state.bounds.left() - bounds.left();
                     } else if bounds.right() + scroll_offset.x > state.bounds.right() {
                         scroll_offset.x = state.bounds.right() - bounds.right();
@@ -3268,3 +3417,46 @@ impl ScrollHandle {
         self.0.borrow().child_bounds.len()
     }
 }
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    #[test]
+    fn scroll_handle_aligns_wide_children_to_left_edge() {
+        let handle = ScrollHandle::new();
+        {
+            let mut state = handle.0.borrow_mut();
+            state.bounds = Bounds::new(point(px(0.), px(0.)), size(px(80.), px(20.)));
+            state.child_bounds = vec![Bounds::new(point(px(25.), px(0.)), size(px(200.), px(20.)))];
+            state.overflow.x = Overflow::Scroll;
+            state.active_item = Some(ScrollActiveItem {
+                index: 0,
+                strategy: ScrollStrategy::default(),
+            });
+        }
+
+        handle.scroll_to_active_item();
+
+        assert_eq!(handle.offset().x, px(-25.));
+    }
+
+    #[test]
+    fn scroll_handle_aligns_tall_children_to_top_edge() {
+        let handle = ScrollHandle::new();
+        {
+            let mut state = handle.0.borrow_mut();
+            state.bounds = Bounds::new(point(px(0.), px(0.)), size(px(20.), px(80.)));
+            state.child_bounds = vec![Bounds::new(point(px(0.), px(25.)), size(px(20.), px(200.)))];
+            state.overflow.y = Overflow::Scroll;
+            state.active_item = Some(ScrollActiveItem {
+                index: 0,
+                strategy: ScrollStrategy::default(),
+            });
+        }
+
+        handle.scroll_to_active_item();
+
+        assert_eq!(handle.offset().y, px(-25.));
+    }
+}

crates/gpui/src/elements/surface.rs 🔗

@@ -29,6 +29,7 @@ pub struct Surface {
 }
 
 /// Create a new surface element.
+#[cfg(target_os = "macos")]
 pub fn surface(source: impl Into<SurfaceSource>) -> Surface {
     Surface {
         source: source.into(),

crates/gpui/src/elements/text.rs 🔗

@@ -2,10 +2,11 @@ use crate::{
     ActiveTooltip, AnyView, App, Bounds, DispatchPhase, Element, ElementId, GlobalElementId,
     HighlightStyle, Hitbox, HitboxBehavior, InspectorElementId, IntoElement, LayoutId,
     MouseDownEvent, MouseMoveEvent, MouseUpEvent, Pixels, Point, SharedString, Size, TextOverflow,
-    TextRun, TextStyle, TooltipId, WhiteSpace, Window, WrappedLine, WrappedLineLayout,
-    register_tooltip_mouse_handlers, set_tooltip_on_window,
+    TextRun, TextStyle, TooltipId, TruncateFrom, WhiteSpace, Window, WrappedLine,
+    WrappedLineLayout, register_tooltip_mouse_handlers, set_tooltip_on_window,
 };
 use anyhow::Context as _;
+use itertools::Itertools;
 use smallvec::SmallVec;
 use std::{
     borrow::Cow,
@@ -353,7 +354,7 @@ impl TextLayout {
                     None
                 };
 
-                let (truncate_width, truncation_suffix) =
+                let (truncate_width, truncation_affix, truncate_from) =
                     if let Some(text_overflow) = text_style.text_overflow.clone() {
                         let width = known_dimensions.width.or(match available_space.width {
                             crate::AvailableSpace::Definite(x) => match text_style.line_clamp {
@@ -364,17 +365,24 @@ impl TextLayout {
                         });
 
                         match text_overflow {
-                            TextOverflow::Truncate(s) => (width, s),
+                            TextOverflow::Truncate(s) => (width, s, TruncateFrom::End),
+                            TextOverflow::TruncateStart(s) => (width, s, TruncateFrom::Start),
                         }
                     } else {
-                        (None, "".into())
+                        (None, "".into(), TruncateFrom::End)
                     };
 
+                // Only use cached layout if:
+                // 1. We have a cached size
+                // 2. wrap_width matches (or both are None)
+                // 3. truncate_width is None (if truncate_width is Some, we need to re-layout
+                //    because the previous layout may have been computed without truncation)
                 if let Some(text_layout) = element_state.0.borrow().as_ref()
-                    && text_layout.size.is_some()
+                    && let Some(size) = text_layout.size
                     && (wrap_width.is_none() || wrap_width == text_layout.wrap_width)
+                    && truncate_width.is_none()
                 {
-                    return text_layout.size.unwrap();
+                    return size;
                 }
 
                 let mut line_wrapper = cx.text_system().line_wrapper(text_style.font(), font_size);
@@ -382,8 +390,9 @@ impl TextLayout {
                     line_wrapper.truncate_line(
                         text.clone(),
                         truncate_width,
-                        &truncation_suffix,
+                        &truncation_affix,
                         &runs,
+                        truncate_from,
                     )
                 } else {
                     (text.clone(), Cow::Borrowed(&*runs))
@@ -597,14 +606,14 @@ impl TextLayout {
             .unwrap()
             .lines
             .iter()
-            .map(|s| s.text.to_string())
-            .collect::<Vec<_>>()
+            .map(|s| &s.text)
             .join("\n")
     }
 
     /// The text for this layout (with soft-wraps as newlines)
     pub fn wrapped_text(&self) -> String {
-        let mut lines = Vec::new();
+        let mut accumulator = String::new();
+
         for wrapped in self.0.borrow().as_ref().unwrap().lines.iter() {
             let mut seen = 0;
             for boundary in wrapped.layout.wrap_boundaries.iter() {
@@ -612,13 +621,16 @@ impl TextLayout {
                     [boundary.glyph_ix]
                     .index;
 
-                lines.push(wrapped.text[seen..index].to_string());
+                accumulator.push_str(&wrapped.text[seen..index]);
+                accumulator.push('\n');
                 seen = index;
             }
-            lines.push(wrapped.text[seen..].to_string());
+            accumulator.push_str(&wrapped.text[seen..]);
+            accumulator.push('\n');
         }
-
-        lines.join("\n")
+        // Remove trailing newline
+        accumulator.pop();
+        accumulator
     }
 }
 

crates/gpui/src/elements/uniform_list.rs 🔗

@@ -712,8 +712,8 @@ mod test {
     #[gpui::test]
     fn test_scroll_strategy_nearest(cx: &mut TestAppContext) {
         use crate::{
-            Context, FocusHandle, ScrollStrategy, UniformListScrollHandle, Window, actions, div,
-            prelude::*, px, uniform_list,
+            Context, FocusHandle, ScrollStrategy, UniformListScrollHandle, Window, div, prelude::*,
+            px, uniform_list,
         };
         use std::ops::Range;
 
@@ -788,7 +788,7 @@ mod test {
 
         let (view, cx) = cx.add_window_view(|window, cx| {
             let focus_handle = cx.focus_handle();
-            window.focus(&focus_handle);
+            window.focus(&focus_handle, cx);
             TestView {
                 scroll_handle: UniformListScrollHandle::new(),
                 index: 0,

crates/gpui/src/executor.rs 🔗

@@ -1,6 +1,7 @@
-use crate::{App, PlatformDispatcher, RunnableMeta, RunnableVariant};
+use crate::{App, PlatformDispatcher, RunnableMeta, RunnableVariant, TaskTiming, profiler};
 use async_task::Runnable;
 use futures::channel::mpsc;
+use parking_lot::{Condvar, Mutex};
 use smol::prelude::*;
 use std::{
     fmt::Debug,
@@ -46,6 +47,52 @@ pub struct ForegroundExecutor {
     not_send: PhantomData<Rc<()>>,
 }
 
+/// Realtime task priority
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+#[repr(u8)]
+pub enum RealtimePriority {
+    /// Audio task
+    Audio,
+    /// Other realtime task
+    #[default]
+    Other,
+}
+
+/// Task priority
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+#[repr(u8)]
+pub enum Priority {
+    /// Realtime priority
+    ///
+    /// Spawning a task with this priority will spin it off on a separate thread dedicated just to that task.
+    Realtime(RealtimePriority),
+    /// High priority
+    ///
+    /// Only use for tasks that are critical to the user experience / responsiveness of the editor.
+    High,
+    /// Medium priority, probably suits most of your use cases.
+    #[default]
+    Medium,
+    /// Low priority
+    ///
+    /// Prioritize this for background work that can come in large quantities
+    /// to not starve the executor of resources for high priority tasks
+    Low,
+}
+
+impl Priority {
+    #[allow(dead_code)]
+    pub(crate) const fn probability(&self) -> u32 {
+        match self {
+            // realtime priorities are not considered for probability scheduling
+            Priority::Realtime(_) => 0,
+            Priority::High => 60,
+            Priority::Medium => 30,
+            Priority::Low => 10,
+        }
+    }
+}
+
 /// Task is a primitive that allows work to happen in the background.
 ///
 /// It implements [`Future`] so you can `.await` on it.
@@ -151,7 +198,77 @@ impl BackgroundExecutor {
     where
         R: Send + 'static,
     {
-        self.spawn_internal::<R>(Box::pin(future), None)
+        self.spawn_with_priority(Priority::default(), future)
+    }
+
+    /// Enqueues the given future to be run to completion on a background thread.
+    #[track_caller]
+    pub fn spawn_with_priority<R>(
+        &self,
+        priority: Priority,
+        future: impl Future<Output = R> + Send + 'static,
+    ) -> Task<R>
+    where
+        R: Send + 'static,
+    {
+        self.spawn_internal::<R>(Box::pin(future), None, priority)
+    }
+
+    /// Enqueues the given future to be run to completion on a background thread and blocking the current task on it.
+    ///
+    /// This allows to spawn background work that borrows from its scope. Note that the supplied future will run to
+    /// completion before the current task is resumed, even if the current task is slated for cancellation.
+    pub async fn await_on_background<R>(&self, future: impl Future<Output = R> + Send) -> R
+    where
+        R: Send,
+    {
+        // We need to ensure that cancellation of the parent task does not drop the environment
+        // before the our own task has completed or got cancelled.
+        struct NotifyOnDrop<'a>(&'a (Condvar, Mutex<bool>));
+
+        impl Drop for NotifyOnDrop<'_> {
+            fn drop(&mut self) {
+                *self.0.1.lock() = true;
+                self.0.0.notify_all();
+            }
+        }
+
+        struct WaitOnDrop<'a>(&'a (Condvar, Mutex<bool>));
+
+        impl Drop for WaitOnDrop<'_> {
+            fn drop(&mut self) {
+                let mut done = self.0.1.lock();
+                if !*done {
+                    self.0.0.wait(&mut done);
+                }
+            }
+        }
+
+        let dispatcher = self.dispatcher.clone();
+        let location = core::panic::Location::caller();
+
+        let pair = &(Condvar::new(), Mutex::new(false));
+        let _wait_guard = WaitOnDrop(pair);
+
+        let (runnable, task) = unsafe {
+            async_task::Builder::new()
+                .metadata(RunnableMeta { location })
+                .spawn_unchecked(
+                    move |_| async {
+                        let _notify_guard = NotifyOnDrop(pair);
+                        future.await
+                    },
+                    move |runnable| {
+                        dispatcher.dispatch(
+                            RunnableVariant::Meta(runnable),
+                            None,
+                            Priority::default(),
+                        )
+                    },
+                )
+        };
+        runnable.schedule();
+        task.await
     }
 
     /// Enqueues the given future to be run to completion on a background thread.
@@ -165,7 +282,7 @@ impl BackgroundExecutor {
     where
         R: Send + 'static,
     {
-        self.spawn_internal::<R>(Box::pin(future), Some(label))
+        self.spawn_internal::<R>(Box::pin(future), Some(label), Priority::default())
     }
 
     #[track_caller]
@@ -173,15 +290,65 @@ impl BackgroundExecutor {
         &self,
         future: AnyFuture<R>,
         label: Option<TaskLabel>,
+        #[cfg_attr(
+            target_os = "windows",
+            expect(
+                unused_variables,
+                reason = "Multi priority scheduler is broken on windows"
+            )
+        )]
+        priority: Priority,
     ) -> Task<R> {
         let dispatcher = self.dispatcher.clone();
-        let location = core::panic::Location::caller();
-        let (runnable, task) = async_task::Builder::new()
-            .metadata(RunnableMeta { location })
-            .spawn(
-                move |_| future,
-                move |runnable| dispatcher.dispatch(RunnableVariant::Meta(runnable), label),
+        #[cfg(target_os = "windows")]
+        let priority = Priority::Medium; // multi-prio scheduler is broken on windows
+
+        let (runnable, task) = if let Priority::Realtime(realtime) = priority {
+            let location = core::panic::Location::caller();
+            let (mut tx, rx) = flume::bounded::<Runnable<RunnableMeta>>(1);
+
+            dispatcher.spawn_realtime(
+                realtime,
+                Box::new(move || {
+                    while let Ok(runnable) = rx.recv() {
+                        let start = Instant::now();
+                        let location = runnable.metadata().location;
+                        let mut timing = TaskTiming {
+                            location,
+                            start,
+                            end: None,
+                        };
+                        profiler::add_task_timing(timing);
+
+                        runnable.run();
+
+                        let end = Instant::now();
+                        timing.end = Some(end);
+                        profiler::add_task_timing(timing);
+                    }
+                }),
             );
+
+            async_task::Builder::new()
+                .metadata(RunnableMeta { location })
+                .spawn(
+                    move |_| future,
+                    move |runnable| {
+                        let _ = tx.send(runnable);
+                    },
+                )
+        } else {
+            let location = core::panic::Location::caller();
+            async_task::Builder::new()
+                .metadata(RunnableMeta { location })
+                .spawn(
+                    move |_| future,
+                    move |runnable| {
+                        dispatcher.dispatch(RunnableVariant::Meta(runnable), label, priority)
+                    },
+                )
+        };
+
         runnable.schedule();
         Task(TaskState::Spawned(task))
     }
@@ -354,11 +521,28 @@ impl BackgroundExecutor {
     where
         F: FnOnce(&mut Scope<'scope>),
     {
-        let mut scope = Scope::new(self.clone());
+        let mut scope = Scope::new(self.clone(), Priority::default());
         (scheduler)(&mut scope);
         let spawned = mem::take(&mut scope.futures)
             .into_iter()
-            .map(|f| self.spawn(f))
+            .map(|f| self.spawn_with_priority(scope.priority, f))
+            .collect::<Vec<_>>();
+        for task in spawned {
+            task.await;
+        }
+    }
+
+    /// Scoped lets you start a number of tasks and waits
+    /// for all of them to complete before returning.
+    pub async fn scoped_priority<'scope, F>(&self, priority: Priority, scheduler: F)
+    where
+        F: FnOnce(&mut Scope<'scope>),
+    {
+        let mut scope = Scope::new(self.clone(), priority);
+        (scheduler)(&mut scope);
+        let spawned = mem::take(&mut scope.futures)
+            .into_iter()
+            .map(|f| self.spawn_with_priority(scope.priority, f))
             .collect::<Vec<_>>();
         for task in spawned {
             task.await;
@@ -494,6 +678,19 @@ impl ForegroundExecutor {
     /// Enqueues the given Task to run on the main thread at some point in the future.
     #[track_caller]
     pub fn spawn<R>(&self, future: impl Future<Output = R> + 'static) -> Task<R>
+    where
+        R: 'static,
+    {
+        self.spawn_with_priority(Priority::default(), future)
+    }
+
+    /// Enqueues the given Task to run on the main thread at some point in the future.
+    #[track_caller]
+    pub fn spawn_with_priority<R>(
+        &self,
+        priority: Priority,
+        future: impl Future<Output = R> + 'static,
+    ) -> Task<R>
     where
         R: 'static,
     {
@@ -505,16 +702,19 @@ impl ForegroundExecutor {
             dispatcher: Arc<dyn PlatformDispatcher>,
             future: AnyLocalFuture<R>,
             location: &'static core::panic::Location<'static>,
+            priority: Priority,
         ) -> Task<R> {
             let (runnable, task) = spawn_local_with_source_location(
                 future,
-                move |runnable| dispatcher.dispatch_on_main_thread(RunnableVariant::Meta(runnable)),
+                move |runnable| {
+                    dispatcher.dispatch_on_main_thread(RunnableVariant::Meta(runnable), priority)
+                },
                 RunnableMeta { location },
             );
             runnable.schedule();
             Task(TaskState::Spawned(task))
         }
-        inner::<R>(dispatcher, Box::pin(future), location)
+        inner::<R>(dispatcher, Box::pin(future), location, priority)
     }
 }
 
@@ -590,6 +790,7 @@ where
 /// Scope manages a set of tasks that are enqueued and waited on together. See [`BackgroundExecutor::scoped`].
 pub struct Scope<'a> {
     executor: BackgroundExecutor,
+    priority: Priority,
     futures: Vec<Pin<Box<dyn Future<Output = ()> + Send + 'static>>>,
     tx: Option<mpsc::Sender<()>>,
     rx: mpsc::Receiver<()>,
@@ -597,10 +798,11 @@ pub struct Scope<'a> {
 }
 
 impl<'a> Scope<'a> {
-    fn new(executor: BackgroundExecutor) -> Self {
+    fn new(executor: BackgroundExecutor, priority: Priority) -> Self {
         let (tx, rx) = mpsc::channel(1);
         Self {
             executor,
+            priority,
             tx: Some(tx),
             rx,
             futures: Default::default(),

crates/gpui/src/geometry.rs 🔗

@@ -1416,9 +1416,9 @@ where
     /// ```
     pub fn contains(&self, point: &Point<T>) -> bool {
         point.x >= self.origin.x
-            && point.x <= self.origin.x.clone() + self.size.width.clone()
+            && point.x < self.origin.x.clone() + self.size.width.clone()
             && point.y >= self.origin.y
-            && point.y <= self.origin.y.clone() + self.size.height.clone()
+            && point.y < self.origin.y.clone() + self.size.height.clone()
     }
 
     /// Checks if this bounds is completely contained within another bounds.
@@ -2648,6 +2648,18 @@ impl Debug for Pixels {
     }
 }
 
+impl std::iter::Sum for Pixels {
+    fn sum<I: Iterator<Item = Self>>(iter: I) -> Self {
+        iter.fold(Self::ZERO, |a, b| a + b)
+    }
+}
+
+impl<'a> std::iter::Sum<&'a Pixels> for Pixels {
+    fn sum<I: Iterator<Item = &'a Self>>(iter: I) -> Self {
+        iter.fold(Self::ZERO, |a, b| a + *b)
+    }
+}
+
 impl TryFrom<&'_ str> for Pixels {
     type Error = anyhow::Error;
 
@@ -3567,7 +3579,7 @@ pub const fn relative(fraction: f32) -> DefiniteLength {
 }
 
 /// Returns the Golden Ratio, i.e. `~(1.0 + sqrt(5.0)) / 2.0`.
-pub fn phi() -> DefiniteLength {
+pub const fn phi() -> DefiniteLength {
     relative(1.618_034)
 }
 
@@ -3580,7 +3592,7 @@ pub fn phi() -> DefiniteLength {
 /// # Returns
 ///
 /// A `Rems` representing the specified number of rems.
-pub fn rems(rems: f32) -> Rems {
+pub const fn rems(rems: f32) -> Rems {
     Rems(rems)
 }
 
@@ -3608,7 +3620,7 @@ pub const fn px(pixels: f32) -> Pixels {
 /// # Returns
 ///
 /// A `Length` variant set to `Auto`.
-pub fn auto() -> Length {
+pub const fn auto() -> Length {
     Length::Auto
 }
 

crates/gpui/src/gpui.rs 🔗

@@ -31,6 +31,8 @@ mod path_builder;
 mod platform;
 pub mod prelude;
 mod profiler;
+#[cfg(target_os = "linux")]
+mod queue;
 mod scene;
 mod shared_string;
 mod shared_uri;
@@ -89,16 +91,20 @@ pub use keymap::*;
 pub use path_builder::*;
 pub use platform::*;
 pub use profiler::*;
+#[cfg(target_os = "linux")]
+pub(crate) use queue::{PriorityQueueReceiver, PriorityQueueSender};
 pub use refineable::*;
 pub use scene::*;
 pub use shared_string::*;
 pub use shared_uri::*;
 pub use smol::Timer;
+use std::{any::Any, future::Future};
 pub use style::*;
 pub use styled::*;
 pub use subscription::*;
 pub use svg_renderer::*;
 pub(crate) use tab_stop::*;
+use taffy::TaffyLayoutEngine;
 pub use taffy::{AvailableSpace, LayoutId};
 #[cfg(any(test, feature = "test-support"))]
 pub use test::*;
@@ -109,9 +115,6 @@ pub use util::{FutureExt, Timeout, arc_cow::ArcCow};
 pub use view::*;
 pub use window::*;
 
-use std::{any::Any, future::Future};
-use taffy::TaffyLayoutEngine;
-
 /// The context trait, allows the different contexts in GPUI to be used
 /// interchangeably for certain operations.
 pub trait AppContext {

crates/gpui/src/interactive.rs 🔗

@@ -174,6 +174,40 @@ pub struct MouseClickEvent {
     pub up: MouseUpEvent,
 }
 
+/// The stage of a pressure click event.
+#[derive(Clone, Copy, Debug, Default, PartialEq)]
+pub enum PressureStage {
+    /// No pressure.
+    #[default]
+    Zero,
+    /// Normal click pressure.
+    Normal,
+    /// High pressure, enough to trigger a force click.
+    Force,
+}
+
+/// A mouse pressure event from the platform. Generated when a force-sensitive trackpad is pressed hard.
+/// Currently only implemented for macOS trackpads.
+#[derive(Debug, Clone, Default)]
+pub struct MousePressureEvent {
+    /// Pressure of the current stage as a float between 0 and 1
+    pub pressure: f32,
+    /// The pressure stage of the event.
+    pub stage: PressureStage,
+    /// The position of the mouse on the window.
+    pub position: Point<Pixels>,
+    /// The modifiers that were held down when the mouse pressure changed.
+    pub modifiers: Modifiers,
+}
+
+impl Sealed for MousePressureEvent {}
+impl InputEvent for MousePressureEvent {
+    fn to_platform_input(self) -> PlatformInput {
+        PlatformInput::MousePressure(self)
+    }
+}
+impl MouseEvent for MousePressureEvent {}
+
 /// A click event that was generated by a keyboard button being pressed and released.
 #[derive(Clone, Debug, Default)]
 pub struct KeyboardClickEvent {
@@ -571,6 +605,8 @@ pub enum PlatformInput {
     MouseDown(MouseDownEvent),
     /// The mouse was released.
     MouseUp(MouseUpEvent),
+    /// Mouse pressure.
+    MousePressure(MousePressureEvent),
     /// The mouse was moved.
     MouseMove(MouseMoveEvent),
     /// The mouse exited the window.
@@ -590,6 +626,7 @@ impl PlatformInput {
             PlatformInput::MouseDown(event) => Some(event),
             PlatformInput::MouseUp(event) => Some(event),
             PlatformInput::MouseMove(event) => Some(event),
+            PlatformInput::MousePressure(event) => Some(event),
             PlatformInput::MouseExited(event) => Some(event),
             PlatformInput::ScrollWheel(event) => Some(event),
             PlatformInput::FileDrop(event) => Some(event),
@@ -604,6 +641,7 @@ impl PlatformInput {
             PlatformInput::MouseDown(_) => None,
             PlatformInput::MouseUp(_) => None,
             PlatformInput::MouseMove(_) => None,
+            PlatformInput::MousePressure(_) => None,
             PlatformInput::MouseExited(_) => None,
             PlatformInput::ScrollWheel(_) => None,
             PlatformInput::FileDrop(_) => None,
@@ -667,8 +705,8 @@ mod test {
         });
 
         window
-            .update(cx, |test_view, window, _cx| {
-                window.focus(&test_view.focus_handle)
+            .update(cx, |test_view, window, cx| {
+                window.focus(&test_view.focus_handle, cx)
             })
             .unwrap();
 

crates/gpui/src/key_dispatch.rs 🔗

@@ -462,6 +462,17 @@ impl DispatchTree {
         (bindings, partial, context_stack)
     }
 
+    /// Find the bindings that can follow the current input sequence.
+    pub fn possible_next_bindings_for_input(
+        &self,
+        input: &[Keystroke],
+        context_stack: &[KeyContext],
+    ) -> Vec<KeyBinding> {
+        self.keymap
+            .borrow()
+            .possible_next_bindings_for_input(input, context_stack)
+    }
+
     /// dispatch_key processes the keystroke
     /// input should be set to the value of `pending` from the previous call to dispatch_key.
     /// This returns three instructions to the input handler:
@@ -610,8 +621,8 @@ impl DispatchTree {
 #[cfg(test)]
 mod tests {
     use crate::{
-        self as gpui, DispatchResult, Element, ElementId, GlobalElementId, InspectorElementId,
-        Keystroke, LayoutId, Style,
+        self as gpui, AppContext, DispatchResult, Element, ElementId, GlobalElementId,
+        InspectorElementId, Keystroke, LayoutId, Style,
     };
     use core::panic;
     use smallvec::SmallVec;
@@ -619,8 +630,8 @@ mod tests {
 
     use crate::{
         Action, ActionRegistry, App, Bounds, Context, DispatchTree, FocusHandle, InputHandler,
-        IntoElement, KeyBinding, KeyContext, Keymap, Pixels, Point, Render, TestAppContext,
-        UTF16Selection, Window,
+        IntoElement, KeyBinding, KeyContext, Keymap, Pixels, Point, Render, Subscription,
+        TestAppContext, UTF16Selection, Window,
     };
 
     #[derive(PartialEq, Eq)]
@@ -723,6 +734,213 @@ mod tests {
         assert!(!result.pending_has_binding);
     }
 
+    #[crate::test]
+    fn test_pending_input_observers_notified_on_focus_change(cx: &mut TestAppContext) {
+        #[derive(Clone)]
+        struct CustomElement {
+            focus_handle: FocusHandle,
+            text: Rc<RefCell<String>>,
+        }
+
+        impl CustomElement {
+            fn new(cx: &mut Context<Self>) -> Self {
+                Self {
+                    focus_handle: cx.focus_handle(),
+                    text: Rc::default(),
+                }
+            }
+        }
+
+        impl Element for CustomElement {
+            type RequestLayoutState = ();
+
+            type PrepaintState = ();
+
+            fn id(&self) -> Option<ElementId> {
+                Some("custom".into())
+            }
+
+            fn source_location(&self) -> Option<&'static panic::Location<'static>> {
+                None
+            }
+
+            fn request_layout(
+                &mut self,
+                _: Option<&GlobalElementId>,
+                _: Option<&InspectorElementId>,
+                window: &mut Window,
+                cx: &mut App,
+            ) -> (LayoutId, Self::RequestLayoutState) {
+                (window.request_layout(Style::default(), [], cx), ())
+            }
+
+            fn prepaint(
+                &mut self,
+                _: Option<&GlobalElementId>,
+                _: Option<&InspectorElementId>,
+                _: Bounds<Pixels>,
+                _: &mut Self::RequestLayoutState,
+                window: &mut Window,
+                cx: &mut App,
+            ) -> Self::PrepaintState {
+                window.set_focus_handle(&self.focus_handle, cx);
+            }
+
+            fn paint(
+                &mut self,
+                _: Option<&GlobalElementId>,
+                _: Option<&InspectorElementId>,
+                _: Bounds<Pixels>,
+                _: &mut Self::RequestLayoutState,
+                _: &mut Self::PrepaintState,
+                window: &mut Window,
+                cx: &mut App,
+            ) {
+                let mut key_context = KeyContext::default();
+                key_context.add("Terminal");
+                window.set_key_context(key_context);
+                window.handle_input(&self.focus_handle, self.clone(), cx);
+                window.on_action(std::any::TypeId::of::<TestAction>(), |_, _, _, _| {});
+            }
+        }
+
+        impl IntoElement for CustomElement {
+            type Element = Self;
+
+            fn into_element(self) -> Self::Element {
+                self
+            }
+        }
+
+        impl InputHandler for CustomElement {
+            fn selected_text_range(
+                &mut self,
+                _: bool,
+                _: &mut Window,
+                _: &mut App,
+            ) -> Option<UTF16Selection> {
+                None
+            }
+
+            fn marked_text_range(&mut self, _: &mut Window, _: &mut App) -> Option<Range<usize>> {
+                None
+            }
+
+            fn text_for_range(
+                &mut self,
+                _: Range<usize>,
+                _: &mut Option<Range<usize>>,
+                _: &mut Window,
+                _: &mut App,
+            ) -> Option<String> {
+                None
+            }
+
+            fn replace_text_in_range(
+                &mut self,
+                replacement_range: Option<Range<usize>>,
+                text: &str,
+                _: &mut Window,
+                _: &mut App,
+            ) {
+                if replacement_range.is_some() {
+                    unimplemented!()
+                }
+                self.text.borrow_mut().push_str(text)
+            }
+
+            fn replace_and_mark_text_in_range(
+                &mut self,
+                replacement_range: Option<Range<usize>>,
+                new_text: &str,
+                _: Option<Range<usize>>,
+                _: &mut Window,
+                _: &mut App,
+            ) {
+                if replacement_range.is_some() {
+                    unimplemented!()
+                }
+                self.text.borrow_mut().push_str(new_text)
+            }
+
+            fn unmark_text(&mut self, _: &mut Window, _: &mut App) {}
+
+            fn bounds_for_range(
+                &mut self,
+                _: Range<usize>,
+                _: &mut Window,
+                _: &mut App,
+            ) -> Option<Bounds<Pixels>> {
+                None
+            }
+
+            fn character_index_for_point(
+                &mut self,
+                _: Point<Pixels>,
+                _: &mut Window,
+                _: &mut App,
+            ) -> Option<usize> {
+                None
+            }
+        }
+
+        impl Render for CustomElement {
+            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
+                self.clone()
+            }
+        }
+
+        cx.update(|cx| {
+            cx.bind_keys([KeyBinding::new("ctrl-b", TestAction, Some("Terminal"))]);
+            cx.bind_keys([KeyBinding::new("ctrl-b h", TestAction, Some("Terminal"))]);
+        });
+
+        let (test, cx) = cx.add_window_view(|_, cx| CustomElement::new(cx));
+        let focus_handle = test.update(cx, |test, _| test.focus_handle.clone());
+
+        let pending_input_changed_count = Rc::new(RefCell::new(0usize));
+        let pending_input_changed_count_for_observer = pending_input_changed_count.clone();
+
+        struct PendingInputObserver {
+            _subscription: Subscription,
+        }
+
+        let _observer = cx.update(|window, cx| {
+            cx.new(|cx| PendingInputObserver {
+                _subscription: cx.observe_pending_input(window, move |_, _, _| {
+                    *pending_input_changed_count_for_observer.borrow_mut() += 1;
+                }),
+            })
+        });
+
+        cx.update(|window, cx| {
+            window.focus(&focus_handle, cx);
+            window.activate_window();
+        });
+
+        cx.simulate_keystrokes("ctrl-b");
+
+        let count_after_pending = Rc::new(RefCell::new(0usize));
+        let count_after_pending_for_assertion = count_after_pending.clone();
+
+        cx.update(|window, cx| {
+            assert!(window.has_pending_keystrokes());
+            *count_after_pending.borrow_mut() = *pending_input_changed_count.borrow();
+            assert!(*count_after_pending.borrow() > 0);
+
+            window.focus(&cx.focus_handle(), cx);
+
+            assert!(!window.has_pending_keystrokes());
+        });
+
+        // Focus-triggered pending-input notifications are deferred to the end of the current
+        // effect cycle, so the observer callback should run after the focus update completes.
+        cx.update(|_, _| {
+            let count_after_focus_change = *pending_input_changed_count.borrow();
+            assert!(count_after_focus_change > *count_after_pending_for_assertion.borrow());
+        });
+    }
+
     #[crate::test]
     fn test_input_handler_pending(cx: &mut TestAppContext) {
         #[derive(Clone)]
@@ -876,8 +1094,9 @@ mod tests {
             cx.bind_keys([KeyBinding::new("ctrl-b h", TestAction, Some("Terminal"))]);
         });
         let (test, cx) = cx.add_window_view(|_, cx| CustomElement::new(cx));
+        let focus_handle = test.update(cx, |test, _| test.focus_handle.clone());
         cx.update(|window, cx| {
-            window.focus(&test.read(cx).focus_handle);
+            window.focus(&focus_handle, cx);
             window.activate_window();
         });
         cx.simulate_keystrokes("ctrl-b [");

crates/gpui/src/keymap.rs 🔗

@@ -215,6 +215,41 @@ impl Keymap {
             Some(contexts.len())
         }
     }
+
+    /// Find the bindings that can follow the current input sequence.
+    pub fn possible_next_bindings_for_input(
+        &self,
+        input: &[Keystroke],
+        context_stack: &[KeyContext],
+    ) -> Vec<KeyBinding> {
+        let mut bindings = self
+            .bindings()
+            .enumerate()
+            .rev()
+            .filter_map(|(ix, binding)| {
+                let depth = self.binding_enabled(binding, context_stack)?;
+                let pending = binding.match_keystrokes(input);
+                match pending {
+                    None => None,
+                    Some(is_pending) => {
+                        if !is_pending || is_no_action(&*binding.action) {
+                            return None;
+                        }
+                        Some((depth, BindingIndex(ix), binding))
+                    }
+                }
+            })
+            .collect::<Vec<_>>();
+
+        bindings.sort_by(|(depth_a, ix_a, _), (depth_b, ix_b, _)| {
+            depth_b.cmp(depth_a).then(ix_b.cmp(ix_a))
+        });
+
+        bindings
+            .into_iter()
+            .map(|(_, _, binding)| binding.clone())
+            .collect::<Vec<_>>()
+    }
 }
 
 #[cfg(test)]

crates/gpui/src/platform.rs 🔗

@@ -39,9 +39,10 @@ use crate::{
     Action, AnyWindowHandle, App, AsyncWindowContext, BackgroundExecutor, Bounds,
     DEFAULT_WINDOW_SIZE, DevicePixels, DispatchEventResult, Font, FontId, FontMetrics, FontRun,
     ForegroundExecutor, GlyphId, GpuSpecs, ImageSource, Keymap, LineLayout, Pixels, PlatformInput,
-    Point, RenderGlyphParams, RenderImage, RenderImageParams, RenderSvgParams, Scene, ShapedGlyph,
-    ShapedRun, SharedString, Size, SvgRenderer, SystemWindowTab, Task, TaskLabel, TaskTiming,
-    ThreadTaskTimings, Window, WindowControlArea, hash, point, px, size,
+    Point, Priority, RealtimePriority, RenderGlyphParams, RenderImage, RenderImageParams,
+    RenderSvgParams, Scene, ShapedGlyph, ShapedRun, SharedString, Size, SvgRenderer,
+    SystemWindowTab, Task, TaskLabel, TaskTiming, ThreadTaskTimings, Window, WindowControlArea,
+    hash, point, px, size,
 };
 use anyhow::Result;
 use async_task::Runnable;
@@ -261,12 +262,18 @@ pub(crate) trait Platform: 'static {
     fn set_cursor_style(&self, style: CursorStyle);
     fn should_auto_hide_scrollbars(&self) -> bool;
 
-    #[cfg(any(target_os = "linux", target_os = "freebsd"))]
-    fn write_to_primary(&self, item: ClipboardItem);
+    fn read_from_clipboard(&self) -> Option<ClipboardItem>;
     fn write_to_clipboard(&self, item: ClipboardItem);
+
     #[cfg(any(target_os = "linux", target_os = "freebsd"))]
     fn read_from_primary(&self) -> Option<ClipboardItem>;
-    fn read_from_clipboard(&self) -> Option<ClipboardItem>;
+    #[cfg(any(target_os = "linux", target_os = "freebsd"))]
+    fn write_to_primary(&self, item: ClipboardItem);
+
+    #[cfg(target_os = "macos")]
+    fn read_from_find_pasteboard(&self) -> Option<ClipboardItem>;
+    #[cfg(target_os = "macos")]
+    fn write_to_find_pasteboard(&self, item: ClipboardItem);
 
     fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>>;
     fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>>;
@@ -289,6 +296,13 @@ pub trait PlatformDisplay: Send + Sync + Debug {
     /// Get the bounds for this display
     fn bounds(&self) -> Bounds<Pixels>;
 
+    /// Get the visible bounds for this display, excluding taskbar/dock areas.
+    /// This is the usable area where windows can be placed without being obscured.
+    /// Defaults to the full display bounds if not overridden.
+    fn visible_bounds(&self) -> Bounds<Pixels> {
+        self.bounds()
+    }
+
     /// Get the default bounds for this display to place a window
     fn default_bounds(&self) -> Bounds<Pixels> {
         let bounds = self.bounds();
@@ -580,9 +594,10 @@ pub trait PlatformDispatcher: Send + Sync {
     fn get_all_timings(&self) -> Vec<ThreadTaskTimings>;
     fn get_current_thread_timings(&self) -> Vec<TaskTiming>;
     fn is_main_thread(&self) -> bool;
-    fn dispatch(&self, runnable: RunnableVariant, label: Option<TaskLabel>);
-    fn dispatch_on_main_thread(&self, runnable: RunnableVariant);
+    fn dispatch(&self, runnable: RunnableVariant, label: Option<TaskLabel>, priority: Priority);
+    fn dispatch_on_main_thread(&self, runnable: RunnableVariant, priority: Priority);
     fn dispatch_after(&self, duration: Duration, runnable: RunnableVariant);
+    fn spawn_realtime(&self, priority: RealtimePriority, f: Box<dyn FnOnce() + Send>);
 
     fn now(&self) -> Instant {
         Instant::now()
@@ -1339,6 +1354,10 @@ pub enum WindowKind {
     /// docks, notifications or wallpapers.
     #[cfg(all(target_os = "linux", feature = "wayland"))]
     LayerShell(layer_shell::LayerShellOptions),
+
+    /// A window that appears on top of its parent window and blocks interaction with it
+    /// until the modal window is closed
+    Dialog,
 }
 
 /// The appearance of the window, as defined by the operating system.

crates/gpui/src/platform/linux/dispatcher.rs 🔗

@@ -1,17 +1,21 @@
-use crate::{
-    GLOBAL_THREAD_TIMINGS, PlatformDispatcher, RunnableVariant, THREAD_TIMINGS, TaskLabel,
-    TaskTiming, ThreadTaskTimings,
-};
 use calloop::{
-    EventLoop,
+    EventLoop, PostAction,
     channel::{self, Sender},
     timer::TimeoutAction,
 };
+use util::ResultExt;
+
 use std::{
+    mem::MaybeUninit,
     thread,
     time::{Duration, Instant},
 };
-use util::ResultExt;
+
+use crate::{
+    GLOBAL_THREAD_TIMINGS, PlatformDispatcher, Priority, PriorityQueueReceiver,
+    PriorityQueueSender, RealtimePriority, RunnableVariant, THREAD_TIMINGS, TaskLabel, TaskTiming,
+    ThreadTaskTimings, profiler,
+};
 
 struct TimerAfter {
     duration: Duration,
@@ -19,27 +23,30 @@ struct TimerAfter {
 }
 
 pub(crate) struct LinuxDispatcher {
-    main_sender: Sender<RunnableVariant>,
+    main_sender: PriorityQueueCalloopSender<RunnableVariant>,
     timer_sender: Sender<TimerAfter>,
-    background_sender: flume::Sender<RunnableVariant>,
+    background_sender: PriorityQueueSender<RunnableVariant>,
     _background_threads: Vec<thread::JoinHandle<()>>,
     main_thread_id: thread::ThreadId,
 }
 
+const MIN_THREADS: usize = 2;
+
 impl LinuxDispatcher {
-    pub fn new(main_sender: Sender<RunnableVariant>) -> Self {
-        let (background_sender, background_receiver) = flume::unbounded::<RunnableVariant>();
-        let thread_count = std::thread::available_parallelism()
-            .map(|i| i.get())
-            .unwrap_or(1);
+    pub fn new(main_sender: PriorityQueueCalloopSender<RunnableVariant>) -> Self {
+        let (background_sender, background_receiver) = PriorityQueueReceiver::new();
+        let thread_count =
+            std::thread::available_parallelism().map_or(MIN_THREADS, |i| i.get().max(MIN_THREADS));
 
+        // These thread should really be lower prio then the foreground
+        // executor
         let mut background_threads = (0..thread_count)
             .map(|i| {
-                let receiver = background_receiver.clone();
+                let mut receiver = background_receiver.clone();
                 std::thread::Builder::new()
                     .name(format!("Worker-{i}"))
                     .spawn(move || {
-                        for runnable in receiver {
+                        for runnable in receiver.iter() {
                             let start = Instant::now();
 
                             let mut location = match runnable {
@@ -50,7 +57,7 @@ impl LinuxDispatcher {
                                         start,
                                         end: None,
                                     };
-                                    Self::add_task_timing(timing);
+                                    profiler::add_task_timing(timing);
 
                                     runnable.run();
                                     timing
@@ -62,7 +69,7 @@ impl LinuxDispatcher {
                                         start,
                                         end: None,
                                     };
-                                    Self::add_task_timing(timing);
+                                    profiler::add_task_timing(timing);
 
                                     runnable.run();
                                     timing
@@ -71,7 +78,7 @@ impl LinuxDispatcher {
 
                             let end = Instant::now();
                             location.end = Some(end);
-                            Self::add_task_timing(location);
+                            profiler::add_task_timing(location);
 
                             log::trace!(
                                 "background thread {}: ran runnable. took: {:?}",
@@ -112,7 +119,7 @@ impl LinuxDispatcher {
                                                         start,
                                                         end: None,
                                                     };
-                                                    Self::add_task_timing(timing);
+                                                    profiler::add_task_timing(timing);
 
                                                     runnable.run();
                                                     timing
@@ -123,7 +130,7 @@ impl LinuxDispatcher {
                                                         start,
                                                         end: None,
                                                     };
-                                                    Self::add_task_timing(timing);
+                                                    profiler::add_task_timing(timing);
 
                                                     runnable.run();
                                                     timing
@@ -132,7 +139,7 @@ impl LinuxDispatcher {
                                             let end = Instant::now();
 
                                             timing.end = Some(end);
-                                            Self::add_task_timing(timing);
+                                            profiler::add_task_timing(timing);
                                         }
                                         TimeoutAction::Drop
                                     },
@@ -156,22 +163,6 @@ impl LinuxDispatcher {
             main_thread_id: thread::current().id(),
         }
     }
-
-    pub(crate) fn add_task_timing(timing: TaskTiming) {
-        THREAD_TIMINGS.with(|timings| {
-            let mut timings = timings.lock();
-            let timings = &mut timings.timings;
-
-            if let Some(last_timing) = timings.iter_mut().rev().next() {
-                if last_timing.location == timing.location {
-                    last_timing.end = timing.end;
-                    return;
-                }
-            }
-
-            timings.push_back(timing);
-        });
-    }
 }
 
 impl PlatformDispatcher for LinuxDispatcher {
@@ -198,22 +189,26 @@ impl PlatformDispatcher for LinuxDispatcher {
         thread::current().id() == self.main_thread_id
     }
 
-    fn dispatch(&self, runnable: RunnableVariant, _: Option<TaskLabel>) {
-        self.background_sender.send(runnable).unwrap();
+    fn dispatch(&self, runnable: RunnableVariant, _: Option<TaskLabel>, priority: Priority) {
+        self.background_sender
+            .send(priority, runnable)
+            .unwrap_or_else(|_| panic!("blocking sender returned without value"));
     }
 
-    fn dispatch_on_main_thread(&self, runnable: RunnableVariant) {
-        self.main_sender.send(runnable).unwrap_or_else(|runnable| {
-            // NOTE: Runnable may wrap a Future that is !Send.
-            //
-            // This is usually safe because we only poll it on the main thread.
-            // However if the send fails, we know that:
-            // 1. main_receiver has been dropped (which implies the app is shutting down)
-            // 2. we are on a background thread.
-            // It is not safe to drop something !Send on the wrong thread, and
-            // the app will exit soon anyway, so we must forget the runnable.
-            std::mem::forget(runnable);
-        });
+    fn dispatch_on_main_thread(&self, runnable: RunnableVariant, priority: Priority) {
+        self.main_sender
+            .send(priority, runnable)
+            .unwrap_or_else(|runnable| {
+                // NOTE: Runnable may wrap a Future that is !Send.
+                //
+                // This is usually safe because we only poll it on the main thread.
+                // However if the send fails, we know that:
+                // 1. main_receiver has been dropped (which implies the app is shutting down)
+                // 2. we are on a background thread.
+                // It is not safe to drop something !Send on the wrong thread, and
+                // the app will exit soon anyway, so we must forget the runnable.
+                std::mem::forget(runnable);
+            });
     }
 
     fn dispatch_after(&self, duration: Duration, runnable: RunnableVariant) {
@@ -221,4 +216,255 @@ impl PlatformDispatcher for LinuxDispatcher {
             .send(TimerAfter { duration, runnable })
             .ok();
     }
+
+    fn spawn_realtime(&self, priority: RealtimePriority, f: Box<dyn FnOnce() + Send>) {
+        std::thread::spawn(move || {
+            // SAFETY: always safe to call
+            let thread_id = unsafe { libc::pthread_self() };
+
+            let policy = match priority {
+                RealtimePriority::Audio => libc::SCHED_FIFO,
+                RealtimePriority::Other => libc::SCHED_RR,
+            };
+            let sched_priority = match priority {
+                RealtimePriority::Audio => 65,
+                RealtimePriority::Other => 45,
+            };
+
+            // SAFETY: all sched_param members are valid when initialized to zero.
+            let mut sched_param =
+                unsafe { MaybeUninit::<libc::sched_param>::zeroed().assume_init() };
+            sched_param.sched_priority = sched_priority;
+            // SAFETY: sched_param is a valid initialized structure
+            let result = unsafe { libc::pthread_setschedparam(thread_id, policy, &sched_param) };
+            if result != 0 {
+                log::warn!("failed to set realtime thread priority to {:?}", priority);
+            }
+
+            f();
+        });
+    }
+}
+
+pub struct PriorityQueueCalloopSender<T> {
+    sender: PriorityQueueSender<T>,
+    ping: calloop::ping::Ping,
+}
+
+impl<T> PriorityQueueCalloopSender<T> {
+    fn new(tx: PriorityQueueSender<T>, ping: calloop::ping::Ping) -> Self {
+        Self { sender: tx, ping }
+    }
+
+    fn send(&self, priority: Priority, item: T) -> Result<(), crate::queue::SendError<T>> {
+        let res = self.sender.send(priority, item);
+        if res.is_ok() {
+            self.ping.ping();
+        }
+        res
+    }
+}
+
+impl<T> Drop for PriorityQueueCalloopSender<T> {
+    fn drop(&mut self) {
+        self.ping.ping();
+    }
+}
+
+pub struct PriorityQueueCalloopReceiver<T> {
+    receiver: PriorityQueueReceiver<T>,
+    source: calloop::ping::PingSource,
+    ping: calloop::ping::Ping,
+}
+
+impl<T> PriorityQueueCalloopReceiver<T> {
+    pub fn new() -> (PriorityQueueCalloopSender<T>, Self) {
+        let (ping, source) = calloop::ping::make_ping().expect("Failed to create a Ping.");
+
+        let (tx, rx) = PriorityQueueReceiver::new();
+
+        (
+            PriorityQueueCalloopSender::new(tx, ping.clone()),
+            Self {
+                receiver: rx,
+                source,
+                ping,
+            },
+        )
+    }
+}
+
+use calloop::channel::Event;
+
+#[derive(Debug)]
+pub struct ChannelError(calloop::ping::PingError);
+
+impl std::fmt::Display for ChannelError {
+    #[cfg_attr(feature = "nightly_coverage", coverage(off))]
+    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+        std::fmt::Display::fmt(&self.0, f)
+    }
+}
+
+impl std::error::Error for ChannelError {
+    #[cfg_attr(feature = "nightly_coverage", coverage(off))]
+    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
+        Some(&self.0)
+    }
+}
+
+impl<T> calloop::EventSource for PriorityQueueCalloopReceiver<T> {
+    type Event = Event<T>;
+    type Metadata = ();
+    type Ret = ();
+    type Error = ChannelError;
+
+    fn process_events<F>(
+        &mut self,
+        readiness: calloop::Readiness,
+        token: calloop::Token,
+        mut callback: F,
+    ) -> Result<calloop::PostAction, Self::Error>
+    where
+        F: FnMut(Self::Event, &mut Self::Metadata) -> Self::Ret,
+    {
+        let mut clear_readiness = false;
+        let mut disconnected = false;
+
+        let action = self
+            .source
+            .process_events(readiness, token, |(), &mut ()| {
+                let mut is_empty = true;
+
+                let mut receiver = self.receiver.clone();
+                for runnable in receiver.try_iter() {
+                    match runnable {
+                        Ok(r) => {
+                            callback(Event::Msg(r), &mut ());
+                            is_empty = false;
+                        }
+                        Err(_) => {
+                            disconnected = true;
+                        }
+                    }
+                }
+
+                if disconnected {
+                    callback(Event::Closed, &mut ());
+                }
+
+                if is_empty {
+                    clear_readiness = true;
+                }
+            })
+            .map_err(ChannelError)?;
+
+        if disconnected {
+            Ok(PostAction::Remove)
+        } else if clear_readiness {
+            Ok(action)
+        } else {
+            // Re-notify the ping source so we can try again.
+            self.ping.ping();
+            Ok(PostAction::Continue)
+        }
+    }
+
+    fn register(
+        &mut self,
+        poll: &mut calloop::Poll,
+        token_factory: &mut calloop::TokenFactory,
+    ) -> calloop::Result<()> {
+        self.source.register(poll, token_factory)
+    }
+
+    fn reregister(
+        &mut self,
+        poll: &mut calloop::Poll,
+        token_factory: &mut calloop::TokenFactory,
+    ) -> calloop::Result<()> {
+        self.source.reregister(poll, token_factory)
+    }
+
+    fn unregister(&mut self, poll: &mut calloop::Poll) -> calloop::Result<()> {
+        self.source.unregister(poll)
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    #[test]
+    fn calloop_works() {
+        let mut event_loop = calloop::EventLoop::try_new().unwrap();
+        let handle = event_loop.handle();
+
+        let (tx, rx) = PriorityQueueCalloopReceiver::new();
+
+        struct Data {
+            got_msg: bool,
+            got_closed: bool,
+        }
+
+        let mut data = Data {
+            got_msg: false,
+            got_closed: false,
+        };
+
+        let _channel_token = handle
+            .insert_source(rx, move |evt, &mut (), data: &mut Data| match evt {
+                Event::Msg(()) => {
+                    data.got_msg = true;
+                }
+
+                Event::Closed => {
+                    data.got_closed = true;
+                }
+            })
+            .unwrap();
+
+        // nothing is sent, nothing is received
+        event_loop
+            .dispatch(Some(::std::time::Duration::ZERO), &mut data)
+            .unwrap();
+
+        assert!(!data.got_msg);
+        assert!(!data.got_closed);
+        // a message is send
+
+        tx.send(Priority::Medium, ()).unwrap();
+        event_loop
+            .dispatch(Some(::std::time::Duration::ZERO), &mut data)
+            .unwrap();
+
+        assert!(data.got_msg);
+        assert!(!data.got_closed);
+
+        // the sender is dropped
+        drop(tx);
+        event_loop
+            .dispatch(Some(::std::time::Duration::ZERO), &mut data)
+            .unwrap();
+
+        assert!(data.got_msg);
+        assert!(data.got_closed);
+    }
 }
+
+// running 1 test
+// test platform::linux::dispatcher::tests::tomato ... FAILED
+
+// failures:
+
+// ---- platform::linux::dispatcher::tests::tomato stdout ----
+// [crates/gpui/src/platform/linux/dispatcher.rs:262:9]
+// returning 1 tasks to process
+// [crates/gpui/src/platform/linux/dispatcher.rs:480:75] evt = Msg(
+//     (),
+// )
+// returning 0 tasks to process
+
+// thread 'platform::linux::dispatcher::tests::tomato' (478301) panicked at crates/gpui/src/platform/linux/dispatcher.rs:515:9:
+// assertion failed: data.got_closed
+// note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

crates/gpui/src/platform/linux/platform.rs 🔗

@@ -14,7 +14,7 @@ use std::{
 };
 
 use anyhow::{Context as _, anyhow};
-use calloop::{LoopSignal, channel::Channel};
+use calloop::LoopSignal;
 use futures::channel::oneshot;
 use util::ResultExt as _;
 use util::command::{new_smol_command, new_std_command};
@@ -25,8 +25,8 @@ use crate::{
     Action, AnyWindowHandle, BackgroundExecutor, ClipboardItem, CursorStyle, DisplayId,
     ForegroundExecutor, Keymap, LinuxDispatcher, Menu, MenuItem, OwnedMenu, PathPromptOptions,
     Pixels, Platform, PlatformDisplay, PlatformKeyboardLayout, PlatformKeyboardMapper,
-    PlatformTextSystem, PlatformWindow, Point, Result, RunnableVariant, Task, WindowAppearance,
-    WindowParams, px,
+    PlatformTextSystem, PlatformWindow, Point, PriorityQueueCalloopReceiver, Result,
+    RunnableVariant, Task, WindowAppearance, WindowParams, px,
 };
 
 #[cfg(any(feature = "wayland", feature = "x11"))]
@@ -43,6 +43,50 @@ pub(crate) const KEYRING_LABEL: &str = "zed-github-account";
 const FILE_PICKER_PORTAL_MISSING: &str =
     "Couldn't open file picker due to missing xdg-desktop-portal implementation.";
 
+#[cfg(any(feature = "x11", feature = "wayland"))]
+pub trait ResultExt {
+    type Ok;
+
+    fn notify_err(self, msg: &'static str) -> Self::Ok;
+}
+
+#[cfg(any(feature = "x11", feature = "wayland"))]
+impl<T> ResultExt for anyhow::Result<T> {
+    type Ok = T;
+
+    fn notify_err(self, msg: &'static str) -> T {
+        match self {
+            Ok(v) => v,
+            Err(e) => {
+                use ashpd::desktop::notification::{Notification, NotificationProxy, Priority};
+                use futures::executor::block_on;
+
+                let proxy = block_on(NotificationProxy::new()).expect(msg);
+
+                let notification_id = "dev.zed.Oops";
+                block_on(
+                    proxy.add_notification(
+                        notification_id,
+                        Notification::new("Zed failed to launch")
+                            .body(Some(
+                                format!(
+                                    "{e:?}. See https://zed.dev/docs/linux for troubleshooting steps."
+                                )
+                                .as_str(),
+                            ))
+                            .priority(Priority::High)
+                            .icon(ashpd::desktop::Icon::with_names(&[
+                                "dialog-question-symbolic",
+                            ])),
+                    )
+                ).expect(msg);
+
+                panic!("{msg}");
+            }
+        }
+    }
+}
+
 pub trait LinuxClient {
     fn compositor_name(&self) -> &'static str;
     fn with_common<R>(&self, f: impl FnOnce(&mut LinuxCommon) -> R) -> R;
@@ -105,8 +149,8 @@ pub(crate) struct LinuxCommon {
 }
 
 impl LinuxCommon {
-    pub fn new(signal: LoopSignal) -> (Self, Channel<RunnableVariant>) {
-        let (main_sender, main_receiver) = calloop::channel::channel::<RunnableVariant>();
+    pub fn new(signal: LoopSignal) -> (Self, PriorityQueueCalloopReceiver<RunnableVariant>) {
+        let (main_sender, main_receiver) = PriorityQueueCalloopReceiver::new();
 
         #[cfg(any(feature = "wayland", feature = "x11"))]
         let text_system = Arc::new(crate::CosmicTextSystem::new());
@@ -605,8 +649,9 @@ pub(super) fn open_uri_internal(
                     .activation_token(activation_token.clone().map(ashpd::ActivationToken::from))
                     .send_uri(&uri)
                     .await
+                    .and_then(|e| e.response())
                 {
-                    Ok(_) => return,
+                    Ok(()) => return,
                     Err(e) => log::error!("Failed to open with dbus: {}", e),
                 }
 

crates/gpui/src/platform/linux/wayland/client.rs 🔗

@@ -17,7 +17,7 @@ use collections::HashMap;
 use filedescriptor::Pipe;
 use http_client::Url;
 use smallvec::SmallVec;
-use util::ResultExt;
+use util::ResultExt as _;
 use wayland_backend::client::ObjectId;
 use wayland_backend::protocol::WEnum;
 use wayland_client::event_created_child;
@@ -36,12 +36,6 @@ use wayland_client::{
         wl_shm_pool, wl_surface,
     },
 };
-use wayland_protocols::wp::cursor_shape::v1::client::{
-    wp_cursor_shape_device_v1, wp_cursor_shape_manager_v1,
-};
-use wayland_protocols::wp::fractional_scale::v1::client::{
-    wp_fractional_scale_manager_v1, wp_fractional_scale_v1,
-};
 use wayland_protocols::wp::primary_selection::zv1::client::zwp_primary_selection_offer_v1::{
     self, ZwpPrimarySelectionOfferV1,
 };
@@ -61,6 +55,14 @@ use wayland_protocols::xdg::decoration::zv1::client::{
     zxdg_decoration_manager_v1, zxdg_toplevel_decoration_v1,
 };
 use wayland_protocols::xdg::shell::client::{xdg_surface, xdg_toplevel, xdg_wm_base};
+use wayland_protocols::{
+    wp::cursor_shape::v1::client::{wp_cursor_shape_device_v1, wp_cursor_shape_manager_v1},
+    xdg::dialog::v1::client::xdg_wm_dialog_v1::{self, XdgWmDialogV1},
+};
+use wayland_protocols::{
+    wp::fractional_scale::v1::client::{wp_fractional_scale_manager_v1, wp_fractional_scale_v1},
+    xdg::dialog::v1::client::xdg_dialog_v1::XdgDialogV1,
+};
 use wayland_protocols_plasma::blur::client::{org_kde_kwin_blur, org_kde_kwin_blur_manager};
 use wayland_protocols_wlr::layer_shell::v1::client::{zwlr_layer_shell_v1, zwlr_layer_surface_v1};
 use xkbcommon::xkb::ffi::XKB_KEYMAP_FORMAT_TEXT_V1;
@@ -76,11 +78,11 @@ use crate::{
     FileDropEvent, ForegroundExecutor, KeyDownEvent, KeyUpEvent, Keystroke, LinuxCommon,
     LinuxKeyboardLayout, Modifiers, ModifiersChangedEvent, MouseButton, MouseDownEvent,
     MouseExitEvent, MouseMoveEvent, MouseUpEvent, NavigationDirection, Pixels, PlatformDisplay,
-    PlatformInput, PlatformKeyboardLayout, Point, SCROLL_LINES, ScrollDelta, ScrollWheelEvent,
-    Size, TouchPhase, WindowParams, point, px, size,
+    PlatformInput, PlatformKeyboardLayout, Point, ResultExt as _, SCROLL_LINES, ScrollDelta,
+    ScrollWheelEvent, Size, TouchPhase, WindowParams, point, profiler, px, size,
 };
 use crate::{
-    LinuxDispatcher, RunnableVariant, TaskTiming,
+    RunnableVariant, TaskTiming,
     platform::{PlatformWindow, blade::BladeContext},
 };
 use crate::{
@@ -122,6 +124,7 @@ pub struct Globals {
     pub layer_shell: Option<zwlr_layer_shell_v1::ZwlrLayerShellV1>,
     pub blur_manager: Option<org_kde_kwin_blur_manager::OrgKdeKwinBlurManager>,
     pub text_input_manager: Option<zwp_text_input_manager_v3::ZwpTextInputManagerV3>,
+    pub dialog: Option<xdg_wm_dialog_v1::XdgWmDialogV1>,
     pub executor: ForegroundExecutor,
 }
 
@@ -132,6 +135,7 @@ impl Globals {
         qh: QueueHandle<WaylandClientStatePtr>,
         seat: wl_seat::WlSeat,
     ) -> Self {
+        let dialog_v = XdgWmDialogV1::interface().version;
         Globals {
             activation: globals.bind(&qh, 1..=1, ()).ok(),
             compositor: globals
@@ -160,6 +164,7 @@ impl Globals {
             layer_shell: globals.bind(&qh, 1..=5, ()).ok(),
             blur_manager: globals.bind(&qh, 1..=1, ()).ok(),
             text_input_manager: globals.bind(&qh, 1..=1, ()).ok(),
+            dialog: globals.bind(&qh, dialog_v..=dialog_v, ()).ok(),
             executor,
             qh,
         }
@@ -503,7 +508,7 @@ impl WaylandClient {
                                         start,
                                         end: None,
                                     };
-                                    LinuxDispatcher::add_task_timing(timing);
+                                    profiler::add_task_timing(timing);
 
                                     runnable.run();
                                     timing
@@ -515,7 +520,7 @@ impl WaylandClient {
                                         start,
                                         end: None,
                                     };
-                                    LinuxDispatcher::add_task_timing(timing);
+                                    profiler::add_task_timing(timing);
 
                                     runnable.run();
                                     timing
@@ -524,14 +529,15 @@ impl WaylandClient {
 
                             let end = Instant::now();
                             timing.end = Some(end);
-                            LinuxDispatcher::add_task_timing(timing);
+                            profiler::add_task_timing(timing);
                         });
                     }
                 }
             })
             .unwrap();
 
-        let gpu_context = BladeContext::new().expect("Unable to init GPU context");
+        // This could be unified with the notification handling in zed/main:fail_to_open_window.
+        let gpu_context = BladeContext::new().notify_err("Unable to init GPU context");
 
         let seat = seat.unwrap();
         let globals = Globals::new(
@@ -728,10 +734,7 @@ impl LinuxClient for WaylandClient {
     ) -> anyhow::Result<Box<dyn PlatformWindow>> {
         let mut state = self.0.borrow_mut();
 
-        let parent = state
-            .keyboard_focused_window
-            .as_ref()
-            .and_then(|w| w.toplevel());
+        let parent = state.keyboard_focused_window.clone();
 
         let (window, surface_id) = WaylandWindow::new(
             handle,
@@ -750,7 +753,12 @@ impl LinuxClient for WaylandClient {
     fn set_cursor_style(&self, style: CursorStyle) {
         let mut state = self.0.borrow_mut();
 
-        let need_update = state.cursor_style != Some(style);
+        let need_update = state.cursor_style != Some(style)
+            && (state.mouse_focused_window.is_none()
+                || state
+                    .mouse_focused_window
+                    .as_ref()
+                    .is_some_and(|w| !w.is_blocked()));
 
         if need_update {
             let serial = state.serial_tracker.get(SerialKind::MouseEnter);
@@ -1010,7 +1018,7 @@ impl Dispatch<WlCallback, ObjectId> for WaylandClientStatePtr {
     }
 }
 
-fn get_window(
+pub(crate) fn get_window(
     mut state: &mut RefMut<WaylandClientState>,
     surface_id: &ObjectId,
 ) -> Option<WaylandWindowStatePtr> {
@@ -1419,7 +1427,7 @@ impl Dispatch<wl_keyboard::WlKeyboard, ()> for WaylandClientStatePtr {
                         state.repeat.current_keycode = Some(keycode);
 
                         let rate = state.repeat.characters_per_second;
-                        let repeat_interval = Duration::from_secs(1) / rate;
+                        let repeat_interval = Duration::from_secs(1) / rate.max(1);
                         let id = state.repeat.current_id;
                         state
                             .loop_handle
@@ -1653,6 +1661,30 @@ impl Dispatch<wl_pointer::WlPointer, ()> for WaylandClientStatePtr {
                 state.mouse_location = Some(point(px(surface_x as f32), px(surface_y as f32)));
 
                 if let Some(window) = state.mouse_focused_window.clone() {
+                    if window.is_blocked() {
+                        let default_style = CursorStyle::Arrow;
+                        if state.cursor_style != Some(default_style) {
+                            let serial = state.serial_tracker.get(SerialKind::MouseEnter);
+                            state.cursor_style = Some(default_style);
+
+                            if let Some(cursor_shape_device) = &state.cursor_shape_device {
+                                cursor_shape_device.set_shape(serial, default_style.to_shape());
+                            } else {
+                                // cursor-shape-v1 isn't supported, set the cursor using a surface.
+                                let wl_pointer = state
+                                    .wl_pointer
+                                    .clone()
+                                    .expect("window is focused by pointer");
+                                let scale = window.primary_output_scale();
+                                state.cursor.set_icon(
+                                    &wl_pointer,
+                                    serial,
+                                    default_style.to_icon_names(),
+                                    scale,
+                                );
+                            }
+                        }
+                    }
                     if state
                         .keyboard_focused_window
                         .as_ref()
@@ -2224,3 +2256,27 @@ impl Dispatch<zwp_primary_selection_source_v1::ZwpPrimarySelectionSourceV1, ()>
         }
     }
 }
+
+impl Dispatch<XdgWmDialogV1, ()> for WaylandClientStatePtr {
+    fn event(
+        _: &mut Self,
+        _: &XdgWmDialogV1,
+        _: <XdgWmDialogV1 as Proxy>::Event,
+        _: &(),
+        _: &Connection,
+        _: &QueueHandle<Self>,
+    ) {
+    }
+}
+
+impl Dispatch<XdgDialogV1, ()> for WaylandClientStatePtr {
+    fn event(
+        _state: &mut Self,
+        _proxy: &XdgDialogV1,
+        _event: <XdgDialogV1 as Proxy>::Event,
+        _data: &(),
+        _conn: &Connection,
+        _qhandle: &QueueHandle<Self>,
+    ) {
+    }
+}

crates/gpui/src/platform/linux/wayland/window.rs 🔗

@@ -7,7 +7,7 @@ use std::{
 };
 
 use blade_graphics as gpu;
-use collections::HashMap;
+use collections::{FxHashSet, HashMap};
 use futures::channel::oneshot::Receiver;
 
 use raw_window_handle as rwh;
@@ -20,7 +20,7 @@ use wayland_protocols::xdg::shell::client::xdg_surface;
 use wayland_protocols::xdg::shell::client::xdg_toplevel::{self};
 use wayland_protocols::{
     wp::fractional_scale::v1::client::wp_fractional_scale_v1,
-    xdg::shell::client::xdg_toplevel::XdgToplevel,
+    xdg::dialog::v1::client::xdg_dialog_v1::XdgDialogV1,
 };
 use wayland_protocols_plasma::blur::client::org_kde_kwin_blur;
 use wayland_protocols_wlr::layer_shell::v1::client::zwlr_layer_surface_v1;
@@ -29,7 +29,7 @@ use crate::{
     AnyWindowHandle, Bounds, Decorations, Globals, GpuSpecs, Modifiers, Output, Pixels,
     PlatformDisplay, PlatformInput, Point, PromptButton, PromptLevel, RequestFrameOptions,
     ResizeEdge, Size, Tiling, WaylandClientStatePtr, WindowAppearance, WindowBackgroundAppearance,
-    WindowBounds, WindowControlArea, WindowControls, WindowDecorations, WindowParams,
+    WindowBounds, WindowControlArea, WindowControls, WindowDecorations, WindowParams, get_window,
     layer_shell::LayerShellNotSupportedError, px, size,
 };
 use crate::{
@@ -87,6 +87,8 @@ struct InProgressConfigure {
 pub struct WaylandWindowState {
     surface_state: WaylandSurfaceState,
     acknowledged_first_configure: bool,
+    parent: Option<WaylandWindowStatePtr>,
+    children: FxHashSet<ObjectId>,
     pub surface: wl_surface::WlSurface,
     app_id: Option<String>,
     appearance: WindowAppearance,
@@ -126,7 +128,7 @@ impl WaylandSurfaceState {
         surface: &wl_surface::WlSurface,
         globals: &Globals,
         params: &WindowParams,
-        parent: Option<XdgToplevel>,
+        parent: Option<WaylandWindowStatePtr>,
     ) -> anyhow::Result<Self> {
         // For layer_shell windows, create a layer surface instead of an xdg surface
         if let WindowKind::LayerShell(options) = &params.kind {
@@ -178,10 +180,28 @@ impl WaylandSurfaceState {
             .get_xdg_surface(&surface, &globals.qh, surface.id());
 
         let toplevel = xdg_surface.get_toplevel(&globals.qh, surface.id());
-        if params.kind == WindowKind::Floating {
-            toplevel.set_parent(parent.as_ref());
+        let xdg_parent = parent.as_ref().and_then(|w| w.toplevel());
+
+        if params.kind == WindowKind::Floating || params.kind == WindowKind::Dialog {
+            toplevel.set_parent(xdg_parent.as_ref());
         }
 
+        let dialog = if params.kind == WindowKind::Dialog {
+            let dialog = globals.dialog.as_ref().map(|dialog| {
+                let xdg_dialog = dialog.get_xdg_dialog(&toplevel, &globals.qh, ());
+                xdg_dialog.set_modal();
+                xdg_dialog
+            });
+
+            if let Some(parent) = parent.as_ref() {
+                parent.add_child(surface.id());
+            }
+
+            dialog
+        } else {
+            None
+        };
+
         if let Some(size) = params.window_min_size {
             toplevel.set_min_size(size.width.0 as i32, size.height.0 as i32);
         }
@@ -198,6 +218,7 @@ impl WaylandSurfaceState {
             xdg_surface,
             toplevel,
             decoration,
+            dialog,
         }))
     }
 }
@@ -206,6 +227,7 @@ pub struct WaylandXdgSurfaceState {
     xdg_surface: xdg_surface::XdgSurface,
     toplevel: xdg_toplevel::XdgToplevel,
     decoration: Option<zxdg_toplevel_decoration_v1::ZxdgToplevelDecorationV1>,
+    dialog: Option<XdgDialogV1>,
 }
 
 pub struct WaylandLayerSurfaceState {
@@ -258,7 +280,13 @@ impl WaylandSurfaceState {
                 xdg_surface,
                 toplevel,
                 decoration: _decoration,
+                dialog,
             }) => {
+                // drop the dialog before toplevel so compositor can explicitly unapply it's effects
+                if let Some(dialog) = dialog {
+                    dialog.destroy();
+                }
+
                 // The role object (toplevel) must always be destroyed before the xdg_surface.
                 // See https://wayland.app/protocols/xdg-shell#xdg_surface:request:destroy
                 toplevel.destroy();
@@ -288,6 +316,7 @@ impl WaylandWindowState {
         globals: Globals,
         gpu_context: &BladeContext,
         options: WindowParams,
+        parent: Option<WaylandWindowStatePtr>,
     ) -> anyhow::Result<Self> {
         let renderer = {
             let raw_window = RawWindow {
@@ -319,6 +348,8 @@ impl WaylandWindowState {
         Ok(Self {
             surface_state,
             acknowledged_first_configure: false,
+            parent,
+            children: FxHashSet::default(),
             surface,
             app_id: None,
             blur: None,
@@ -391,6 +422,10 @@ impl Drop for WaylandWindow {
     fn drop(&mut self) {
         let mut state = self.0.state.borrow_mut();
         let surface_id = state.surface.id();
+        if let Some(parent) = state.parent.as_ref() {
+            parent.state.borrow_mut().children.remove(&surface_id);
+        }
+
         let client = state.client.clone();
 
         state.renderer.destroy();
@@ -448,10 +483,10 @@ impl WaylandWindow {
         client: WaylandClientStatePtr,
         params: WindowParams,
         appearance: WindowAppearance,
-        parent: Option<XdgToplevel>,
+        parent: Option<WaylandWindowStatePtr>,
     ) -> anyhow::Result<(Self, ObjectId)> {
         let surface = globals.compositor.create_surface(&globals.qh, ());
-        let surface_state = WaylandSurfaceState::new(&surface, &globals, &params, parent)?;
+        let surface_state = WaylandSurfaceState::new(&surface, &globals, &params, parent.clone())?;
 
         if let Some(fractional_scale_manager) = globals.fractional_scale_manager.as_ref() {
             fractional_scale_manager.get_fractional_scale(&surface, &globals.qh, surface.id());
@@ -473,6 +508,7 @@ impl WaylandWindow {
                 globals,
                 gpu_context,
                 params,
+                parent,
             )?)),
             callbacks: Rc::new(RefCell::new(Callbacks::default())),
         });
@@ -501,6 +537,16 @@ impl WaylandWindowStatePtr {
         Rc::ptr_eq(&self.state, &other.state)
     }
 
+    pub fn add_child(&self, child: ObjectId) {
+        let mut state = self.state.borrow_mut();
+        state.children.insert(child);
+    }
+
+    pub fn is_blocked(&self) -> bool {
+        let state = self.state.borrow();
+        !state.children.is_empty()
+    }
+
     pub fn frame(&self) {
         let mut state = self.state.borrow_mut();
         state.surface.frame(&state.globals.qh, state.surface.id());
@@ -818,6 +864,9 @@ impl WaylandWindowStatePtr {
     }
 
     pub fn handle_ime(&self, ime: ImeInput) {
+        if self.is_blocked() {
+            return;
+        }
         let mut state = self.state.borrow_mut();
         if let Some(mut input_handler) = state.input_handler.take() {
             drop(state);
@@ -894,6 +943,21 @@ impl WaylandWindowStatePtr {
     }
 
     pub fn close(&self) {
+        let state = self.state.borrow();
+        let client = state.client.get_client();
+        #[allow(clippy::mutable_key_type)]
+        let children = state.children.clone();
+        drop(state);
+
+        for child in children {
+            let mut client_state = client.borrow_mut();
+            let window = get_window(&mut client_state, &child);
+            drop(client_state);
+
+            if let Some(child) = window {
+                child.close();
+            }
+        }
         let mut callbacks = self.callbacks.borrow_mut();
         if let Some(fun) = callbacks.close.take() {
             fun()
@@ -901,6 +965,9 @@ impl WaylandWindowStatePtr {
     }
 
     pub fn handle_input(&self, input: PlatformInput) {
+        if self.is_blocked() {
+            return;
+        }
         if let Some(ref mut fun) = self.callbacks.borrow_mut().input
             && !fun(input.clone()).propagate
         {
@@ -1025,13 +1092,26 @@ impl PlatformWindow for WaylandWindow {
     fn resize(&mut self, size: Size<Pixels>) {
         let state = self.borrow();
         let state_ptr = self.0.clone();
-        let dp_size = size.to_device_pixels(self.scale_factor());
+
+        // Keep window geometry consistent with configure handling. On Wayland, window geometry is
+        // surface-local: resizing should not attempt to translate the window; the compositor
+        // controls placement. We also account for client-side decoration insets and tiling.
+        let window_geometry = inset_by_tiling(
+            Bounds {
+                origin: Point::default(),
+                size,
+            },
+            state.inset(),
+            state.tiling,
+        )
+        .map(|v| v.0 as i32)
+        .map_size(|v| if v <= 0 { 1 } else { v });
 
         state.surface_state.set_geometry(
-            state.bounds.origin.x.0 as i32,
-            state.bounds.origin.y.0 as i32,
-            dp_size.width.0,
-            dp_size.height.0,
+            window_geometry.origin.x,
+            window_geometry.origin.y,
+            window_geometry.size.width,
+            window_geometry.size.height,
         );
 
         state

crates/gpui/src/platform/linux/x11/client.rs 🔗

@@ -1,4 +1,4 @@
-use crate::{Capslock, LinuxDispatcher, RunnableVariant, TaskTiming, xcb_flush};
+use crate::{Capslock, ResultExt as _, RunnableVariant, TaskTiming, profiler, xcb_flush};
 use anyhow::{Context as _, anyhow};
 use ashpd::WindowIdentifier;
 use calloop::{
@@ -18,7 +18,7 @@ use std::{
     rc::{Rc, Weak},
     time::{Duration, Instant},
 };
-use util::ResultExt;
+use util::ResultExt as _;
 
 use x11rb::{
     connection::{Connection, RequestConnection},
@@ -29,7 +29,7 @@ use x11rb::{
     protocol::xkb::ConnectionExt as _,
     protocol::xproto::{
         AtomEnum, ChangeWindowAttributesAux, ClientMessageData, ClientMessageEvent,
-        ConnectionExt as _, EventMask, Visibility,
+        ConnectionExt as _, EventMask, ModMask, Visibility,
     },
     protocol::{Event, randr, render, xinput, xkb, xproto},
     resource_manager::Database,
@@ -222,7 +222,7 @@ pub struct X11ClientState {
 pub struct X11ClientStatePtr(pub Weak<RefCell<X11ClientState>>);
 
 impl X11ClientStatePtr {
-    fn get_client(&self) -> Option<X11Client> {
+    pub fn get_client(&self) -> Option<X11Client> {
         self.0.upgrade().map(X11Client)
     }
 
@@ -322,7 +322,7 @@ impl X11Client {
                                         start,
                                         end: None,
                                     };
-                                    LinuxDispatcher::add_task_timing(timing);
+                                    profiler::add_task_timing(timing);
 
                                     runnable.run();
                                     timing
@@ -334,7 +334,7 @@ impl X11Client {
                                         start,
                                         end: None,
                                     };
-                                    LinuxDispatcher::add_task_timing(timing);
+                                    profiler::add_task_timing(timing);
 
                                     runnable.run();
                                     timing
@@ -343,7 +343,7 @@ impl X11Client {
 
                             let end = Instant::now();
                             timing.end = Some(end);
-                            LinuxDispatcher::add_task_timing(timing);
+                            profiler::add_task_timing(timing);
                         });
                     }
                 }
@@ -437,7 +437,7 @@ impl X11Client {
             .to_string();
         let keyboard_layout = LinuxKeyboardLayout::new(layout_name.into());
 
-        let gpu_context = BladeContext::new().context("Unable to init GPU context")?;
+        let gpu_context = BladeContext::new().notify_err("Unable to init GPU context");
 
         let resource_database = x11rb::resource_manager::new_from_default(&xcb_connection)
             .context("Failed to create resource database")?;
@@ -752,7 +752,7 @@ impl X11Client {
         }
     }
 
-    fn get_window(&self, win: xproto::Window) -> Option<X11WindowStatePtr> {
+    pub(crate) fn get_window(&self, win: xproto::Window) -> Option<X11WindowStatePtr> {
         let state = self.0.borrow();
         state
             .windows
@@ -789,12 +789,12 @@ impl X11Client {
                 let [atom, arg1, arg2, arg3, arg4] = event.data.as_data32();
                 let mut state = self.0.borrow_mut();
 
-                if atom == state.atoms.WM_DELETE_WINDOW {
+                if atom == state.atoms.WM_DELETE_WINDOW && window.should_close() {
                     // window "x" button clicked by user
-                    if window.should_close() {
-                        // Rest of the close logic is handled in drop_window()
-                        window.close();
-                    }
+                    // Rest of the close logic is handled in drop_window()
+                    drop(state);
+                    window.close();
+                    state = self.0.borrow_mut();
                 } else if atom == state.atoms._NET_WM_SYNC_REQUEST {
                     window.state.borrow_mut().last_sync_counter =
                         Some(x11rb::protocol::sync::Int64 {
@@ -944,6 +944,8 @@ impl X11Client {
                 let window = self.get_window(event.event)?;
                 window.set_active(false);
                 let mut state = self.0.borrow_mut();
+                // Set last scroll values to `None` so that a large delta isn't created if scrolling is done outside the window (the valuator is global)
+                reset_all_pointer_device_scroll_positions(&mut state.pointer_device_states);
                 state.keyboard_focused_window = None;
                 if let Some(compose_state) = state.compose_state.as_mut() {
                     compose_state.reset();
@@ -1018,6 +1020,12 @@ impl X11Client {
                 let modifiers = modifiers_from_state(event.state);
                 state.modifiers = modifiers;
                 state.pre_key_char_down.take();
+
+                // Macros containing modifiers might result in
+                // the modifiers missing from the event.
+                // We therefore update the mask from the global state.
+                update_xkb_mask_from_event_state(&mut state.xkb, event.state);
+
                 let keystroke = {
                     let code = event.detail.into();
                     let mut keystroke = crate::Keystroke::from_xkb(&state.xkb, modifiers, code);
@@ -1083,6 +1091,11 @@ impl X11Client {
                 let modifiers = modifiers_from_state(event.state);
                 state.modifiers = modifiers;
 
+                // Macros containing modifiers might result in
+                // the modifiers missing from the event.
+                // We therefore update the mask from the global state.
+                update_xkb_mask_from_event_state(&mut state.xkb, event.state);
+
                 let keystroke = {
                     let code = event.detail.into();
                     let keystroke = crate::Keystroke::from_xkb(&state.xkb, modifiers, code);
@@ -1205,6 +1218,33 @@ impl X11Client {
             Event::XinputMotion(event) => {
                 let window = self.get_window(event.event)?;
                 let mut state = self.0.borrow_mut();
+                if window.is_blocked() {
+                    // We want to set the cursor to the default arrow
+                    // when the window is blocked
+                    let style = CursorStyle::Arrow;
+
+                    let current_style = state
+                        .cursor_styles
+                        .get(&window.x_window)
+                        .unwrap_or(&CursorStyle::Arrow);
+                    if *current_style != style
+                        && let Some(cursor) = state.get_cursor_icon(style)
+                    {
+                        state.cursor_styles.insert(window.x_window, style);
+                        check_reply(
+                            || "Failed to set cursor style",
+                            state.xcb_connection.change_window_attributes(
+                                window.x_window,
+                                &ChangeWindowAttributesAux {
+                                    cursor: Some(cursor),
+                                    ..Default::default()
+                                },
+                            ),
+                        )
+                        .log_err();
+                        state.xcb_connection.flush().log_err();
+                    };
+                }
                 let pressed_button = pressed_button_from_mask(event.button_mask[0]);
                 let position = point(
                     px(event.event_x as f32 / u16::MAX as f32 / state.scale_factor),
@@ -1478,7 +1518,7 @@ impl LinuxClient for X11Client {
         let parent_window = state
             .keyboard_focused_window
             .and_then(|focused_window| state.windows.get(&focused_window))
-            .map(|window| window.window.x_window);
+            .map(|w| w.window.clone());
         let x_window = state
             .xcb_connection
             .generate_id()
@@ -1533,7 +1573,15 @@ impl LinuxClient for X11Client {
             .cursor_styles
             .get(&focused_window)
             .unwrap_or(&CursorStyle::Arrow);
-        if *current_style == style {
+
+        let window = state
+            .mouse_focused_window
+            .and_then(|w| state.windows.get(&w));
+
+        let should_change = *current_style != style
+            && (window.is_none() || window.is_some_and(|w| !w.is_blocked()));
+
+        if !should_change {
             return;
         }
 
@@ -2516,3 +2564,19 @@ fn get_dpi_factor((width_px, height_px): (u32, u32), (width_mm, height_mm): (u64
 fn valid_scale_factor(scale_factor: f32) -> bool {
     scale_factor.is_sign_positive() && scale_factor.is_normal()
 }
+
+#[inline]
+fn update_xkb_mask_from_event_state(xkb: &mut xkbc::State, event_state: xproto::KeyButMask) {
+    let depressed_mods = event_state.remove((ModMask::LOCK | ModMask::M2).bits());
+    let latched_mods = xkb.serialize_mods(xkbc::STATE_MODS_LATCHED);
+    let locked_mods = xkb.serialize_mods(xkbc::STATE_MODS_LOCKED);
+    let locked_layout = xkb.serialize_layout(xkbc::STATE_LAYOUT_LOCKED);
+    xkb.update_mask(
+        depressed_mods.into(),
+        latched_mods,
+        locked_mods,
+        0,
+        0,
+        locked_layout,
+    );
+}

crates/gpui/src/platform/linux/x11/window.rs 🔗

@@ -11,6 +11,7 @@ use crate::{
 };
 
 use blade_graphics as gpu;
+use collections::FxHashSet;
 use raw_window_handle as rwh;
 use util::{ResultExt, maybe};
 use x11rb::{
@@ -74,6 +75,7 @@ x11rb::atom_manager! {
         _NET_WM_WINDOW_TYPE,
         _NET_WM_WINDOW_TYPE_NOTIFICATION,
         _NET_WM_WINDOW_TYPE_DIALOG,
+        _NET_WM_STATE_MODAL,
         _NET_WM_SYNC,
         _NET_SUPPORTED,
         _MOTIF_WM_HINTS,
@@ -249,6 +251,8 @@ pub struct Callbacks {
 
 pub struct X11WindowState {
     pub destroyed: bool,
+    parent: Option<X11WindowStatePtr>,
+    children: FxHashSet<xproto::Window>,
     client: X11ClientStatePtr,
     executor: ForegroundExecutor,
     atoms: XcbAtoms,
@@ -394,7 +398,7 @@ impl X11WindowState {
         atoms: &XcbAtoms,
         scale_factor: f32,
         appearance: WindowAppearance,
-        parent_window: Option<xproto::Window>,
+        parent_window: Option<X11WindowStatePtr>,
     ) -> anyhow::Result<Self> {
         let x_screen_index = params
             .display_id
@@ -427,6 +431,7 @@ impl X11WindowState {
             // https://stackoverflow.com/questions/43218127/x11-xlib-xcb-creating-a-window-requires-border-pixel-if-specifying-colormap-wh
             .border_pixel(visual_set.black_pixel)
             .colormap(colormap)
+            .override_redirect((params.kind == WindowKind::PopUp) as u32)
             .event_mask(
                 xproto::EventMask::EXPOSURE
                     | xproto::EventMask::STRUCTURE_NOTIFY
@@ -546,8 +551,8 @@ impl X11WindowState {
                 )?;
             }
 
-            if params.kind == WindowKind::Floating {
-                if let Some(parent_window) = parent_window {
+            if params.kind == WindowKind::Floating || params.kind == WindowKind::Dialog {
+                if let Some(parent_window) = parent_window.as_ref().map(|w| w.x_window) {
                     // WM_TRANSIENT_FOR hint indicating the main application window. For floating windows, we set
                     // a parent window (WM_TRANSIENT_FOR) such that the window manager knows where to
                     // place the floating window in relation to the main window.
@@ -563,11 +568,23 @@ impl X11WindowState {
                         ),
                     )?;
                 }
+            }
+
+            let parent = if params.kind == WindowKind::Dialog
+                && let Some(parent) = parent_window
+            {
+                parent.add_child(x_window);
+
+                Some(parent)
+            } else {
+                None
+            };
 
+            if params.kind == WindowKind::Dialog {
                 // _NET_WM_WINDOW_TYPE_DIALOG indicates that this is a dialog (floating) window
                 // https://specifications.freedesktop.org/wm-spec/1.4/ar01s05.html
                 check_reply(
-                    || "X11 ChangeProperty32 setting window type for floating window failed.",
+                    || "X11 ChangeProperty32 setting window type for dialog window failed.",
                     xcb.change_property32(
                         xproto::PropMode::REPLACE,
                         x_window,
@@ -576,6 +593,20 @@ impl X11WindowState {
                         &[atoms._NET_WM_WINDOW_TYPE_DIALOG],
                     ),
                 )?;
+
+                // We set the modal state for dialog windows, so that the window manager
+                // can handle it appropriately (e.g., prevent interaction with the parent window
+                // while the dialog is open).
+                check_reply(
+                    || "X11 ChangeProperty32 setting modal state for dialog window failed.",
+                    xcb.change_property32(
+                        xproto::PropMode::REPLACE,
+                        x_window,
+                        atoms._NET_WM_STATE,
+                        xproto::AtomEnum::ATOM,
+                        &[atoms._NET_WM_STATE_MODAL],
+                    ),
+                )?;
             }
 
             check_reply(
@@ -667,6 +698,8 @@ impl X11WindowState {
             let display = Rc::new(X11Display::new(xcb, scale_factor, x_screen_index)?);
 
             Ok(Self {
+                parent,
+                children: FxHashSet::default(),
                 client,
                 executor,
                 display,
@@ -720,6 +753,11 @@ pub(crate) struct X11Window(pub X11WindowStatePtr);
 impl Drop for X11Window {
     fn drop(&mut self) {
         let mut state = self.0.state.borrow_mut();
+
+        if let Some(parent) = state.parent.as_ref() {
+            parent.state.borrow_mut().children.remove(&self.0.x_window);
+        }
+
         state.renderer.destroy();
 
         let destroy_x_window = maybe!({
@@ -734,8 +772,6 @@ impl Drop for X11Window {
         .log_err();
 
         if destroy_x_window.is_some() {
-            // Mark window as destroyed so that we can filter out when X11 events
-            // for it still come in.
             state.destroyed = true;
 
             let this_ptr = self.0.clone();
@@ -773,7 +809,7 @@ impl X11Window {
         atoms: &XcbAtoms,
         scale_factor: f32,
         appearance: WindowAppearance,
-        parent_window: Option<xproto::Window>,
+        parent_window: Option<X11WindowStatePtr>,
     ) -> anyhow::Result<Self> {
         let ptr = X11WindowStatePtr {
             state: Rc::new(RefCell::new(X11WindowState::new(
@@ -979,7 +1015,31 @@ impl X11WindowStatePtr {
         Ok(())
     }
 
+    pub fn add_child(&self, child: xproto::Window) {
+        let mut state = self.state.borrow_mut();
+        state.children.insert(child);
+    }
+
+    pub fn is_blocked(&self) -> bool {
+        let state = self.state.borrow();
+        !state.children.is_empty()
+    }
+
     pub fn close(&self) {
+        let state = self.state.borrow();
+        let client = state.client.clone();
+        #[allow(clippy::mutable_key_type)]
+        let children = state.children.clone();
+        drop(state);
+
+        if let Some(client) = client.get_client() {
+            for child in children {
+                if let Some(child_window) = client.get_window(child) {
+                    child_window.close();
+                }
+            }
+        }
+
         let mut callbacks = self.callbacks.borrow_mut();
         if let Some(fun) = callbacks.close.take() {
             fun()
@@ -994,6 +1054,9 @@ impl X11WindowStatePtr {
     }
 
     pub fn handle_input(&self, input: PlatformInput) {
+        if self.is_blocked() {
+            return;
+        }
         if let Some(ref mut fun) = self.callbacks.borrow_mut().input
             && !fun(input.clone()).propagate
         {
@@ -1016,6 +1079,9 @@ impl X11WindowStatePtr {
     }
 
     pub fn handle_ime_commit(&self, text: String) {
+        if self.is_blocked() {
+            return;
+        }
         let mut state = self.state.borrow_mut();
         if let Some(mut input_handler) = state.input_handler.take() {
             drop(state);
@@ -1026,6 +1092,9 @@ impl X11WindowStatePtr {
     }
 
     pub fn handle_ime_preedit(&self, text: String) {
+        if self.is_blocked() {
+            return;
+        }
         let mut state = self.state.borrow_mut();
         if let Some(mut input_handler) = state.input_handler.take() {
             drop(state);
@@ -1036,6 +1105,9 @@ impl X11WindowStatePtr {
     }
 
     pub fn handle_ime_unmark(&self) {
+        if self.is_blocked() {
+            return;
+        }
         let mut state = self.state.borrow_mut();
         if let Some(mut input_handler) = state.input_handler.take() {
             drop(state);
@@ -1046,6 +1118,9 @@ impl X11WindowStatePtr {
     }
 
     pub fn handle_ime_delete(&self) {
+        if self.is_blocked() {
+            return;
+        }
         let mut state = self.state.borrow_mut();
         if let Some(mut input_handler) = state.input_handler.take() {
             drop(state);

crates/gpui/src/platform/mac.rs 🔗

@@ -5,6 +5,7 @@ mod display;
 mod display_link;
 mod events;
 mod keyboard;
+mod pasteboard;
 
 #[cfg(feature = "screen-capture")]
 mod screen_capture;
@@ -21,8 +22,6 @@ use metal_renderer as renderer;
 #[cfg(feature = "macos-blade")]
 use crate::platform::blade as renderer;
 
-mod attributed_string;
-
 #[cfg(feature = "font-kit")]
 mod open_type;
 
@@ -135,6 +134,8 @@ unsafe impl objc::Encode for NSRange {
     }
 }
 
+/// Allow NSString::alloc use here because it sets autorelease
+#[allow(clippy::disallowed_methods)]
 unsafe fn ns_string(string: &str) -> id {
     unsafe { NSString::alloc(nil).init_str(string).autorelease() }
 }

crates/gpui/src/platform/mac/attributed_string.rs 🔗

@@ -1,119 +0,0 @@
-use cocoa::base::id;
-use cocoa::foundation::NSRange;
-use objc::{class, msg_send, sel, sel_impl};
-
-/// The `cocoa` crate does not define NSAttributedString (and related Cocoa classes),
-/// which are needed for copying rich text (that is, text intermingled with images)
-/// to the clipboard. This adds access to those APIs.
-#[allow(non_snake_case)]
-pub trait NSAttributedString: Sized {
-    unsafe fn alloc(_: Self) -> id {
-        msg_send![class!(NSAttributedString), alloc]
-    }
-
-    unsafe fn init_attributed_string(self, string: id) -> id;
-    unsafe fn appendAttributedString_(self, attr_string: id);
-    unsafe fn RTFDFromRange_documentAttributes_(self, range: NSRange, attrs: id) -> id;
-    unsafe fn RTFFromRange_documentAttributes_(self, range: NSRange, attrs: id) -> id;
-    unsafe fn string(self) -> id;
-}
-
-impl NSAttributedString for id {
-    unsafe fn init_attributed_string(self, string: id) -> id {
-        msg_send![self, initWithString: string]
-    }
-
-    unsafe fn appendAttributedString_(self, attr_string: id) {
-        let _: () = msg_send![self, appendAttributedString: attr_string];
-    }
-
-    unsafe fn RTFDFromRange_documentAttributes_(self, range: NSRange, attrs: id) -> id {
-        msg_send![self, RTFDFromRange: range documentAttributes: attrs]
-    }
-
-    unsafe fn RTFFromRange_documentAttributes_(self, range: NSRange, attrs: id) -> id {
-        msg_send![self, RTFFromRange: range documentAttributes: attrs]
-    }
-
-    unsafe fn string(self) -> id {
-        msg_send![self, string]
-    }
-}
-
-pub trait NSMutableAttributedString: NSAttributedString {
-    unsafe fn alloc(_: Self) -> id {
-        msg_send![class!(NSMutableAttributedString), alloc]
-    }
-}
-
-impl NSMutableAttributedString for id {}
-
-#[cfg(test)]
-mod tests {
-    use super::*;
-    use cocoa::appkit::NSImage;
-    use cocoa::base::nil;
-    use cocoa::foundation::NSString;
-    #[test]
-    #[ignore] // This was SIGSEGV-ing on CI but not locally; need to investigate https://github.com/zed-industries/zed/actions/runs/10362363230/job/28684225486?pr=15782#step:4:1348
-    fn test_nsattributed_string() {
-        // TODO move these to parent module once it's actually ready to be used
-        #[allow(non_snake_case)]
-        pub trait NSTextAttachment: Sized {
-            unsafe fn alloc(_: Self) -> id {
-                msg_send![class!(NSTextAttachment), alloc]
-            }
-        }
-
-        impl NSTextAttachment for id {}
-
-        unsafe {
-            let image: id = msg_send![class!(NSImage), alloc];
-            image.initWithContentsOfFile_(NSString::alloc(nil).init_str("test.jpeg"));
-            let _size = image.size();
-
-            let string = NSString::alloc(nil).init_str("Test String");
-            let attr_string = NSMutableAttributedString::alloc(nil).init_attributed_string(string);
-            let hello_string = NSString::alloc(nil).init_str("Hello World");
-            let hello_attr_string =
-                NSAttributedString::alloc(nil).init_attributed_string(hello_string);
-            attr_string.appendAttributedString_(hello_attr_string);
-
-            let attachment = NSTextAttachment::alloc(nil);
-            let _: () = msg_send![attachment, setImage: image];
-            let image_attr_string =
-                msg_send![class!(NSAttributedString), attributedStringWithAttachment: attachment];
-            attr_string.appendAttributedString_(image_attr_string);
-
-            let another_string = NSString::alloc(nil).init_str("Another String");
-            let another_attr_string =
-                NSAttributedString::alloc(nil).init_attributed_string(another_string);
-            attr_string.appendAttributedString_(another_attr_string);
-
-            let _len: cocoa::foundation::NSUInteger = msg_send![attr_string, length];
-
-            ///////////////////////////////////////////////////
-            // pasteboard.clearContents();
-
-            let rtfd_data = attr_string.RTFDFromRange_documentAttributes_(
-                NSRange::new(0, msg_send![attr_string, length]),
-                nil,
-            );
-            assert_ne!(rtfd_data, nil);
-            // if rtfd_data != nil {
-            //     pasteboard.setData_forType(rtfd_data, NSPasteboardTypeRTFD);
-            // }
-
-            // let rtf_data = attributed_string.RTFFromRange_documentAttributes_(
-            //     NSRange::new(0, attributed_string.length()),
-            //     nil,
-            // );
-            // if rtf_data != nil {
-            //     pasteboard.setData_forType(rtf_data, NSPasteboardTypeRTF);
-            // }
-
-            // let plain_text = attributed_string.string();
-            // pasteboard.setString_forType(plain_text, NSPasteboardTypeString);
-        }
-    }
-}

crates/gpui/src/platform/mac/dispatcher.rs 🔗

@@ -3,11 +3,22 @@
 #![allow(non_snake_case)]
 
 use crate::{
-    GLOBAL_THREAD_TIMINGS, PlatformDispatcher, RunnableMeta, RunnableVariant, THREAD_TIMINGS,
-    TaskLabel, TaskTiming, ThreadTaskTimings,
+    GLOBAL_THREAD_TIMINGS, PlatformDispatcher, Priority, RealtimePriority, RunnableMeta,
+    RunnableVariant, THREAD_TIMINGS, TaskLabel, TaskTiming, ThreadTaskTimings,
 };
 
+use anyhow::Context;
 use async_task::Runnable;
+use mach2::{
+    kern_return::KERN_SUCCESS,
+    mach_time::mach_timebase_info_data_t,
+    thread_policy::{
+        THREAD_EXTENDED_POLICY, THREAD_EXTENDED_POLICY_COUNT, THREAD_PRECEDENCE_POLICY,
+        THREAD_PRECEDENCE_POLICY_COUNT, THREAD_TIME_CONSTRAINT_POLICY,
+        THREAD_TIME_CONSTRAINT_POLICY_COUNT, thread_extended_policy_data_t,
+        thread_precedence_policy_data_t, thread_time_constraint_policy_data_t,
+    },
+};
 use objc::{
     class, msg_send,
     runtime::{BOOL, YES},
@@ -15,9 +26,11 @@ use objc::{
 };
 use std::{
     ffi::c_void,
+    mem::MaybeUninit,
     ptr::{NonNull, addr_of},
     time::{Duration, Instant},
 };
+use util::ResultExt;
 
 /// All items in the generated file are marked as pub, so we're gonna wrap it in a separate mod to prevent
 /// these pub items from leaking into public API.
@@ -56,7 +69,7 @@ impl PlatformDispatcher for MacDispatcher {
         is_main_thread == YES
     }
 
-    fn dispatch(&self, runnable: RunnableVariant, _: Option<TaskLabel>) {
+    fn dispatch(&self, runnable: RunnableVariant, _: Option<TaskLabel>, priority: Priority) {
         let (context, trampoline) = match runnable {
             RunnableVariant::Meta(runnable) => (
                 runnable.into_raw().as_ptr() as *mut c_void,
@@ -67,16 +80,24 @@ impl PlatformDispatcher for MacDispatcher {
                 Some(trampoline_compat as unsafe extern "C" fn(*mut c_void)),
             ),
         };
+
+        let queue_priority = match priority {
+            Priority::Realtime(_) => unreachable!(),
+            Priority::High => DISPATCH_QUEUE_PRIORITY_HIGH as isize,
+            Priority::Medium => DISPATCH_QUEUE_PRIORITY_DEFAULT as isize,
+            Priority::Low => DISPATCH_QUEUE_PRIORITY_LOW as isize,
+        };
+
         unsafe {
             dispatch_async_f(
-                dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH.try_into().unwrap(), 0),
+                dispatch_get_global_queue(queue_priority, 0),
                 context,
                 trampoline,
             );
         }
     }
 
-    fn dispatch_on_main_thread(&self, runnable: RunnableVariant) {
+    fn dispatch_on_main_thread(&self, runnable: RunnableVariant, _priority: Priority) {
         let (context, trampoline) = match runnable {
             RunnableVariant::Meta(runnable) => (
                 runnable.into_raw().as_ptr() as *mut c_void,
@@ -110,6 +131,120 @@ impl PlatformDispatcher for MacDispatcher {
             dispatch_after_f(when, queue, context, trampoline);
         }
     }
+
+    fn spawn_realtime(&self, priority: RealtimePriority, f: Box<dyn FnOnce() + Send>) {
+        std::thread::spawn(move || {
+            match priority {
+                RealtimePriority::Audio => set_audio_thread_priority(),
+                RealtimePriority::Other => set_high_thread_priority(),
+            }
+            .context(format!("for priority {:?}", priority))
+            .log_err();
+
+            f();
+        });
+    }
+}
+
+fn set_high_thread_priority() -> anyhow::Result<()> {
+    // SAFETY: always safe to call
+    let thread_id = unsafe { libc::pthread_self() };
+
+    // SAFETY: all sched_param members are valid when initialized to zero.
+    let mut sched_param = unsafe { MaybeUninit::<libc::sched_param>::zeroed().assume_init() };
+    sched_param.sched_priority = 45;
+
+    let result = unsafe { libc::pthread_setschedparam(thread_id, libc::SCHED_FIFO, &sched_param) };
+    if result != 0 {
+        anyhow::bail!("failed to set realtime thread priority")
+    }
+
+    Ok(())
+}
+
+fn set_audio_thread_priority() -> anyhow::Result<()> {
+    // https://chromium.googlesource.com/chromium/chromium/+/master/base/threading/platform_thread_mac.mm#93
+
+    // SAFETY: always safe to call
+    let thread_id = unsafe { libc::pthread_self() };
+
+    // SAFETY: thread_id is a valid thread id
+    let thread_id = unsafe { libc::pthread_mach_thread_np(thread_id) };
+
+    // Fixed priority thread
+    let mut policy = thread_extended_policy_data_t { timeshare: 0 };
+
+    // SAFETY: thread_id is a valid thread id
+    // SAFETY: thread_extended_policy_data_t is passed as THREAD_EXTENDED_POLICY
+    let result = unsafe {
+        mach2::thread_policy::thread_policy_set(
+            thread_id,
+            THREAD_EXTENDED_POLICY,
+            &mut policy as *mut _ as *mut _,
+            THREAD_EXTENDED_POLICY_COUNT,
+        )
+    };
+
+    if result != KERN_SUCCESS {
+        anyhow::bail!("failed to set thread extended policy");
+    }
+
+    // relatively high priority
+    let mut precedence = thread_precedence_policy_data_t { importance: 63 };
+
+    // SAFETY: thread_id is a valid thread id
+    // SAFETY: thread_precedence_policy_data_t is passed as THREAD_PRECEDENCE_POLICY
+    let result = unsafe {
+        mach2::thread_policy::thread_policy_set(
+            thread_id,
+            THREAD_PRECEDENCE_POLICY,
+            &mut precedence as *mut _ as *mut _,
+            THREAD_PRECEDENCE_POLICY_COUNT,
+        )
+    };
+
+    if result != KERN_SUCCESS {
+        anyhow::bail!("failed to set thread precedence policy");
+    }
+
+    const GUARANTEED_AUDIO_DUTY_CYCLE: f32 = 0.75;
+    const MAX_AUDIO_DUTY_CYCLE: f32 = 0.85;
+
+    // ~128 frames @ 44.1KHz
+    const TIME_QUANTUM: f32 = 2.9;
+
+    const AUDIO_TIME_NEEDED: f32 = GUARANTEED_AUDIO_DUTY_CYCLE * TIME_QUANTUM;
+    const MAX_TIME_ALLOWED: f32 = MAX_AUDIO_DUTY_CYCLE * TIME_QUANTUM;
+
+    let mut timebase_info = mach_timebase_info_data_t { numer: 0, denom: 0 };
+    // SAFETY: timebase_info is a valid pointer to a mach_timebase_info_data_t struct
+    unsafe { mach2::mach_time::mach_timebase_info(&mut timebase_info) };
+
+    let ms_to_abs_time = ((timebase_info.denom as f32) / (timebase_info.numer as f32)) * 1000000f32;
+
+    let mut time_constraints = thread_time_constraint_policy_data_t {
+        period: (TIME_QUANTUM * ms_to_abs_time) as u32,
+        computation: (AUDIO_TIME_NEEDED * ms_to_abs_time) as u32,
+        constraint: (MAX_TIME_ALLOWED * ms_to_abs_time) as u32,
+        preemptible: 0,
+    };
+
+    // SAFETY: thread_id is a valid thread id
+    // SAFETY: thread_precedence_pthread_time_constraint_policy_data_t is passed as THREAD_TIME_CONSTRAINT_POLICY
+    let result = unsafe {
+        mach2::thread_policy::thread_policy_set(
+            thread_id,
+            THREAD_TIME_CONSTRAINT_POLICY,
+            &mut time_constraints as *mut _ as *mut _,
+            THREAD_TIME_CONSTRAINT_POLICY_COUNT,
+        )
+    };
+
+    if result != KERN_SUCCESS {
+        anyhow::bail!("failed to set thread time constraint policy");
+    }
+
+    Ok(())
 }
 
 extern "C" fn trampoline(runnable: *mut c_void) {

crates/gpui/src/platform/mac/display.rs 🔗

@@ -1,9 +1,10 @@
-use crate::{Bounds, DisplayId, Pixels, PlatformDisplay, px, size};
+use super::ns_string;
+use crate::{Bounds, DisplayId, Pixels, PlatformDisplay, point, px, size};
 use anyhow::Result;
 use cocoa::{
     appkit::NSScreen,
     base::{id, nil},
-    foundation::{NSDictionary, NSString},
+    foundation::{NSArray, NSDictionary},
 };
 use core_foundation::uuid::{CFUUIDGetUUIDBytes, CFUUIDRef};
 use core_graphics::display::{CGDirectDisplayID, CGDisplayBounds, CGGetActiveDisplayList};
@@ -35,7 +36,7 @@ impl MacDisplay {
             let screens = NSScreen::screens(nil);
             let screen = cocoa::foundation::NSArray::objectAtIndex(screens, 0);
             let device_description = NSScreen::deviceDescription(screen);
-            let screen_number_key: id = NSString::alloc(nil).init_str("NSScreenNumber");
+            let screen_number_key: id = ns_string("NSScreenNumber");
             let screen_number = device_description.objectForKey_(screen_number_key);
             let screen_number: CGDirectDisplayID = msg_send![screen_number, unsignedIntegerValue];
             Self(screen_number)
@@ -114,4 +115,53 @@ impl PlatformDisplay for MacDisplay {
             }
         }
     }
+
+    fn visible_bounds(&self) -> Bounds<Pixels> {
+        unsafe {
+            let dominated_screen = self.get_nsscreen();
+
+            if dominated_screen == nil {
+                return self.bounds();
+            }
+
+            let screen_frame = NSScreen::frame(dominated_screen);
+            let visible_frame = NSScreen::visibleFrame(dominated_screen);
+
+            // Convert from bottom-left origin (AppKit) to top-left origin
+            let origin_y =
+                screen_frame.size.height - visible_frame.origin.y - visible_frame.size.height
+                    + screen_frame.origin.y;
+
+            Bounds {
+                origin: point(
+                    px(visible_frame.origin.x as f32 - screen_frame.origin.x as f32),
+                    px(origin_y as f32),
+                ),
+                size: size(
+                    px(visible_frame.size.width as f32),
+                    px(visible_frame.size.height as f32),
+                ),
+            }
+        }
+    }
+}
+
+impl MacDisplay {
+    /// Find the NSScreen corresponding to this display
+    unsafe fn get_nsscreen(&self) -> id {
+        let screens = unsafe { NSScreen::screens(nil) };
+        let count = unsafe { NSArray::count(screens) };
+        let screen_number_key: id = unsafe { ns_string("NSScreenNumber") };
+
+        for i in 0..count {
+            let screen = unsafe { NSArray::objectAtIndex(screens, i) };
+            let device_description = unsafe { NSScreen::deviceDescription(screen) };
+            let screen_number = unsafe { device_description.objectForKey_(screen_number_key) };
+            let screen_id: CGDirectDisplayID = msg_send![screen_number, unsignedIntegerValue];
+            if screen_id == self.0 {
+                return screen;
+            }
+        }
+        nil
+    }
 }

crates/gpui/src/platform/mac/events.rs 🔗

@@ -1,7 +1,8 @@
 use crate::{
     Capslock, KeyDownEvent, KeyUpEvent, Keystroke, Modifiers, ModifiersChangedEvent, MouseButton,
-    MouseDownEvent, MouseExitEvent, MouseMoveEvent, MouseUpEvent, NavigationDirection, Pixels,
-    PlatformInput, ScrollDelta, ScrollWheelEvent, TouchPhase,
+    MouseDownEvent, MouseExitEvent, MouseMoveEvent, MousePressureEvent, MouseUpEvent,
+    NavigationDirection, Pixels, PlatformInput, PressureStage, ScrollDelta, ScrollWheelEvent,
+    TouchPhase,
     platform::mac::{
         LMGetKbdType, NSStringExt, TISCopyCurrentKeyboardLayoutInputSource,
         TISGetInputSourceProperty, UCKeyTranslate, kTISPropertyUnicodeKeyLayoutData,
@@ -187,6 +188,26 @@ impl PlatformInput {
                         })
                     })
                 }
+                NSEventType::NSEventTypePressure => {
+                    let stage = native_event.stage();
+                    let pressure = native_event.pressure();
+
+                    window_height.map(|window_height| {
+                        Self::MousePressure(MousePressureEvent {
+                            stage: match stage {
+                                1 => PressureStage::Normal,
+                                2 => PressureStage::Force,
+                                _ => PressureStage::Zero,
+                            },
+                            pressure,
+                            modifiers: read_modifiers(native_event),
+                            position: point(
+                                px(native_event.locationInWindow().x as f32),
+                                window_height - px(native_event.locationInWindow().y as f32),
+                            ),
+                        })
+                    })
+                }
                 // Some mice (like Logitech MX Master) send navigation buttons as swipe events
                 NSEventType::NSEventTypeSwipe => {
                     let navigation_direction = match native_event.phase() {

crates/gpui/src/platform/mac/metal_renderer.rs 🔗

@@ -46,9 +46,9 @@ pub unsafe fn new_renderer(
     _native_window: *mut c_void,
     _native_view: *mut c_void,
     _bounds: crate::Size<f32>,
-    _transparent: bool,
+    transparent: bool,
 ) -> Renderer {
-    MetalRenderer::new(context)
+    MetalRenderer::new(context, transparent)
 }
 
 pub(crate) struct InstanceBufferPool {
@@ -128,7 +128,7 @@ pub struct PathRasterizationVertex {
 }
 
 impl MetalRenderer {
-    pub fn new(instance_buffer_pool: Arc<Mutex<InstanceBufferPool>>) -> Self {
+    pub fn new(instance_buffer_pool: Arc<Mutex<InstanceBufferPool>>, transparent: bool) -> Self {
         // Prefer low‐power integrated GPUs on Intel Mac. On Apple
         // Silicon, there is only ever one GPU, so this is equivalent to
         // `metal::Device::system_default()`.
@@ -152,7 +152,9 @@ impl MetalRenderer {
         let layer = metal::MetalLayer::new();
         layer.set_device(&device);
         layer.set_pixel_format(MTLPixelFormat::BGRA8Unorm);
-        layer.set_opaque(false);
+        // Support direct-to-display rendering if the window is not transparent
+        // https://developer.apple.com/documentation/metal/managing-your-game-window-for-metal-in-macos
+        layer.set_opaque(!transparent);
         layer.set_maximum_drawable_count(3);
         unsafe {
             let _: () = msg_send![&*layer, setAllowsNextDrawableTimeout: NO];
@@ -352,8 +354,8 @@ impl MetalRenderer {
         }
     }
 
-    pub fn update_transparency(&self, _transparent: bool) {
-        // todo(mac)?
+    pub fn update_transparency(&self, transparent: bool) {
+        self.layer.set_opaque(!transparent);
     }
 
     pub fn destroy(&self) {

crates/gpui/src/platform/mac/open_type.rs 🔗

@@ -52,6 +52,11 @@ pub fn apply_features_and_fallbacks(
             &kCFTypeDictionaryKeyCallBacks,
             &kCFTypeDictionaryValueCallBacks,
         );
+
+        for value in &values {
+            CFRelease(*value as _);
+        }
+
         let new_descriptor = CTFontDescriptorCreateWithAttributes(attrs);
         CFRelease(attrs as _);
         let new_descriptor = CTFontDescriptor::wrap_under_create_rule(new_descriptor);

crates/gpui/src/platform/mac/pasteboard.rs 🔗

@@ -0,0 +1,344 @@
+use core::slice;
+use std::ffi::c_void;
+
+use cocoa::{
+    appkit::{NSPasteboard, NSPasteboardTypePNG, NSPasteboardTypeString, NSPasteboardTypeTIFF},
+    base::{id, nil},
+    foundation::NSData,
+};
+use objc::{msg_send, runtime::Object, sel, sel_impl};
+use strum::IntoEnumIterator as _;
+
+use crate::{
+    ClipboardEntry, ClipboardItem, ClipboardString, Image, ImageFormat, asset_cache::hash,
+    platform::mac::ns_string,
+};
+
+pub struct Pasteboard {
+    inner: id,
+    text_hash_type: id,
+    metadata_type: id,
+}
+
+impl Pasteboard {
+    pub fn general() -> Self {
+        unsafe { Self::new(NSPasteboard::generalPasteboard(nil)) }
+    }
+
+    pub fn find() -> Self {
+        unsafe { Self::new(NSPasteboard::pasteboardWithName(nil, NSPasteboardNameFind)) }
+    }
+
+    #[cfg(test)]
+    pub fn unique() -> Self {
+        unsafe { Self::new(NSPasteboard::pasteboardWithUniqueName(nil)) }
+    }
+
+    unsafe fn new(inner: id) -> Self {
+        Self {
+            inner,
+            text_hash_type: unsafe { ns_string("zed-text-hash") },
+            metadata_type: unsafe { ns_string("zed-metadata") },
+        }
+    }
+
+    pub fn read(&self) -> Option<ClipboardItem> {
+        // First, see if it's a string.
+        unsafe {
+            let pasteboard_types: id = self.inner.types();
+            let string_type: id = ns_string("public.utf8-plain-text");
+
+            if msg_send![pasteboard_types, containsObject: string_type] {
+                let data = self.inner.dataForType(string_type);
+                if data == nil {
+                    return None;
+                } else if data.bytes().is_null() {
+                    // https://developer.apple.com/documentation/foundation/nsdata/1410616-bytes?language=objc
+                    // "If the length of the NSData object is 0, this property returns nil."
+                    return Some(self.read_string(&[]));
+                } else {
+                    let bytes =
+                        slice::from_raw_parts(data.bytes() as *mut u8, data.length() as usize);
+
+                    return Some(self.read_string(bytes));
+                }
+            }
+
+            // If it wasn't a string, try the various supported image types.
+            for format in ImageFormat::iter() {
+                if let Some(item) = self.read_image(format) {
+                    return Some(item);
+                }
+            }
+        }
+
+        // If it wasn't a string or a supported image type, give up.
+        None
+    }
+
+    fn read_image(&self, format: ImageFormat) -> Option<ClipboardItem> {
+        let mut ut_type: UTType = format.into();
+
+        unsafe {
+            let types: id = self.inner.types();
+            if msg_send![types, containsObject: ut_type.inner()] {
+                self.data_for_type(ut_type.inner_mut()).map(|bytes| {
+                    let bytes = bytes.to_vec();
+                    let id = hash(&bytes);
+
+                    ClipboardItem {
+                        entries: vec![ClipboardEntry::Image(Image { format, bytes, id })],
+                    }
+                })
+            } else {
+                None
+            }
+        }
+    }
+
+    fn read_string(&self, text_bytes: &[u8]) -> ClipboardItem {
+        unsafe {
+            let text = String::from_utf8_lossy(text_bytes).to_string();
+            let metadata = self
+                .data_for_type(self.text_hash_type)
+                .and_then(|hash_bytes| {
+                    let hash_bytes = hash_bytes.try_into().ok()?;
+                    let hash = u64::from_be_bytes(hash_bytes);
+                    let metadata = self.data_for_type(self.metadata_type)?;
+
+                    if hash == ClipboardString::text_hash(&text) {
+                        String::from_utf8(metadata.to_vec()).ok()
+                    } else {
+                        None
+                    }
+                });
+
+            ClipboardItem {
+                entries: vec![ClipboardEntry::String(ClipboardString { text, metadata })],
+            }
+        }
+    }
+
+    unsafe fn data_for_type(&self, kind: id) -> Option<&[u8]> {
+        unsafe {
+            let data = self.inner.dataForType(kind);
+            if data == nil {
+                None
+            } else {
+                Some(slice::from_raw_parts(
+                    data.bytes() as *mut u8,
+                    data.length() as usize,
+                ))
+            }
+        }
+    }
+
+    pub fn write(&self, item: ClipboardItem) {
+        unsafe {
+            match item.entries.as_slice() {
+                [] => {
+                    // Writing an empty list of entries just clears the clipboard.
+                    self.inner.clearContents();
+                }
+                [ClipboardEntry::String(string)] => {
+                    self.write_plaintext(string);
+                }
+                [ClipboardEntry::Image(image)] => {
+                    self.write_image(image);
+                }
+                [ClipboardEntry::ExternalPaths(_)] => {}
+                _ => {
+                    // Agus NB: We're currently only writing string entries to the clipboard when we have more than one.
+                    //
+                    // This was the existing behavior before I refactored the outer clipboard code:
+                    // https://github.com/zed-industries/zed/blob/65f7412a0265552b06ce122655369d6cc7381dd6/crates/gpui/src/platform/mac/platform.rs#L1060-L1110
+                    //
+                    // Note how `any_images` is always `false`. We should fix that, but that's orthogonal to the refactor.
+
+                    let mut combined = ClipboardString {
+                        text: String::new(),
+                        metadata: None,
+                    };
+
+                    for entry in item.entries {
+                        match entry {
+                            ClipboardEntry::String(text) => {
+                                combined.text.push_str(&text.text());
+                                if combined.metadata.is_none() {
+                                    combined.metadata = text.metadata;
+                                }
+                            }
+                            _ => {}
+                        }
+                    }
+
+                    self.write_plaintext(&combined);
+                }
+            }
+        }
+    }
+
+    fn write_plaintext(&self, string: &ClipboardString) {
+        unsafe {
+            self.inner.clearContents();
+
+            let text_bytes = NSData::dataWithBytes_length_(
+                nil,
+                string.text.as_ptr() as *const c_void,
+                string.text.len() as u64,
+            );
+            self.inner
+                .setData_forType(text_bytes, NSPasteboardTypeString);
+
+            if let Some(metadata) = string.metadata.as_ref() {
+                let hash_bytes = ClipboardString::text_hash(&string.text).to_be_bytes();
+                let hash_bytes = NSData::dataWithBytes_length_(
+                    nil,
+                    hash_bytes.as_ptr() as *const c_void,
+                    hash_bytes.len() as u64,
+                );
+                self.inner.setData_forType(hash_bytes, self.text_hash_type);
+
+                let metadata_bytes = NSData::dataWithBytes_length_(
+                    nil,
+                    metadata.as_ptr() as *const c_void,
+                    metadata.len() as u64,
+                );
+                self.inner
+                    .setData_forType(metadata_bytes, self.metadata_type);
+            }
+        }
+    }
+
+    unsafe fn write_image(&self, image: &Image) {
+        unsafe {
+            self.inner.clearContents();
+
+            let bytes = NSData::dataWithBytes_length_(
+                nil,
+                image.bytes.as_ptr() as *const c_void,
+                image.bytes.len() as u64,
+            );
+
+            self.inner
+                .setData_forType(bytes, Into::<UTType>::into(image.format).inner_mut());
+        }
+    }
+}
+
+#[link(name = "AppKit", kind = "framework")]
+unsafe extern "C" {
+    /// [Apple's documentation](https://developer.apple.com/documentation/appkit/nspasteboardnamefind?language=objc)
+    pub static NSPasteboardNameFind: id;
+}
+
+impl From<ImageFormat> for UTType {
+    fn from(value: ImageFormat) -> Self {
+        match value {
+            ImageFormat::Png => Self::png(),
+            ImageFormat::Jpeg => Self::jpeg(),
+            ImageFormat::Tiff => Self::tiff(),
+            ImageFormat::Webp => Self::webp(),
+            ImageFormat::Gif => Self::gif(),
+            ImageFormat::Bmp => Self::bmp(),
+            ImageFormat::Svg => Self::svg(),
+            ImageFormat::Ico => Self::ico(),
+        }
+    }
+}
+
+// See https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/
+pub struct UTType(id);
+
+impl UTType {
+    pub fn png() -> Self {
+        // https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/png
+        Self(unsafe { NSPasteboardTypePNG }) // This is a rare case where there's a built-in NSPasteboardType
+    }
+
+    pub fn jpeg() -> Self {
+        // https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/jpeg
+        Self(unsafe { ns_string("public.jpeg") })
+    }
+
+    pub fn gif() -> Self {
+        // https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/gif
+        Self(unsafe { ns_string("com.compuserve.gif") })
+    }
+
+    pub fn webp() -> Self {
+        // https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/webp
+        Self(unsafe { ns_string("org.webmproject.webp") })
+    }
+
+    pub fn bmp() -> Self {
+        // https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/bmp
+        Self(unsafe { ns_string("com.microsoft.bmp") })
+    }
+
+    pub fn svg() -> Self {
+        // https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/svg
+        Self(unsafe { ns_string("public.svg-image") })
+    }
+
+    pub fn ico() -> Self {
+        // https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/ico
+        Self(unsafe { ns_string("com.microsoft.ico") })
+    }
+
+    pub fn tiff() -> Self {
+        // https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/tiff
+        Self(unsafe { NSPasteboardTypeTIFF }) // This is a rare case where there's a built-in NSPasteboardType
+    }
+
+    fn inner(&self) -> *const Object {
+        self.0
+    }
+
+    pub fn inner_mut(&self) -> *mut Object {
+        self.0 as *mut _
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use cocoa::{appkit::NSPasteboardTypeString, foundation::NSData};
+
+    use crate::{ClipboardEntry, ClipboardItem, ClipboardString};
+
+    use super::*;
+
+    #[test]
+    fn test_string() {
+        let pasteboard = Pasteboard::unique();
+        assert_eq!(pasteboard.read(), None);
+
+        let item = ClipboardItem::new_string("1".to_string());
+        pasteboard.write(item.clone());
+        assert_eq!(pasteboard.read(), Some(item));
+
+        let item = ClipboardItem {
+            entries: vec![ClipboardEntry::String(
+                ClipboardString::new("2".to_string()).with_json_metadata(vec![3, 4]),
+            )],
+        };
+        pasteboard.write(item.clone());
+        assert_eq!(pasteboard.read(), Some(item));
+
+        let text_from_other_app = "text from other app";
+        unsafe {
+            let bytes = NSData::dataWithBytes_length_(
+                nil,
+                text_from_other_app.as_ptr() as *const c_void,
+                text_from_other_app.len() as u64,
+            );
+            pasteboard
+                .inner
+                .setData_forType(bytes, NSPasteboardTypeString);
+        }
+        assert_eq!(
+            pasteboard.read(),
+            Some(ClipboardItem::new_string(text_from_other_app.to_string()))
+        );
+    }
+}

crates/gpui/src/platform/mac/platform.rs 🔗

@@ -1,29 +1,24 @@
 use super::{
-    BoolExt, MacKeyboardLayout, MacKeyboardMapper,
-    attributed_string::{NSAttributedString, NSMutableAttributedString},
-    events::key_to_native,
-    renderer,
+    BoolExt, MacKeyboardLayout, MacKeyboardMapper, events::key_to_native, ns_string, renderer,
 };
 use crate::{
-    Action, AnyWindowHandle, BackgroundExecutor, ClipboardEntry, ClipboardItem, ClipboardString,
-    CursorStyle, ForegroundExecutor, Image, ImageFormat, KeyContext, Keymap, MacDispatcher,
-    MacDisplay, MacWindow, Menu, MenuItem, OsMenu, OwnedMenu, PathPromptOptions, Platform,
-    PlatformDisplay, PlatformKeyboardLayout, PlatformKeyboardMapper, PlatformTextSystem,
-    PlatformWindow, Result, SystemMenuType, Task, WindowAppearance, WindowParams, hash,
+    Action, AnyWindowHandle, BackgroundExecutor, ClipboardItem, CursorStyle, ForegroundExecutor,
+    KeyContext, Keymap, MacDispatcher, MacDisplay, MacWindow, Menu, MenuItem, OsMenu, OwnedMenu,
+    PathPromptOptions, Platform, PlatformDisplay, PlatformKeyboardLayout, PlatformKeyboardMapper,
+    PlatformTextSystem, PlatformWindow, Result, SystemMenuType, Task, WindowAppearance,
+    WindowParams, platform::mac::pasteboard::Pasteboard,
 };
 use anyhow::{Context as _, anyhow};
 use block::ConcreteBlock;
 use cocoa::{
     appkit::{
         NSApplication, NSApplicationActivationPolicy::NSApplicationActivationPolicyRegular,
-        NSEventModifierFlags, NSMenu, NSMenuItem, NSModalResponse, NSOpenPanel, NSPasteboard,
-        NSPasteboardTypePNG, NSPasteboardTypeRTF, NSPasteboardTypeRTFD, NSPasteboardTypeString,
-        NSPasteboardTypeTIFF, NSSavePanel, NSVisualEffectState, NSVisualEffectView, NSWindow,
+        NSEventModifierFlags, NSMenu, NSMenuItem, NSModalResponse, NSOpenPanel, NSSavePanel,
+        NSVisualEffectState, NSVisualEffectView, NSWindow,
     },
     base::{BOOL, NO, YES, id, nil, selector},
     foundation::{
-        NSArray, NSAutoreleasePool, NSBundle, NSData, NSInteger, NSProcessInfo, NSRange, NSString,
-        NSUInteger, NSURL,
+        NSArray, NSAutoreleasePool, NSBundle, NSInteger, NSProcessInfo, NSString, NSUInteger, NSURL,
     },
 };
 use core_foundation::{
@@ -49,7 +44,6 @@ use ptr::null_mut;
 use semver::Version;
 use std::{
     cell::Cell,
-    convert::TryInto,
     ffi::{CStr, OsStr, c_void},
     os::{raw::c_char, unix::ffi::OsStrExt},
     path::{Path, PathBuf},
@@ -58,7 +52,6 @@ use std::{
     slice, str,
     sync::{Arc, OnceLock},
 };
-use strum::IntoEnumIterator;
 use util::{
     ResultExt,
     command::{new_smol_command, new_std_command},
@@ -164,9 +157,8 @@ pub(crate) struct MacPlatformState {
     text_system: Arc<dyn PlatformTextSystem>,
     renderer_context: renderer::Context,
     headless: bool,
-    pasteboard: id,
-    text_hash_pasteboard_type: id,
-    metadata_pasteboard_type: id,
+    general_pasteboard: Pasteboard,
+    find_pasteboard: Pasteboard,
     reopen: Option<Box<dyn FnMut()>>,
     on_keyboard_layout_change: Option<Box<dyn FnMut()>>,
     quit: Option<Box<dyn FnMut()>>,
@@ -206,9 +198,8 @@ impl MacPlatform {
             background_executor: BackgroundExecutor::new(dispatcher.clone()),
             foreground_executor: ForegroundExecutor::new(dispatcher),
             renderer_context: renderer::Context::default(),
-            pasteboard: unsafe { NSPasteboard::generalPasteboard(nil) },
-            text_hash_pasteboard_type: unsafe { ns_string("zed-text-hash") },
-            metadata_pasteboard_type: unsafe { ns_string("zed-metadata") },
+            general_pasteboard: Pasteboard::general(),
+            find_pasteboard: Pasteboard::find(),
             reopen: None,
             quit: None,
             menu_command: None,
@@ -224,20 +215,6 @@ impl MacPlatform {
         }))
     }
 
-    unsafe fn read_from_pasteboard(&self, pasteboard: *mut Object, kind: id) -> Option<&[u8]> {
-        unsafe {
-            let data = pasteboard.dataForType(kind);
-            if data == nil {
-                None
-            } else {
-                Some(slice::from_raw_parts(
-                    data.bytes() as *mut u8,
-                    data.length() as usize,
-                ))
-            }
-        }
-    }
-
     unsafe fn create_menu_bar(
         &self,
         menus: &Vec<Menu>,
@@ -1034,117 +1011,24 @@ impl Platform for MacPlatform {
         }
     }
 
-    fn write_to_clipboard(&self, item: ClipboardItem) {
-        use crate::ClipboardEntry;
-
-        unsafe {
-            // We only want to use NSAttributedString if there are multiple entries to write.
-            if item.entries.len() <= 1 {
-                match item.entries.first() {
-                    Some(entry) => match entry {
-                        ClipboardEntry::String(string) => {
-                            self.write_plaintext_to_clipboard(string);
-                        }
-                        ClipboardEntry::Image(image) => {
-                            self.write_image_to_clipboard(image);
-                        }
-                        ClipboardEntry::ExternalPaths(_) => {}
-                    },
-                    None => {
-                        // Writing an empty list of entries just clears the clipboard.
-                        let state = self.0.lock();
-                        state.pasteboard.clearContents();
-                    }
-                }
-            } else {
-                let mut any_images = false;
-                let attributed_string = {
-                    let mut buf = NSMutableAttributedString::alloc(nil)
-                        // TODO can we skip this? Or at least part of it?
-                        .init_attributed_string(NSString::alloc(nil).init_str(""));
-
-                    for entry in item.entries {
-                        if let ClipboardEntry::String(ClipboardString { text, metadata: _ }) = entry
-                        {
-                            let to_append = NSAttributedString::alloc(nil)
-                                .init_attributed_string(NSString::alloc(nil).init_str(&text));
-
-                            buf.appendAttributedString_(to_append);
-                        }
-                    }
-
-                    buf
-                };
-
-                let state = self.0.lock();
-                state.pasteboard.clearContents();
-
-                // Only set rich text clipboard types if we actually have 1+ images to include.
-                if any_images {
-                    let rtfd_data = attributed_string.RTFDFromRange_documentAttributes_(
-                        NSRange::new(0, msg_send![attributed_string, length]),
-                        nil,
-                    );
-                    if rtfd_data != nil {
-                        state
-                            .pasteboard
-                            .setData_forType(rtfd_data, NSPasteboardTypeRTFD);
-                    }
-
-                    let rtf_data = attributed_string.RTFFromRange_documentAttributes_(
-                        NSRange::new(0, attributed_string.length()),
-                        nil,
-                    );
-                    if rtf_data != nil {
-                        state
-                            .pasteboard
-                            .setData_forType(rtf_data, NSPasteboardTypeRTF);
-                    }
-                }
-
-                let plain_text = attributed_string.string();
-                state
-                    .pasteboard
-                    .setString_forType(plain_text, NSPasteboardTypeString);
-            }
-        }
-    }
-
     fn read_from_clipboard(&self) -> Option<ClipboardItem> {
         let state = self.0.lock();
-        let pasteboard = state.pasteboard;
-
-        // First, see if it's a string.
-        unsafe {
-            let types: id = pasteboard.types();
-            let string_type: id = ns_string("public.utf8-plain-text");
-
-            if msg_send![types, containsObject: string_type] {
-                let data = pasteboard.dataForType(string_type);
-                if data == nil {
-                    return None;
-                } else if data.bytes().is_null() {
-                    // https://developer.apple.com/documentation/foundation/nsdata/1410616-bytes?language=objc
-                    // "If the length of the NSData object is 0, this property returns nil."
-                    return Some(self.read_string_from_clipboard(&state, &[]));
-                } else {
-                    let bytes =
-                        slice::from_raw_parts(data.bytes() as *mut u8, data.length() as usize);
+        state.general_pasteboard.read()
+    }
 
-                    return Some(self.read_string_from_clipboard(&state, bytes));
-                }
-            }
+    fn write_to_clipboard(&self, item: ClipboardItem) {
+        let state = self.0.lock();
+        state.general_pasteboard.write(item);
+    }
 
-            // If it wasn't a string, try the various supported image types.
-            for format in ImageFormat::iter() {
-                if let Some(item) = try_clipboard_image(pasteboard, format) {
-                    return Some(item);
-                }
-            }
-        }
+    fn read_from_find_pasteboard(&self) -> Option<ClipboardItem> {
+        let state = self.0.lock();
+        state.find_pasteboard.read()
+    }
 
-        // If it wasn't a string or a supported image type, give up.
-        None
+    fn write_to_find_pasteboard(&self, item: ClipboardItem) {
+        let state = self.0.lock();
+        state.find_pasteboard.write(item);
     }
 
     fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>> {
@@ -1253,116 +1137,6 @@ impl Platform for MacPlatform {
     }
 }
 
-impl MacPlatform {
-    unsafe fn read_string_from_clipboard(
-        &self,
-        state: &MacPlatformState,
-        text_bytes: &[u8],
-    ) -> ClipboardItem {
-        unsafe {
-            let text = String::from_utf8_lossy(text_bytes).to_string();
-            let metadata = self
-                .read_from_pasteboard(state.pasteboard, state.text_hash_pasteboard_type)
-                .and_then(|hash_bytes| {
-                    let hash_bytes = hash_bytes.try_into().ok()?;
-                    let hash = u64::from_be_bytes(hash_bytes);
-                    let metadata = self
-                        .read_from_pasteboard(state.pasteboard, state.metadata_pasteboard_type)?;
-
-                    if hash == ClipboardString::text_hash(&text) {
-                        String::from_utf8(metadata.to_vec()).ok()
-                    } else {
-                        None
-                    }
-                });
-
-            ClipboardItem {
-                entries: vec![ClipboardEntry::String(ClipboardString { text, metadata })],
-            }
-        }
-    }
-
-    unsafe fn write_plaintext_to_clipboard(&self, string: &ClipboardString) {
-        unsafe {
-            let state = self.0.lock();
-            state.pasteboard.clearContents();
-
-            let text_bytes = NSData::dataWithBytes_length_(
-                nil,
-                string.text.as_ptr() as *const c_void,
-                string.text.len() as u64,
-            );
-            state
-                .pasteboard
-                .setData_forType(text_bytes, NSPasteboardTypeString);
-
-            if let Some(metadata) = string.metadata.as_ref() {
-                let hash_bytes = ClipboardString::text_hash(&string.text).to_be_bytes();
-                let hash_bytes = NSData::dataWithBytes_length_(
-                    nil,
-                    hash_bytes.as_ptr() as *const c_void,
-                    hash_bytes.len() as u64,
-                );
-                state
-                    .pasteboard
-                    .setData_forType(hash_bytes, state.text_hash_pasteboard_type);
-
-                let metadata_bytes = NSData::dataWithBytes_length_(
-                    nil,
-                    metadata.as_ptr() as *const c_void,
-                    metadata.len() as u64,
-                );
-                state
-                    .pasteboard
-                    .setData_forType(metadata_bytes, state.metadata_pasteboard_type);
-            }
-        }
-    }
-
-    unsafe fn write_image_to_clipboard(&self, image: &Image) {
-        unsafe {
-            let state = self.0.lock();
-            state.pasteboard.clearContents();
-
-            let bytes = NSData::dataWithBytes_length_(
-                nil,
-                image.bytes.as_ptr() as *const c_void,
-                image.bytes.len() as u64,
-            );
-
-            state
-                .pasteboard
-                .setData_forType(bytes, Into::<UTType>::into(image.format).inner_mut());
-        }
-    }
-}
-
-fn try_clipboard_image(pasteboard: id, format: ImageFormat) -> Option<ClipboardItem> {
-    let mut ut_type: UTType = format.into();
-
-    unsafe {
-        let types: id = pasteboard.types();
-        if msg_send![types, containsObject: ut_type.inner()] {
-            let data = pasteboard.dataForType(ut_type.inner_mut());
-            if data == nil {
-                None
-            } else {
-                let bytes = Vec::from(slice::from_raw_parts(
-                    data.bytes() as *mut u8,
-                    data.length() as usize,
-                ));
-                let id = hash(&bytes);
-
-                Some(ClipboardItem {
-                    entries: vec![ClipboardEntry::Image(Image { format, bytes, id })],
-                })
-            }
-        } else {
-            None
-        }
-    }
-}
-
 unsafe fn path_from_objc(path: id) -> PathBuf {
     let len = msg_send![path, lengthOfBytesUsingEncoding: NSUTF8StringEncoding];
     let bytes = unsafe { path.UTF8String() as *const u8 };
@@ -1543,10 +1317,6 @@ extern "C" fn handle_dock_menu(this: &mut Object, _: Sel, _: id) -> id {
     }
 }
 
-unsafe fn ns_string(string: &str) -> id {
-    unsafe { NSString::alloc(nil).init_str(string).autorelease() }
-}
-
 unsafe fn ns_url_to_path(url: id) -> Result<PathBuf> {
     let path: *mut c_char = msg_send![url, fileSystemRepresentation];
     anyhow::ensure!(!path.is_null(), "url is not a file path: {}", unsafe {
@@ -1607,120 +1377,3 @@ mod security {
     pub const errSecUserCanceled: OSStatus = -128;
     pub const errSecItemNotFound: OSStatus = -25300;
 }
-
-impl From<ImageFormat> for UTType {
-    fn from(value: ImageFormat) -> Self {
-        match value {
-            ImageFormat::Png => Self::png(),
-            ImageFormat::Jpeg => Self::jpeg(),
-            ImageFormat::Tiff => Self::tiff(),
-            ImageFormat::Webp => Self::webp(),
-            ImageFormat::Gif => Self::gif(),
-            ImageFormat::Bmp => Self::bmp(),
-            ImageFormat::Svg => Self::svg(),
-            ImageFormat::Ico => Self::ico(),
-        }
-    }
-}
-
-// See https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/
-struct UTType(id);
-
-impl UTType {
-    pub fn png() -> Self {
-        // https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/png
-        Self(unsafe { NSPasteboardTypePNG }) // This is a rare case where there's a built-in NSPasteboardType
-    }
-
-    pub fn jpeg() -> Self {
-        // https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/jpeg
-        Self(unsafe { ns_string("public.jpeg") })
-    }
-
-    pub fn gif() -> Self {
-        // https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/gif
-        Self(unsafe { ns_string("com.compuserve.gif") })
-    }
-
-    pub fn webp() -> Self {
-        // https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/webp
-        Self(unsafe { ns_string("org.webmproject.webp") })
-    }
-
-    pub fn bmp() -> Self {
-        // https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/bmp
-        Self(unsafe { ns_string("com.microsoft.bmp") })
-    }
-
-    pub fn svg() -> Self {
-        // https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/svg
-        Self(unsafe { ns_string("public.svg-image") })
-    }
-
-    pub fn ico() -> Self {
-        // https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/ico
-        Self(unsafe { ns_string("com.microsoft.ico") })
-    }
-
-    pub fn tiff() -> Self {
-        // https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/tiff
-        Self(unsafe { NSPasteboardTypeTIFF }) // This is a rare case where there's a built-in NSPasteboardType
-    }
-
-    fn inner(&self) -> *const Object {
-        self.0
-    }
-
-    fn inner_mut(&self) -> *mut Object {
-        self.0 as *mut _
-    }
-}
-
-#[cfg(test)]
-mod tests {
-    use crate::ClipboardItem;
-
-    use super::*;
-
-    #[test]
-    fn test_clipboard() {
-        let platform = build_platform();
-        assert_eq!(platform.read_from_clipboard(), None);
-
-        let item = ClipboardItem::new_string("1".to_string());
-        platform.write_to_clipboard(item.clone());
-        assert_eq!(platform.read_from_clipboard(), Some(item));
-
-        let item = ClipboardItem {
-            entries: vec![ClipboardEntry::String(
-                ClipboardString::new("2".to_string()).with_json_metadata(vec![3, 4]),
-            )],
-        };
-        platform.write_to_clipboard(item.clone());
-        assert_eq!(platform.read_from_clipboard(), Some(item));
-
-        let text_from_other_app = "text from other app";
-        unsafe {
-            let bytes = NSData::dataWithBytes_length_(
-                nil,
-                text_from_other_app.as_ptr() as *const c_void,
-                text_from_other_app.len() as u64,
-            );
-            platform
-                .0
-                .lock()
-                .pasteboard
-                .setData_forType(bytes, NSPasteboardTypeString);
-        }
-        assert_eq!(
-            platform.read_from_clipboard(),
-            Some(ClipboardItem::new_string(text_from_other_app.to_string()))
-        );
-    }
-
-    fn build_platform() -> MacPlatform {
-        let platform = MacPlatform::new(false);
-        platform.0.lock().pasteboard = unsafe { NSPasteboard::pasteboardWithUniqueName(nil) };
-        platform
-    }
-}

crates/gpui/src/platform/mac/screen_capture.rs 🔗

@@ -1,3 +1,4 @@
+use super::ns_string;
 use crate::{
     DevicePixels, ForegroundExecutor, SharedString, SourceMetadata,
     platform::{ScreenCaptureFrame, ScreenCaptureSource, ScreenCaptureStream},
@@ -7,7 +8,7 @@ use anyhow::{Result, anyhow};
 use block::ConcreteBlock;
 use cocoa::{
     base::{YES, id, nil},
-    foundation::{NSArray, NSString},
+    foundation::NSArray,
 };
 use collections::HashMap;
 use core_foundation::base::TCFType;
@@ -109,13 +110,21 @@ impl ScreenCaptureSource for MacScreenCaptureSource {
             let _: id = msg_send![configuration, setHeight: meta.resolution.height.0 as i64];
             let stream: id = msg_send![stream, initWithFilter:filter configuration:configuration delegate:delegate];
 
+            // Stream contains filter, configuration, and delegate internally so we release them here
+            // to prevent a memory leak when steam is dropped
+            let _: () = msg_send![filter, release];
+            let _: () = msg_send![configuration, release];
+            let _: () = msg_send![delegate, release];
+
             let (mut tx, rx) = oneshot::channel();
 
             let mut error: id = nil;
             let _: () = msg_send![stream, addStreamOutput:output type:SCStreamOutputTypeScreen sampleHandlerQueue:0 error:&mut error as *mut id];
             if error != nil {
                 let message: id = msg_send![error, localizedDescription];
-                tx.send(Err(anyhow!("failed to add stream  output {message:?}")))
+                let _: () = msg_send![stream, release];
+                let _: () = msg_send![output, release];
+                tx.send(Err(anyhow!("failed to add stream output {message:?}")))
                     .ok();
                 return rx;
             }
@@ -131,8 +140,10 @@ impl ScreenCaptureSource for MacScreenCaptureSource {
                         };
                         Ok(Box::new(stream) as Box<dyn ScreenCaptureStream>)
                     } else {
+                        let _: () = msg_send![stream, release];
+                        let _: () = msg_send![output, release];
                         let message: id = msg_send![error, localizedDescription];
-                        Err(anyhow!("failed to stop screen capture stream {message:?}"))
+                        Err(anyhow!("failed to start screen capture stream {message:?}"))
                     };
                     if let Some(tx) = tx.borrow_mut().take() {
                         tx.send(result).ok();
@@ -195,7 +206,7 @@ unsafe fn screen_id_to_human_label() -> HashMap<CGDirectDisplayID, ScreenMeta> {
     let screens: id = msg_send![class!(NSScreen), screens];
     let count: usize = msg_send![screens, count];
     let mut map = HashMap::default();
-    let screen_number_key = unsafe { NSString::alloc(nil).init_str("NSScreenNumber") };
+    let screen_number_key = unsafe { ns_string("NSScreenNumber") };
     for i in 0..count {
         let screen: id = msg_send![screens, objectAtIndex: i];
         let device_desc: id = msg_send![screen, deviceDescription];

crates/gpui/src/platform/mac/text_system.rs 🔗

@@ -8,6 +8,7 @@ use anyhow::anyhow;
 use cocoa::appkit::CGFloat;
 use collections::HashMap;
 use core_foundation::{
+    array::{CFArray, CFArrayRef},
     attributed_string::CFMutableAttributedString,
     base::{CFRange, TCFType},
     number::CFNumber,
@@ -21,8 +22,10 @@ use core_graphics::{
 };
 use core_text::{
     font::CTFont,
+    font_collection::CTFontCollectionRef,
     font_descriptor::{
-        kCTFontSlantTrait, kCTFontSymbolicTrait, kCTFontWeightTrait, kCTFontWidthTrait,
+        CTFontDescriptor, kCTFontSlantTrait, kCTFontSymbolicTrait, kCTFontWeightTrait,
+        kCTFontWidthTrait,
     },
     line::CTLine,
     string_attributes::kCTFontAttributeName,
@@ -97,7 +100,26 @@ impl PlatformTextSystem for MacTextSystem {
     fn all_font_names(&self) -> Vec<String> {
         let mut names = Vec::new();
         let collection = core_text::font_collection::create_for_all_families();
-        let Some(descriptors) = collection.get_descriptors() else {
+        // NOTE: We intentionally avoid using `collection.get_descriptors()` here because
+        // it has a memory leak bug in core-text v21.0.0. The upstream code uses
+        // `wrap_under_get_rule` but `CTFontCollectionCreateMatchingFontDescriptors`
+        // follows the Create Rule (caller owns the result), so it should use
+        // `wrap_under_create_rule`. We call the function directly with correct memory management.
+        unsafe extern "C" {
+            fn CTFontCollectionCreateMatchingFontDescriptors(
+                collection: CTFontCollectionRef,
+            ) -> CFArrayRef;
+        }
+        let descriptors: Option<CFArray<CTFontDescriptor>> = unsafe {
+            let array_ref =
+                CTFontCollectionCreateMatchingFontDescriptors(collection.as_concrete_TypeRef());
+            if array_ref.is_null() {
+                None
+            } else {
+                Some(CFArray::wrap_under_create_rule(array_ref))
+            }
+        };
+        let Some(descriptors) = descriptors else {
             return names;
         };
         for descriptor in descriptors.into_iter() {

crates/gpui/src/platform/mac/window.rs 🔗

@@ -62,9 +62,12 @@ static mut BLURRED_VIEW_CLASS: *const Class = ptr::null();
 #[allow(non_upper_case_globals)]
 const NSWindowStyleMaskNonactivatingPanel: NSWindowStyleMask =
     NSWindowStyleMask::from_bits_retain(1 << 7);
+// WindowLevel const value ref: https://docs.rs/core-graphics2/0.4.1/src/core_graphics2/window_level.rs.html
 #[allow(non_upper_case_globals)]
 const NSNormalWindowLevel: NSInteger = 0;
 #[allow(non_upper_case_globals)]
+const NSFloatingWindowLevel: NSInteger = 3;
+#[allow(non_upper_case_globals)]
 const NSPopUpWindowLevel: NSInteger = 101;
 #[allow(non_upper_case_globals)]
 const NSTrackingMouseEnteredAndExited: NSUInteger = 0x01;
@@ -153,6 +156,10 @@ unsafe fn build_classes() {
                     sel!(mouseMoved:),
                     handle_view_event as extern "C" fn(&Object, Sel, id),
                 );
+                decl.add_method(
+                    sel!(pressureChangeWithEvent:),
+                    handle_view_event as extern "C" fn(&Object, Sel, id),
+                );
                 decl.add_method(
                     sel!(mouseExited:),
                     handle_view_event as extern "C" fn(&Object, Sel, id),
@@ -419,6 +426,8 @@ struct MacWindowState {
     select_previous_tab_callback: Option<Box<dyn FnMut()>>,
     toggle_tab_bar_callback: Option<Box<dyn FnMut()>>,
     activated_least_once: bool,
+    // The parent window if this window is a sheet (Dialog kind)
+    sheet_parent: Option<id>,
 }
 
 impl MacWindowState {
@@ -618,11 +627,16 @@ impl MacWindow {
             }
 
             let native_window: id = match kind {
-                WindowKind::Normal | WindowKind::Floating => msg_send![WINDOW_CLASS, alloc],
+                WindowKind::Normal => {
+                    msg_send![WINDOW_CLASS, alloc]
+                }
                 WindowKind::PopUp => {
                     style_mask |= NSWindowStyleMaskNonactivatingPanel;
                     msg_send![PANEL_CLASS, alloc]
                 }
+                WindowKind::Floating | WindowKind::Dialog => {
+                    msg_send![PANEL_CLASS, alloc]
+                }
             };
 
             let display = display_id
@@ -725,6 +739,7 @@ impl MacWindow {
                 select_previous_tab_callback: None,
                 toggle_tab_bar_callback: None,
                 activated_least_once: false,
+                sheet_parent: None,
             })));
 
             (*native_window).set_ivar(
@@ -775,13 +790,22 @@ impl MacWindow {
             content_view.addSubview_(native_view.autorelease());
             native_window.makeFirstResponder_(native_view);
 
+            let app: id = NSApplication::sharedApplication(nil);
+            let main_window: id = msg_send![app, mainWindow];
+            let mut sheet_parent = None;
+
             match kind {
                 WindowKind::Normal | WindowKind::Floating => {
-                    native_window.setLevel_(NSNormalWindowLevel);
+                    if kind == WindowKind::Floating {
+                        // Let the window float keep above normal windows.
+                        native_window.setLevel_(NSFloatingWindowLevel);
+                    } else {
+                        native_window.setLevel_(NSNormalWindowLevel);
+                    }
                     native_window.setAcceptsMouseMovedEvents_(YES);
 
                     if let Some(tabbing_identifier) = tabbing_identifier {
-                        let tabbing_id = NSString::alloc(nil).init_str(tabbing_identifier.as_str());
+                        let tabbing_id = ns_string(tabbing_identifier.as_str());
                         let _: () = msg_send![native_window, setTabbingIdentifier: tabbing_id];
                     } else {
                         let _: () = msg_send![native_window, setTabbingIdentifier:nil];
@@ -812,10 +836,23 @@ impl MacWindow {
                         NSWindowCollectionBehavior::NSWindowCollectionBehaviorFullScreenAuxiliary
                     );
                 }
+                WindowKind::Dialog => {
+                    if !main_window.is_null() {
+                        let parent = {
+                            let active_sheet: id = msg_send![main_window, attachedSheet];
+                            if active_sheet.is_null() {
+                                main_window
+                            } else {
+                                active_sheet
+                            }
+                        };
+                        let _: () =
+                            msg_send![parent, beginSheet: native_window completionHandler: nil];
+                        sheet_parent = Some(parent);
+                    }
+                }
             }
 
-            let app = NSApplication::sharedApplication(nil);
-            let main_window: id = msg_send![app, mainWindow];
             if allows_automatic_window_tabbing
                 && !main_window.is_null()
                 && main_window != native_window
@@ -857,7 +894,11 @@ impl MacWindow {
             // the window position might be incorrect if the main screen (the screen that contains the window that has focus)
             //  is different from the primary screen.
             NSWindow::setFrameTopLeftPoint_(native_window, window_rect.origin);
-            window.0.lock().move_traffic_light();
+            {
+                let mut window_state = window.0.lock();
+                window_state.move_traffic_light();
+                window_state.sheet_parent = sheet_parent;
+            }
 
             pool.drain();
 
@@ -904,8 +945,8 @@ impl MacWindow {
     pub fn get_user_tabbing_preference() -> Option<UserTabbingPreference> {
         unsafe {
             let defaults: id = NSUserDefaults::standardUserDefaults();
-            let domain = NSString::alloc(nil).init_str("NSGlobalDomain");
-            let key = NSString::alloc(nil).init_str("AppleWindowTabbingMode");
+            let domain = ns_string("NSGlobalDomain");
+            let key = ns_string("AppleWindowTabbingMode");
 
             let dict: id = msg_send![defaults, persistentDomainForName: domain];
             let value: id = if !dict.is_null() {
@@ -934,6 +975,7 @@ impl Drop for MacWindow {
         let mut this = self.0.lock();
         this.renderer.destroy();
         let window = this.native_window;
+        let sheet_parent = this.sheet_parent.take();
         this.display_link.take();
         unsafe {
             this.native_window.setDelegate_(nil);
@@ -942,6 +984,9 @@ impl Drop for MacWindow {
         this.executor
             .spawn(async move {
                 unsafe {
+                    if let Some(parent) = sheet_parent {
+                        let _: () = msg_send![parent, endSheet: window];
+                    }
                     window.close();
                     window.autorelease();
                 }
@@ -1033,7 +1078,7 @@ impl PlatformWindow for MacWindow {
             }
 
             if let Some(tabbing_identifier) = tabbing_identifier {
-                let tabbing_id = NSString::alloc(nil).init_str(tabbing_identifier.as_str());
+                let tabbing_id = ns_string(tabbing_identifier.as_str());
                 let _: () = msg_send![native_window, setTabbingIdentifier: tabbing_id];
             } else {
                 let _: () = msg_send![native_window, setTabbingIdentifier:nil];
@@ -1059,10 +1104,8 @@ impl PlatformWindow for MacWindow {
                 return None;
             }
             let device_description: id = msg_send![screen, deviceDescription];
-            let screen_number: id = NSDictionary::valueForKey_(
-                device_description,
-                NSString::alloc(nil).init_str("NSScreenNumber"),
-            );
+            let screen_number: id =
+                NSDictionary::valueForKey_(device_description, ns_string("NSScreenNumber"));
 
             let screen_number: u32 = msg_send![screen_number, unsignedIntValue];
 
@@ -1188,6 +1231,7 @@ impl PlatformWindow for MacWindow {
             let (done_tx, done_rx) = oneshot::channel();
             let done_tx = Cell::new(Some(done_tx));
             let block = ConcreteBlock::new(move |answer: NSInteger| {
+                let _: () = msg_send![alert, release];
                 if let Some(done_tx) = done_tx.take() {
                     let _ = done_tx.send(answer.try_into().unwrap());
                 }
@@ -1505,8 +1549,8 @@ impl PlatformWindow for MacWindow {
             .spawn(async move {
                 unsafe {
                     let defaults: id = NSUserDefaults::standardUserDefaults();
-                    let domain = NSString::alloc(nil).init_str("NSGlobalDomain");
-                    let key = NSString::alloc(nil).init_str("AppleActionOnDoubleClick");
+                    let domain = ns_string("NSGlobalDomain");
+                    let key = ns_string("AppleActionOnDoubleClick");
 
                     let dict: id = msg_send![defaults, persistentDomainForName: domain];
                     let action: id = if !dict.is_null() {
@@ -2508,7 +2552,7 @@ where
 unsafe fn display_id_for_screen(screen: id) -> CGDirectDisplayID {
     unsafe {
         let device_description = NSScreen::deviceDescription(screen);
-        let screen_number_key: id = NSString::alloc(nil).init_str("NSScreenNumber");
+        let screen_number_key: id = ns_string("NSScreenNumber");
         let screen_number = device_description.objectForKey_(screen_number_key);
         let screen_number: NSUInteger = msg_send![screen_number, unsignedIntegerValue];
         screen_number as CGDirectDisplayID
@@ -2554,7 +2598,7 @@ unsafe fn remove_layer_background(layer: id) {
             // `description` reflects its name and some parameters. Currently `NSVisualEffectView`
             // uses a `CAFilter` named "colorSaturate". If one day they switch to `CIFilter`, the
             // `description` will still contain "Saturat" ("... inputSaturation = ...").
-            let test_string: id = NSString::alloc(nil).init_str("Saturat").autorelease();
+            let test_string: id = ns_string("Saturat");
             let count = NSArray::count(filters);
             for i in 0..count {
                 let description: id = msg_send![filters.objectAtIndex(i), description];

crates/gpui/src/platform/test/dispatcher.rs 🔗

@@ -1,4 +1,4 @@
-use crate::{PlatformDispatcher, RunnableVariant, TaskLabel};
+use crate::{PlatformDispatcher, Priority, RunnableVariant, TaskLabel};
 use backtrace::Backtrace;
 use collections::{HashMap, HashSet, VecDeque};
 use parking::Unparker;
@@ -284,7 +284,7 @@ impl PlatformDispatcher for TestDispatcher {
         state.start_time + state.time
     }
 
-    fn dispatch(&self, runnable: RunnableVariant, label: Option<TaskLabel>) {
+    fn dispatch(&self, runnable: RunnableVariant, label: Option<TaskLabel>, _priority: Priority) {
         {
             let mut state = self.state.lock();
             if label.is_some_and(|label| state.deprioritized_task_labels.contains(&label)) {
@@ -296,7 +296,7 @@ impl PlatformDispatcher for TestDispatcher {
         self.unpark_all();
     }
 
-    fn dispatch_on_main_thread(&self, runnable: RunnableVariant) {
+    fn dispatch_on_main_thread(&self, runnable: RunnableVariant, _priority: Priority) {
         self.state
             .lock()
             .foreground
@@ -318,4 +318,10 @@ impl PlatformDispatcher for TestDispatcher {
     fn as_test(&self) -> Option<&TestDispatcher> {
         Some(self)
     }
+
+    fn spawn_realtime(&self, _priority: crate::RealtimePriority, f: Box<dyn FnOnce() + Send>) {
+        std::thread::spawn(move || {
+            f();
+        });
+    }
 }

crates/gpui/src/platform/test/platform.rs 🔗

@@ -32,6 +32,8 @@ pub(crate) struct TestPlatform {
     current_clipboard_item: Mutex<Option<ClipboardItem>>,
     #[cfg(any(target_os = "linux", target_os = "freebsd"))]
     current_primary_item: Mutex<Option<ClipboardItem>>,
+    #[cfg(target_os = "macos")]
+    current_find_pasteboard_item: Mutex<Option<ClipboardItem>>,
     pub(crate) prompts: RefCell<TestPrompts>,
     screen_capture_sources: RefCell<Vec<TestScreenCaptureSource>>,
     pub opened_url: RefCell<Option<String>>,
@@ -117,6 +119,8 @@ impl TestPlatform {
             current_clipboard_item: Mutex::new(None),
             #[cfg(any(target_os = "linux", target_os = "freebsd"))]
             current_primary_item: Mutex::new(None),
+            #[cfg(target_os = "macos")]
+            current_find_pasteboard_item: Mutex::new(None),
             weak: weak.clone(),
             opened_url: Default::default(),
             #[cfg(target_os = "windows")]
@@ -398,9 +402,8 @@ impl Platform for TestPlatform {
         false
     }
 
-    #[cfg(any(target_os = "linux", target_os = "freebsd"))]
-    fn write_to_primary(&self, item: ClipboardItem) {
-        *self.current_primary_item.lock() = Some(item);
+    fn read_from_clipboard(&self) -> Option<ClipboardItem> {
+        self.current_clipboard_item.lock().clone()
     }
 
     fn write_to_clipboard(&self, item: ClipboardItem) {
@@ -412,8 +415,19 @@ impl Platform for TestPlatform {
         self.current_primary_item.lock().clone()
     }
 
-    fn read_from_clipboard(&self) -> Option<ClipboardItem> {
-        self.current_clipboard_item.lock().clone()
+    #[cfg(any(target_os = "linux", target_os = "freebsd"))]
+    fn write_to_primary(&self, item: ClipboardItem) {
+        *self.current_primary_item.lock() = Some(item);
+    }
+
+    #[cfg(target_os = "macos")]
+    fn read_from_find_pasteboard(&self) -> Option<ClipboardItem> {
+        self.current_find_pasteboard_item.lock().clone()
+    }
+
+    #[cfg(target_os = "macos")]
+    fn write_to_find_pasteboard(&self, item: ClipboardItem) {
+        *self.current_find_pasteboard_item.lock() = Some(item);
     }
 
     fn write_credentials(&self, _url: &str, _username: &str, _password: &[u8]) -> Task<Result<()>> {

crates/gpui/src/platform/windows/dispatcher.rs 🔗

@@ -7,9 +7,7 @@ use std::{
 use flume::Sender;
 use util::ResultExt;
 use windows::{
-    System::Threading::{
-        ThreadPool, ThreadPoolTimer, TimerElapsedHandler, WorkItemHandler, WorkItemPriority,
-    },
+    System::Threading::{ThreadPool, ThreadPoolTimer, TimerElapsedHandler, WorkItemHandler},
     Win32::{
         Foundation::{LPARAM, WPARAM},
         UI::WindowsAndMessaging::PostMessageW,
@@ -55,7 +53,7 @@ impl WindowsDispatcher {
                 Ok(())
             })
         };
-        ThreadPool::RunWithPriorityAsync(&handler, WorkItemPriority::High).log_err();
+        ThreadPool::RunAsync(&handler).log_err();
     }
 
     fn dispatch_on_threadpool_after(&self, runnable: RunnableVariant, duration: Duration) {
@@ -148,14 +146,19 @@ impl PlatformDispatcher for WindowsDispatcher {
         current().id() == self.main_thread_id
     }
 
-    fn dispatch(&self, runnable: RunnableVariant, label: Option<TaskLabel>) {
+    fn dispatch(
+        &self,
+        runnable: RunnableVariant,
+        label: Option<TaskLabel>,
+        _priority: gpui::Priority,
+    ) {
         self.dispatch_on_threadpool(runnable);
         if let Some(label) = label {
             log::debug!("TaskLabel: {label:?}");
         }
     }
 
-    fn dispatch_on_main_thread(&self, runnable: RunnableVariant) {
+    fn dispatch_on_main_thread(&self, runnable: RunnableVariant, _priority: gpui::Priority) {
         match self.main_sender.send(runnable) {
             Ok(_) => {
                 if !self.wake_posted.swap(true, Ordering::AcqRel) {
@@ -187,4 +190,9 @@ impl PlatformDispatcher for WindowsDispatcher {
     fn dispatch_after(&self, duration: Duration, runnable: RunnableVariant) {
         self.dispatch_on_threadpool_after(runnable, duration);
     }
+
+    fn spawn_realtime(&self, _priority: crate::RealtimePriority, _f: Box<dyn FnOnce() + Send>) {
+        // disabled on windows for now.
+        unimplemented!();
+    }
 }

crates/gpui/src/platform/windows/display.rs 🔗

@@ -23,6 +23,7 @@ pub(crate) struct WindowsDisplay {
     pub display_id: DisplayId,
     scale_factor: f32,
     bounds: Bounds<Pixels>,
+    visible_bounds: Bounds<Pixels>,
     physical_bounds: Bounds<DevicePixels>,
     uuid: Uuid,
 }
@@ -36,6 +37,7 @@ impl WindowsDisplay {
         let screen = available_monitors().into_iter().nth(display_id.0 as _)?;
         let info = get_monitor_info(screen).log_err()?;
         let monitor_size = info.monitorInfo.rcMonitor;
+        let work_area = info.monitorInfo.rcWork;
         let uuid = generate_uuid(&info.szDevice);
         let scale_factor = get_scale_factor_for_monitor(screen).log_err()?;
         let physical_size = size(
@@ -55,6 +57,14 @@ impl WindowsDisplay {
                 ),
                 size: physical_size.to_pixels(scale_factor),
             },
+            visible_bounds: Bounds {
+                origin: logical_point(work_area.left as f32, work_area.top as f32, scale_factor),
+                size: size(
+                    (work_area.right - work_area.left) as f32 / scale_factor,
+                    (work_area.bottom - work_area.top) as f32 / scale_factor,
+                )
+                .map(crate::px),
+            },
             physical_bounds: Bounds {
                 origin: point(monitor_size.left.into(), monitor_size.top.into()),
                 size: physical_size,
@@ -66,6 +76,7 @@ impl WindowsDisplay {
     pub fn new_with_handle(monitor: HMONITOR) -> anyhow::Result<Self> {
         let info = get_monitor_info(monitor)?;
         let monitor_size = info.monitorInfo.rcMonitor;
+        let work_area = info.monitorInfo.rcWork;
         let uuid = generate_uuid(&info.szDevice);
         let display_id = available_monitors()
             .iter()
@@ -89,6 +100,14 @@ impl WindowsDisplay {
                 ),
                 size: physical_size.to_pixels(scale_factor),
             },
+            visible_bounds: Bounds {
+                origin: logical_point(work_area.left as f32, work_area.top as f32, scale_factor),
+                size: size(
+                    (work_area.right - work_area.left) as f32 / scale_factor,
+                    (work_area.bottom - work_area.top) as f32 / scale_factor,
+                )
+                .map(crate::px),
+            },
             physical_bounds: Bounds {
                 origin: point(monitor_size.left.into(), monitor_size.top.into()),
                 size: physical_size,
@@ -100,6 +119,7 @@ impl WindowsDisplay {
     fn new_with_handle_and_id(handle: HMONITOR, display_id: DisplayId) -> anyhow::Result<Self> {
         let info = get_monitor_info(handle)?;
         let monitor_size = info.monitorInfo.rcMonitor;
+        let work_area = info.monitorInfo.rcWork;
         let uuid = generate_uuid(&info.szDevice);
         let scale_factor = get_scale_factor_for_monitor(handle)?;
         let physical_size = size(
@@ -119,6 +139,14 @@ impl WindowsDisplay {
                 ),
                 size: physical_size.to_pixels(scale_factor),
             },
+            visible_bounds: Bounds {
+                origin: logical_point(work_area.left as f32, work_area.top as f32, scale_factor),
+                size: size(
+                    (work_area.right - work_area.left) as f32 / scale_factor,
+                    (work_area.bottom - work_area.top) as f32 / scale_factor,
+                )
+                .map(crate::px),
+            },
             physical_bounds: Bounds {
                 origin: point(monitor_size.left.into(), monitor_size.top.into()),
                 size: physical_size,
@@ -193,6 +221,10 @@ impl PlatformDisplay for WindowsDisplay {
     fn bounds(&self) -> Bounds<Pixels> {
         self.bounds
     }
+
+    fn visible_bounds(&self) -> Bounds<Pixels> {
+        self.visible_bounds
+    }
 }
 
 fn available_monitors() -> SmallVec<[HMONITOR; 4]> {

crates/gpui/src/platform/windows/events.rs 🔗

@@ -40,6 +40,11 @@ impl WindowsWindowInner {
         lparam: LPARAM,
     ) -> LRESULT {
         let handled = match msg {
+            // eagerly activate the window, so calls to `active_window` will work correctly
+            WM_MOUSEACTIVATE => {
+                unsafe { SetActiveWindow(handle).ok() };
+                None
+            }
             WM_ACTIVATE => self.handle_activate_msg(wparam),
             WM_CREATE => self.handle_create_msg(handle),
             WM_MOVE => self.handle_move_msg(handle, lparam),
@@ -265,6 +270,14 @@ impl WindowsWindowInner {
 
     fn handle_destroy_msg(&self, handle: HWND) -> Option<isize> {
         let callback = { self.state.callbacks.close.take() };
+        // Re-enable parent window if this was a modal dialog
+        if let Some(parent_hwnd) = self.parent_hwnd {
+            unsafe {
+                let _ = EnableWindow(parent_hwnd, true);
+                let _ = SetForegroundWindow(parent_hwnd);
+            }
+        }
+
         if let Some(callback) = callback {
             callback();
         }

crates/gpui/src/platform/windows/platform.rs 🔗

@@ -659,7 +659,7 @@ impl Platform for WindowsPlatform {
             if let Err(err) = result {
                 // ERROR_NOT_FOUND means the credential doesn't exist.
                 // Return Ok(None) to match macOS and Linux behavior.
-                if err.code().0 == ERROR_NOT_FOUND.0 as i32 {
+                if err.code() == ERROR_NOT_FOUND.to_hresult() {
                     return Ok(None);
                 }
                 return Err(err.into());

crates/gpui/src/platform/windows/window.rs 🔗

@@ -83,6 +83,7 @@ pub(crate) struct WindowsWindowInner {
     pub(crate) validation_number: usize,
     pub(crate) main_receiver: flume::Receiver<RunnableVariant>,
     pub(crate) platform_window_handle: HWND,
+    pub(crate) parent_hwnd: Option<HWND>,
 }
 
 impl WindowsWindowState {
@@ -241,6 +242,7 @@ impl WindowsWindowInner {
             main_receiver: context.main_receiver.clone(),
             platform_window_handle: context.platform_window_handle,
             system_settings: WindowsSystemSettings::new(context.display),
+            parent_hwnd: context.parent_hwnd,
         }))
     }
 
@@ -368,6 +370,7 @@ struct WindowCreateContext {
     disable_direct_composition: bool,
     directx_devices: DirectXDevices,
     invalidate_devices: Arc<AtomicBool>,
+    parent_hwnd: Option<HWND>,
 }
 
 impl WindowsWindow {
@@ -390,6 +393,20 @@ impl WindowsWindow {
             invalidate_devices,
         } = creation_info;
         register_window_class(icon);
+        let parent_hwnd = if params.kind == WindowKind::Dialog {
+            let parent_window = unsafe { GetActiveWindow() };
+            if parent_window.is_invalid() {
+                None
+            } else {
+                // Disable the parent window to make this dialog modal
+                unsafe {
+                    EnableWindow(parent_window, false).as_bool();
+                };
+                Some(parent_window)
+            }
+        } else {
+            None
+        };
         let hide_title_bar = params
             .titlebar
             .as_ref()
@@ -416,8 +433,14 @@ impl WindowsWindow {
             if params.is_minimizable {
                 dwstyle |= WS_MINIMIZEBOX;
             }
+            let dwexstyle = if params.kind == WindowKind::Dialog {
+                dwstyle |= WS_POPUP | WS_CAPTION;
+                WS_EX_DLGMODALFRAME
+            } else {
+                WS_EX_APPWINDOW
+            };
 
-            (WS_EX_APPWINDOW, dwstyle)
+            (dwexstyle, dwstyle)
         };
         if !disable_direct_composition {
             dwexstyle |= WS_EX_NOREDIRECTIONBITMAP;
@@ -449,6 +472,7 @@ impl WindowsWindow {
             disable_direct_composition,
             directx_devices,
             invalidate_devices,
+            parent_hwnd,
         };
         let creation_result = unsafe {
             CreateWindowExW(
@@ -460,7 +484,7 @@ impl WindowsWindow {
                 CW_USEDEFAULT,
                 CW_USEDEFAULT,
                 CW_USEDEFAULT,
-                None,
+                parent_hwnd,
                 None,
                 Some(hinstance.into()),
                 Some(&context as *const _ as *const _),
@@ -716,8 +740,8 @@ impl PlatformWindow for WindowsWindow {
                         ShowWindowAsync(hwnd, SW_RESTORE).ok().log_err();
                     }
 
-                    SetActiveWindow(hwnd).log_err();
-                    SetFocus(Some(hwnd)).log_err();
+                    SetActiveWindow(hwnd).ok();
+                    SetFocus(Some(hwnd)).ok();
                 }
 
                 // premium ragebait by windows, this is needed because the window

crates/gpui/src/profiler.rs 🔗

@@ -216,3 +216,19 @@ impl Drop for ThreadTimings {
         thread_timings.swap_remove(index);
     }
 }
+
+pub(crate) fn add_task_timing(timing: TaskTiming) {
+    THREAD_TIMINGS.with(|timings| {
+        let mut timings = timings.lock();
+        let timings = &mut timings.timings;
+
+        if let Some(last_timing) = timings.iter_mut().rev().next() {
+            if last_timing.location == timing.location {
+                last_timing.end = timing.end;
+                return;
+            }
+        }
+
+        timings.push_back(timing);
+    });
+}

crates/gpui/src/queue.rs 🔗

@@ -0,0 +1,329 @@
+use std::{
+    collections::VecDeque,
+    fmt,
+    iter::FusedIterator,
+    sync::{Arc, atomic::AtomicUsize},
+};
+
+use rand::{Rng, SeedableRng, rngs::SmallRng};
+
+use crate::Priority;
+
+struct PriorityQueues<T> {
+    high_priority: VecDeque<T>,
+    medium_priority: VecDeque<T>,
+    low_priority: VecDeque<T>,
+}
+
+impl<T> PriorityQueues<T> {
+    fn is_empty(&self) -> bool {
+        self.high_priority.is_empty()
+            && self.medium_priority.is_empty()
+            && self.low_priority.is_empty()
+    }
+}
+
+struct PriorityQueueState<T> {
+    queues: parking_lot::Mutex<PriorityQueues<T>>,
+    condvar: parking_lot::Condvar,
+    receiver_count: AtomicUsize,
+    sender_count: AtomicUsize,
+}
+
+impl<T> PriorityQueueState<T> {
+    fn send(&self, priority: Priority, item: T) -> Result<(), SendError<T>> {
+        if self
+            .receiver_count
+            .load(std::sync::atomic::Ordering::Relaxed)
+            == 0
+        {
+            return Err(SendError(item));
+        }
+
+        let mut queues = self.queues.lock();
+        match priority {
+            Priority::Realtime(_) => unreachable!(),
+            Priority::High => queues.high_priority.push_back(item),
+            Priority::Medium => queues.medium_priority.push_back(item),
+            Priority::Low => queues.low_priority.push_back(item),
+        };
+        self.condvar.notify_one();
+        Ok(())
+    }
+
+    fn recv<'a>(&'a self) -> Result<parking_lot::MutexGuard<'a, PriorityQueues<T>>, RecvError> {
+        let mut queues = self.queues.lock();
+
+        let sender_count = self.sender_count.load(std::sync::atomic::Ordering::Relaxed);
+        if queues.is_empty() && sender_count == 0 {
+            return Err(crate::queue::RecvError);
+        }
+
+        while queues.is_empty() {
+            self.condvar.wait(&mut queues);
+        }
+
+        Ok(queues)
+    }
+
+    fn try_recv<'a>(
+        &'a self,
+    ) -> Result<Option<parking_lot::MutexGuard<'a, PriorityQueues<T>>>, RecvError> {
+        let mut queues = self.queues.lock();
+
+        let sender_count = self.sender_count.load(std::sync::atomic::Ordering::Relaxed);
+        if queues.is_empty() && sender_count == 0 {
+            return Err(crate::queue::RecvError);
+        }
+
+        if queues.is_empty() {
+            Ok(None)
+        } else {
+            Ok(Some(queues))
+        }
+    }
+}
+
+pub(crate) struct PriorityQueueSender<T> {
+    state: Arc<PriorityQueueState<T>>,
+}
+
+impl<T> PriorityQueueSender<T> {
+    fn new(state: Arc<PriorityQueueState<T>>) -> Self {
+        Self { state }
+    }
+
+    pub(crate) fn send(&self, priority: Priority, item: T) -> Result<(), SendError<T>> {
+        self.state.send(priority, item)?;
+        Ok(())
+    }
+}
+
+impl<T> Drop for PriorityQueueSender<T> {
+    fn drop(&mut self) {
+        self.state
+            .sender_count
+            .fetch_sub(1, std::sync::atomic::Ordering::AcqRel);
+    }
+}
+
+pub(crate) struct PriorityQueueReceiver<T> {
+    state: Arc<PriorityQueueState<T>>,
+    rand: SmallRng,
+    disconnected: bool,
+}
+
+impl<T> Clone for PriorityQueueReceiver<T> {
+    fn clone(&self) -> Self {
+        self.state
+            .receiver_count
+            .fetch_add(1, std::sync::atomic::Ordering::AcqRel);
+        Self {
+            state: Arc::clone(&self.state),
+            rand: SmallRng::seed_from_u64(0),
+            disconnected: self.disconnected,
+        }
+    }
+}
+
+pub(crate) struct SendError<T>(T);
+
+impl<T: fmt::Debug> fmt::Debug for SendError<T> {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        f.debug_tuple("SendError").field(&self.0).finish()
+    }
+}
+
+#[derive(Debug)]
+pub(crate) struct RecvError;
+
+#[allow(dead_code)]
+impl<T> PriorityQueueReceiver<T> {
+    pub(crate) fn new() -> (PriorityQueueSender<T>, Self) {
+        let state = PriorityQueueState {
+            queues: parking_lot::Mutex::new(PriorityQueues {
+                high_priority: VecDeque::new(),
+                medium_priority: VecDeque::new(),
+                low_priority: VecDeque::new(),
+            }),
+            condvar: parking_lot::Condvar::new(),
+            receiver_count: AtomicUsize::new(1),
+            sender_count: AtomicUsize::new(1),
+        };
+        let state = Arc::new(state);
+
+        let sender = PriorityQueueSender::new(Arc::clone(&state));
+
+        let receiver = PriorityQueueReceiver {
+            state,
+            rand: SmallRng::seed_from_u64(0),
+            disconnected: false,
+        };
+
+        (sender, receiver)
+    }
+
+    /// Tries to pop one element from the priority queue without blocking.
+    ///
+    /// This will early return if there are no elements in the queue.
+    ///
+    /// This method is best suited if you only intend to pop one element, for better performance
+    /// on large queues see [`Self::try_iter`]
+    ///
+    /// # Errors
+    ///
+    /// If the sender was dropped
+    pub(crate) fn try_pop(&mut self) -> Result<Option<T>, RecvError> {
+        self.pop_inner(false)
+    }
+
+    /// Pops an element from the priority queue blocking if necessary.
+    ///
+    /// This method is best suited if you only intend to pop one element, for better performance
+    /// on large queues see [`Self::iter``]
+    ///
+    /// # Errors
+    ///
+    /// If the sender was dropped
+    pub(crate) fn pop(&mut self) -> Result<T, RecvError> {
+        self.pop_inner(true).map(|e| e.unwrap())
+    }
+
+    /// Returns an iterator over the elements of the queue
+    /// this iterator will end when all elements have been consumed and will not wait for new ones.
+    pub(crate) fn try_iter(self) -> TryIter<T> {
+        TryIter {
+            receiver: self,
+            ended: false,
+        }
+    }
+
+    /// Returns an iterator over the elements of the queue
+    /// this iterator will wait for new elements if the queue is empty.
+    pub(crate) fn iter(self) -> Iter<T> {
+        Iter(self)
+    }
+
+    #[inline(always)]
+    // algorithm is the loaded die from biased coin from
+    // https://www.keithschwarz.com/darts-dice-coins/
+    fn pop_inner(&mut self, block: bool) -> Result<Option<T>, RecvError> {
+        use Priority as P;
+
+        let mut queues = if !block {
+            let Some(queues) = self.state.try_recv()? else {
+                return Ok(None);
+            };
+            queues
+        } else {
+            self.state.recv()?
+        };
+
+        let high = P::High.probability() * !queues.high_priority.is_empty() as u32;
+        let medium = P::Medium.probability() * !queues.medium_priority.is_empty() as u32;
+        let low = P::Low.probability() * !queues.low_priority.is_empty() as u32;
+        let mut mass = high + medium + low; //%
+
+        if !queues.high_priority.is_empty() {
+            let flip = self.rand.random_ratio(P::High.probability(), mass);
+            if flip {
+                return Ok(queues.high_priority.pop_front());
+            }
+            mass -= P::High.probability();
+        }
+
+        if !queues.medium_priority.is_empty() {
+            let flip = self.rand.random_ratio(P::Medium.probability(), mass);
+            if flip {
+                return Ok(queues.medium_priority.pop_front());
+            }
+            mass -= P::Medium.probability();
+        }
+
+        if !queues.low_priority.is_empty() {
+            let flip = self.rand.random_ratio(P::Low.probability(), mass);
+            if flip {
+                return Ok(queues.low_priority.pop_front());
+            }
+        }
+
+        Ok(None)
+    }
+}
+
+impl<T> Drop for PriorityQueueReceiver<T> {
+    fn drop(&mut self) {
+        self.state
+            .receiver_count
+            .fetch_sub(1, std::sync::atomic::Ordering::AcqRel);
+    }
+}
+
+/// If None is returned the sender disconnected
+pub(crate) struct Iter<T>(PriorityQueueReceiver<T>);
+impl<T> Iterator for Iter<T> {
+    type Item = T;
+
+    fn next(&mut self) -> Option<Self::Item> {
+        self.0.pop().ok()
+    }
+}
+impl<T> FusedIterator for Iter<T> {}
+
+/// If None is returned there are no more elements in the queue
+pub(crate) struct TryIter<T> {
+    receiver: PriorityQueueReceiver<T>,
+    ended: bool,
+}
+impl<T> Iterator for TryIter<T> {
+    type Item = Result<T, RecvError>;
+
+    fn next(&mut self) -> Option<Self::Item> {
+        if self.ended {
+            return None;
+        }
+
+        let res = self.receiver.try_pop();
+        self.ended = res.is_err();
+
+        res.transpose()
+    }
+}
+impl<T> FusedIterator for TryIter<T> {}
+
+#[cfg(test)]
+mod tests {
+    use collections::HashSet;
+
+    use super::*;
+
+    #[test]
+    fn all_tasks_get_yielded() {
+        let (tx, mut rx) = PriorityQueueReceiver::new();
+        tx.send(Priority::Medium, 20).unwrap();
+        tx.send(Priority::High, 30).unwrap();
+        tx.send(Priority::Low, 10).unwrap();
+        tx.send(Priority::Medium, 21).unwrap();
+        tx.send(Priority::High, 31).unwrap();
+
+        drop(tx);
+
+        assert_eq!(
+            rx.iter().collect::<HashSet<_>>(),
+            [30, 31, 20, 21, 10].into_iter().collect::<HashSet<_>>()
+        )
+    }
+
+    #[test]
+    fn new_high_prio_task_get_scheduled_quickly() {
+        let (tx, mut rx) = PriorityQueueReceiver::new();
+        for _ in 0..100 {
+            tx.send(Priority::Low, 1).unwrap();
+        }
+
+        assert_eq!(rx.pop().unwrap(), 1);
+        tx.send(Priority::High, 3).unwrap();
+        assert_eq!(rx.pop().unwrap(), 3);
+        assert_eq!(rx.pop().unwrap(), 1);
+    }
+}

crates/gpui/src/style.rs 🔗

@@ -252,6 +252,7 @@ pub struct Style {
     pub box_shadow: Vec<BoxShadow>,
 
     /// The text style of this element
+    #[refineable]
     pub text: TextStyleRefinement,
 
     /// The mouse cursor style shown when the mouse pointer is over an element.
@@ -264,6 +265,10 @@ pub struct Style {
     /// Equivalent to the Tailwind `grid-cols-<number>`
     pub grid_cols: Option<u16>,
 
+    /// The grid columns with min-content minimum sizing.
+    /// Unlike grid_cols, it won't shrink to width 0 in AvailableSpace::MinContent constraints.
+    pub grid_cols_min_content: Option<u16>,
+
     /// The row span of this element
     /// Equivalent to the Tailwind `grid-rows-<number>`
     pub grid_rows: Option<u16>,
@@ -329,9 +334,13 @@ pub enum WhiteSpace {
 /// How to truncate text that overflows the width of the element
 #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
 pub enum TextOverflow {
-    /// Truncate the text when it doesn't fit, and represent this truncation by displaying the
-    /// provided string.
+    /// Truncate the text at the end when it doesn't fit, and represent this truncation by
+    /// displaying the provided string (e.g., "very long te…").
     Truncate(SharedString),
+    /// Truncate the text at the start when it doesn't fit, and represent this truncation by
+    /// displaying the provided string at the beginning (e.g., "…ong text here").
+    /// Typically more adequate for file paths where the end is more important than the beginning.
+    TruncateStart(SharedString),
 }
 
 /// How to align text within the element
@@ -771,6 +780,7 @@ impl Default for Style {
             opacity: None,
             grid_rows: None,
             grid_cols: None,
+            grid_cols_min_content: None,
             grid_location: None,
 
             #[cfg(debug_assertions)]
@@ -1469,4 +1479,21 @@ mod tests {
             ]
         );
     }
+
+    #[perf]
+    fn test_text_style_refinement() {
+        let mut style = Style::default();
+        style.refine(&StyleRefinement::default().text_size(px(20.0)));
+        style.refine(&StyleRefinement::default().font_weight(FontWeight::SEMIBOLD));
+
+        assert_eq!(
+            Some(AbsoluteLength::from(px(20.0))),
+            style.text_style().unwrap().font_size
+        );
+
+        assert_eq!(
+            Some(FontWeight::SEMIBOLD),
+            style.text_style().unwrap().font_weight
+        );
+    }
 }

crates/gpui/src/styled.rs 🔗

@@ -1,8 +1,9 @@
 use crate::{
     self as gpui, AbsoluteLength, AlignContent, AlignItems, BorderStyle, CursorStyle,
-    DefiniteLength, Display, Fill, FlexDirection, FlexWrap, Font, FontStyle, FontWeight,
-    GridPlacement, Hsla, JustifyContent, Length, SharedString, StrikethroughStyle, StyleRefinement,
-    TextAlign, TextOverflow, TextStyleRefinement, UnderlineStyle, WhiteSpace, px, relative, rems,
+    DefiniteLength, Display, Fill, FlexDirection, FlexWrap, Font, FontFeatures, FontStyle,
+    FontWeight, GridPlacement, Hsla, JustifyContent, Length, SharedString, StrikethroughStyle,
+    StyleRefinement, TextAlign, TextOverflow, TextStyleRefinement, UnderlineStyle, WhiteSpace, px,
+    relative, rems,
 };
 pub use gpui_macros::{
     border_style_methods, box_shadow_style_methods, cursor_style_methods, margin_style_methods,
@@ -63,43 +64,41 @@ pub trait Styled: Sized {
     /// Sets the whitespace of the element to `normal`.
     /// [Docs](https://tailwindcss.com/docs/whitespace#normal)
     fn whitespace_normal(mut self) -> Self {
-        self.text_style()
-            .get_or_insert_with(Default::default)
-            .white_space = Some(WhiteSpace::Normal);
+        self.text_style().white_space = Some(WhiteSpace::Normal);
         self
     }
 
     /// Sets the whitespace of the element to `nowrap`.
     /// [Docs](https://tailwindcss.com/docs/whitespace#nowrap)
     fn whitespace_nowrap(mut self) -> Self {
-        self.text_style()
-            .get_or_insert_with(Default::default)
-            .white_space = Some(WhiteSpace::Nowrap);
+        self.text_style().white_space = Some(WhiteSpace::Nowrap);
         self
     }
 
-    /// Sets the truncate overflowing text with an ellipsis (…) if needed.
+    /// Sets the truncate overflowing text with an ellipsis (…) at the end if needed.
     /// [Docs](https://tailwindcss.com/docs/text-overflow#ellipsis)
     fn text_ellipsis(mut self) -> Self {
-        self.text_style()
-            .get_or_insert_with(Default::default)
-            .text_overflow = Some(TextOverflow::Truncate(ELLIPSIS));
+        self.text_style().text_overflow = Some(TextOverflow::Truncate(ELLIPSIS));
+        self
+    }
+
+    /// Sets the truncate overflowing text with an ellipsis (…) at the start if needed.
+    /// Typically more adequate for file paths where the end is more important than the beginning.
+    /// Note: This doesn't exist in Tailwind CSS.
+    fn text_ellipsis_start(mut self) -> Self {
+        self.text_style().text_overflow = Some(TextOverflow::TruncateStart(ELLIPSIS));
         self
     }
 
     /// Sets the text overflow behavior of the element.
     fn text_overflow(mut self, overflow: TextOverflow) -> Self {
-        self.text_style()
-            .get_or_insert_with(Default::default)
-            .text_overflow = Some(overflow);
+        self.text_style().text_overflow = Some(overflow);
         self
     }
 
     /// Set the text alignment of the element.
     fn text_align(mut self, align: TextAlign) -> Self {
-        self.text_style()
-            .get_or_insert_with(Default::default)
-            .text_align = Some(align);
+        self.text_style().text_align = Some(align);
         self
     }
 
@@ -127,7 +126,7 @@ pub trait Styled: Sized {
     /// Sets number of lines to show before truncating the text.
     /// [Docs](https://tailwindcss.com/docs/line-clamp)
     fn line_clamp(mut self, lines: usize) -> Self {
-        let mut text_style = self.text_style().get_or_insert_with(Default::default);
+        let mut text_style = self.text_style();
         text_style.line_clamp = Some(lines);
         self.overflow_hidden()
     }
@@ -395,7 +394,7 @@ pub trait Styled: Sized {
     }
 
     /// Returns a mutable reference to the text style that has been configured on this element.
-    fn text_style(&mut self) -> &mut Option<TextStyleRefinement> {
+    fn text_style(&mut self) -> &mut TextStyleRefinement {
         let style: &mut StyleRefinement = self.style();
         &mut style.text
     }
@@ -404,7 +403,7 @@ pub trait Styled: Sized {
     ///
     /// This value cascades to its child elements.
     fn text_color(mut self, color: impl Into<Hsla>) -> Self {
-        self.text_style().get_or_insert_with(Default::default).color = Some(color.into());
+        self.text_style().color = Some(color.into());
         self
     }
 
@@ -412,9 +411,7 @@ pub trait Styled: Sized {
     ///
     /// This value cascades to its child elements.
     fn font_weight(mut self, weight: FontWeight) -> Self {
-        self.text_style()
-            .get_or_insert_with(Default::default)
-            .font_weight = Some(weight);
+        self.text_style().font_weight = Some(weight);
         self
     }
 
@@ -422,9 +419,7 @@ pub trait Styled: Sized {
     ///
     /// This value cascades to its child elements.
     fn text_bg(mut self, bg: impl Into<Hsla>) -> Self {
-        self.text_style()
-            .get_or_insert_with(Default::default)
-            .background_color = Some(bg.into());
+        self.text_style().background_color = Some(bg.into());
         self
     }
 
@@ -432,97 +427,77 @@ pub trait Styled: Sized {
     ///
     /// This value cascades to its child elements.
     fn text_size(mut self, size: impl Into<AbsoluteLength>) -> Self {
-        self.text_style()
-            .get_or_insert_with(Default::default)
-            .font_size = Some(size.into());
+        self.text_style().font_size = Some(size.into());
         self
     }
 
     /// Sets the text size to 'extra small'.
     /// [Docs](https://tailwindcss.com/docs/font-size#setting-the-font-size)
     fn text_xs(mut self) -> Self {
-        self.text_style()
-            .get_or_insert_with(Default::default)
-            .font_size = Some(rems(0.75).into());
+        self.text_style().font_size = Some(rems(0.75).into());
         self
     }
 
     /// Sets the text size to 'small'.
     /// [Docs](https://tailwindcss.com/docs/font-size#setting-the-font-size)
     fn text_sm(mut self) -> Self {
-        self.text_style()
-            .get_or_insert_with(Default::default)
-            .font_size = Some(rems(0.875).into());
+        self.text_style().font_size = Some(rems(0.875).into());
         self
     }
 
     /// Sets the text size to 'base'.
     /// [Docs](https://tailwindcss.com/docs/font-size#setting-the-font-size)
     fn text_base(mut self) -> Self {
-        self.text_style()
-            .get_or_insert_with(Default::default)
-            .font_size = Some(rems(1.0).into());
+        self.text_style().font_size = Some(rems(1.0).into());
         self
     }
 
     /// Sets the text size to 'large'.
     /// [Docs](https://tailwindcss.com/docs/font-size#setting-the-font-size)
     fn text_lg(mut self) -> Self {
-        self.text_style()
-            .get_or_insert_with(Default::default)
-            .font_size = Some(rems(1.125).into());
+        self.text_style().font_size = Some(rems(1.125).into());
         self
     }
 
     /// Sets the text size to 'extra large'.
     /// [Docs](https://tailwindcss.com/docs/font-size#setting-the-font-size)
     fn text_xl(mut self) -> Self {
-        self.text_style()
-            .get_or_insert_with(Default::default)
-            .font_size = Some(rems(1.25).into());
+        self.text_style().font_size = Some(rems(1.25).into());
         self
     }
 
     /// Sets the text size to 'extra extra large'.
     /// [Docs](https://tailwindcss.com/docs/font-size#setting-the-font-size)
     fn text_2xl(mut self) -> Self {
-        self.text_style()
-            .get_or_insert_with(Default::default)
-            .font_size = Some(rems(1.5).into());
+        self.text_style().font_size = Some(rems(1.5).into());
         self
     }
 
     /// Sets the text size to 'extra extra extra large'.
     /// [Docs](https://tailwindcss.com/docs/font-size#setting-the-font-size)
     fn text_3xl(mut self) -> Self {
-        self.text_style()
-            .get_or_insert_with(Default::default)
-            .font_size = Some(rems(1.875).into());
+        self.text_style().font_size = Some(rems(1.875).into());
         self
     }
 
     /// Sets the font style of the element to italic.
     /// [Docs](https://tailwindcss.com/docs/font-style#italicizing-text)
     fn italic(mut self) -> Self {
-        self.text_style()
-            .get_or_insert_with(Default::default)
-            .font_style = Some(FontStyle::Italic);
+        self.text_style().font_style = Some(FontStyle::Italic);
         self
     }
 
     /// Sets the font style of the element to normal (not italic).
     /// [Docs](https://tailwindcss.com/docs/font-style#displaying-text-normally)
     fn not_italic(mut self) -> Self {
-        self.text_style()
-            .get_or_insert_with(Default::default)
-            .font_style = Some(FontStyle::Normal);
+        self.text_style().font_style = Some(FontStyle::Normal);
         self
     }
 
     /// Sets the text decoration to underline.
     /// [Docs](https://tailwindcss.com/docs/text-decoration-line#underling-text)
     fn underline(mut self) -> Self {
-        let style = self.text_style().get_or_insert_with(Default::default);
+        let style = self.text_style();
         style.underline = Some(UnderlineStyle {
             thickness: px(1.),
             ..Default::default()
@@ -533,7 +508,7 @@ pub trait Styled: Sized {
     /// Sets the decoration of the text to have a line through it.
     /// [Docs](https://tailwindcss.com/docs/text-decoration-line#adding-a-line-through-text)
     fn line_through(mut self) -> Self {
-        let style = self.text_style().get_or_insert_with(Default::default);
+        let style = self.text_style();
         style.strikethrough = Some(StrikethroughStyle {
             thickness: px(1.),
             ..Default::default()
@@ -545,15 +520,13 @@ pub trait Styled: Sized {
     ///
     /// This value cascades to its child elements.
     fn text_decoration_none(mut self) -> Self {
-        self.text_style()
-            .get_or_insert_with(Default::default)
-            .underline = None;
+        self.text_style().underline = None;
         self
     }
 
     /// Sets the color for the underline on this element
     fn text_decoration_color(mut self, color: impl Into<Hsla>) -> Self {
-        let style = self.text_style().get_or_insert_with(Default::default);
+        let style = self.text_style();
         let underline = style.underline.get_or_insert_with(Default::default);
         underline.color = Some(color.into());
         self
@@ -562,7 +535,7 @@ pub trait Styled: Sized {
     /// Sets the text decoration style to a solid line.
     /// [Docs](https://tailwindcss.com/docs/text-decoration-style)
     fn text_decoration_solid(mut self) -> Self {
-        let style = self.text_style().get_or_insert_with(Default::default);
+        let style = self.text_style();
         let underline = style.underline.get_or_insert_with(Default::default);
         underline.wavy = false;
         self
@@ -571,7 +544,7 @@ pub trait Styled: Sized {
     /// Sets the text decoration style to a wavy line.
     /// [Docs](https://tailwindcss.com/docs/text-decoration-style)
     fn text_decoration_wavy(mut self) -> Self {
-        let style = self.text_style().get_or_insert_with(Default::default);
+        let style = self.text_style();
         let underline = style.underline.get_or_insert_with(Default::default);
         underline.wavy = true;
         self
@@ -580,7 +553,7 @@ pub trait Styled: Sized {
     /// Sets the text decoration to be 0px thick.
     /// [Docs](https://tailwindcss.com/docs/text-decoration-thickness)
     fn text_decoration_0(mut self) -> Self {
-        let style = self.text_style().get_or_insert_with(Default::default);
+        let style = self.text_style();
         let underline = style.underline.get_or_insert_with(Default::default);
         underline.thickness = px(0.);
         self
@@ -589,7 +562,7 @@ pub trait Styled: Sized {
     /// Sets the text decoration to be 1px thick.
     /// [Docs](https://tailwindcss.com/docs/text-decoration-thickness)
     fn text_decoration_1(mut self) -> Self {
-        let style = self.text_style().get_or_insert_with(Default::default);
+        let style = self.text_style();
         let underline = style.underline.get_or_insert_with(Default::default);
         underline.thickness = px(1.);
         self
@@ -598,7 +571,7 @@ pub trait Styled: Sized {
     /// Sets the text decoration to be 2px thick.
     /// [Docs](https://tailwindcss.com/docs/text-decoration-thickness)
     fn text_decoration_2(mut self) -> Self {
-        let style = self.text_style().get_or_insert_with(Default::default);
+        let style = self.text_style();
         let underline = style.underline.get_or_insert_with(Default::default);
         underline.thickness = px(2.);
         self
@@ -607,7 +580,7 @@ pub trait Styled: Sized {
     /// Sets the text decoration to be 4px thick.
     /// [Docs](https://tailwindcss.com/docs/text-decoration-thickness)
     fn text_decoration_4(mut self) -> Self {
-        let style = self.text_style().get_or_insert_with(Default::default);
+        let style = self.text_style();
         let underline = style.underline.get_or_insert_with(Default::default);
         underline.thickness = px(4.);
         self
@@ -616,7 +589,7 @@ pub trait Styled: Sized {
     /// Sets the text decoration to be 8px thick.
     /// [Docs](https://tailwindcss.com/docs/text-decoration-thickness)
     fn text_decoration_8(mut self) -> Self {
-        let style = self.text_style().get_or_insert_with(Default::default);
+        let style = self.text_style();
         let underline = style.underline.get_or_insert_with(Default::default);
         underline.thickness = px(8.);
         self
@@ -624,9 +597,13 @@ pub trait Styled: Sized {
 
     /// Sets the font family of this element and its children.
     fn font_family(mut self, family_name: impl Into<SharedString>) -> Self {
-        self.text_style()
-            .get_or_insert_with(Default::default)
-            .font_family = Some(family_name.into());
+        self.text_style().font_family = Some(family_name.into());
+        self
+    }
+
+    /// Sets the font features of this element and its children.
+    fn font_features(mut self, features: FontFeatures) -> Self {
+        self.text_style().font_features = Some(features);
         self
     }
 
@@ -640,7 +617,7 @@ pub trait Styled: Sized {
             style,
         } = font;
 
-        let text_style = self.text_style().get_or_insert_with(Default::default);
+        let text_style = self.text_style();
         text_style.font_family = Some(family);
         text_style.font_features = Some(features);
         text_style.font_weight = Some(weight);
@@ -652,9 +629,7 @@ pub trait Styled: Sized {
 
     /// Sets the line height of this element and its children.
     fn line_height(mut self, line_height: impl Into<DefiniteLength>) -> Self {
-        self.text_style()
-            .get_or_insert_with(Default::default)
-            .line_height = Some(line_height.into());
+        self.text_style().line_height = Some(line_height.into());
         self
     }
 
@@ -670,6 +645,13 @@ pub trait Styled: Sized {
         self
     }
 
+    /// Sets the grid columns with min-content minimum sizing.
+    /// Unlike grid_cols, it won't shrink to width 0 in AvailableSpace::MinContent constraints.
+    fn grid_cols_min_content(mut self, cols: u16) -> Self {
+        self.style().grid_cols_min_content = Some(cols);
+        self
+    }
+
     /// Sets the grid rows of this element.
     fn grid_rows(mut self, rows: u16) -> Self {
         self.style().grid_rows = Some(rows);

crates/gpui/src/taffy.rs 🔗

@@ -8,6 +8,7 @@ use std::{fmt::Debug, ops::Range};
 use taffy::{
     TaffyTree, TraversePartialTree as _,
     geometry::{Point as TaffyPoint, Rect as TaffyRect, Size as TaffySize},
+    prelude::min_content,
     style::AvailableSpace as TaffyAvailableSpace,
     tree::NodeId,
 };
@@ -314,6 +315,14 @@ impl ToTaffy<taffy::style::Style> for Style {
                 .unwrap_or_default()
         }
 
+        fn to_grid_repeat_min_content<T: taffy::style::CheapCloneStr>(
+            unit: &Option<u16>,
+        ) -> Vec<taffy::GridTemplateComponent<T>> {
+            // grid-template-columns: repeat(<number>, minmax(min-content, 1fr));
+            unit.map(|count| vec![repeat(count, vec![minmax(min_content(), fr(1.0))])])
+                .unwrap_or_default()
+        }
+
         taffy::style::Style {
             display: self.display.into(),
             overflow: self.overflow.into(),
@@ -338,7 +347,11 @@ impl ToTaffy<taffy::style::Style> for Style {
             flex_grow: self.flex_grow,
             flex_shrink: self.flex_shrink,
             grid_template_rows: to_grid_repeat(&self.grid_rows),
-            grid_template_columns: to_grid_repeat(&self.grid_cols),
+            grid_template_columns: if self.grid_cols_min_content.is_some() {
+                to_grid_repeat_min_content(&self.grid_cols_min_content)
+            } else {
+                to_grid_repeat(&self.grid_cols)
+            },
             grid_row: self
                 .grid_location
                 .as_ref()

crates/gpui/src/test.rs 🔗

@@ -69,7 +69,10 @@ pub fn run_test(
                         std::mem::forget(error);
                     } else {
                         if is_multiple_runs {
-                            eprintln!("failing seed: {}", seed);
+                            eprintln!("failing seed: {seed}");
+                            eprintln!(
+                                "You can rerun from this seed by setting the environmental variable SEED to {seed}"
+                            );
                         }
                         if let Some(on_fail_fn) = on_fail_fn {
                             on_fail_fn()

crates/gpui/src/text_system/line.rs 🔗

@@ -64,6 +64,8 @@ impl ShapedLine {
         &self,
         origin: Point<Pixels>,
         line_height: Pixels,
+        align: TextAlign,
+        align_width: Option<Pixels>,
         window: &mut Window,
         cx: &mut App,
     ) -> Result<()> {
@@ -71,8 +73,8 @@ impl ShapedLine {
             origin,
             &self.layout,
             line_height,
-            TextAlign::default(),
-            None,
+            align,
+            align_width,
             &self.decoration_runs,
             &[],
             window,
@@ -87,6 +89,8 @@ impl ShapedLine {
         &self,
         origin: Point<Pixels>,
         line_height: Pixels,
+        align: TextAlign,
+        align_width: Option<Pixels>,
         window: &mut Window,
         cx: &mut App,
     ) -> Result<()> {
@@ -94,8 +98,8 @@ impl ShapedLine {
             origin,
             &self.layout,
             line_height,
-            TextAlign::default(),
-            None,
+            align,
+            align_width,
             &self.decoration_runs,
             &[],
             window,

crates/gpui/src/text_system/line_wrapper.rs 🔗

@@ -2,6 +2,15 @@ use crate::{FontId, FontRun, Pixels, PlatformTextSystem, SharedString, TextRun,
 use collections::HashMap;
 use std::{borrow::Cow, iter, sync::Arc};
 
+/// Determines whether to truncate text from the start or end.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+pub enum TruncateFrom {
+    /// Truncate text from the start.
+    Start,
+    /// Truncate text from the end.
+    End,
+}
+
 /// The GPUI line wrapper, used to wrap lines of text to a given width.
 pub struct LineWrapper {
     platform_text_system: Arc<dyn PlatformTextSystem>,
@@ -128,40 +137,83 @@ impl LineWrapper {
         })
     }
 
-    /// Truncate a line of text to the given width with this wrapper's font and font size.
-    pub fn truncate_line<'a>(
+    /// Determines if a line should be truncated based on its width.
+    ///
+    /// Returns the truncation index in `line`.
+    pub fn should_truncate_line(
         &mut self,
-        line: SharedString,
+        line: &str,
         truncate_width: Pixels,
-        truncation_suffix: &str,
-        runs: &'a [TextRun],
-    ) -> (SharedString, Cow<'a, [TextRun]>) {
+        truncation_affix: &str,
+        truncate_from: TruncateFrom,
+    ) -> Option<usize> {
         let mut width = px(0.);
-        let mut suffix_width = truncation_suffix
+        let suffix_width = truncation_affix
             .chars()
             .map(|c| self.width_for_char(c))
             .fold(px(0.0), |a, x| a + x);
-        let mut char_indices = line.char_indices();
         let mut truncate_ix = 0;
-        for (ix, c) in char_indices {
-            if width + suffix_width < truncate_width {
-                truncate_ix = ix;
-            }
 
-            let char_width = self.width_for_char(c);
-            width += char_width;
+        match truncate_from {
+            TruncateFrom::Start => {
+                for (ix, c) in line.char_indices().rev() {
+                    if width + suffix_width < truncate_width {
+                        truncate_ix = ix;
+                    }
 
-            if width.floor() > truncate_width {
-                let result =
-                    SharedString::from(format!("{}{}", &line[..truncate_ix], truncation_suffix));
-                let mut runs = runs.to_vec();
-                update_runs_after_truncation(&result, truncation_suffix, &mut runs);
+                    let char_width = self.width_for_char(c);
+                    width += char_width;
 
-                return (result, Cow::Owned(runs));
+                    if width.floor() > truncate_width {
+                        return Some(truncate_ix);
+                    }
+                }
+            }
+            TruncateFrom::End => {
+                for (ix, c) in line.char_indices() {
+                    if width + suffix_width < truncate_width {
+                        truncate_ix = ix;
+                    }
+
+                    let char_width = self.width_for_char(c);
+                    width += char_width;
+
+                    if width.floor() > truncate_width {
+                        return Some(truncate_ix);
+                    }
+                }
             }
         }
 
-        (line, Cow::Borrowed(runs))
+        None
+    }
+
+    /// Truncate a line of text to the given width with this wrapper's font and font size.
+    pub fn truncate_line<'a>(
+        &mut self,
+        line: SharedString,
+        truncate_width: Pixels,
+        truncation_affix: &str,
+        runs: &'a [TextRun],
+        truncate_from: TruncateFrom,
+    ) -> (SharedString, Cow<'a, [TextRun]>) {
+        if let Some(truncate_ix) =
+            self.should_truncate_line(&line, truncate_width, truncation_affix, truncate_from)
+        {
+            let result = match truncate_from {
+                TruncateFrom::Start => {
+                    SharedString::from(format!("{truncation_affix}{}", &line[truncate_ix + 1..]))
+                }
+                TruncateFrom::End => {
+                    SharedString::from(format!("{}{truncation_affix}", &line[..truncate_ix]))
+                }
+            };
+            let mut runs = runs.to_vec();
+            update_runs_after_truncation(&result, truncation_affix, &mut runs, truncate_from);
+            (result, Cow::Owned(runs))
+        } else {
+            (line, Cow::Borrowed(runs))
+        }
     }
 
     /// Any character in this list should be treated as a word character,
@@ -182,6 +234,11 @@ impl LineWrapper {
         // Cyrillic for Russian, Ukrainian, etc.
         // https://en.wikipedia.org/wiki/Cyrillic_script_in_Unicode
         matches!(c, '\u{0400}'..='\u{04FF}') ||
+
+        // Vietnamese (https://vietunicode.sourceforge.net/charset/)
+        matches!(c, '\u{1E00}'..='\u{1EFF}') || // Latin Extended Additional
+        matches!(c, '\u{0300}'..='\u{036F}') || // Combining Diacritical Marks
+
         // Some other known special characters that should be treated as word characters,
         // e.g. `a-b`, `var_name`, `I'm`, '@mention`, `#hashtag`, `100%`, `3.1415`,
         // `2^3`, `a~b`, `a=1`, `Self::new`, etc.
@@ -225,15 +282,35 @@ impl LineWrapper {
     }
 }
 
-fn update_runs_after_truncation(result: &str, ellipsis: &str, runs: &mut Vec<TextRun>) {
+fn update_runs_after_truncation(
+    result: &str,
+    ellipsis: &str,
+    runs: &mut Vec<TextRun>,
+    truncate_from: TruncateFrom,
+) {
     let mut truncate_at = result.len() - ellipsis.len();
-    for (run_index, run) in runs.iter_mut().enumerate() {
-        if run.len <= truncate_at {
-            truncate_at -= run.len;
-        } else {
-            run.len = truncate_at + ellipsis.len();
-            runs.truncate(run_index + 1);
-            break;
+    match truncate_from {
+        TruncateFrom::Start => {
+            for (run_index, run) in runs.iter_mut().enumerate().rev() {
+                if run.len <= truncate_at {
+                    truncate_at -= run.len;
+                } else {
+                    run.len = truncate_at + ellipsis.len();
+                    runs.splice(..run_index, std::iter::empty());
+                    break;
+                }
+            }
+        }
+        TruncateFrom::End => {
+            for (run_index, run) in runs.iter_mut().enumerate() {
+                if run.len <= truncate_at {
+                    truncate_at -= run.len;
+                } else {
+                    run.len = truncate_at + ellipsis.len();
+                    runs.truncate(run_index + 1);
+                    break;
+                }
+            }
         }
     }
 }
@@ -483,7 +560,7 @@ mod tests {
     }
 
     #[test]
-    fn test_truncate_line() {
+    fn test_truncate_line_end() {
         let mut wrapper = build_wrapper();
 
         fn perform_test(
@@ -494,8 +571,13 @@ mod tests {
         ) {
             let dummy_run_lens = vec![text.len()];
             let dummy_runs = generate_test_runs(&dummy_run_lens);
-            let (result, dummy_runs) =
-                wrapper.truncate_line(text.into(), px(220.), ellipsis, &dummy_runs);
+            let (result, dummy_runs) = wrapper.truncate_line(
+                text.into(),
+                px(220.),
+                ellipsis,
+                &dummy_runs,
+                TruncateFrom::End,
+            );
             assert_eq!(result, expected);
             assert_eq!(dummy_runs.first().unwrap().len, result.len());
         }
@@ -521,7 +603,50 @@ mod tests {
     }
 
     #[test]
-    fn test_truncate_multiple_runs() {
+    fn test_truncate_line_start() {
+        let mut wrapper = build_wrapper();
+
+        fn perform_test(
+            wrapper: &mut LineWrapper,
+            text: &'static str,
+            expected: &'static str,
+            ellipsis: &str,
+        ) {
+            let dummy_run_lens = vec![text.len()];
+            let dummy_runs = generate_test_runs(&dummy_run_lens);
+            let (result, dummy_runs) = wrapper.truncate_line(
+                text.into(),
+                px(220.),
+                ellipsis,
+                &dummy_runs,
+                TruncateFrom::Start,
+            );
+            assert_eq!(result, expected);
+            assert_eq!(dummy_runs.first().unwrap().len, result.len());
+        }
+
+        perform_test(
+            &mut wrapper,
+            "aaaa bbbb cccc ddddd eeee fff gg",
+            "cccc ddddd eeee fff gg",
+            "",
+        );
+        perform_test(
+            &mut wrapper,
+            "aaaa bbbb cccc ddddd eeee fff gg",
+            "…ccc ddddd eeee fff gg",
+            "…",
+        );
+        perform_test(
+            &mut wrapper,
+            "aaaa bbbb cccc ddddd eeee fff gg",
+            "......dddd eeee fff gg",
+            "......",
+        );
+    }
+
+    #[test]
+    fn test_truncate_multiple_runs_end() {
         let mut wrapper = build_wrapper();
 
         fn perform_test(
@@ -534,7 +659,7 @@ mod tests {
         ) {
             let dummy_runs = generate_test_runs(run_lens);
             let (result, dummy_runs) =
-                wrapper.truncate_line(text.into(), line_width, "…", &dummy_runs);
+                wrapper.truncate_line(text.into(), line_width, "…", &dummy_runs, TruncateFrom::End);
             assert_eq!(result, expected);
             for (run, result_len) in dummy_runs.iter().zip(result_run_len) {
                 assert_eq!(run.len, *result_len);
@@ -580,10 +705,75 @@ mod tests {
     }
 
     #[test]
-    fn test_update_run_after_truncation() {
+    fn test_truncate_multiple_runs_start() {
+        let mut wrapper = build_wrapper();
+
+        #[track_caller]
+        fn perform_test(
+            wrapper: &mut LineWrapper,
+            text: &'static str,
+            expected: &str,
+            run_lens: &[usize],
+            result_run_len: &[usize],
+            line_width: Pixels,
+        ) {
+            let dummy_runs = generate_test_runs(run_lens);
+            let (result, dummy_runs) = wrapper.truncate_line(
+                text.into(),
+                line_width,
+                "…",
+                &dummy_runs,
+                TruncateFrom::Start,
+            );
+            assert_eq!(result, expected);
+            for (run, result_len) in dummy_runs.iter().zip(result_run_len) {
+                assert_eq!(run.len, *result_len);
+            }
+        }
+        // Case 0: Normal
+        // Text: abcdefghijkl
+        // Runs: Run0 { len: 12, ... }
+        //
+        // Truncate res: …ijkl (truncate_at = 9)
+        // Run res: Run0 { string: …ijkl, len: 7, ... }
+        perform_test(&mut wrapper, "abcdefghijkl", "…ijkl", &[12], &[7], px(50.));
+        // Case 1: Drop some runs
+        // Text: abcdefghijkl
+        // Runs: Run0 { len: 4, ... }, Run1 { len: 4, ... }, Run2 { len: 4, ... }
+        //
+        // Truncate res: …ghijkl (truncate_at = 7)
+        // Runs res: Run0 { string: …gh, len: 5, ... }, Run1 { string: ijkl, len:
+        // 4, ... }
+        perform_test(
+            &mut wrapper,
+            "abcdefghijkl",
+            "…ghijkl",
+            &[4, 4, 4],
+            &[5, 4],
+            px(70.),
+        );
+        // Case 2: Truncate at start of some run
+        // Text: abcdefghijkl
+        // Runs: Run0 { len: 4, ... }, Run1 { len: 4, ... }, Run2 { len: 4, ... }
+        //
+        // Truncate res: abcdefgh… (truncate_at = 3)
+        // Runs res: Run0 { string: …, len: 3, ... }, Run1 { string: efgh, len:
+        // 4, ... }, Run2 { string: ijkl, len: 4, ... }
+        perform_test(
+            &mut wrapper,
+            "abcdefghijkl",
+            "…efghijkl",
+            &[4, 4, 4],
+            &[3, 4, 4],
+            px(90.),
+        );
+    }
+
+    #[test]
+    fn test_update_run_after_truncation_end() {
         fn perform_test(result: &str, run_lens: &[usize], result_run_lens: &[usize]) {
             let mut dummy_runs = generate_test_runs(run_lens);
-            update_runs_after_truncation(result, "…", &mut dummy_runs);
+            update_runs_after_truncation(result, "…", &mut dummy_runs, TruncateFrom::End);
             for (run, result_len) in dummy_runs.iter().zip(result_run_lens) {
                 assert_eq!(run.len, *result_len);
             }
@@ -618,7 +808,12 @@ mod tests {
         #[track_caller]
         fn assert_word(word: &str) {
             for c in word.chars() {
-                assert!(LineWrapper::is_word_char(c), "assertion failed for '{}'", c);
+                assert!(
+                    LineWrapper::is_word_char(c),
+                    "assertion failed for '{}' (unicode 0x{:x})",
+                    c,
+                    c as u32
+                );
             }
         }
 
@@ -661,6 +856,8 @@ mod tests {
         assert_word("ƀƁƂƃƄƅƆƇƈƉƊƋƌƍƎƏ");
         // Cyrillic
         assert_word("АБВГДЕЖЗИЙКЛМНОП");
+        // Vietnamese (https://github.com/zed-industries/zed/issues/23245)
+        assert_word("ThậmchíđếnkhithuachạychúngcònnhẫntâmgiếtnốtsốđôngtùchínhtrịởYênBáivàCaoBằng");
 
         // non-word characters
         assert_not_word("你好");

crates/gpui/src/window.rs 🔗

@@ -9,14 +9,15 @@ use crate::{
     KeyBinding, KeyContext, KeyDownEvent, KeyEvent, Keystroke, KeystrokeEvent, LayoutId,
     LineLayoutIndex, Modifiers, ModifiersChangedEvent, MonochromeSprite, MouseButton, MouseEvent,
     MouseMoveEvent, MouseUpEvent, Path, Pixels, PlatformAtlas, PlatformDisplay, PlatformInput,
-    PlatformInputHandler, PlatformWindow, Point, PolychromeSprite, PromptButton, PromptLevel, Quad,
-    Render, RenderGlyphParams, RenderImage, RenderImageParams, RenderSvgParams, Replay, ResizeEdge,
-    SMOOTH_SVG_SCALE_FACTOR, SUBPIXEL_VARIANTS_X, SUBPIXEL_VARIANTS_Y, ScaledPixels, Scene, Shadow,
-    SharedString, Size, StrikethroughStyle, Style, SubscriberSet, Subscription, SystemWindowTab,
-    SystemWindowTabController, TabStopMap, TaffyLayoutEngine, Task, TextStyle, TextStyleRefinement,
-    TransformationMatrix, Underline, UnderlineStyle, WindowAppearance, WindowBackgroundAppearance,
-    WindowBounds, WindowControls, WindowDecorations, WindowOptions, WindowParams, WindowTextSystem,
-    point, prelude::*, px, rems, size, transparent_black,
+    PlatformInputHandler, PlatformWindow, Point, PolychromeSprite, Priority, PromptButton,
+    PromptLevel, Quad, Render, RenderGlyphParams, RenderImage, RenderImageParams, RenderSvgParams,
+    Replay, ResizeEdge, SMOOTH_SVG_SCALE_FACTOR, SUBPIXEL_VARIANTS_X, SUBPIXEL_VARIANTS_Y,
+    ScaledPixels, Scene, Shadow, SharedString, Size, StrikethroughStyle, Style, SubscriberSet,
+    Subscription, SystemWindowTab, SystemWindowTabController, TabStopMap, TaffyLayoutEngine, Task,
+    TextStyle, TextStyleRefinement, TransformationMatrix, Underline, UnderlineStyle,
+    WindowAppearance, WindowBackgroundAppearance, WindowBounds, WindowControls, WindowDecorations,
+    WindowOptions, WindowParams, WindowTextSystem, point, prelude::*, px, rems, size,
+    transparent_black,
 };
 use anyhow::{Context as _, Result, anyhow};
 use collections::{FxHashMap, FxHashSet};
@@ -344,8 +345,8 @@ impl FocusHandle {
     }
 
     /// Moves the focus to the element associated with this handle.
-    pub fn focus(&self, window: &mut Window) {
-        window.focus(self)
+    pub fn focus(&self, window: &mut Window, cx: &mut App) {
+        window.focus(self, cx)
     }
 
     /// Obtains whether the element associated with this handle is currently focused.
@@ -875,7 +876,9 @@ pub struct Window {
     active: Rc<Cell<bool>>,
     hovered: Rc<Cell<bool>>,
     pub(crate) needs_present: Rc<Cell<bool>>,
-    pub(crate) last_input_timestamp: Rc<Cell<Instant>>,
+    /// Tracks recent input event timestamps to determine if input is arriving at a high rate.
+    /// Used to selectively enable VRR optimization only when input rate exceeds 60fps.
+    pub(crate) input_rate_tracker: Rc<RefCell<InputRateTracker>>,
     last_input_modality: InputModality,
     pub(crate) refreshing: bool,
     pub(crate) activation_observers: SubscriberSet<(), AnyObserver>,
@@ -896,6 +899,51 @@ struct ModifierState {
     saw_keystroke: bool,
 }
 
+/// Tracks input event timestamps to determine if input is arriving at a high rate.
+/// Used for selective VRR (Variable Refresh Rate) optimization.
+#[derive(Clone, Debug)]
+pub(crate) struct InputRateTracker {
+    timestamps: Vec<Instant>,
+    window: Duration,
+    inputs_per_second: u32,
+    sustain_until: Instant,
+    sustain_duration: Duration,
+}
+
+impl Default for InputRateTracker {
+    fn default() -> Self {
+        Self {
+            timestamps: Vec::new(),
+            window: Duration::from_millis(100),
+            inputs_per_second: 60,
+            sustain_until: Instant::now(),
+            sustain_duration: Duration::from_secs(1),
+        }
+    }
+}
+
+impl InputRateTracker {
+    pub fn record_input(&mut self) {
+        let now = Instant::now();
+        self.timestamps.push(now);
+        self.prune_old_timestamps(now);
+
+        let min_events = self.inputs_per_second as u128 * self.window.as_millis() / 1000;
+        if self.timestamps.len() as u128 >= min_events {
+            self.sustain_until = now + self.sustain_duration;
+        }
+    }
+
+    pub fn is_high_rate(&self) -> bool {
+        Instant::now() < self.sustain_until
+    }
+
+    fn prune_old_timestamps(&mut self, now: Instant) {
+        self.timestamps
+            .retain(|&t| now.duration_since(t) <= self.window);
+    }
+}
+
 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
 pub(crate) enum DrawPhase {
     None,
@@ -918,86 +966,69 @@ pub(crate) struct ElementStateBox {
     pub(crate) type_name: &'static str,
 }
 
-fn default_bounds(display_id: Option<DisplayId>, cx: &mut App) -> Bounds<Pixels> {
-    #[cfg(target_os = "macos")]
-    {
-        const CASCADE_OFFSET: f32 = 25.0;
-
-        let display = display_id
-            .map(|id| cx.find_display(id))
-            .unwrap_or_else(|| cx.primary_display());
-
-        let display_bounds = display
-            .as_ref()
-            .map(|d| d.bounds())
-            .unwrap_or_else(|| Bounds::new(point(px(0.), px(0.)), DEFAULT_WINDOW_SIZE));
-
-        // TODO, BUG: if you open a window with the currently active window
-        // on the stack, this will erroneously select the 'unwrap_or_else'
-        // code path
-        let (base_origin, base_size) = cx
-            .active_window()
-            .and_then(|w| {
-                w.update(cx, |_, window, _| {
-                    let bounds = window.bounds();
-                    (bounds.origin, bounds.size)
-                })
-                .ok()
-            })
-            .unwrap_or_else(|| {
-                let default_bounds = display
-                    .as_ref()
-                    .map(|d| d.default_bounds())
-                    .unwrap_or_else(|| Bounds::new(point(px(0.), px(0.)), DEFAULT_WINDOW_SIZE));
-                (default_bounds.origin, default_bounds.size)
-            });
-
-        let cascade_offset = point(px(CASCADE_OFFSET), px(CASCADE_OFFSET));
-        let proposed_origin = base_origin + cascade_offset;
-        let proposed_bounds = Bounds::new(proposed_origin, base_size);
-
-        let display_right = display_bounds.origin.x + display_bounds.size.width;
-        let display_bottom = display_bounds.origin.y + display_bounds.size.height;
-        let window_right = proposed_bounds.origin.x + proposed_bounds.size.width;
-        let window_bottom = proposed_bounds.origin.y + proposed_bounds.size.height;
-
-        let fits_horizontally = window_right <= display_right;
-        let fits_vertically = window_bottom <= display_bottom;
-
-        let final_origin = match (fits_horizontally, fits_vertically) {
-            (true, true) => proposed_origin,
-            (false, true) => point(display_bounds.origin.x, base_origin.y),
-            (true, false) => point(base_origin.x, display_bounds.origin.y),
-            (false, false) => display_bounds.origin,
-        };
-
-        Bounds::new(final_origin, base_size)
-    }
-
-    #[cfg(not(target_os = "macos"))]
-    {
-        const DEFAULT_WINDOW_OFFSET: Point<Pixels> = point(px(0.), px(35.));
-
-        // TODO, BUG: if you open a window with the currently active window
-        // on the stack, this will erroneously select the 'unwrap_or_else'
-        // code path
-        cx.active_window()
-            .and_then(|w| w.update(cx, |_, window, _| window.bounds()).ok())
-            .map(|mut bounds| {
-                bounds.origin += DEFAULT_WINDOW_OFFSET;
-                bounds
-            })
-            .unwrap_or_else(|| {
-                let display = display_id
-                    .map(|id| cx.find_display(id))
-                    .unwrap_or_else(|| cx.primary_display());
-
-                display
-                    .as_ref()
-                    .map(|display| display.default_bounds())
-                    .unwrap_or_else(|| Bounds::new(point(px(0.), px(0.)), DEFAULT_WINDOW_SIZE))
-            })
-    }
+fn default_bounds(display_id: Option<DisplayId>, cx: &mut App) -> WindowBounds {
+    // TODO, BUG: if you open a window with the currently active window
+    // on the stack, this will erroneously fallback to `None`
+    //
+    // TODO these should be the initial window bounds not considering maximized/fullscreen
+    let active_window_bounds = cx
+        .active_window()
+        .and_then(|w| w.update(cx, |_, window, _| window.window_bounds()).ok());
+
+    const CASCADE_OFFSET: f32 = 25.0;
+
+    let display = display_id
+        .map(|id| cx.find_display(id))
+        .unwrap_or_else(|| cx.primary_display());
+
+    let default_placement = || Bounds::new(point(px(0.), px(0.)), DEFAULT_WINDOW_SIZE);
+
+    // Use visible_bounds to exclude taskbar/dock areas
+    let display_bounds = display
+        .as_ref()
+        .map(|d| d.visible_bounds())
+        .unwrap_or_else(default_placement);
+
+    let (
+        Bounds {
+            origin: base_origin,
+            size: base_size,
+        },
+        window_bounds_ctor,
+    ): (_, fn(Bounds<Pixels>) -> WindowBounds) = match active_window_bounds {
+        Some(bounds) => match bounds {
+            WindowBounds::Windowed(bounds) => (bounds, WindowBounds::Windowed),
+            WindowBounds::Maximized(bounds) => (bounds, WindowBounds::Maximized),
+            WindowBounds::Fullscreen(bounds) => (bounds, WindowBounds::Fullscreen),
+        },
+        None => (
+            display
+                .as_ref()
+                .map(|d| d.default_bounds())
+                .unwrap_or_else(default_placement),
+            WindowBounds::Windowed,
+        ),
+    };
+
+    let cascade_offset = point(px(CASCADE_OFFSET), px(CASCADE_OFFSET));
+    let proposed_origin = base_origin + cascade_offset;
+    let proposed_bounds = Bounds::new(proposed_origin, base_size);
+
+    let display_right = display_bounds.origin.x + display_bounds.size.width;
+    let display_bottom = display_bounds.origin.y + display_bounds.size.height;
+    let window_right = proposed_bounds.origin.x + proposed_bounds.size.width;
+    let window_bottom = proposed_bounds.origin.y + proposed_bounds.size.height;
+
+    let fits_horizontally = window_right <= display_right;
+    let fits_vertically = window_bottom <= display_bottom;
+
+    let final_origin = match (fits_horizontally, fits_vertically) {
+        (true, true) => proposed_origin,
+        (false, true) => point(display_bounds.origin.x, base_origin.y),
+        (true, false) => point(base_origin.x, display_bounds.origin.y),
+        (false, false) => display_bounds.origin,
+    };
+    window_bounds_ctor(Bounds::new(final_origin, base_size))
 }
 
 impl Window {
@@ -1024,13 +1055,11 @@ impl Window {
             tabbing_identifier,
         } = options;
 
-        let bounds = window_bounds
-            .map(|bounds| bounds.get_bounds())
-            .unwrap_or_else(|| default_bounds(display_id, cx));
+        let window_bounds = window_bounds.unwrap_or_else(|| default_bounds(display_id, cx));
         let mut platform_window = cx.platform.open_window(
             handle,
             WindowParams {
-                bounds,
+                bounds: window_bounds.get_bounds(),
                 titlebar,
                 kind,
                 is_movable,
@@ -1065,18 +1094,16 @@ impl Window {
         let hovered = Rc::new(Cell::new(platform_window.is_hovered()));
         let needs_present = Rc::new(Cell::new(false));
         let next_frame_callbacks: Rc<RefCell<Vec<FrameCallback>>> = Default::default();
-        let last_input_timestamp = Rc::new(Cell::new(Instant::now()));
+        let input_rate_tracker = Rc::new(RefCell::new(InputRateTracker::default()));
 
         platform_window
             .request_decorations(window_decorations.unwrap_or(WindowDecorations::Server));
         platform_window.set_background_appearance(window_background);
 
-        if let Some(ref window_open_state) = window_bounds {
-            match window_open_state {
-                WindowBounds::Fullscreen(_) => platform_window.toggle_fullscreen(),
-                WindowBounds::Maximized(_) => platform_window.zoom(),
-                WindowBounds::Windowed(_) => {}
-            }
+        match window_bounds {
+            WindowBounds::Fullscreen(_) => platform_window.toggle_fullscreen(),
+            WindowBounds::Maximized(_) => platform_window.zoom(),
+            WindowBounds::Windowed(_) => {}
         }
 
         platform_window.on_close(Box::new({
@@ -1095,7 +1122,7 @@ impl Window {
             let active = active.clone();
             let needs_present = needs_present.clone();
             let next_frame_callbacks = next_frame_callbacks.clone();
-            let last_input_timestamp = last_input_timestamp.clone();
+            let input_rate_tracker = input_rate_tracker.clone();
             move |request_frame_options| {
                 let next_frame_callbacks = next_frame_callbacks.take();
                 if !next_frame_callbacks.is_empty() {
@@ -1108,12 +1135,12 @@ impl Window {
                         .log_err();
                 }
 
-                // Keep presenting the current scene for 1 extra second since the
-                // last input to prevent the display from underclocking the refresh rate.
+                // Keep presenting if input was recently arriving at a high rate (>= 60fps).
+                // Once high-rate input is detected, we sustain presentation for 1 second
+                // to prevent display underclocking during active input.
                 let needs_present = request_frame_options.require_presentation
                     || needs_present.get()
-                    || (active.get()
-                        && last_input_timestamp.get().elapsed() < Duration::from_secs(1));
+                    || (active.get() && input_rate_tracker.borrow_mut().is_high_rate());
 
                 if invalidator.is_dirty() || request_frame_options.force_render {
                     measure("frame duration", || {
@@ -1121,7 +1148,6 @@ impl Window {
                             .update(&mut cx, |_, window, cx| {
                                 let arena_clear_needed = window.draw(cx);
                                 window.present();
-                                // drop the arena elements after present to reduce latency
                                 arena_clear_needed.clear();
                             })
                             .log_err();
@@ -1319,7 +1345,7 @@ impl Window {
             active,
             hovered,
             needs_present,
-            last_input_timestamp,
+            input_rate_tracker,
             last_input_modality: InputModality::Mouse,
             refreshing: false,
             activation_observers: SubscriberSet::new(),
@@ -1456,13 +1482,25 @@ impl Window {
     }
 
     /// Move focus to the element associated with the given [`FocusHandle`].
-    pub fn focus(&mut self, handle: &FocusHandle) {
+    pub fn focus(&mut self, handle: &FocusHandle, cx: &mut App) {
         if !self.focus_enabled || self.focus == Some(handle.id) {
             return;
         }
 
         self.focus = Some(handle.id);
         self.clear_pending_keystrokes();
+
+        // Avoid re-entrant entity updates by deferring observer notifications to the end of the
+        // current effect cycle, and only for this window.
+        let window_handle = self.handle;
+        cx.defer(move |cx| {
+            window_handle
+                .update(cx, |_, window, cx| {
+                    window.pending_input_changed(cx);
+                })
+                .ok();
+        });
+
         self.refresh();
     }
 
@@ -1483,24 +1521,24 @@ impl Window {
     }
 
     /// Move focus to next tab stop.
-    pub fn focus_next(&mut self) {
+    pub fn focus_next(&mut self, cx: &mut App) {
         if !self.focus_enabled {
             return;
         }
 
         if let Some(handle) = self.rendered_frame.tab_stops.next(self.focus.as_ref()) {
-            self.focus(&handle)
+            self.focus(&handle, cx)
         }
     }
 
     /// Move focus to previous tab stop.
-    pub fn focus_prev(&mut self) {
+    pub fn focus_prev(&mut self, cx: &mut App) {
         if !self.focus_enabled {
             return;
         }
 
         if let Some(handle) = self.rendered_frame.tab_stops.prev(self.focus.as_ref()) {
-            self.focus(&handle)
+            self.focus(&handle, cx)
         }
     }
 
@@ -1518,7 +1556,8 @@ impl Window {
         style
     }
 
-    /// Check if the platform window is maximized
+    /// Check if the platform window is maximized.
+    ///
     /// On some platforms (namely Windows) this is different than the bounds being the size of the display
     pub fn is_maximized(&self) -> bool {
         self.platform_window.is_maximized()
@@ -1745,6 +1784,27 @@ impl Window {
         })
     }
 
+    /// Spawn the future returned by the given closure on the application thread
+    /// pool, with the given priority. The closure is provided a handle to the
+    /// current window and an `AsyncWindowContext` for use within your future.
+    #[track_caller]
+    pub fn spawn_with_priority<AsyncFn, R>(
+        &self,
+        priority: Priority,
+        cx: &App,
+        f: AsyncFn,
+    ) -> Task<R>
+    where
+        R: 'static,
+        AsyncFn: AsyncFnOnce(&mut AsyncWindowContext) -> R + 'static,
+    {
+        let handle = self.handle;
+        cx.spawn_with_priority(priority, async move |app| {
+            let mut async_window_cx = AsyncWindowContext::new_context(app.clone(), handle);
+            f(&mut async_window_cx).await
+        })
+    }
+
     fn bounds_changed(&mut self, cx: &mut App) {
         self.scale_factor = self.platform_window.scale_factor();
         self.viewport_size = self.platform_window.content_size();
@@ -1959,7 +2019,7 @@ impl Window {
     }
 
     /// Determine whether the given action is available along the dispatch path to the currently focused element.
-    pub fn is_action_available(&self, action: &dyn Action, cx: &mut App) -> bool {
+    pub fn is_action_available(&self, action: &dyn Action, cx: &App) -> bool {
         let node_id =
             self.focus_node_id_in_rendered_frame(self.focused(cx).map(|handle| handle.id));
         self.rendered_frame
@@ -1967,6 +2027,14 @@ impl Window {
             .is_action_available(action, node_id)
     }
 
+    /// Determine whether the given action is available along the dispatch path to the given focus_handle.
+    pub fn is_action_available_in(&self, action: &dyn Action, focus_handle: &FocusHandle) -> bool {
+        let node_id = self.focus_node_id_in_rendered_frame(Some(focus_handle.id));
+        self.rendered_frame
+            .dispatch_tree
+            .is_action_available(action, node_id)
+    }
+
     /// The position of the mouse relative to the window.
     pub fn mouse_position(&self) -> Point<Pixels> {
         self.mouse_position
@@ -2006,7 +2074,9 @@ impl Window {
         if let Some(input_handler) = self.platform_window.take_input_handler() {
             self.rendered_frame.input_handlers.push(Some(input_handler));
         }
-        self.draw_roots(cx);
+        if !cx.mode.skip_drawing() {
+            self.draw_roots(cx);
+        }
         self.dirty_views.clear();
         self.next_frame.window_active = self.active.get();
 
@@ -3667,8 +3737,6 @@ impl Window {
     /// Dispatch a mouse or keyboard event on the window.
     #[profiling::function]
     pub fn dispatch_event(&mut self, event: PlatformInput, cx: &mut App) -> DispatchEventResult {
-        self.last_input_timestamp.set(Instant::now());
-
         // Track whether this input was keyboard-based for focus-visible styling
         self.last_input_modality = match &event {
             PlatformInput::KeyDown(_) | PlatformInput::ModifiersChanged(_) => {
@@ -3701,6 +3769,9 @@ impl Window {
                 self.modifiers = mouse_up.modifiers;
                 PlatformInput::MouseUp(mouse_up)
             }
+            PlatformInput::MousePressure(mouse_pressure) => {
+                PlatformInput::MousePressure(mouse_pressure)
+            }
             PlatformInput::MouseExited(mouse_exited) => {
                 self.modifiers = mouse_exited.modifiers;
                 PlatformInput::MouseExited(mouse_exited)
@@ -3766,6 +3837,10 @@ impl Window {
             self.dispatch_key_event(any_key_event, cx);
         }
 
+        if self.invalidator.is_dirty() {
+            self.input_rate_tracker.borrow_mut().record_input();
+        }
+
         DispatchEventResult {
             propagate: cx.propagate_event,
             default_prevented: self.default_prevented,
@@ -4005,7 +4080,7 @@ impl Window {
         self.dispatch_keystroke_observers(event, None, context_stack, cx);
     }
 
-    fn pending_input_changed(&mut self, cx: &mut App) {
+    pub(crate) fn pending_input_changed(&mut self, cx: &mut App) {
         self.pending_input_observers
             .clone()
             .retain(&(), |callback| callback(self, cx));
@@ -4423,6 +4498,13 @@ impl Window {
         dispatch_tree.highest_precedence_binding_for_action(action, &context_stack)
     }
 
+    /// Find the bindings that can follow the current input sequence for the current context stack.
+    pub fn possible_bindings_for_input(&self, input: &[Keystroke]) -> Vec<KeyBinding> {
+        self.rendered_frame
+            .dispatch_tree
+            .possible_next_bindings_for_input(input, &self.context_stack())
+    }
+
     fn context_stack_for_focus_handle(
         &self,
         focus_handle: &FocusHandle,
@@ -4932,7 +5014,7 @@ impl<V: 'static> From<WindowHandle<V>> for AnyWindowHandle {
 }
 
 /// A handle to a window with any root view type, which can be downcast to a window with a specific root view type.
-#[derive(Copy, Clone, PartialEq, Eq, Hash)]
+#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
 pub struct AnyWindowHandle {
     pub(crate) id: WindowId,
     state_type: TypeId,
@@ -5082,6 +5164,18 @@ impl From<SharedString> for ElementId {
     }
 }
 
+impl From<String> for ElementId {
+    fn from(name: String) -> Self {
+        ElementId::Name(name.into())
+    }
+}
+
+impl From<Arc<str>> for ElementId {
+    fn from(name: Arc<str>) -> Self {
+        ElementId::Name(name.into())
+    }
+}
+
 impl From<Arc<std::path::Path>> for ElementId {
     fn from(path: Arc<std::path::Path>) -> Self {
         ElementId::Path(path)

crates/gpui/src/window/prompts.rs 🔗

@@ -44,10 +44,10 @@ impl PromptHandle {
             if let Some(sender) = sender.take() {
                 sender.send(e.0).ok();
                 window_handle
-                    .update(cx, |_, window, _cx| {
+                    .update(cx, |_, window, cx| {
                         window.prompt.take();
                         if let Some(previous_focus) = &previous_focus {
-                            window.focus(previous_focus);
+                            window.focus(previous_focus, cx);
                         }
                     })
                     .ok();
@@ -55,7 +55,7 @@ impl PromptHandle {
         })
         .detach();
 
-        window.focus(&view.focus_handle(cx));
+        window.focus(&view.focus_handle(cx), cx);
 
         RenderablePromptHandle {
             view: Box::new(view),

crates/gpui_macros/src/derive_visual_context.rs 🔗

@@ -62,7 +62,7 @@ pub fn derive_visual_context(input: TokenStream) -> TokenStream {
                 V: gpui::Focusable,
             {
                 let focus_handle = gpui::Focusable::focus_handle(entity, self.#app_variable);
-                self.#window_variable.focus(&focus_handle)
+                self.#window_variable.focus(&focus_handle, self.#app_variable)
             }
         }
     };

crates/gpui_tokio/src/gpui_tokio.rs 🔗

@@ -5,25 +5,48 @@ use util::defer;
 
 pub use tokio::task::JoinError;
 
+/// Initializes the Tokio wrapper using a new Tokio runtime with 2 worker threads.
+///
+/// If you need more threads (or access to the runtime outside of GPUI), you can create the runtime
+/// yourself and pass a Handle to `init_from_handle`.
 pub fn init(cx: &mut App) {
-    cx.set_global(GlobalTokio::new());
+    let runtime = tokio::runtime::Builder::new_multi_thread()
+        // Since we now have two executors, let's try to keep our footprint small
+        .worker_threads(2)
+        .enable_all()
+        .build()
+        .expect("Failed to initialize Tokio");
+
+    cx.set_global(GlobalTokio::new(RuntimeHolder::Owned(runtime)));
+}
+
+/// Initializes the Tokio wrapper using a Tokio runtime handle.
+pub fn init_from_handle(cx: &mut App, handle: tokio::runtime::Handle) {
+    cx.set_global(GlobalTokio::new(RuntimeHolder::Shared(handle)));
+}
+
+enum RuntimeHolder {
+    Owned(tokio::runtime::Runtime),
+    Shared(tokio::runtime::Handle),
+}
+
+impl RuntimeHolder {
+    pub fn handle(&self) -> &tokio::runtime::Handle {
+        match self {
+            RuntimeHolder::Owned(runtime) => runtime.handle(),
+            RuntimeHolder::Shared(handle) => handle,
+        }
+    }
 }
 
 struct GlobalTokio {
-    runtime: tokio::runtime::Runtime,
+    runtime: RuntimeHolder,
 }
 
 impl Global for GlobalTokio {}
 
 impl GlobalTokio {
-    fn new() -> Self {
-        let runtime = tokio::runtime::Builder::new_multi_thread()
-            // Since we now have two executors, let's try to keep our footprint small
-            .worker_threads(2)
-            .enable_all()
-            .build()
-            .expect("Failed to initialize Tokio");
-
+    fn new(runtime: RuntimeHolder) -> Self {
         Self { runtime }
     }
 }
@@ -40,7 +63,7 @@ impl Tokio {
         R: Send + 'static,
     {
         cx.read_global(|tokio: &GlobalTokio, cx| {
-            let join_handle = tokio.runtime.spawn(f);
+            let join_handle = tokio.runtime.handle().spawn(f);
             let abort_handle = join_handle.abort_handle();
             let cancel = defer(move || {
                 abort_handle.abort();
@@ -62,7 +85,7 @@ impl Tokio {
         R: Send + 'static,
     {
         cx.read_global(|tokio: &GlobalTokio, cx| {
-            let join_handle = tokio.runtime.spawn(f);
+            let join_handle = tokio.runtime.handle().spawn(f);
             let abort_handle = join_handle.abort_handle();
             let cancel = defer(move || {
                 abort_handle.abort();

crates/http_client/Cargo.toml 🔗

@@ -28,7 +28,6 @@ http-body.workspace = true
 http.workspace = true
 log.workspace = true
 parking_lot.workspace = true
-reqwest.workspace = true
 serde.workspace = true
 serde_json.workspace = true
 serde_urlencoded.workspace = true

crates/http_client/src/async_body.rs 🔗

@@ -88,17 +88,6 @@ impl From<&'static str> for AsyncBody {
     }
 }
 
-impl TryFrom<reqwest::Body> for AsyncBody {
-    type Error = anyhow::Error;
-
-    fn try_from(value: reqwest::Body) -> Result<Self, Self::Error> {
-        value
-            .as_bytes()
-            .ok_or_else(|| anyhow::anyhow!("Underlying data is a stream"))
-            .map(|bytes| Self::from_bytes(Bytes::copy_from_slice(bytes)))
-    }
-}
-
 impl<T: Into<Self>> From<Option<T>> for AsyncBody {
     fn from(body: Option<T>) -> Self {
         match body {

crates/http_client/src/github_download.rs 🔗

@@ -1,4 +1,4 @@
-use std::{future::Future, path::Path, pin::Pin, task::Poll};
+use std::{path::Path, pin::Pin, task::Poll};
 
 use anyhow::{Context, Result};
 use async_compression::futures::bufread::GzipDecoder;
@@ -85,65 +85,6 @@ pub async fn download_server_binary(
     Ok(())
 }
 
-pub async fn fetch_github_binary_with_digest_check<ValidityCheck, ValidityCheckFuture>(
-    binary_path: &Path,
-    metadata_path: &Path,
-    expected_digest: Option<String>,
-    url: &str,
-    asset_kind: AssetKind,
-    download_destination: &Path,
-    http_client: &dyn HttpClient,
-    validity_check: ValidityCheck,
-) -> Result<()>
-where
-    ValidityCheck: FnOnce() -> ValidityCheckFuture,
-    ValidityCheckFuture: Future<Output = Result<()>>,
-{
-    let metadata = GithubBinaryMetadata::read_from_file(metadata_path)
-        .await
-        .ok();
-
-    if let Some(metadata) = metadata {
-        let validity_check_result = validity_check().await;
-
-        if let (Some(actual_digest), Some(expected_digest_ref)) =
-            (&metadata.digest, &expected_digest)
-        {
-            if actual_digest == expected_digest_ref {
-                if validity_check_result.is_ok() {
-                    return Ok(());
-                }
-            } else {
-                log::info!(
-                    "SHA-256 mismatch for {binary_path:?} asset, downloading new asset. Expected: {expected_digest_ref}, Got: {actual_digest}"
-                );
-            }
-        } else if validity_check_result.is_ok() {
-            return Ok(());
-        }
-    }
-
-    download_server_binary(
-        http_client,
-        url,
-        expected_digest.as_deref(),
-        download_destination,
-        asset_kind,
-    )
-    .await?;
-
-    GithubBinaryMetadata::write_to_file(
-        &GithubBinaryMetadata {
-            metadata_version: 1,
-            digest: expected_digest,
-        },
-        metadata_path,
-    )
-    .await?;
-
-    Ok(())
-}
-
 async fn stream_response_archive(
     response: impl AsyncRead + Unpin,
     url: &str,

crates/http_client/src/http_client.rs 🔗

@@ -8,10 +8,7 @@ use derive_more::Deref;
 use http::HeaderValue;
 pub use http::{self, Method, Request, Response, StatusCode, Uri, request::Builder};
 
-use futures::{
-    FutureExt as _,
-    future::{self, BoxFuture},
-};
+use futures::future::BoxFuture;
 use parking_lot::Mutex;
 use serde::Serialize;
 use std::sync::Arc;
@@ -110,14 +107,6 @@ pub trait HttpClient: 'static + Send + Sync {
     fn as_fake(&self) -> &FakeHttpClient {
         panic!("called as_fake on {}", type_name::<Self>())
     }
-
-    fn send_multipart_form<'a>(
-        &'a self,
-        _url: &str,
-        _request: reqwest::multipart::Form,
-    ) -> BoxFuture<'a, anyhow::Result<Response<AsyncBody>>> {
-        future::ready(Err(anyhow!("not implemented"))).boxed()
-    }
 }
 
 /// An [`HttpClient`] that may have a proxy.
@@ -165,14 +154,6 @@ impl HttpClient for HttpClientWithProxy {
     fn as_fake(&self) -> &FakeHttpClient {
         self.client.as_fake()
     }
-
-    fn send_multipart_form<'a>(
-        &'a self,
-        url: &str,
-        form: reqwest::multipart::Form,
-    ) -> BoxFuture<'a, anyhow::Result<Response<AsyncBody>>> {
-        self.client.send_multipart_form(url, form)
-    }
 }
 
 /// An [`HttpClient`] that has a base URL.
@@ -306,14 +287,6 @@ impl HttpClient for HttpClientWithUrl {
     fn as_fake(&self) -> &FakeHttpClient {
         self.client.as_fake()
     }
-
-    fn send_multipart_form<'a>(
-        &'a self,
-        url: &str,
-        request: reqwest::multipart::Form,
-    ) -> BoxFuture<'a, anyhow::Result<Response<AsyncBody>>> {
-        self.client.send_multipart_form(url, request)
-    }
 }
 
 pub fn read_proxy_from_env() -> Option<Url> {
@@ -408,6 +381,7 @@ impl FakeHttpClient {
     }
 
     pub fn with_404_response() -> Arc<HttpClientWithUrl> {
+        log::warn!("Using fake HTTP client with 404 response");
         Self::create(|_| async move {
             Ok(Response::builder()
                 .status(404)
@@ -417,6 +391,7 @@ impl FakeHttpClient {
     }
 
     pub fn with_200_response() -> Arc<HttpClientWithUrl> {
+        log::warn!("Using fake HTTP client with 200 response");
         Self::create(|_| async move {
             Ok(Response::builder()
                 .status(200)

crates/icons/src/icons.rs 🔗

@@ -34,8 +34,8 @@ pub enum IconName {
     ArrowRightLeft,
     ArrowUp,
     ArrowUpRight,
-    Attach,
     AtSign,
+    Attach,
     AudioOff,
     AudioOn,
     Backspace,
@@ -45,10 +45,11 @@ pub enum IconName {
     BellRing,
     Binary,
     Blocks,
-    BoltOutlined,
     BoltFilled,
+    BoltOutlined,
     Book,
     BookCopy,
+    Box,
     CaseSensitive,
     Chat,
     Check,
@@ -80,13 +81,12 @@ pub enum IconName {
     Debug,
     DebugBreakpoint,
     DebugContinue,
+    DebugDetach,
     DebugDisabledBreakpoint,
     DebugDisabledLogBreakpoint,
-    DebugDetach,
     DebugIgnoreBreakpoints,
     DebugLogBreakpoint,
     DebugPause,
-    DebugStepBack,
     DebugStepInto,
     DebugStepOut,
     DebugStepOver,
@@ -137,10 +137,12 @@ pub enum IconName {
     GenericRestore,
     GitBranch,
     GitBranchAlt,
+    GitBranchPlus,
     Github,
     Hash,
     HistoryRerun,
     Image,
+    Inception,
     Indicator,
     Info,
     Json,
@@ -148,6 +150,7 @@ pub enum IconName {
     Library,
     LineHeight,
     Link,
+    Linux,
     ListCollapse,
     ListFilter,
     ListTodo,
@@ -173,8 +176,8 @@ pub enum IconName {
     PencilUnavailable,
     Person,
     Pin,
-    PlayOutlined,
     PlayFilled,
+    PlayOutlined,
     Plus,
     Power,
     Public,
@@ -257,18 +260,18 @@ pub enum IconName {
     XCircle,
     XCircleFilled,
     ZedAgent,
+    ZedAgentTwo,
     ZedAssistant,
     ZedBurnMode,
     ZedBurnModeOn,
-    ZedSrcCustom,
-    ZedSrcExtension,
     ZedPredict,
     ZedPredictDisabled,
     ZedPredictDown,
     ZedPredictError,
     ZedPredictUp,
+    ZedSrcCustom,
+    ZedSrcExtension,
     ZedXCopilot,
-    Linux,
 }
 
 impl IconName {

crates/image_viewer/src/image_info.rs 🔗

@@ -77,9 +77,7 @@ impl Render for ImageInfo {
             .to_string(),
         );
 
-        div().child(
-            Button::new("image-metadata", components.join(" • ")).label_size(LabelSize::Small),
-        )
+        div().child(Label::new(components.join(" • ")).size(LabelSize::Small))
     }
 }
 

crates/image_viewer/src/image_viewer.rs 🔗

@@ -11,7 +11,7 @@ use gpui::{
     InteractiveElement, IntoElement, ObjectFit, ParentElement, Render, Styled, Task, WeakEntity,
     Window, canvas, div, fill, img, opaque_grey, point, size,
 };
-use language::{DiskState, File as _};
+use language::File as _;
 use persistence::IMAGE_VIEWER;
 use project::{ImageItem, Project, ProjectPath, image_store::ImageItemEvent};
 use settings::Settings;
@@ -195,7 +195,7 @@ impl Item for ImageView {
     }
 
     fn has_deleted_file(&self, cx: &App) -> bool {
-        self.image_item.read(cx).file.disk_state() == DiskState::Deleted
+        self.image_item.read(cx).file.disk_state().is_deleted()
     }
     fn buffer_kind(&self, _: &App) -> workspace::item::ItemBufferKind {
         workspace::item::ItemBufferKind::Singleton

crates/inspector_ui/src/div_inspector.rs 🔗

@@ -686,7 +686,6 @@ impl CompletionProvider for RustStyleCompletionProvider {
         position: language::Anchor,
         _text: &str,
         _trigger_in_words: bool,
-        _menu_is_open: bool,
         cx: &mut Context<Editor>,
     ) -> bool {
         completion_replace_range(&buffer.read(cx).snapshot(), &position).is_some()

crates/json_schema_store/Cargo.toml 🔗

@@ -20,6 +20,7 @@ dap.workspace = true
 extension.workspace = true
 gpui.workspace = true
 language.workspace = true
+lsp.workspace = true
 paths.workspace = true
 project.workspace = true
 schemars.workspace = true

crates/json_schema_store/src/json_schema_store.rs 🔗

@@ -2,9 +2,12 @@
 use std::{str::FromStr, sync::Arc};
 
 use anyhow::{Context as _, Result};
-use gpui::{App, AsyncApp, BorrowAppContext as _, Entity, WeakEntity};
-use language::LanguageRegistry;
-use project::LspStore;
+use gpui::{App, AsyncApp, BorrowAppContext as _, Entity, Task, WeakEntity};
+use language::{LanguageRegistry, language_settings::all_language_settings};
+use lsp::LanguageServerBinaryOptions;
+use project::{LspStore, lsp_store::LocalLspAdapterDelegate};
+use settings::LSP_SETTINGS_SCHEMA_URL_PREFIX;
+use util::schemars::{AllowTrailingCommas, DefaultDenyUnknownFields};
 
 // Origin: https://github.com/SchemaStore/schemastore
 const TSCONFIG_SCHEMA: &str = include_str!("schemas/tsconfig.json");
@@ -74,23 +77,28 @@ fn handle_schema_request(
     lsp_store: Entity<LspStore>,
     uri: String,
     cx: &mut AsyncApp,
-) -> Result<String> {
-    let languages = lsp_store.read_with(cx, |lsp_store, _| lsp_store.languages.clone())?;
-    let schema = resolve_schema_request(&languages, uri, cx)?;
-    serde_json::to_string(&schema).context("Failed to serialize schema")
+) -> Task<Result<String>> {
+    let languages = lsp_store.read_with(cx, |lsp_store, _| lsp_store.languages.clone());
+    cx.spawn(async move |cx| {
+        let languages = languages?;
+        let schema = resolve_schema_request(&languages, lsp_store, uri, cx).await?;
+        serde_json::to_string(&schema).context("Failed to serialize schema")
+    })
 }
 
-pub fn resolve_schema_request(
+pub async fn resolve_schema_request(
     languages: &Arc<LanguageRegistry>,
+    lsp_store: Entity<LspStore>,
     uri: String,
     cx: &mut AsyncApp,
 ) -> Result<serde_json::Value> {
     let path = uri.strip_prefix("zed://schemas/").context("Invalid URI")?;
-    resolve_schema_request_inner(languages, path, cx)
+    resolve_schema_request_inner(languages, lsp_store, path, cx).await
 }
 
-pub fn resolve_schema_request_inner(
+pub async fn resolve_schema_request_inner(
     languages: &Arc<LanguageRegistry>,
+    lsp_store: Entity<LspStore>,
     path: &str,
     cx: &mut AsyncApp,
 ) -> Result<serde_json::Value> {
@@ -98,37 +106,106 @@ pub fn resolve_schema_request_inner(
     let schema_name = schema_name.unwrap_or(path);
 
     let schema = match schema_name {
-        "settings" => cx.update(|cx| {
-            let font_names = &cx.text_system().all_font_names();
-            let language_names = &languages
-                .language_names()
+        "settings" if rest.is_some_and(|r| r.starts_with("lsp/")) => {
+            let lsp_name = rest
+                .and_then(|r| {
+                    r.strip_prefix(
+                        LSP_SETTINGS_SCHEMA_URL_PREFIX
+                            .strip_prefix("zed://schemas/settings/")
+                            .unwrap(),
+                    )
+                })
+                .context("Invalid LSP schema path")?;
+
+            let adapter = languages
+                .all_lsp_adapters()
+                .into_iter()
+                .find(|adapter| adapter.name().as_ref() as &str == lsp_name)
+                .with_context(|| format!("LSP adapter not found: {}", lsp_name))?;
+
+            let delegate = cx.update(|inner_cx| {
+                lsp_store.update(inner_cx, |lsp_store, inner_cx| {
+                    let Some(local) = lsp_store.as_local() else {
+                        return None;
+                    };
+                    let Some(worktree) = local.worktree_store.read(inner_cx).worktrees().next() else {
+                        return None;
+                    };
+                    Some(LocalLspAdapterDelegate::from_local_lsp(
+                        local, &worktree, inner_cx,
+                    ))
+                })
+            })?.context("Failed to create adapter delegate - either LSP store is not in local mode or no worktree is available")?;
+
+            let adapter_for_schema = adapter.clone();
+
+            let binary = adapter
+                .get_language_server_command(
+                    delegate,
+                    None,
+                    LanguageServerBinaryOptions {
+                        allow_path_lookup: true,
+                        allow_binary_download: false,
+                        pre_release: false,
+                    },
+                    cx,
+                )
+                .await
+                .await
+                .0.with_context(|| format!("Failed to find language server {lsp_name} to generate initialization params schema"))?;
+
+            adapter_for_schema
+                .adapter
+                .clone()
+                .initialization_options_schema(&binary)
+                .await
+                .unwrap_or_else(|| {
+                    serde_json::json!({
+                        "type": "object",
+                        "additionalProperties": true
+                    })
+                })
+        }
+        "settings" => {
+            let lsp_adapter_names = languages
+                .all_lsp_adapters()
                 .into_iter()
-                .map(|name| name.to_string())
+                .map(|adapter| adapter.name().to_string())
                 .collect::<Vec<_>>();
 
-            let mut icon_theme_names = vec![];
-            let mut theme_names = vec![];
-            if let Some(registry) = theme::ThemeRegistry::try_global(cx) {
-                icon_theme_names.extend(
-                    registry
-                        .list_icon_themes()
-                        .into_iter()
-                        .map(|icon_theme| icon_theme.name),
-                );
-                theme_names.extend(registry.list_names());
-            }
-            let icon_theme_names = icon_theme_names.as_slice();
-            let theme_names = theme_names.as_slice();
-
-            cx.global::<settings::SettingsStore>().json_schema(
-                &settings::SettingsJsonSchemaParams {
-                    language_names,
-                    font_names,
-                    theme_names,
-                    icon_theme_names,
-                },
-            )
-        })?,
+            cx.update(|cx| {
+                let font_names = &cx.text_system().all_font_names();
+                let language_names = &languages
+                    .language_names()
+                    .into_iter()
+                    .map(|name| name.to_string())
+                    .collect::<Vec<_>>();
+
+                let mut icon_theme_names = vec![];
+                let mut theme_names = vec![];
+                if let Some(registry) = theme::ThemeRegistry::try_global(cx) {
+                    icon_theme_names.extend(
+                        registry
+                            .list_icon_themes()
+                            .into_iter()
+                            .map(|icon_theme| icon_theme.name),
+                    );
+                    theme_names.extend(registry.list_names());
+                }
+                let icon_theme_names = icon_theme_names.as_slice();
+                let theme_names = theme_names.as_slice();
+
+                cx.global::<settings::SettingsStore>().json_schema(
+                    &settings::SettingsJsonSchemaParams {
+                        language_names,
+                        font_names,
+                        theme_names,
+                        icon_theme_names,
+                        lsp_adapter_names: &lsp_adapter_names,
+                    },
+                )
+            })?
+        }
         "keymap" => cx.update(settings::KeymapFile::generate_json_schema_for_registered_actions)?,
         "action" => {
             let normalized_action_name = rest.context("No Action name provided")?;
@@ -159,14 +236,35 @@ pub fn resolve_schema_request_inner(
             }
         }
         "snippets" => snippet_provider::format::VsSnippetsFile::generate_json_schema(),
+        "jsonc" => jsonc_schema(),
         _ => {
-            anyhow::bail!("Unrecognized builtin JSON schema: {}", schema_name);
+            anyhow::bail!("Unrecognized builtin JSON schema: {schema_name}");
         }
     };
     Ok(schema)
 }
 
-pub fn all_schema_file_associations(cx: &mut App) -> serde_json::Value {
+const JSONC_LANGUAGE_NAME: &str = "JSONC";
+
+pub fn all_schema_file_associations(
+    languages: &Arc<LanguageRegistry>,
+    cx: &mut App,
+) -> serde_json::Value {
+    let extension_globs = languages
+        .available_language_for_name(JSONC_LANGUAGE_NAME)
+        .map(|language| language.matcher().path_suffixes.clone())
+        .into_iter()
+        .flatten()
+        // Path suffixes can be entire file names or just their extensions.
+        .flat_map(|path_suffix| [format!("*.{path_suffix}"), path_suffix]);
+    let override_globs = all_language_settings(None, cx)
+        .file_types
+        .get(JSONC_LANGUAGE_NAME)
+        .into_iter()
+        .flat_map(|(_, glob_strings)| glob_strings)
+        .cloned();
+    let jsonc_globs = extension_globs.chain(override_globs).collect::<Vec<_>>();
+
     let mut file_associations = serde_json::json!([
         {
             "fileMatch": [
@@ -211,6 +309,10 @@ pub fn all_schema_file_associations(cx: &mut App) -> serde_json::Value {
             "fileMatch": ["package.json"],
             "url": "zed://schemas/package_json"
         },
+        {
+            "fileMatch": &jsonc_globs,
+            "url": "zed://schemas/jsonc"
+        },
     ]);
 
     #[cfg(debug_assertions)]
@@ -233,7 +335,7 @@ pub fn all_schema_file_associations(cx: &mut App) -> serde_json::Value {
             let file_name = normalized_action_name_to_file_name(normalized_name.clone());
             serde_json::json!({
                 "fileMatch": [file_name],
-                "url": format!("zed://schemas/action/{}", normalized_name)
+                "url": format!("zed://schemas/action/{normalized_name}")
             })
         }),
     );
@@ -249,6 +351,26 @@ fn package_json_schema() -> serde_json::Value {
     serde_json::Value::from_str(PACKAGE_JSON_SCHEMA).unwrap()
 }
 
+fn jsonc_schema() -> serde_json::Value {
+    let generator = schemars::generate::SchemaSettings::draft2019_09()
+        .with_transform(DefaultDenyUnknownFields)
+        .with_transform(AllowTrailingCommas)
+        .into_generator();
+    let meta_schema = generator
+        .settings()
+        .meta_schema
+        .as_ref()
+        .expect("meta_schema should be present in schemars settings")
+        .to_string();
+    let defs = generator.definitions();
+    let schema = schemars::json_schema!({
+        "$schema": meta_schema,
+        "allowTrailingCommas": true,
+        "$defs": defs,
+    });
+    serde_json::to_value(schema).unwrap()
+}
+
 fn generate_inspector_style_schema() -> serde_json::Value {
     let schema = schemars::generate::SchemaSettings::draft2019_09()
         .with_transform(util::schemars::DefaultDenyUnknownFields)

crates/keymap_editor/src/keymap_editor.rs 🔗

@@ -81,50 +81,61 @@ pub fn init(cx: &mut App) {
     let keymap_event_channel = KeymapEventChannel::new();
     cx.set_global(keymap_event_channel);
 
-    fn common(filter: Option<String>, cx: &mut App) {
-        workspace::with_active_or_new_workspace(cx, move |workspace, window, cx| {
-            workspace
-                .with_local_workspace(window, cx, move |workspace, window, cx| {
-                    let existing = workspace
-                        .active_pane()
-                        .read(cx)
-                        .items()
-                        .find_map(|item| item.downcast::<KeymapEditor>());
-
-                    let keymap_editor = if let Some(existing) = existing {
-                        workspace.activate_item(&existing, true, true, window, cx);
-                        existing
-                    } else {
-                        let keymap_editor =
-                            cx.new(|cx| KeymapEditor::new(workspace.weak_handle(), window, cx));
-                        workspace.add_item_to_active_pane(
-                            Box::new(keymap_editor.clone()),
-                            None,
-                            true,
-                            window,
-                            cx,
-                        );
-                        keymap_editor
-                    };
-
-                    if let Some(filter) = filter {
-                        keymap_editor.update(cx, |editor, cx| {
-                            editor.filter_editor.update(cx, |editor, cx| {
-                                editor.clear(window, cx);
-                                editor.insert(&filter, window, cx);
-                            });
-                            if !editor.has_binding_for(&filter) {
-                                open_binding_modal_after_loading(cx)
-                            }
-                        })
-                    }
-                })
-                .detach();
-        })
+    fn open_keymap_editor(
+        filter: Option<String>,
+        workspace: &mut Workspace,
+        window: &mut Window,
+        cx: &mut Context<Workspace>,
+    ) {
+        workspace
+            .with_local_workspace(window, cx, |workspace, window, cx| {
+                let existing = workspace
+                    .active_pane()
+                    .read(cx)
+                    .items()
+                    .find_map(|item| item.downcast::<KeymapEditor>());
+
+                let keymap_editor = if let Some(existing) = existing {
+                    workspace.activate_item(&existing, true, true, window, cx);
+                    existing
+                } else {
+                    let keymap_editor =
+                        cx.new(|cx| KeymapEditor::new(workspace.weak_handle(), window, cx));
+                    workspace.add_item_to_active_pane(
+                        Box::new(keymap_editor.clone()),
+                        None,
+                        true,
+                        window,
+                        cx,
+                    );
+                    keymap_editor
+                };
+
+                if let Some(filter) = filter {
+                    keymap_editor.update(cx, |editor, cx| {
+                        editor.filter_editor.update(cx, |editor, cx| {
+                            editor.clear(window, cx);
+                            editor.insert(&filter, window, cx);
+                        });
+                        if !editor.has_binding_for(&filter) {
+                            open_binding_modal_after_loading(cx)
+                        }
+                    })
+                }
+            })
+            .detach_and_log_err(cx);
     }
 
-    cx.on_action(|_: &OpenKeymap, cx| common(None, cx));
-    cx.on_action(|action: &ChangeKeybinding, cx| common(Some(action.action.clone()), cx));
+    cx.observe_new(|workspace: &mut Workspace, _window, _cx| {
+        workspace
+            .register_action(|workspace, _: &OpenKeymap, window, cx| {
+                open_keymap_editor(None, workspace, window, cx);
+            })
+            .register_action(|workspace, action: &ChangeKeybinding, window, cx| {
+                open_keymap_editor(Some(action.action.clone()), workspace, window, cx);
+            });
+    })
+    .detach();
 
     register_serializable_item::<KeymapEditor>(cx);
 }
@@ -900,7 +911,7 @@ impl KeymapEditor {
             .focus_handle(cx)
             .contains_focused(window, cx)
         {
-            window.focus(&self.filter_editor.focus_handle(cx));
+            window.focus(&self.filter_editor.focus_handle(cx), cx);
         } else {
             self.filter_editor.update(cx, |editor, cx| {
                 editor.select_all(&Default::default(), window, cx);
@@ -937,7 +948,7 @@ impl KeymapEditor {
             if let Some(scroll_strategy) = scroll {
                 self.scroll_to_item(index, scroll_strategy, cx);
             }
-            window.focus(&self.focus_handle);
+            window.focus(&self.focus_handle, cx);
             cx.notify();
         }
     }
@@ -987,7 +998,7 @@ impl KeymapEditor {
             });
 
             let context_menu_handle = context_menu.focus_handle(cx);
-            window.defer(cx, move |window, _cx| window.focus(&context_menu_handle));
+            window.defer(cx, move |window, cx| window.focus(&context_menu_handle, cx));
             let subscription = cx.subscribe_in(
                 &context_menu,
                 window,
@@ -1003,7 +1014,7 @@ impl KeymapEditor {
 
     fn dismiss_context_menu(&mut self, window: &mut Window, cx: &mut Context<Self>) {
         self.context_menu.take();
-        window.focus(&self.focus_handle);
+        window.focus(&self.focus_handle, cx);
         cx.notify();
     }
 
@@ -1219,7 +1230,7 @@ impl KeymapEditor {
                         window,
                         cx,
                     );
-                    window.focus(&modal.focus_handle(cx));
+                    window.focus(&modal.focus_handle(cx), cx);
                     modal
                 });
             })
@@ -1327,7 +1338,7 @@ impl KeymapEditor {
                     editor.stop_recording(&StopRecording, window, cx);
                     editor.clear_keystrokes(&ClearKeystrokes, window, cx);
                 });
-                window.focus(&self.filter_editor.focus_handle(cx));
+                window.focus(&self.filter_editor.focus_handle(cx), cx);
             }
         }
     }
@@ -2687,32 +2698,32 @@ impl KeybindingEditorModalFocusState {
             .map(|i| i as i32)
     }
 
-    fn focus_index(&self, mut index: i32, window: &mut Window) {
+    fn focus_index(&self, mut index: i32, window: &mut Window, cx: &mut App) {
         if index < 0 {
             index = self.handles.len() as i32 - 1;
         }
         if index >= self.handles.len() as i32 {
             index = 0;
         }
-        window.focus(&self.handles[index as usize]);
+        window.focus(&self.handles[index as usize], cx);
     }
 
-    fn focus_next(&self, window: &mut Window, cx: &App) {
+    fn focus_next(&self, window: &mut Window, cx: &mut App) {
         let index_to_focus = if let Some(index) = self.focused_index(window, cx) {
             index + 1
         } else {
             0
         };
-        self.focus_index(index_to_focus, window);
+        self.focus_index(index_to_focus, window, cx);
     }
 
-    fn focus_previous(&self, window: &mut Window, cx: &App) {
+    fn focus_previous(&self, window: &mut Window, cx: &mut App) {
         let index_to_focus = if let Some(index) = self.focused_index(window, cx) {
             index - 1
         } else {
             self.handles.len() as i32 - 1
         };
-        self.focus_index(index_to_focus, window);
+        self.focus_index(index_to_focus, window, cx);
     }
 }
 
@@ -2746,7 +2757,7 @@ impl ActionArgumentsEditor {
     ) -> Self {
         let focus_handle = cx.focus_handle();
         cx.on_focus_in(&focus_handle, window, |this, window, cx| {
-            this.editor.focus_handle(cx).focus(window);
+            this.editor.focus_handle(cx).focus(window, cx);
         })
         .detach();
         let editor = cx.new(|cx| {
@@ -2799,7 +2810,7 @@ impl ActionArgumentsEditor {
 
                 this.update_in(cx, |this, window, cx| {
                     if this.editor.focus_handle(cx).is_focused(window) {
-                        editor.focus_handle(cx).focus(window);
+                        editor.focus_handle(cx).focus(window, cx);
                     }
                     this.editor = editor;
                     this.backup_temp_dir = backup_temp_dir;
@@ -3001,7 +3012,6 @@ impl CompletionProvider for KeyContextCompletionProvider {
         _position: language::Anchor,
         text: &str,
         _trigger_in_words: bool,
-        _menu_is_open: bool,
         _cx: &mut Context<Editor>,
     ) -> bool {
         text.chars()

crates/keymap_editor/src/ui_components/keystroke_input.rs 🔗

@@ -388,7 +388,7 @@ impl KeystrokeInput {
         window: &mut Window,
         cx: &mut Context<Self>,
     ) {
-        window.focus(&self.inner_focus_handle);
+        window.focus(&self.inner_focus_handle, cx);
         self.clear_keystrokes(&ClearKeystrokes, window, cx);
         self.previous_modifiers = window.modifiers();
         #[cfg(test)]
@@ -407,7 +407,7 @@ impl KeystrokeInput {
         if !self.is_recording(window) {
             return;
         }
-        window.focus(&self.outer_focus_handle);
+        window.focus(&self.outer_focus_handle, cx);
         if let Some(close_keystrokes_start) = self.close_keystrokes_start.take()
             && close_keystrokes_start < self.keystrokes.len()
         {

crates/language/Cargo.toml 🔗

@@ -32,6 +32,7 @@ async-trait.workspace = true
 clock.workspace = true
 collections.workspace = true
 ec4rs.workspace = true
+encoding_rs.workspace = true
 fs.workspace = true
 futures.workspace = true
 fuzzy.workspace = true
@@ -48,6 +49,7 @@ rand = { workspace = true, optional = true }
 regex.workspace = true
 rpc.workspace = true
 schemars.workspace = true
+semver.workspace = true
 serde.workspace = true
 serde_json.workspace = true
 settings.workspace = true

crates/language/src/buffer.rs 🔗

@@ -1,15 +1,15 @@
 pub mod row_chunk;
 
 use crate::{
-    DebuggerTextObject, LanguageScope, Outline, OutlineConfig, RunnableCapture, RunnableTag,
-    TextObject, TreeSitterOptions,
+    DebuggerTextObject, LanguageScope, Outline, OutlineConfig, PLAIN_TEXT, RunnableCapture,
+    RunnableTag, TextObject, TreeSitterOptions,
     diagnostic_set::{DiagnosticEntry, DiagnosticEntryRef, DiagnosticGroup},
     language_settings::{LanguageSettings, language_settings},
     outline::OutlineItem,
     row_chunk::RowChunks,
     syntax_map::{
-        SyntaxLayer, SyntaxMap, SyntaxMapCapture, SyntaxMapCaptures, SyntaxMapMatch,
-        SyntaxMapMatches, SyntaxSnapshot, ToTreeSitterPoint,
+        MAX_BYTES_TO_QUERY, SyntaxLayer, SyntaxMap, SyntaxMapCapture, SyntaxMapCaptures,
+        SyntaxMapMatch, SyntaxMapMatches, SyntaxSnapshot, ToTreeSitterPoint,
     },
     task_context::RunnableRange,
     text_diff::text_diff,
@@ -22,9 +22,10 @@ pub use crate::{
     proto,
 };
 use anyhow::{Context as _, Result};
+use clock::Lamport;
 pub use clock::ReplicaId;
-use clock::{Global, Lamport};
 use collections::{HashMap, HashSet};
+use encoding_rs::Encoding;
 use fs::MTime;
 use futures::channel::oneshot;
 use gpui::{
@@ -32,9 +33,8 @@ use gpui::{
     Task, TaskLabel, TextStyle,
 };
 
-use itertools::Itertools;
 use lsp::{LanguageServerId, NumberOrString};
-use parking_lot::{Mutex, RawMutex, lock_api::MutexGuard};
+use parking_lot::Mutex;
 use serde::{Deserialize, Serialize};
 use serde_json::Value;
 use settings::WorktreeId;
@@ -45,7 +45,7 @@ use std::{
     borrow::Cow,
     cell::Cell,
     cmp::{self, Ordering, Reverse},
-    collections::{BTreeMap, BTreeSet, hash_map},
+    collections::{BTreeMap, BTreeSet},
     future::Future,
     iter::{self, Iterator, Peekable},
     mem,
@@ -131,29 +131,39 @@ pub struct Buffer {
     has_unsaved_edits: Cell<(clock::Global, bool)>,
     change_bits: Vec<rc::Weak<Cell<bool>>>,
     _subscriptions: Vec<gpui::Subscription>,
-    tree_sitter_data: Arc<Mutex<TreeSitterData>>,
+    tree_sitter_data: Arc<TreeSitterData>,
+    encoding: &'static Encoding,
+    has_bom: bool,
 }
 
-#[derive(Debug, Clone)]
+#[derive(Debug)]
 pub struct TreeSitterData {
     chunks: RowChunks,
-    brackets_by_chunks: Vec<Option<Vec<BracketMatch<usize>>>>,
+    brackets_by_chunks: Mutex<Vec<Option<Vec<BracketMatch<usize>>>>>,
 }
 
 const MAX_ROWS_IN_A_CHUNK: u32 = 50;
 
 impl TreeSitterData {
-    fn clear(&mut self) {
-        self.brackets_by_chunks = vec![None; self.chunks.len()];
+    fn clear(&mut self, snapshot: text::BufferSnapshot) {
+        self.chunks = RowChunks::new(snapshot, MAX_ROWS_IN_A_CHUNK);
+        self.brackets_by_chunks.get_mut().clear();
+        self.brackets_by_chunks
+            .get_mut()
+            .resize(self.chunks.len(), None);
     }
 
     fn new(snapshot: text::BufferSnapshot) -> Self {
         let chunks = RowChunks::new(snapshot, MAX_ROWS_IN_A_CHUNK);
         Self {
-            brackets_by_chunks: vec![None; chunks.len()],
+            brackets_by_chunks: Mutex::new(vec![None; chunks.len()]),
             chunks,
         }
     }
+
+    fn version(&self) -> &clock::Global {
+        self.chunks.version()
+    }
 }
 
 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
@@ -177,7 +187,7 @@ pub struct BufferSnapshot {
     remote_selections: TreeMap<ReplicaId, SelectionSet>,
     language: Option<Arc<Language>>,
     non_text_state_update_count: usize,
-    tree_sitter_data: Arc<Mutex<TreeSitterData>>,
+    tree_sitter_data: Arc<TreeSitterData>,
 }
 
 /// The kind and amount of indentation in a particular line. For now,
@@ -238,6 +248,8 @@ struct SelectionSet {
 pub struct Diagnostic {
     /// The name of the service that produced this diagnostic.
     pub source: Option<String>,
+    /// The ID provided by the dynamic registration that produced this diagnostic.
+    pub registration_id: Option<SharedString>,
     /// A machine-readable code that identifies this diagnostic.
     pub code: Option<NumberOrString>,
     pub code_description: Option<lsp::Uri>,
@@ -352,7 +364,8 @@ pub enum BufferEvent {
     /// The buffer is in need of a reload
     ReloadNeeded,
     /// The buffer's language was changed.
-    LanguageChanged,
+    /// The boolean indicates whether this buffer did not have a language before, but does now.
+    LanguageChanged(bool),
     /// The buffer's syntax trees were updated.
     Reparsed,
     /// The buffer's diagnostics were updated.
@@ -414,6 +427,9 @@ pub enum DiskState {
     Present { mtime: MTime },
     /// Deleted file that was previously present.
     Deleted,
+    /// An old version of a file that was previously present
+    /// usually from a version control system. e.g. A git blob
+    Historic { was_deleted: bool },
 }
 
 impl DiskState {
@@ -423,6 +439,7 @@ impl DiskState {
             DiskState::New => None,
             DiskState::Present { mtime } => Some(mtime),
             DiskState::Deleted => None,
+            DiskState::Historic { .. } => None,
         }
     }
 
@@ -431,6 +448,16 @@ impl DiskState {
             DiskState::New => false,
             DiskState::Present { .. } => true,
             DiskState::Deleted => false,
+            DiskState::Historic { .. } => false,
+        }
+    }
+
+    /// Returns true if this state represents a deleted file.
+    pub fn is_deleted(&self) -> bool {
+        match self {
+            DiskState::Deleted => true,
+            DiskState::Historic { was_deleted } => *was_deleted,
+            _ => false,
         }
     }
 }
@@ -1060,7 +1087,7 @@ impl Buffer {
         let tree_sitter_data = TreeSitterData::new(snapshot);
         Self {
             saved_mtime,
-            tree_sitter_data: Arc::new(Mutex::new(tree_sitter_data)),
+            tree_sitter_data: Arc::new(tree_sitter_data),
             saved_version: buffer.version(),
             preview_version: buffer.version(),
             reload_task: None,
@@ -1090,6 +1117,8 @@ impl Buffer {
             has_conflict: false,
             change_bits: Default::default(),
             _subscriptions: Vec::new(),
+            encoding: encoding_rs::UTF_8,
+            has_bom: false,
         }
     }
 
@@ -1117,7 +1146,7 @@ impl Buffer {
                 file: None,
                 diagnostics: Default::default(),
                 remote_selections: Default::default(),
-                tree_sitter_data: Arc::new(Mutex::new(tree_sitter_data)),
+                tree_sitter_data: Arc::new(tree_sitter_data),
                 language,
                 non_text_state_update_count: 0,
             }
@@ -1139,7 +1168,7 @@ impl Buffer {
         BufferSnapshot {
             text,
             syntax,
-            tree_sitter_data: Arc::new(Mutex::new(tree_sitter_data)),
+            tree_sitter_data: Arc::new(tree_sitter_data),
             file: None,
             diagnostics: Default::default(),
             remote_selections: Default::default(),
@@ -1168,7 +1197,7 @@ impl Buffer {
         BufferSnapshot {
             text,
             syntax,
-            tree_sitter_data: Arc::new(Mutex::new(tree_sitter_data)),
+            tree_sitter_data: Arc::new(tree_sitter_data),
             file: None,
             diagnostics: Default::default(),
             remote_selections: Default::default(),
@@ -1185,10 +1214,16 @@ impl Buffer {
         syntax_map.interpolate(&text);
         let syntax = syntax_map.snapshot();
 
+        let tree_sitter_data = if self.text.version() != *self.tree_sitter_data.version() {
+            Arc::new(TreeSitterData::new(text.clone()))
+        } else {
+            self.tree_sitter_data.clone()
+        };
+
         BufferSnapshot {
             text,
             syntax,
-            tree_sitter_data: self.tree_sitter_data.clone(),
+            tree_sitter_data,
             file: self.file.clone(),
             remote_selections: self.remote_selections.clone(),
             diagnostics: self.diagnostics.clone(),
@@ -1367,6 +1402,26 @@ impl Buffer {
         self.saved_mtime
     }
 
+    /// Returns the character encoding of the buffer's file.
+    pub fn encoding(&self) -> &'static Encoding {
+        self.encoding
+    }
+
+    /// Sets the character encoding of the buffer.
+    pub fn set_encoding(&mut self, encoding: &'static Encoding) {
+        self.encoding = encoding;
+    }
+
+    /// Returns whether the buffer has a Byte Order Mark.
+    pub fn has_bom(&self) -> bool {
+        self.has_bom
+    }
+
+    /// Sets whether the buffer has a Byte Order Mark.
+    pub fn set_has_bom(&mut self, has_bom: bool) {
+        self.has_bom = has_bom;
+    }
+
     /// Assign a language to the buffer.
     pub fn set_language_async(&mut self, language: Option<Arc<Language>>, cx: &mut Context<Self>) {
         self.set_language_(language, cfg!(any(test, feature = "test-support")), cx);
@@ -1385,10 +1440,12 @@ impl Buffer {
     ) {
         self.non_text_state_update_count += 1;
         self.syntax_map.lock().clear(&self.text);
-        self.language = language;
+        let old_language = std::mem::replace(&mut self.language, language);
         self.was_changed();
         self.reparse(cx, may_block);
-        cx.emit(BufferEvent::LanguageChanged);
+        let has_fresh_language =
+            self.language.is_some() && old_language.is_none_or(|old| old == *PLAIN_TEXT);
+        cx.emit(BufferEvent::LanguageChanged(has_fresh_language));
     }
 
     /// Assign a language registry to the buffer. This allows the buffer to retrieve
@@ -1447,19 +1504,23 @@ impl Buffer {
         let (tx, rx) = futures::channel::oneshot::channel();
         let prev_version = self.text.version();
         self.reload_task = Some(cx.spawn(async move |this, cx| {
-            let Some((new_mtime, new_text)) = this.update(cx, |this, cx| {
+            let Some((new_mtime, load_bytes_task, encoding)) = this.update(cx, |this, cx| {
                 let file = this.file.as_ref()?.as_local()?;
-
-                Some((file.disk_state().mtime(), file.load(cx)))
+                Some((
+                    file.disk_state().mtime(),
+                    file.load_bytes(cx),
+                    this.encoding,
+                ))
             })?
             else {
                 return Ok(());
             };
 
-            let new_text = new_text.await?;
-            let diff = this
-                .update(cx, |this, cx| this.diff(new_text.clone(), cx))?
-                .await;
+            let bytes = load_bytes_task.await?;
+            let (cow, _encoding_used, _has_errors) = encoding.decode(&bytes);
+            let new_text = cow.into_owned();
+
+            let diff = this.update(cx, |this, cx| this.diff(new_text, cx))?.await;
             this.update(cx, |this, cx| {
                 if this.version() == diff.base_version {
                     this.finalize_last_transaction();
@@ -1620,6 +1681,16 @@ impl Buffer {
         self.sync_parse_timeout = timeout;
     }
 
+    fn invalidate_tree_sitter_data(&mut self, snapshot: text::BufferSnapshot) {
+        match Arc::get_mut(&mut self.tree_sitter_data) {
+            Some(tree_sitter_data) => tree_sitter_data.clear(snapshot),
+            None => {
+                let tree_sitter_data = TreeSitterData::new(snapshot);
+                self.tree_sitter_data = Arc::new(tree_sitter_data)
+            }
+        }
+    }
+
     /// Called after an edit to synchronize the buffer's main parse tree with
     /// the buffer's new underlying state.
     ///
@@ -1644,6 +1715,9 @@ impl Buffer {
     /// for the same buffer, we only initiate a new parse if we are not already
     /// parsing in the background.
     pub fn reparse(&mut self, cx: &mut Context<Self>, may_block: bool) {
+        if self.text.version() != *self.tree_sitter_data.version() {
+            self.invalidate_tree_sitter_data(self.text.snapshot());
+        }
         if self.reparse.is_some() {
             return;
         }
@@ -1745,7 +1819,7 @@ impl Buffer {
         self.syntax_map.lock().did_parse(syntax_snapshot);
         self.request_autoindent(cx);
         self.parse_status.0.send(ParseStatus::Idle).unwrap();
-        self.tree_sitter_data.lock().clear();
+        self.invalidate_tree_sitter_data(self.text.snapshot());
         cx.emit(BufferEvent::Reparsed);
         cx.notify();
     }
@@ -2214,6 +2288,7 @@ impl Buffer {
                 None => true,
             },
             DiskState::Deleted => false,
+            DiskState::Historic { .. } => false,
         }
     }
 
@@ -3183,15 +3258,22 @@ impl BufferSnapshot {
         struct StartPosition {
             start: Point,
             suffix: SharedString,
+            language: Arc<Language>,
         }
 
         // Find the suggested indentation ranges based on the syntax tree.
         let start = Point::new(prev_non_blank_row.unwrap_or(row_range.start), 0);
         let end = Point::new(row_range.end, 0);
         let range = (start..end).to_offset(&self.text);
-        let mut matches = self.syntax.matches(range.clone(), &self.text, |grammar| {
-            Some(&grammar.indents_config.as_ref()?.query)
-        });
+        let mut matches = self.syntax.matches_with_options(
+            range.clone(),
+            &self.text,
+            TreeSitterOptions {
+                max_bytes_to_query: Some(MAX_BYTES_TO_QUERY),
+                max_start_depth: None,
+            },
+            |grammar| Some(&grammar.indents_config.as_ref()?.query),
+        );
         let indent_configs = matches
             .grammars()
             .iter()
@@ -3220,6 +3302,7 @@ impl BufferSnapshot {
                     start_positions.push(StartPosition {
                         start: Point::from_ts_point(capture.node.start_position()),
                         suffix: suffix.clone(),
+                        language: mat.language.clone(),
                     });
                 }
             }
@@ -3270,8 +3353,7 @@ impl BufferSnapshot {
             // set its end to the outdent position
             if let Some(range_to_truncate) = indent_ranges
                 .iter_mut()
-                .filter(|indent_range| indent_range.contains(&outdent_position))
-                .next_back()
+                .rfind(|indent_range| indent_range.contains(&outdent_position))
             {
                 range_to_truncate.end = outdent_position;
             }
@@ -3281,7 +3363,7 @@ impl BufferSnapshot {
 
         // Find the suggested indentation increases and decreased based on regexes.
         let mut regex_outdent_map = HashMap::default();
-        let mut last_seen_suffix: HashMap<String, Vec<Point>> = HashMap::default();
+        let mut last_seen_suffix: HashMap<String, Vec<StartPosition>> = HashMap::default();
         let mut start_positions_iter = start_positions.iter().peekable();
 
         let mut indent_change_rows = Vec::<(u32, Ordering)>::new();
@@ -3289,14 +3371,21 @@ impl BufferSnapshot {
             Point::new(prev_non_blank_row.unwrap_or(row_range.start), 0)
                 ..Point::new(row_range.end, 0),
             |row, line| {
-                if config
+                let indent_len = self.indent_size_for_line(row).len;
+                let row_language = self.language_at(Point::new(row, indent_len)).cloned();
+                let row_language_config = row_language
+                    .as_ref()
+                    .map(|lang| lang.config())
+                    .unwrap_or(config);
+
+                if row_language_config
                     .decrease_indent_pattern
                     .as_ref()
                     .is_some_and(|regex| regex.is_match(line))
                 {
                     indent_change_rows.push((row, Ordering::Less));
                 }
-                if config
+                if row_language_config
                     .increase_indent_pattern
                     .as_ref()
                     .is_some_and(|regex| regex.is_match(line))
@@ -3305,16 +3394,16 @@ impl BufferSnapshot {
                 }
                 while let Some(pos) = start_positions_iter.peek() {
                     if pos.start.row < row {
-                        let pos = start_positions_iter.next().unwrap();
+                        let pos = start_positions_iter.next().unwrap().clone();
                         last_seen_suffix
                             .entry(pos.suffix.to_string())
                             .or_default()
-                            .push(pos.start);
+                            .push(pos);
                     } else {
                         break;
                     }
                 }
-                for rule in &config.decrease_indent_patterns {
+                for rule in &row_language_config.decrease_indent_patterns {
                     if rule.pattern.as_ref().is_some_and(|r| r.is_match(line)) {
                         let row_start_column = self.indent_size_for_line(row).len;
                         let basis_row = rule
@@ -3322,10 +3411,16 @@ impl BufferSnapshot {
                             .iter()
                             .filter_map(|valid_suffix| last_seen_suffix.get(valid_suffix))
                             .flatten()
-                            .filter(|start_point| start_point.column <= row_start_column)
-                            .max_by_key(|start_point| start_point.row);
-                        if let Some(outdent_to_row) = basis_row {
-                            regex_outdent_map.insert(row, outdent_to_row.row);
+                            .filter(|pos| {
+                                row_language
+                                    .as_ref()
+                                    .or(self.language.as_ref())
+                                    .is_some_and(|lang| Arc::ptr_eq(lang, &pos.language))
+                            })
+                            .filter(|pos| pos.start.column <= row_start_column)
+                            .max_by_key(|pos| pos.start.row);
+                        if let Some(outdent_to) = basis_row {
+                            regex_outdent_map.insert(row, outdent_to.start.row);
                         }
                         break;
                     }
@@ -4021,6 +4116,20 @@ impl BufferSnapshot {
         })
     }
 
+    pub fn outline_items_as_offsets_containing<T: ToOffset>(
+        &self,
+        range: Range<T>,
+        include_extra_context: bool,
+        theme: Option<&SyntaxTheme>,
+    ) -> Vec<OutlineItem<usize>> {
+        self.outline_items_containing_internal(
+            range,
+            include_extra_context,
+            theme,
+            |buffer, range| range.to_offset(buffer),
+        )
+    }
+
     fn outline_items_containing_internal<T: ToOffset, U>(
         &self,
         range: Range<T>,
@@ -4263,177 +4372,125 @@ impl BufferSnapshot {
     pub fn fetch_bracket_ranges(
         &self,
         range: Range<usize>,
-        known_chunks: Option<(&Global, &HashSet<Range<BufferRow>>)>,
+        known_chunks: Option<&HashSet<Range<BufferRow>>>,
     ) -> HashMap<Range<BufferRow>, Vec<BracketMatch<usize>>> {
-        let mut tree_sitter_data = self.latest_tree_sitter_data().clone();
-
-        let known_chunks = match known_chunks {
-            Some((known_version, known_chunks)) => {
-                if !tree_sitter_data
-                    .chunks
-                    .version()
-                    .changed_since(known_version)
-                {
-                    known_chunks.clone()
-                } else {
-                    HashSet::default()
-                }
-            }
-            None => HashSet::default(),
-        };
-
-        let mut new_bracket_matches = HashMap::default();
         let mut all_bracket_matches = HashMap::default();
-        let mut bracket_matches_to_color = HashMap::default();
 
-        for chunk in tree_sitter_data
+        for chunk in self
+            .tree_sitter_data
             .chunks
-            .applicable_chunks(&[self.anchor_before(range.start)..self.anchor_after(range.end)])
+            .applicable_chunks(&[range.to_point(self)])
         {
-            if known_chunks.contains(&chunk.row_range()) {
+            if known_chunks.is_some_and(|chunks| chunks.contains(&chunk.row_range())) {
                 continue;
             }
-            let Some(chunk_range) = tree_sitter_data.chunks.chunk_range(chunk) else {
+            let chunk_range = chunk.anchor_range();
+            let chunk_range = chunk_range.to_offset(&self);
+
+            if let Some(cached_brackets) =
+                &self.tree_sitter_data.brackets_by_chunks.lock()[chunk.id]
+            {
+                all_bracket_matches.insert(chunk.row_range(), cached_brackets.clone());
                 continue;
-            };
-            let chunk_range = chunk_range.to_offset(&tree_sitter_data.chunks.snapshot);
-
-            let bracket_matches = match tree_sitter_data.brackets_by_chunks[chunk.id].take() {
-                Some(cached_brackets) => cached_brackets,
-                None => {
-                    let mut bracket_pairs_ends = Vec::new();
-                    let mut matches =
-                        self.syntax
-                            .matches(chunk_range.clone(), &self.text, |grammar| {
-                                grammar.brackets_config.as_ref().map(|c| &c.query)
-                            });
-                    let configs = matches
-                        .grammars()
-                        .iter()
-                        .map(|grammar| grammar.brackets_config.as_ref().unwrap())
-                        .collect::<Vec<_>>();
-
-                    let chunk_range = chunk_range.clone();
-                    let tree_sitter_matches = iter::from_fn(|| {
-                        while let Some(mat) = matches.peek() {
-                            let mut open = None;
-                            let mut close = None;
-                            let depth = mat.depth;
-                            let config = configs[mat.grammar_index];
-                            let pattern = &config.patterns[mat.pattern_index];
-                            for capture in mat.captures {
-                                if capture.index == config.open_capture_ix {
-                                    open = Some(capture.node.byte_range());
-                                } else if capture.index == config.close_capture_ix {
-                                    close = Some(capture.node.byte_range());
-                                }
-                            }
+            }
 
-                            matches.advance();
+            let mut all_brackets = Vec::new();
+            let mut opens = Vec::new();
+            let mut color_pairs = Vec::new();
 
-                            let Some((open_range, close_range)) = open.zip(close) else {
-                                continue;
-                            };
+            let mut matches = self.syntax.matches_with_options(
+                chunk_range.clone(),
+                &self.text,
+                TreeSitterOptions {
+                    max_bytes_to_query: Some(MAX_BYTES_TO_QUERY),
+                    max_start_depth: None,
+                },
+                |grammar| grammar.brackets_config.as_ref().map(|c| &c.query),
+            );
+            let configs = matches
+                .grammars()
+                .iter()
+                .map(|grammar| grammar.brackets_config.as_ref().unwrap())
+                .collect::<Vec<_>>();
+
+            while let Some(mat) = matches.peek() {
+                let mut open = None;
+                let mut close = None;
+                let syntax_layer_depth = mat.depth;
+                let config = configs[mat.grammar_index];
+                let pattern = &config.patterns[mat.pattern_index];
+                for capture in mat.captures {
+                    if capture.index == config.open_capture_ix {
+                        open = Some(capture.node.byte_range());
+                    } else if capture.index == config.close_capture_ix {
+                        close = Some(capture.node.byte_range());
+                    }
+                }
 
-                            let bracket_range = open_range.start..=close_range.end;
-                            if !bracket_range.overlaps(&chunk_range) {
-                                continue;
-                            }
+                matches.advance();
 
-                            if !pattern.rainbow_exclude
-                                // Also, certain languages have "brackets" that are not brackets, e.g. tags. and such
-                                // bracket will match the entire tag with all text inside.
-                                // For now, avoid highlighting any pair that has more than single char in each bracket.
-                                // We need to  colorize `<Element/>` bracket pairs, so cannot make this check stricter.
-                                && (open_range.len() == 1 || close_range.len() == 1)
-                            {
-                                // Certain tree-sitter grammars may return more bracket pairs than needed:
-                                // see `test_markdown_bracket_colorization` for a set-up that returns pairs with the same start bracket and different end one.
-                                // Pick the pair with the shortest range in case of ambiguity.
-                                match bracket_matches_to_color.entry(open_range.clone()) {
-                                    hash_map::Entry::Vacant(v) => {
-                                        v.insert(close_range.clone());
-                                    }
-                                    hash_map::Entry::Occupied(mut o) => {
-                                        let previous_close_range = o.get();
-                                        let previous_length =
-                                            previous_close_range.end - open_range.start;
-                                        let new_length = close_range.end - open_range.start;
-                                        if new_length < previous_length {
-                                            o.insert(close_range.clone());
-                                        }
-                                    }
-                                }
-                            }
-                            return Some((open_range, close_range, pattern, depth));
-                        }
-                        None
-                    })
-                    .sorted_by_key(|(open_range, _, _, _)| open_range.start)
-                    .collect::<Vec<_>>();
+                let Some((open_range, close_range)) = open.zip(close) else {
+                    continue;
+                };
 
-                    let new_matches = tree_sitter_matches
-                        .into_iter()
-                        .map(|(open_range, close_range, pattern, syntax_layer_depth)| {
-                            let participates_in_colorizing =
-                                bracket_matches_to_color.get(&open_range).is_some_and(
-                                    |close_range_to_color| close_range_to_color == &close_range,
-                                );
-                            let color_index = if participates_in_colorizing {
-                                while let Some(&last_bracket_end) = bracket_pairs_ends.last() {
-                                    if last_bracket_end <= open_range.start {
-                                        bracket_pairs_ends.pop();
-                                    } else {
-                                        break;
-                                    }
-                                }
+                let bracket_range = open_range.start..=close_range.end;
+                if !bracket_range.overlaps(&chunk_range) {
+                    continue;
+                }
 
-                                let bracket_depth = bracket_pairs_ends.len();
-                                bracket_pairs_ends.push(close_range.end);
-                                Some(bracket_depth)
-                            } else {
-                                None
-                            };
+                let index = all_brackets.len();
+                all_brackets.push(BracketMatch {
+                    open_range: open_range.clone(),
+                    close_range: close_range.clone(),
+                    newline_only: pattern.newline_only,
+                    syntax_layer_depth,
+                    color_index: None,
+                });
 
-                            BracketMatch {
-                                open_range,
-                                close_range,
-                                syntax_layer_depth,
-                                newline_only: pattern.newline_only,
-                                color_index,
-                            }
-                        })
-                        .collect::<Vec<_>>();
+                // Certain languages have "brackets" that are not brackets, e.g. tags. and such
+                // bracket will match the entire tag with all text inside.
+                // For now, avoid highlighting any pair that has more than single char in each bracket.
+                // We need to  colorize `<Element/>` bracket pairs, so cannot make this check stricter.
+                let should_color =
+                    !pattern.rainbow_exclude && (open_range.len() == 1 || close_range.len() == 1);
+                if should_color {
+                    opens.push(open_range.clone());
+                    color_pairs.push((open_range, close_range, index));
+                }
+            }
 
-                    new_bracket_matches.insert(chunk.id, new_matches.clone());
-                    new_matches
+            opens.sort_by_key(|r| (r.start, r.end));
+            opens.dedup_by(|a, b| a.start == b.start && a.end == b.end);
+            color_pairs.sort_by_key(|(_, close, _)| close.end);
+
+            let mut open_stack = Vec::new();
+            let mut open_index = 0;
+            for (open, close, index) in color_pairs {
+                while open_index < opens.len() && opens[open_index].start < close.start {
+                    open_stack.push(opens[open_index].clone());
+                    open_index += 1;
                 }
-            };
-            all_bracket_matches.insert(chunk.row_range(), bracket_matches);
-        }
 
-        let mut latest_tree_sitter_data = self.latest_tree_sitter_data();
-        if latest_tree_sitter_data.chunks.version() == &self.version {
-            for (chunk_id, new_matches) in new_bracket_matches {
-                let old_chunks = &mut latest_tree_sitter_data.brackets_by_chunks[chunk_id];
-                if old_chunks.is_none() {
-                    *old_chunks = Some(new_matches);
+                if open_stack.last() == Some(&open) {
+                    let depth_index = open_stack.len() - 1;
+                    all_brackets[index].color_index = Some(depth_index);
+                    open_stack.pop();
                 }
             }
-        }
 
-        all_bracket_matches
-    }
+            all_brackets.sort_by_key(|bracket_match| {
+                (bracket_match.open_range.start, bracket_match.open_range.end)
+            });
 
-    fn latest_tree_sitter_data(&self) -> MutexGuard<'_, RawMutex, TreeSitterData> {
-        let mut tree_sitter_data = self.tree_sitter_data.lock();
-        if self
-            .version
-            .changed_since(tree_sitter_data.chunks.version())
-        {
-            *tree_sitter_data = TreeSitterData::new(self.text.clone());
+            if let empty_slot @ None =
+                &mut self.tree_sitter_data.brackets_by_chunks.lock()[chunk.id]
+            {
+                *empty_slot = Some(all_brackets.clone());
+            }
+            all_bracket_matches.insert(chunk.row_range(), all_brackets);
         }
-        tree_sitter_data
+
+        all_bracket_matches
     }
 
     pub fn all_bracket_ranges(
@@ -5413,6 +5470,7 @@ impl Default for Diagnostic {
             is_unnecessary: false,
             underline: true,
             data: None,
+            registration_id: None,
         }
     }
 }

crates/language/src/buffer/row_chunk.rs 🔗

@@ -3,7 +3,6 @@
 
 use std::{ops::Range, sync::Arc};
 
-use clock::Global;
 use text::{Anchor, OffsetRangeExt as _, Point};
 use util::RangeExt;
 
@@ -19,14 +18,13 @@ use crate::BufferRow;
 /// <https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#inlayHintParams>
 #[derive(Clone)]
 pub struct RowChunks {
-    pub(crate) snapshot: text::BufferSnapshot,
     chunks: Arc<[RowChunk]>,
+    version: clock::Global,
 }
 
 impl std::fmt::Debug for RowChunks {
     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
         f.debug_struct("RowChunks")
-            .field("version", self.snapshot.version())
             .field("chunks", &self.chunks)
             .finish()
     }
@@ -38,34 +36,45 @@ impl RowChunks {
         let last_row = buffer_point_range.end.row;
         let chunks = (buffer_point_range.start.row..=last_row)
             .step_by(max_rows_per_chunk as usize)
+            .collect::<Vec<_>>();
+        let last_chunk_id = chunks.len() - 1;
+        let chunks = chunks
+            .into_iter()
             .enumerate()
-            .map(|(id, chunk_start)| RowChunk {
-                id,
-                start: chunk_start,
-                end_exclusive: (chunk_start + max_rows_per_chunk).min(last_row),
+            .map(|(id, chunk_start)| {
+                let start = Point::new(chunk_start, 0);
+                let end_exclusive = (chunk_start + max_rows_per_chunk).min(last_row);
+                let end = if id == last_chunk_id {
+                    Point::new(end_exclusive, snapshot.line_len(end_exclusive))
+                } else {
+                    Point::new(end_exclusive, 0)
+                };
+                RowChunk {
+                    id,
+                    start: chunk_start,
+                    end_exclusive,
+                    start_anchor: snapshot.anchor_before(start),
+                    end_anchor: snapshot.anchor_after(end),
+                }
             })
             .collect::<Vec<_>>();
         Self {
-            snapshot,
             chunks: Arc::from(chunks),
+            version: snapshot.version().clone(),
         }
     }
 
-    pub fn version(&self) -> &Global {
-        self.snapshot.version()
+    pub fn version(&self) -> &clock::Global {
+        &self.version
     }
 
     pub fn len(&self) -> usize {
         self.chunks.len()
     }
 
-    pub fn applicable_chunks(
-        &self,
-        ranges: &[Range<text::Anchor>],
-    ) -> impl Iterator<Item = RowChunk> {
+    pub fn applicable_chunks(&self, ranges: &[Range<Point>]) -> impl Iterator<Item = RowChunk> {
         let row_ranges = ranges
             .iter()
-            .map(|range| range.to_point(&self.snapshot))
             // Be lenient and yield multiple chunks if they "touch" the exclusive part of the range.
             // This will result in LSP hints [re-]queried for more ranges, but also more hints already visible when scrolling around.
             .map(|point_range| point_range.start.row..point_range.end.row + 1)
@@ -81,23 +90,6 @@ impl RowChunks {
             .copied()
     }
 
-    pub fn chunk_range(&self, chunk: RowChunk) -> Option<Range<Anchor>> {
-        if !self.chunks.contains(&chunk) {
-            return None;
-        }
-
-        let start = Point::new(chunk.start, 0);
-        let end = if self.chunks.last() == Some(&chunk) {
-            Point::new(
-                chunk.end_exclusive,
-                self.snapshot.line_len(chunk.end_exclusive),
-            )
-        } else {
-            Point::new(chunk.end_exclusive, 0)
-        };
-        Some(self.snapshot.anchor_before(start)..self.snapshot.anchor_after(end))
-    }
-
     pub fn previous_chunk(&self, chunk: RowChunk) -> Option<RowChunk> {
         if chunk.id == 0 {
             None
@@ -112,10 +104,16 @@ pub struct RowChunk {
     pub id: usize,
     pub start: BufferRow,
     pub end_exclusive: BufferRow,
+    pub start_anchor: Anchor,
+    pub end_anchor: Anchor,
 }
 
 impl RowChunk {
     pub fn row_range(&self) -> Range<BufferRow> {
         self.start..self.end_exclusive
     }
+
+    pub fn anchor_range(&self) -> Range<Anchor> {
+        self.start_anchor..self.end_anchor
+    }
 }

crates/language/src/buffer_tests.rs 🔗

@@ -6,6 +6,7 @@ use futures::FutureExt as _;
 use gpui::{App, AppContext as _, BorrowAppContext, Entity};
 use gpui::{HighlightStyle, TestAppContext};
 use indoc::indoc;
+use pretty_assertions::assert_eq;
 use proto::deserialize_operation;
 use rand::prelude::*;
 use regex::RegexBuilder;
@@ -46,8 +47,7 @@ fn test_line_endings(cx: &mut gpui::App) {
     init_settings(cx, |_| {});
 
     cx.new(|cx| {
-        let mut buffer =
-            Buffer::local("one\r\ntwo\rthree", cx).with_language(Arc::new(rust_lang()), cx);
+        let mut buffer = Buffer::local("one\r\ntwo\rthree", cx).with_language(rust_lang(), cx);
         assert_eq!(buffer.text(), "one\ntwo\nthree");
         assert_eq!(buffer.line_ending(), LineEnding::Windows);
 
@@ -151,7 +151,7 @@ fn test_select_language(cx: &mut App) {
     let registry = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
     registry.add(Arc::new(Language::new(
         LanguageConfig {
-            name: LanguageName::new("Rust"),
+            name: LanguageName::new_static("Rust"),
             matcher: LanguageMatcher {
                 path_suffixes: vec!["rs".to_string()],
                 ..Default::default()
@@ -173,7 +173,7 @@ fn test_select_language(cx: &mut App) {
     )));
     registry.add(Arc::new(Language::new(
         LanguageConfig {
-            name: LanguageName::new("Make"),
+            name: LanguageName::new_static("Make"),
             matcher: LanguageMatcher {
                 path_suffixes: vec!["Makefile".to_string(), "mk".to_string()],
                 ..Default::default()
@@ -608,7 +608,7 @@ async fn test_normalize_whitespace(cx: &mut gpui::TestAppContext) {
 #[gpui::test]
 async fn test_reparse(cx: &mut gpui::TestAppContext) {
     let text = "fn a() {}";
-    let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(Arc::new(rust_lang()), cx));
+    let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(rust_lang(), cx));
 
     // Wait for the initial text to parse
     cx.executor().run_until_parked();
@@ -735,7 +735,7 @@ async fn test_reparse(cx: &mut gpui::TestAppContext) {
 #[gpui::test]
 async fn test_resetting_language(cx: &mut gpui::TestAppContext) {
     let buffer = cx.new(|cx| {
-        let mut buffer = Buffer::local("{}", cx).with_language(Arc::new(rust_lang()), cx);
+        let mut buffer = Buffer::local("{}", cx).with_language(rust_lang(), cx);
         buffer.set_sync_parse_timeout(Duration::ZERO);
         buffer
     });
@@ -783,29 +783,49 @@ async fn test_outline(cx: &mut gpui::TestAppContext) {
     "#
     .unindent();
 
-    let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(Arc::new(rust_lang()), cx));
-    let outline = buffer.update(cx, |buffer, _| buffer.snapshot().outline(None));
+    let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(rust_lang(), cx));
+    let snapshot = buffer.update(cx, |buffer, _| buffer.snapshot());
+    let outline = snapshot.outline(None);
 
     assert_eq!(
         outline
             .items
             .iter()
-            .map(|item| (item.text.as_str(), item.depth))
+            .map(|item| (
+                item.text.as_str(),
+                item.depth,
+                item.to_point(&snapshot).body_range(&snapshot)
+                    .map(|range| minimize_space(&snapshot.text_for_range(range).collect::<String>()))
+            ))
             .collect::<Vec<_>>(),
         &[
-            ("struct Person", 0),
-            ("name", 1),
-            ("age", 1),
-            ("mod module", 0),
-            ("enum LoginState", 1),
-            ("LoggedOut", 2),
-            ("LoggingOn", 2),
-            ("LoggedIn", 2),
-            ("person", 3),
-            ("time", 3),
-            ("impl Eq for Person", 0),
-            ("impl Drop for Person", 0),
-            ("fn drop", 1),
+            ("struct Person", 0, Some("name: String, age: usize,".to_string())),
+            ("name", 1, None),
+            ("age", 1, None),
+            (
+                "mod module",
+                0,
+                Some(
+                    "enum LoginState { LoggedOut, LoggingOn, LoggedIn { person: Person, time: Instant, } }".to_string()
+                )
+            ),
+            (
+                "enum LoginState",
+                1,
+                Some("LoggedOut, LoggingOn, LoggedIn { person: Person, time: Instant, }".to_string())
+            ),
+            ("LoggedOut", 2, None),
+            ("LoggingOn", 2, None),
+            ("LoggedIn", 2, Some("person: Person, time: Instant,".to_string())),
+            ("person", 3, None),
+            ("time", 3, None),
+            ("impl Eq for Person", 0, Some("".to_string())),
+            (
+                "impl Drop for Person",
+                0,
+                Some("fn drop(&mut self) { println!(\"bye\"); }".to_string())
+            ),
+            ("fn drop", 1, Some("println!(\"bye\");".to_string())),
         ]
     );
 
@@ -840,6 +860,11 @@ async fn test_outline(cx: &mut gpui::TestAppContext) {
         ]
     );
 
+    fn minimize_space(text: &str) -> String {
+        static WHITESPACE: LazyLock<Regex> = LazyLock::new(|| Regex::new("[\\n\\s]+").unwrap());
+        WHITESPACE.replace_all(text, " ").trim().to_string()
+    }
+
     async fn search<'a>(
         outline: &'a Outline<Anchor>,
         query: &'a str,
@@ -865,7 +890,7 @@ async fn test_outline_nodes_with_newlines(cx: &mut gpui::TestAppContext) {
     "#
     .unindent();
 
-    let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(Arc::new(rust_lang()), cx));
+    let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(rust_lang(), cx));
     let outline = buffer.update(cx, |buffer, _| buffer.snapshot().outline(None));
 
     assert_eq!(
@@ -945,7 +970,7 @@ fn test_outline_annotations(cx: &mut App) {
     "#
     .unindent();
 
-    let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(Arc::new(rust_lang()), cx));
+    let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(rust_lang(), cx));
     let outline = buffer.update(cx, |buffer, _| buffer.snapshot().outline(None));
 
     assert_eq!(
@@ -993,7 +1018,7 @@ async fn test_symbols_containing(cx: &mut gpui::TestAppContext) {
     "#
     .unindent();
 
-    let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(Arc::new(rust_lang()), cx));
+    let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(rust_lang(), cx));
     let snapshot = buffer.update(cx, |buffer, _| buffer.snapshot());
 
     // point is at the start of an item
@@ -1068,7 +1093,7 @@ async fn test_symbols_containing(cx: &mut gpui::TestAppContext) {
     "
         .unindent(),
     );
-    let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(Arc::new(rust_lang()), cx));
+    let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(rust_lang(), cx));
     let snapshot = buffer.update(cx, |buffer, _| buffer.snapshot());
 
     // note, it would be nice to actually return the method test in this
@@ -1087,8 +1112,7 @@ fn test_text_objects(cx: &mut App) {
         false,
     );
 
-    let buffer =
-        cx.new(|cx| Buffer::local(text.clone(), cx).with_language(Arc::new(rust_lang()), cx));
+    let buffer = cx.new(|cx| Buffer::local(text.clone(), cx).with_language(rust_lang(), cx));
     let snapshot = buffer.update(cx, |buffer, _| buffer.snapshot());
 
     let matches = snapshot
@@ -1105,10 +1129,116 @@ fn test_text_objects(cx: &mut App) {
                 "fn say() -> u8 { return /* hi */ 1 }",
                 TextObject::AroundFunction
             ),
+            (
+                "fn say() -> u8 { return /* hi */ 1 }",
+                TextObject::InsideClass
+            ),
+            (
+                "impl Hello {\n    fn say() -> u8 { return /* hi */ 1 }\n}",
+                TextObject::AroundClass
+            ),
         ],
     )
 }
 
+#[gpui::test]
+fn test_text_objects_with_has_parent_predicate(cx: &mut App) {
+    use std::borrow::Cow;
+
+    // Create a language with a custom text_objects query that uses #has-parent?
+    // This query only matches closure_expression when it's inside a call_expression
+    let language = Language::new(
+        LanguageConfig {
+            name: "Rust".into(),
+            matcher: LanguageMatcher {
+                path_suffixes: vec!["rs".to_string()],
+                ..Default::default()
+            },
+            ..Default::default()
+        },
+        Some(tree_sitter_rust::LANGUAGE.into()),
+    )
+    .with_queries(LanguageQueries {
+        text_objects: Some(Cow::from(indoc! {r#"
+            ; Only match closures that are arguments to function calls
+            (closure_expression) @function.around
+              (#has-parent? @function.around arguments)
+        "#})),
+        ..Default::default()
+    })
+    .expect("Could not parse queries");
+
+    let (text, ranges) = marked_text_ranges(
+        indoc! {r#"
+            fn main() {
+                let standalone = |x| x + 1;
+                let result = foo(|y| y * ˇ2);
+            }"#
+        },
+        false,
+    );
+
+    let buffer = cx.new(|cx| Buffer::local(text.clone(), cx).with_language(Arc::new(language), cx));
+    let snapshot = buffer.update(cx, |buffer, _| buffer.snapshot());
+
+    let matches = snapshot
+        .text_object_ranges(ranges[0].clone(), TreeSitterOptions::default())
+        .map(|(range, text_object)| (&text[range], text_object))
+        .collect::<Vec<_>>();
+
+    // Should only match the closure inside foo(), not the standalone closure
+    assert_eq!(matches, &[("|y| y * 2", TextObject::AroundFunction),]);
+}
+
+#[gpui::test]
+fn test_text_objects_with_not_has_parent_predicate(cx: &mut App) {
+    use std::borrow::Cow;
+
+    // Create a language with a custom text_objects query that uses #not-has-parent?
+    // This query only matches closure_expression when it's NOT inside a call_expression
+    let language = Language::new(
+        LanguageConfig {
+            name: "Rust".into(),
+            matcher: LanguageMatcher {
+                path_suffixes: vec!["rs".to_string()],
+                ..Default::default()
+            },
+            ..Default::default()
+        },
+        Some(tree_sitter_rust::LANGUAGE.into()),
+    )
+    .with_queries(LanguageQueries {
+        text_objects: Some(Cow::from(indoc! {r#"
+            ; Only match closures that are NOT arguments to function calls
+            (closure_expression) @function.around
+              (#not-has-parent? @function.around arguments)
+        "#})),
+        ..Default::default()
+    })
+    .expect("Could not parse queries");
+
+    let (text, ranges) = marked_text_ranges(
+        indoc! {r#"
+            fn main() {
+                let standalone = |x| x +ˇ 1;
+                let result = foo(|y| y * 2);
+            }"#
+        },
+        false,
+    );
+
+    let buffer = cx.new(|cx| Buffer::local(text.clone(), cx).with_language(Arc::new(language), cx));
+    let snapshot = buffer.update(cx, |buffer, _| buffer.snapshot());
+
+    let matches = snapshot
+        .text_object_ranges(ranges[0].clone(), TreeSitterOptions::default())
+        .map(|(range, text_object)| (&text[range], text_object))
+        .collect::<Vec<_>>();
+
+    // Should only match the standalone closure, not the one inside foo()
+    assert_eq!(matches, &[("|x| x + 1", TextObject::AroundFunction),]);
+}
+
 #[gpui::test]
 fn test_enclosing_bracket_ranges(cx: &mut App) {
     #[track_caller]
@@ -1235,7 +1365,12 @@ fn test_enclosing_bracket_ranges(cx: &mut App) {
 #[gpui::test]
 fn test_enclosing_bracket_ranges_where_brackets_are_not_outermost_children(cx: &mut App) {
     let mut assert = |selection_text, bracket_pair_texts| {
-        assert_bracket_pairs(selection_text, bracket_pair_texts, javascript_lang(), cx)
+        assert_bracket_pairs(
+            selection_text,
+            bracket_pair_texts,
+            Arc::new(javascript_lang()),
+            cx,
+        )
     };
 
     assert(
@@ -1268,7 +1403,7 @@ fn test_enclosing_bracket_ranges_where_brackets_are_not_outermost_children(cx: &
 fn test_range_for_syntax_ancestor(cx: &mut App) {
     cx.new(|cx| {
         let text = "fn a() { b(|c| {}) }";
-        let buffer = Buffer::local(text, cx).with_language(Arc::new(rust_lang()), cx);
+        let buffer = Buffer::local(text, cx).with_language(rust_lang(), cx);
         let snapshot = buffer.snapshot();
 
         assert_eq!(
@@ -1320,7 +1455,7 @@ fn test_autoindent_with_soft_tabs(cx: &mut App) {
 
     cx.new(|cx| {
         let text = "fn a() {}";
-        let mut buffer = Buffer::local(text, cx).with_language(Arc::new(rust_lang()), cx);
+        let mut buffer = Buffer::local(text, cx).with_language(rust_lang(), cx);
 
         buffer.edit([(8..8, "\n\n")], Some(AutoindentMode::EachLine), cx);
         assert_eq!(buffer.text(), "fn a() {\n    \n}");
@@ -1362,7 +1497,7 @@ fn test_autoindent_with_hard_tabs(cx: &mut App) {
 
     cx.new(|cx| {
         let text = "fn a() {}";
-        let mut buffer = Buffer::local(text, cx).with_language(Arc::new(rust_lang()), cx);
+        let mut buffer = Buffer::local(text, cx).with_language(rust_lang(), cx);
 
         buffer.edit([(8..8, "\n\n")], Some(AutoindentMode::EachLine), cx);
         assert_eq!(buffer.text(), "fn a() {\n\t\n}");
@@ -1411,7 +1546,7 @@ fn test_autoindent_does_not_adjust_lines_with_unchanged_suggestion(cx: &mut App)
             .unindent(),
             cx,
         )
-        .with_language(Arc::new(rust_lang()), cx);
+        .with_language(rust_lang(), cx);
 
         // Lines 2 and 3 don't match the indentation suggestion. When editing these lines,
         // their indentation is not adjusted.
@@ -1552,7 +1687,7 @@ fn test_autoindent_does_not_adjust_lines_with_unchanged_suggestion(cx: &mut App)
             .unindent(),
             cx,
         )
-        .with_language(Arc::new(rust_lang()), cx);
+        .with_language(rust_lang(), cx);
 
         // Insert a closing brace. It is outdented.
         buffer.edit_via_marked_text(
@@ -1615,7 +1750,7 @@ fn test_autoindent_does_not_adjust_lines_within_newly_created_errors(cx: &mut Ap
             .unindent(),
             cx,
         )
-        .with_language(Arc::new(rust_lang()), cx);
+        .with_language(rust_lang(), cx);
 
         // Regression test: line does not get outdented due to syntax error
         buffer.edit_via_marked_text(
@@ -1674,7 +1809,7 @@ fn test_autoindent_adjusts_lines_when_only_text_changes(cx: &mut App) {
             .unindent(),
             cx,
         )
-        .with_language(Arc::new(rust_lang()), cx);
+        .with_language(rust_lang(), cx);
 
         buffer.edit_via_marked_text(
             &"
@@ -1724,7 +1859,7 @@ fn test_autoindent_with_edit_at_end_of_buffer(cx: &mut App) {
 
     cx.new(|cx| {
         let text = "a\nb";
-        let mut buffer = Buffer::local(text, cx).with_language(Arc::new(rust_lang()), cx);
+        let mut buffer = Buffer::local(text, cx).with_language(rust_lang(), cx);
         buffer.edit(
             [(0..1, "\n"), (2..3, "\n")],
             Some(AutoindentMode::EachLine),
@@ -1750,7 +1885,7 @@ fn test_autoindent_multi_line_insertion(cx: &mut App) {
         "
         .unindent();
 
-        let mut buffer = Buffer::local(text, cx).with_language(Arc::new(rust_lang()), cx);
+        let mut buffer = Buffer::local(text, cx).with_language(rust_lang(), cx);
         buffer.edit(
             [(Point::new(3, 0)..Point::new(3, 0), "e(\n    f()\n);\n")],
             Some(AutoindentMode::EachLine),
@@ -1787,7 +1922,7 @@ fn test_autoindent_block_mode(cx: &mut App) {
             }
         "#
         .unindent();
-        let mut buffer = Buffer::local(text, cx).with_language(Arc::new(rust_lang()), cx);
+        let mut buffer = Buffer::local(text, cx).with_language(rust_lang(), cx);
 
         // When this text was copied, both of the quotation marks were at the same
         // indent level, but the indentation of the first line was not included in
@@ -1870,7 +2005,7 @@ fn test_autoindent_block_mode_with_newline(cx: &mut App) {
             }
         "#
         .unindent();
-        let mut buffer = Buffer::local(text, cx).with_language(Arc::new(rust_lang()), cx);
+        let mut buffer = Buffer::local(text, cx).with_language(rust_lang(), cx);
 
         // First line contains just '\n', it's indentation is stored in "original_indent_columns"
         let original_indent_columns = vec![Some(4)];
@@ -1922,7 +2057,7 @@ fn test_autoindent_block_mode_without_original_indent_columns(cx: &mut App) {
             }
         "#
         .unindent();
-        let mut buffer = Buffer::local(text, cx).with_language(Arc::new(rust_lang()), cx);
+        let mut buffer = Buffer::local(text, cx).with_language(rust_lang(), cx);
 
         // The original indent columns are not known, so this text is
         // auto-indented in a block as if the first line was copied in
@@ -2013,7 +2148,7 @@ fn test_autoindent_block_mode_multiple_adjacent_ranges(cx: &mut App) {
             false,
         );
 
-        let mut buffer = Buffer::local(text, cx).with_language(Arc::new(rust_lang()), cx);
+        let mut buffer = Buffer::local(text, cx).with_language(rust_lang(), cx);
 
         buffer.edit(
             [
@@ -2027,7 +2162,7 @@ fn test_autoindent_block_mode_multiple_adjacent_ranges(cx: &mut App) {
             cx,
         );
 
-        pretty_assertions::assert_eq!(
+        assert_eq!(
             buffer.text(),
             "
             mod numbers {
@@ -2221,7 +2356,7 @@ async fn test_async_autoindents_preserve_preview(cx: &mut TestAppContext) {
     // Then we request that a preview tab be preserved for the new version, even though it's edited.
     let buffer = cx.new(|cx| {
         let text = "fn a() {}";
-        let mut buffer = Buffer::local(text, cx).with_language(Arc::new(rust_lang()), cx);
+        let mut buffer = Buffer::local(text, cx).with_language(rust_lang(), cx);
 
         // This causes autoindent to be async.
         buffer.set_sync_parse_timeout(Duration::ZERO);
@@ -2679,7 +2814,7 @@ fn test_language_at_with_hidden_languages(cx: &mut App) {
         .unindent();
 
         let language_registry = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
-        language_registry.add(Arc::new(markdown_lang()));
+        language_registry.add(markdown_lang());
         language_registry.add(Arc::new(markdown_inline_lang()));
 
         let mut buffer = Buffer::local(text, cx);
@@ -2721,9 +2856,9 @@ fn test_language_at_for_markdown_code_block(cx: &mut App) {
         .unindent();
 
         let language_registry = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
-        language_registry.add(Arc::new(markdown_lang()));
+        language_registry.add(markdown_lang());
         language_registry.add(Arc::new(markdown_inline_lang()));
-        language_registry.add(Arc::new(rust_lang()));
+        language_registry.add(rust_lang());
 
         let mut buffer = Buffer::local(text, cx);
         buffer.set_language_registry(language_registry.clone());
@@ -3120,7 +3255,7 @@ async fn test_preview_edits(cx: &mut TestAppContext) {
         cx: &mut TestAppContext,
         assert_fn: impl Fn(HighlightedText),
     ) {
-        let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(Arc::new(rust_lang()), cx));
+        let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(rust_lang(), cx));
         let edits = buffer.read_with(cx, |buffer, _| {
             edits
                 .into_iter()
@@ -3531,7 +3666,7 @@ let word=öäpple.bar你 Öäpple word2-öÄpPlE-Pizza-word ÖÄPPLE word
     "#;
 
     let buffer = cx.new(|cx| {
-        let buffer = Buffer::local(contents, cx).with_language(Arc::new(rust_lang()), cx);
+        let buffer = Buffer::local(contents, cx).with_language(rust_lang(), cx);
         assert_eq!(buffer.text(), contents);
         buffer.check_invariants();
         buffer
@@ -3691,7 +3826,7 @@ fn ruby_lang() -> Language {
 fn html_lang() -> Language {
     Language::new(
         LanguageConfig {
-            name: LanguageName::new("HTML"),
+            name: LanguageName::new_static("HTML"),
             block_comment: Some(BlockCommentConfig {
                 start: "<!--".into(),
                 prefix: "".into(),
@@ -3756,78 +3891,6 @@ fn erb_lang() -> Language {
     .unwrap()
 }
 
-fn rust_lang() -> Language {
-    Language::new(
-        LanguageConfig {
-            name: "Rust".into(),
-            matcher: LanguageMatcher {
-                path_suffixes: vec!["rs".to_string()],
-                ..Default::default()
-            },
-            ..Default::default()
-        },
-        Some(tree_sitter_rust::LANGUAGE.into()),
-    )
-    .with_indents_query(
-        r#"
-        (call_expression) @indent
-        (field_expression) @indent
-        (_ "(" ")" @end) @indent
-        (_ "{" "}" @end) @indent
-        "#,
-    )
-    .unwrap()
-    .with_brackets_query(
-        r#"
-        ("{" @open "}" @close)
-        "#,
-    )
-    .unwrap()
-    .with_text_object_query(
-        r#"
-        (function_item
-            body: (_
-                "{"
-                (_)* @function.inside
-                "}" )) @function.around
-
-        (line_comment)+ @comment.around
-
-        (block_comment) @comment.around
-        "#,
-    )
-    .unwrap()
-    .with_outline_query(
-        r#"
-        (line_comment) @annotation
-
-        (struct_item
-            "struct" @context
-            name: (_) @name) @item
-        (enum_item
-            "enum" @context
-            name: (_) @name) @item
-        (enum_variant
-            name: (_) @name) @item
-        (field_declaration
-            name: (_) @name) @item
-        (impl_item
-            "impl" @context
-            trait: (_)? @name
-            "for"? @context
-            type: (_) @name
-            body: (_ "{" (_)* "}")) @item
-        (function_item
-            "fn" @context
-            name: (_) @name) @item
-        (mod_item
-            "mod" @context
-            name: (_) @name) @item
-        "#,
-    )
-    .unwrap()
-}
-
 fn json_lang() -> Language {
     Language::new(
         LanguageConfig {
@@ -3865,32 +3928,6 @@ fn javascript_lang() -> Language {
     .unwrap()
 }
 
-pub fn markdown_lang() -> Language {
-    Language::new(
-        LanguageConfig {
-            name: "Markdown".into(),
-            matcher: LanguageMatcher {
-                path_suffixes: vec!["md".into()],
-                ..Default::default()
-            },
-            ..Default::default()
-        },
-        Some(tree_sitter_md::LANGUAGE.into()),
-    )
-    .with_injection_query(
-        r#"
-            (fenced_code_block
-                (info_string
-                    (language) @injection.language)
-                (code_fence_content) @injection.content)
-
-                ((inline) @injection.content
-                (#set! injection.language "markdown-inline"))
-        "#,
-    )
-    .unwrap()
-}
-
 pub fn markdown_inline_lang() -> Language {
     Language::new(
         LanguageConfig {
@@ -3917,12 +3954,11 @@ fn get_tree_sexp(buffer: &Entity<Buffer>, cx: &mut gpui::TestAppContext) -> Stri
 fn assert_bracket_pairs(
     selection_text: &'static str,
     bracket_pair_texts: Vec<&'static str>,
-    language: Language,
+    language: Arc<Language>,
     cx: &mut App,
 ) {
     let (expected_text, selection_ranges) = marked_text_ranges(selection_text, false);
-    let buffer =
-        cx.new(|cx| Buffer::local(expected_text.clone(), cx).with_language(Arc::new(language), cx));
+    let buffer = cx.new(|cx| Buffer::local(expected_text.clone(), cx).with_language(language, cx));
     let buffer = buffer.update(cx, |buffer, _cx| buffer.snapshot());
 
     let selection_range = selection_ranges[0].clone();

crates/language/src/language.rs 🔗

@@ -43,6 +43,7 @@ pub use manifest::{ManifestDelegate, ManifestName, ManifestProvider, ManifestQue
 use parking_lot::Mutex;
 use regex::Regex;
 use schemars::{JsonSchema, SchemaGenerator, json_schema};
+use semver::Version;
 use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
 use serde_json::Value;
 use settings::WorktreeId;
@@ -66,7 +67,7 @@ use task::RunnableTag;
 pub use task_context::{ContextLocation, ContextProvider, RunnableRange};
 pub use text_diff::{
     DiffOptions, apply_diff_patch, line_diff, text_diff, text_diff_with_options, unified_diff,
-    word_diff_ranges,
+    unified_diff_with_offsets, word_diff_ranges,
 };
 use theme::SyntaxTheme;
 pub use toolchain::{
@@ -136,6 +137,46 @@ pub static PLAIN_TEXT: LazyLock<Arc<Language>> = LazyLock::new(|| {
                 path_suffixes: vec!["txt".to_owned()],
                 first_line_pattern: None,
             },
+            brackets: BracketPairConfig {
+                pairs: vec![
+                    BracketPair {
+                        start: "(".to_string(),
+                        end: ")".to_string(),
+                        close: true,
+                        surround: true,
+                        newline: false,
+                    },
+                    BracketPair {
+                        start: "[".to_string(),
+                        end: "]".to_string(),
+                        close: true,
+                        surround: true,
+                        newline: false,
+                    },
+                    BracketPair {
+                        start: "{".to_string(),
+                        end: "}".to_string(),
+                        close: true,
+                        surround: true,
+                        newline: false,
+                    },
+                    BracketPair {
+                        start: "\"".to_string(),
+                        end: "\"".to_string(),
+                        close: true,
+                        surround: true,
+                        newline: false,
+                    },
+                    BracketPair {
+                        start: "'".to_string(),
+                        end: "'".to_string(),
+                        close: true,
+                        surround: true,
+                        newline: false,
+                    },
+                ],
+                disabled_scopes_by_bracket_ix: Default::default(),
+            },
             ..Default::default()
         },
         None,
@@ -289,6 +330,10 @@ impl CachedLspAdapter {
             .cloned()
             .unwrap_or_else(|| language_name.lsp_id())
     }
+
+    pub fn process_prompt_response(&self, context: &PromptResponseContext, cx: &mut AsyncApp) {
+        self.adapter.process_prompt_response(context, cx)
+    }
 }
 
 /// [`LspAdapterDelegate`] allows [`LspAdapter]` implementations to interface with the application
@@ -307,13 +352,24 @@ pub trait LspAdapterDelegate: Send + Sync {
     async fn npm_package_installed_version(
         &self,
         package_name: &str,
-    ) -> Result<Option<(PathBuf, String)>>;
+    ) -> Result<Option<(PathBuf, Version)>>;
     async fn which(&self, command: &OsStr) -> Option<PathBuf>;
     async fn shell_env(&self) -> HashMap<String, String>;
     async fn read_text_file(&self, path: &RelPath) -> Result<String>;
     async fn try_exec(&self, binary: LanguageServerBinary) -> Result<()>;
 }
 
+/// Context provided to LSP adapters when a user responds to a ShowMessageRequest prompt.
+/// This allows adapters to intercept preference selections (like "Always" or "Never")
+/// and potentially persist them to Zed's settings.
+#[derive(Debug, Clone)]
+pub struct PromptResponseContext {
+    /// The original message shown to the user
+    pub message: String,
+    /// The action (button) the user selected
+    pub selected_action: lsp::MessageActionItem,
+}
+
 #[async_trait(?Send)]
 pub trait LspAdapter: 'static + Send + Sync + DynLspInstaller {
     fn name(&self) -> LanguageServerName;
@@ -405,6 +461,14 @@ pub trait LspAdapter: 'static + Send + Sync + DynLspInstaller {
         Ok(None)
     }
 
+    /// Returns the JSON schema of the initialization_options for the language server.
+    async fn initialization_options_schema(
+        self: Arc<Self>,
+        _language_server_binary: &LanguageServerBinary,
+    ) -> Option<serde_json::Value> {
+        None
+    }
+
     async fn workspace_configuration(
         self: Arc<Self>,
         _: &Arc<dyn LspAdapterDelegate>,
@@ -470,6 +534,11 @@ pub trait LspAdapter: 'static + Send + Sync + DynLspInstaller {
     fn is_extension(&self) -> bool {
         false
     }
+
+    /// Called when a user responds to a ShowMessageRequest from this language server.
+    /// This allows adapters to intercept preference selections (like "Always" or "Never")
+    /// for settings that should be persisted to Zed's settings file.
+    fn process_prompt_response(&self, _context: &PromptResponseContext, _cx: &mut AsyncApp) {}
 }
 
 pub trait LspInstaller {
@@ -495,7 +564,7 @@ pub trait LspInstaller {
         _version: &Self::BinaryVersion,
         _container_dir: &PathBuf,
         _delegate: &dyn LspAdapterDelegate,
-    ) -> impl Future<Output = Option<LanguageServerBinary>> {
+    ) -> impl Send + Future<Output = Option<LanguageServerBinary>> {
         async { None }
     }
 
@@ -504,7 +573,7 @@ pub trait LspInstaller {
         latest_version: Self::BinaryVersion,
         container_dir: PathBuf,
         delegate: &dyn LspAdapterDelegate,
-    ) -> impl Future<Output = Result<LanguageServerBinary>>;
+    ) -> impl Send + Future<Output = Result<LanguageServerBinary>>;
 
     fn cached_server_binary(
         &self,
@@ -535,6 +604,7 @@ pub trait DynLspInstaller {
 #[async_trait(?Send)]
 impl<LI, BinaryVersion> DynLspInstaller for LI
 where
+    BinaryVersion: Send + Sync,
     LI: LspInstaller<BinaryVersion = BinaryVersion> + LspAdapter,
 {
     async fn try_fetch_server_binary(
@@ -553,8 +623,13 @@ where
             .fetch_latest_server_version(delegate.as_ref(), pre_release, cx)
             .await?;
 
-        if let Some(binary) = self
-            .check_if_version_installed(&latest_version, &container_dir, delegate.as_ref())
+        if let Some(binary) = cx
+            .background_executor()
+            .await_on_background(self.check_if_version_installed(
+                &latest_version,
+                &container_dir,
+                delegate.as_ref(),
+            ))
             .await
         {
             log::debug!("language server {:?} is already installed", name.0);
@@ -563,8 +638,13 @@ where
         } else {
             log::debug!("downloading language server {:?}", name.0);
             delegate.update_status(name.clone(), BinaryStatus::Downloading);
-            let binary = self
-                .fetch_server_binary(latest_version, container_dir, delegate.as_ref())
+            let binary = cx
+                .background_executor()
+                .await_on_background(self.fetch_server_binary(
+                    latest_version,
+                    container_dir,
+                    delegate.as_ref(),
+                ))
                 .await;
 
             delegate.update_status(name.clone(), BinaryStatus::None);
@@ -755,6 +835,15 @@ pub struct LanguageConfig {
     /// Delimiters and configuration for recognizing and formatting documentation comments.
     #[serde(default, alias = "documentation")]
     pub documentation_comment: Option<BlockCommentConfig>,
+    /// List markers that are inserted unchanged on newline (e.g., `- `, `* `, `+ `).
+    #[serde(default)]
+    pub unordered_list: Vec<Arc<str>>,
+    /// Configuration for ordered lists with auto-incrementing numbers on newline (e.g., `1. ` becomes `2. `).
+    #[serde(default)]
+    pub ordered_list: Vec<OrderedListConfig>,
+    /// Configuration for task lists where multiple markers map to a single continuation prefix (e.g., `- [x] ` continues as `- [ ] `).
+    #[serde(default)]
+    pub task_list: Option<TaskListConfig>,
     /// A list of additional regex patterns that should be treated as prefixes
     /// for creating boundaries during rewrapping, ensuring content from one
     /// prefixed section doesn't merge with another (e.g., markdown list items).
@@ -826,6 +915,24 @@ pub struct DecreaseIndentConfig {
     pub valid_after: Vec<String>,
 }
 
+/// Configuration for continuing ordered lists with auto-incrementing numbers.
+#[derive(Clone, Debug, Deserialize, JsonSchema)]
+pub struct OrderedListConfig {
+    /// A regex pattern with a capture group for the number portion (e.g., `(\\d+)\\. `).
+    pub pattern: String,
+    /// A format string where `{1}` is replaced with the incremented number (e.g., `{1}. `).
+    pub format: String,
+}
+
+/// Configuration for continuing task lists on newline.
+#[derive(Clone, Debug, Deserialize, JsonSchema)]
+pub struct TaskListConfig {
+    /// The list markers to match (e.g., `- [ ] `, `- [x] `).
+    pub prefixes: Vec<Arc<str>>,
+    /// The marker to insert when continuing the list on a new line (e.g., `- [ ] `).
+    pub continuation: Arc<str>,
+}
+
 #[derive(Clone, Debug, Serialize, Deserialize, Default, JsonSchema)]
 pub struct LanguageMatcher {
     /// Given a list of `LanguageConfig`'s, the language of a file can be determined based on the path extension matching any of the `path_suffixes`.
@@ -982,7 +1089,7 @@ impl<T> Override<T> {
 impl Default for LanguageConfig {
     fn default() -> Self {
         Self {
-            name: LanguageName::new(""),
+            name: LanguageName::new_static(""),
             code_fence_block_name: None,
             grammar: None,
             matcher: LanguageMatcher::default(),
@@ -996,6 +1103,9 @@ impl Default for LanguageConfig {
             line_comments: Default::default(),
             block_comment: Default::default(),
             documentation_comment: Default::default(),
+            unordered_list: Default::default(),
+            ordered_list: Default::default(),
+            task_list: Default::default(),
             rewrap_prefixes: Default::default(),
             scope_opt_in_language_servers: Default::default(),
             overrides: Default::default(),
@@ -2081,6 +2191,21 @@ impl LanguageScope {
         self.language.config.documentation_comment.as_ref()
     }
 
+    /// Returns list markers that are inserted unchanged on newline (e.g., `- `, `* `, `+ `).
+    pub fn unordered_list(&self) -> &[Arc<str>] {
+        &self.language.config.unordered_list
+    }
+
+    /// Returns configuration for ordered lists with auto-incrementing numbers (e.g., `1. ` becomes `2. `).
+    pub fn ordered_list(&self) -> &[OrderedListConfig] {
+        &self.language.config.ordered_list
+    }
+
+    /// Returns configuration for task list continuation, if any (e.g., `- [x] ` continues as `- [ ] `).
+    pub fn task_list(&self) -> Option<&TaskListConfig> {
+        self.language.config.task_list.as_ref()
+    }
+
     /// Returns additional regex patterns that act as prefix markers for creating
     /// boundaries during rewrapping.
     ///
@@ -2374,7 +2499,10 @@ impl CodeLabel {
             "invalid filter range"
         );
         runs.iter().for_each(|(range, _)| {
-            assert!(text.get(range.clone()).is_some(), "invalid run range");
+            assert!(
+                text.get(range.clone()).is_some(),
+                "invalid run range with inputs. Requested range {range:?} in text '{text}'",
+            );
         });
         Self {
             runs,
@@ -2656,7 +2784,28 @@ pub fn rust_lang() -> Arc<Language> {
         text_objects: Some(Cow::from(include_str!(
             "../../languages/src/rust/textobjects.scm"
         ))),
-        ..LanguageQueries::default()
+        highlights: Some(Cow::from(include_str!(
+            "../../languages/src/rust/highlights.scm"
+        ))),
+        embedding: Some(Cow::from(include_str!(
+            "../../languages/src/rust/embedding.scm"
+        ))),
+        injections: Some(Cow::from(include_str!(
+            "../../languages/src/rust/injections.scm"
+        ))),
+        overrides: Some(Cow::from(include_str!(
+            "../../languages/src/rust/overrides.scm"
+        ))),
+        redactions: None,
+        runnables: Some(Cow::from(include_str!(
+            "../../languages/src/rust/runnables.scm"
+        ))),
+        debugger: Some(Cow::from(include_str!(
+            "../../languages/src/rust/debugger.scm"
+        ))),
+        imports: Some(Cow::from(include_str!(
+            "../../languages/src/rust/imports.scm"
+        ))),
     })
     .expect("Could not parse queries");
     Arc::new(language)
@@ -2685,6 +2834,15 @@ pub fn markdown_lang() -> Arc<Language> {
         injections: Some(Cow::from(include_str!(
             "../../languages/src/markdown/injections.scm"
         ))),
+        highlights: Some(Cow::from(include_str!(
+            "../../languages/src/markdown/highlights.scm"
+        ))),
+        indents: Some(Cow::from(include_str!(
+            "../../languages/src/markdown/indents.scm"
+        ))),
+        outline: Some(Cow::from(include_str!(
+            "../../languages/src/markdown/outline.scm"
+        ))),
         ..LanguageQueries::default()
     })
     .expect("Could not parse markdown queries");
@@ -2726,9 +2884,9 @@ mod tests {
         assert_eq!(
             languages.language_names(),
             &[
-                LanguageName::new("JSON"),
-                LanguageName::new("Plain Text"),
-                LanguageName::new("Rust"),
+                LanguageName::new_static("JSON"),
+                LanguageName::new_static("Plain Text"),
+                LanguageName::new_static("Rust"),
             ]
         );
 
@@ -2739,9 +2897,9 @@ mod tests {
         assert_eq!(
             languages.language_names(),
             &[
-                LanguageName::new("JSON"),
-                LanguageName::new("Plain Text"),
-                LanguageName::new("Rust"),
+                LanguageName::new_static("JSON"),
+                LanguageName::new_static("Plain Text"),
+                LanguageName::new_static("Rust"),
             ]
         );
 
@@ -2752,9 +2910,9 @@ mod tests {
         assert_eq!(
             languages.language_names(),
             &[
-                LanguageName::new("JSON"),
-                LanguageName::new("Plain Text"),
-                LanguageName::new("Rust"),
+                LanguageName::new_static("JSON"),
+                LanguageName::new_static("Plain Text"),
+                LanguageName::new_static("Rust"),
             ]
         );
 

crates/language/src/language_registry.rs 🔗

@@ -43,12 +43,18 @@ impl LanguageName {
         Self(SharedString::new(s))
     }
 
+    pub fn new_static(s: &'static str) -> Self {
+        Self(SharedString::new_static(s))
+    }
+
     pub fn from_proto(s: String) -> Self {
         Self(SharedString::from(s))
     }
+
     pub fn to_proto(&self) -> String {
         self.0.to_string()
     }
+
     pub fn lsp_id(&self) -> String {
         match self.0.as_ref() {
             "Plain Text" => "plaintext".to_string(),
@@ -87,9 +93,9 @@ impl std::fmt::Display for LanguageName {
     }
 }
 
-impl<'a> From<&'a str> for LanguageName {
-    fn from(str: &'a str) -> LanguageName {
-        LanguageName(SharedString::new(str))
+impl From<&'static str> for LanguageName {
+    fn from(str: &'static str) -> Self {
+        Self(SharedString::new_static(str))
     }
 }
 
@@ -437,26 +443,14 @@ impl LanguageRegistry {
         language_name: impl Into<LanguageName>,
         mut adapter: crate::FakeLspAdapter,
     ) -> futures::channel::mpsc::UnboundedReceiver<lsp::FakeLanguageServer> {
-        let language_name = language_name.into();
         let adapter_name = LanguageServerName(adapter.name.into());
         let capabilities = adapter.capabilities.clone();
         let initializer = adapter.initializer.take();
-        let adapter = CachedLspAdapter::new(Arc::new(adapter));
-        {
-            let mut state = self.state.write();
-            state
-                .lsp_adapters
-                .entry(language_name)
-                .or_default()
-                .push(adapter.clone());
-            state.all_lsp_adapters.insert(adapter.name(), adapter);
-        }
-
-        self.register_fake_language_server(adapter_name, capabilities, initializer)
+        self.register_fake_lsp_adapter(language_name, adapter);
+        self.register_fake_lsp_server(adapter_name, capabilities, initializer)
     }
 
     /// Register a fake lsp adapter (without the language server)
-    /// The returned channel receives a new instance of the language server every time it is started
     #[cfg(any(feature = "test-support", test))]
     pub fn register_fake_lsp_adapter(
         &self,
@@ -479,7 +473,7 @@ impl LanguageRegistry {
     /// Register a fake language server (without the adapter)
     /// The returned channel receives a new instance of the language server every time it is started
     #[cfg(any(feature = "test-support", test))]
-    pub fn register_fake_language_server(
+    pub fn register_fake_lsp_server(
         &self,
         lsp_name: LanguageServerName,
         capabilities: lsp::ServerCapabilities,
@@ -757,7 +751,7 @@ impl LanguageRegistry {
         self: &Arc<Self>,
         path: &Path,
         content: Option<&Rope>,
-        user_file_types: Option<&FxHashMap<Arc<str>, GlobSet>>,
+        user_file_types: Option<&FxHashMap<Arc<str>, (GlobSet, Vec<String>)>>,
     ) -> Option<AvailableLanguage> {
         let filename = path.file_name().and_then(|filename| filename.to_str());
         // `Path.extension()` returns None for files with a leading '.'
@@ -800,7 +794,7 @@ impl LanguageRegistry {
             let path_matches_custom_suffix = || {
                 user_file_types
                     .and_then(|types| types.get(language_name.as_ref()))
-                    .map_or(None, |custom_suffixes| {
+                    .map_or(None, |(custom_suffixes, _)| {
                         path_suffixes
                             .iter()
                             .find(|(_, candidate)| custom_suffixes.is_match_candidate(candidate))

crates/language/src/language_settings.rs 🔗

@@ -51,7 +51,7 @@ pub struct AllLanguageSettings {
     pub edit_predictions: EditPredictionSettings,
     pub defaults: LanguageSettings,
     languages: HashMap<LanguageName, LanguageSettings>,
-    pub(crate) file_types: FxHashMap<Arc<str>, GlobSet>,
+    pub file_types: FxHashMap<Arc<str>, (GlobSet, Vec<String>)>,
 }
 
 #[derive(Debug, Clone, PartialEq)]
@@ -122,6 +122,10 @@ pub struct LanguageSettings {
     pub whitespace_map: WhitespaceMap,
     /// Whether to start a new line with a comment when a previous line is a comment as well.
     pub extend_comment_on_newline: bool,
+    /// Whether to continue markdown lists when pressing enter.
+    pub extend_list_on_newline: bool,
+    /// Whether to indent list items when pressing tab after a list marker.
+    pub indent_list_on_tab: bool,
     /// Inlay hint related settings.
     pub inlay_hints: InlayHintSettings,
     /// Whether to automatically close brackets.
@@ -373,6 +377,8 @@ impl InlayHintSettings {
 pub struct EditPredictionSettings {
     /// The provider that supplies edit predictions.
     pub provider: settings::EditPredictionProvider,
+    /// Whether to use the experimental edit prediction context retrieval system.
+    pub use_context: bool,
     /// A list of globs representing files that edit predictions should be disabled for.
     /// This list adds to a pre-existing, sensible default set of globs.
     /// Any additional ones you add are combined with them.
@@ -386,6 +392,7 @@ pub struct EditPredictionSettings {
     /// Whether edit predictions are enabled in the assistant panel.
     /// This setting has no effect if globally disabled.
     pub enabled_in_text_threads: bool,
+    pub examples_dir: Option<Arc<Path>>,
 }
 
 impl EditPredictionSettings {
@@ -565,6 +572,8 @@ impl settings::Settings for AllLanguageSettings {
                     tab: SharedString::new(whitespace_map.tab.unwrap().to_string()),
                 },
                 extend_comment_on_newline: settings.extend_comment_on_newline.unwrap(),
+                extend_list_on_newline: settings.extend_list_on_newline.unwrap(),
+                indent_list_on_tab: settings.indent_list_on_tab.unwrap(),
                 inlay_hints: InlayHintSettings {
                     enabled: inlay_hints.enabled.unwrap(),
                     show_value_hints: inlay_hints.show_value_hints.unwrap(),
@@ -622,6 +631,11 @@ impl settings::Settings for AllLanguageSettings {
             .features
             .as_ref()
             .and_then(|f| f.edit_prediction_provider);
+        let use_edit_prediction_context = all_languages
+            .features
+            .as_ref()
+            .and_then(|f| f.experimental_edit_prediction_context_retrieval)
+            .unwrap_or_default();
 
         let edit_predictions = all_languages.edit_predictions.clone().unwrap();
         let edit_predictions_mode = edit_predictions.mode.unwrap();
@@ -649,7 +663,7 @@ impl settings::Settings for AllLanguageSettings {
 
         let enabled_in_text_threads = edit_predictions.enabled_in_text_threads.unwrap();
 
-        let mut file_types: FxHashMap<Arc<str>, GlobSet> = FxHashMap::default();
+        let mut file_types: FxHashMap<Arc<str>, (GlobSet, Vec<String>)> = FxHashMap::default();
 
         for (language, patterns) in all_languages.file_types.iter().flatten() {
             let mut builder = GlobSetBuilder::new();
@@ -658,7 +672,10 @@ impl settings::Settings for AllLanguageSettings {
                 builder.add(Glob::new(pattern).unwrap());
             }
 
-            file_types.insert(language.clone(), builder.build().unwrap());
+            file_types.insert(
+                language.clone(),
+                (builder.build().unwrap(), patterns.0.clone()),
+            );
         }
 
         Self {
@@ -668,6 +685,7 @@ impl settings::Settings for AllLanguageSettings {
                 } else {
                     EditPredictionProvider::None
                 },
+                use_context: use_edit_prediction_context,
                 disabled_globs: disabled_globs
                     .iter()
                     .filter_map(|g| {
@@ -682,6 +700,7 @@ impl settings::Settings for AllLanguageSettings {
                 copilot: copilot_settings,
                 codestral: codestral_settings,
                 enabled_in_text_threads,
+                examples_dir: edit_predictions.examples_dir,
             },
             defaults: default_language_settings,
             languages,

crates/language/src/outline.rs 🔗

@@ -1,4 +1,4 @@
-use crate::{BufferSnapshot, Point, ToPoint};
+use crate::{BufferSnapshot, Point, ToPoint, ToTreeSitterPoint};
 use fuzzy::{StringMatch, StringMatchCandidate};
 use gpui::{BackgroundExecutor, HighlightStyle};
 use std::ops::Range;
@@ -48,6 +48,54 @@ impl<T: ToPoint> OutlineItem<T> {
                 .map(|r| r.start.to_point(buffer)..r.end.to_point(buffer)),
         }
     }
+
+    pub fn body_range(&self, buffer: &BufferSnapshot) -> Option<Range<Point>> {
+        if let Some(range) = self.body_range.as_ref() {
+            return Some(range.start.to_point(buffer)..range.end.to_point(buffer));
+        }
+
+        let range = self.range.start.to_point(buffer)..self.range.end.to_point(buffer);
+        let start_indent = buffer.indent_size_for_line(range.start.row);
+        let node = buffer.syntax_ancestor(range.clone())?;
+
+        let mut cursor = node.walk();
+        loop {
+            let node = cursor.node();
+            if node.start_position() >= range.start.to_ts_point()
+                && node.end_position() <= range.end.to_ts_point()
+            {
+                break;
+            }
+            cursor.goto_first_child_for_point(range.start.to_ts_point());
+        }
+
+        if !cursor.goto_last_child() {
+            return None;
+        }
+        let body_node = loop {
+            let node = cursor.node();
+            if node.child_count() > 0 {
+                break node;
+            }
+            if !cursor.goto_previous_sibling() {
+                return None;
+            }
+        };
+
+        let mut start_row = body_node.start_position().row as u32;
+        let mut end_row = body_node.end_position().row as u32;
+
+        while start_row < end_row && buffer.indent_size_for_line(start_row) == start_indent {
+            start_row += 1;
+        }
+        while start_row < end_row && buffer.indent_size_for_line(end_row - 1) == start_indent {
+            end_row -= 1;
+        }
+        if start_row < end_row {
+            return Some(Point::new(start_row, 0)..Point::new(end_row, 0));
+        }
+        None
+    }
 }
 
 impl<T> Outline<T> {

crates/language/src/proto.rs 🔗

@@ -3,6 +3,7 @@
 use crate::{CursorShape, Diagnostic, DiagnosticSourceKind, diagnostic_set::DiagnosticEntry};
 use anyhow::{Context as _, Result};
 use clock::ReplicaId;
+use gpui::SharedString;
 use lsp::{DiagnosticSeverity, LanguageServerId};
 use rpc::proto;
 use serde_json::Value;
@@ -239,6 +240,11 @@ pub fn serialize_diagnostics<'a>(
             is_disk_based: entry.diagnostic.is_disk_based,
             is_unnecessary: entry.diagnostic.is_unnecessary,
             data: entry.diagnostic.data.as_ref().map(|data| data.to_string()),
+            registration_id: entry
+                .diagnostic
+                .registration_id
+                .as_ref()
+                .map(ToString::to_string),
         })
         .collect()
 }
@@ -457,6 +463,7 @@ pub fn deserialize_diagnostics(
                     is_disk_based: diagnostic.is_disk_based,
                     is_unnecessary: diagnostic.is_unnecessary,
                     underline: diagnostic.underline,
+                    registration_id: diagnostic.registration_id.map(SharedString::from),
                     source_kind: match proto::diagnostic::SourceKind::from_i32(
                         diagnostic.source_kind,
                     )? {

crates/language/src/syntax_map.rs 🔗

@@ -19,7 +19,12 @@ use std::{
 use streaming_iterator::StreamingIterator;
 use sum_tree::{Bias, Dimensions, SeekTarget, SumTree};
 use text::{Anchor, BufferSnapshot, OffsetRangeExt, Point, Rope, ToOffset, ToPoint};
-use tree_sitter::{Node, Query, QueryCapture, QueryCaptures, QueryCursor, QueryMatches, Tree};
+use tree_sitter::{
+    Node, Query, QueryCapture, QueryCaptures, QueryCursor, QueryMatch, QueryMatches,
+    QueryPredicateArg, Tree,
+};
+
+pub const MAX_BYTES_TO_QUERY: usize = 16 * 1024;
 
 pub struct SyntaxMap {
     snapshot: SyntaxSnapshot,
@@ -80,6 +85,7 @@ struct SyntaxMapMatchesLayer<'a> {
     next_captures: Vec<QueryCapture<'a>>,
     has_next: bool,
     matches: QueryMatches<'a, 'a, TextProvider<'a>, &'a [u8]>,
+    query: &'a Query,
     grammar_index: usize,
     _query_cursor: QueryCursorHandle,
 }
@@ -1096,12 +1102,15 @@ impl<'a> SyntaxMapCaptures<'a> {
 
 #[derive(Default)]
 pub struct TreeSitterOptions {
-    max_start_depth: Option<u32>,
+    pub max_start_depth: Option<u32>,
+    pub max_bytes_to_query: Option<usize>,
 }
+
 impl TreeSitterOptions {
     pub fn max_start_depth(max_start_depth: u32) -> Self {
         Self {
             max_start_depth: Some(max_start_depth),
+            max_bytes_to_query: None,
         }
     }
 }
@@ -1135,6 +1144,14 @@ impl<'a> SyntaxMapMatches<'a> {
             };
             cursor.set_max_start_depth(options.max_start_depth);
 
+            if let Some(max_bytes_to_query) = options.max_bytes_to_query {
+                let midpoint = (range.start + range.end) / 2;
+                let containing_range_start = midpoint.saturating_sub(max_bytes_to_query / 2);
+                let containing_range_end =
+                    containing_range_start.saturating_add(max_bytes_to_query);
+                cursor.set_containing_byte_range(containing_range_start..containing_range_end);
+            }
+
             cursor.set_byte_range(range.clone());
             let matches = cursor.matches(query, layer.node(), TextProvider(text));
             let grammar_index = result
@@ -1150,6 +1167,7 @@ impl<'a> SyntaxMapMatches<'a> {
                 depth: layer.depth,
                 grammar_index,
                 matches,
+                query,
                 next_pattern_index: 0,
                 next_captures: Vec::new(),
                 has_next: false,
@@ -1215,6 +1233,19 @@ impl<'a> SyntaxMapMatches<'a> {
 
         true
     }
+
+    // pub fn set_byte_range(&mut self, range: Range<usize>) {
+    //     for layer in &mut self.layers {
+    //         layer.matches.set_byte_range(range.clone());
+    //         layer.advance();
+    //     }
+    //     self.layers.sort_unstable_by_key(|layer| layer.sort_key());
+    //     self.active_layer_count = self
+    //         .layers
+    //         .iter()
+    //         .position(|layer| !layer.has_next)
+    //         .unwrap_or(self.layers.len());
+    // }
 }
 
 impl SyntaxMapCapturesLayer<'_> {
@@ -1234,13 +1265,20 @@ impl SyntaxMapCapturesLayer<'_> {
 
 impl SyntaxMapMatchesLayer<'_> {
     fn advance(&mut self) {
-        if let Some(mat) = self.matches.next() {
-            self.next_captures.clear();
-            self.next_captures.extend_from_slice(mat.captures);
-            self.next_pattern_index = mat.pattern_index;
-            self.has_next = true;
-        } else {
-            self.has_next = false;
+        loop {
+            if let Some(mat) = self.matches.next() {
+                if !satisfies_custom_predicates(self.query, mat) {
+                    continue;
+                }
+                self.next_captures.clear();
+                self.next_captures.extend_from_slice(mat.captures);
+                self.next_pattern_index = mat.pattern_index;
+                self.has_next = true;
+                return;
+            } else {
+                self.has_next = false;
+                return;
+            }
         }
     }
 
@@ -1269,6 +1307,39 @@ impl<'a> Iterator for SyntaxMapCaptures<'a> {
     }
 }
 
+fn satisfies_custom_predicates(query: &Query, mat: &QueryMatch) -> bool {
+    for predicate in query.general_predicates(mat.pattern_index) {
+        let satisfied = match predicate.operator.as_ref() {
+            "has-parent?" => has_parent(&predicate.args, mat),
+            "not-has-parent?" => !has_parent(&predicate.args, mat),
+            _ => true,
+        };
+        if !satisfied {
+            return false;
+        }
+    }
+    true
+}
+
+fn has_parent(args: &[QueryPredicateArg], mat: &QueryMatch) -> bool {
+    let (
+        Some(QueryPredicateArg::Capture(capture_ix)),
+        Some(QueryPredicateArg::String(parent_kind)),
+    ) = (args.first(), args.get(1))
+    else {
+        return false;
+    };
+
+    let Some(capture) = mat.captures.iter().find(|c| c.index == *capture_ix) else {
+        return false;
+    };
+
+    capture
+        .node
+        .parent()
+        .is_some_and(|p| p.kind() == parent_kind.as_ref())
+}
+
 fn join_ranges(
     a: impl Iterator<Item = Range<usize>>,
     b: impl Iterator<Item = Range<usize>>,
@@ -1629,6 +1700,10 @@ impl<'a> SyntaxLayer<'a> {
 
         let mut query_cursor = QueryCursorHandle::new();
         query_cursor.set_byte_range(offset.saturating_sub(1)..offset.saturating_add(1));
+        query_cursor.set_containing_byte_range(
+            offset.saturating_sub(MAX_BYTES_TO_QUERY / 2)
+                ..offset.saturating_add(MAX_BYTES_TO_QUERY / 2),
+        );
 
         let mut smallest_match: Option<(u32, Range<usize>)> = None;
         let mut matches = query_cursor.matches(&config.query, self.node(), text);
@@ -1915,6 +1990,8 @@ impl Drop for QueryCursorHandle {
         let mut cursor = self.0.take().unwrap();
         cursor.set_byte_range(0..usize::MAX);
         cursor.set_point_range(Point::zero().to_ts_point()..Point::MAX.to_ts_point());
+        cursor.set_containing_byte_range(0..usize::MAX);
+        cursor.set_containing_point_range(Point::zero().to_ts_point()..Point::MAX.to_ts_point());
         QUERY_CURSORS.lock().push(cursor)
     }
 }

crates/language/src/syntax_map/syntax_map_tests.rs 🔗

@@ -1,9 +1,9 @@
 use super::*;
 use crate::{
-    LanguageConfig, LanguageMatcher,
-    buffer_tests::{markdown_inline_lang, markdown_lang},
+    LanguageConfig, LanguageMatcher, buffer_tests::markdown_inline_lang, markdown_lang, rust_lang,
 };
 use gpui::App;
+use pretty_assertions::assert_eq;
 use rand::rngs::StdRng;
 use std::{env, ops::Range, sync::Arc};
 use text::{Buffer, BufferId, ReplicaId};
@@ -84,7 +84,7 @@ fn test_splice_included_ranges() {
 #[gpui::test]
 fn test_syntax_map_layers_for_range(cx: &mut App) {
     let registry = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
-    let language = Arc::new(rust_lang());
+    let language = rust_lang();
     registry.add(language.clone());
 
     let mut buffer = Buffer::new(
@@ -181,11 +181,11 @@ fn test_syntax_map_layers_for_range(cx: &mut App) {
 #[gpui::test]
 fn test_dynamic_language_injection(cx: &mut App) {
     let registry = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
-    let markdown = Arc::new(markdown_lang());
+    let markdown = markdown_lang();
     let markdown_inline = Arc::new(markdown_inline_lang());
     registry.add(markdown.clone());
     registry.add(markdown_inline.clone());
-    registry.add(Arc::new(rust_lang()));
+    registry.add(rust_lang());
     registry.add(Arc::new(ruby_lang()));
 
     let mut buffer = Buffer::new(
@@ -291,7 +291,7 @@ fn test_typing_multiple_new_injections(cx: &mut App) {
     assert_capture_ranges(
         &syntax_map,
         &buffer,
-        &["field"],
+        &["property"],
         "fn a() { test_macro!(b.«c»(vec![d.«e»])) }",
     );
 }
@@ -329,16 +329,16 @@ fn test_pasting_new_injection_line_between_others(cx: &mut App) {
     assert_capture_ranges(
         &syntax_map,
         &buffer,
-        &["struct"],
+        &["type"],
         "
         fn a() {
-            b!(«B {}»);
-            c!(«C {}»);
-            d!(«D {}»);
-            h!(«H {}»);
-            e!(«E {}»);
-            f!(«F {}»);
-            g!(«G {}»);
+            b!(«B» {});
+            c!(«C» {});
+            d!(«D» {});
+            h!(«H» {});
+            e!(«E» {});
+            f!(«F» {});
+            g!(«G» {});
         }
         ",
     );
@@ -376,7 +376,7 @@ fn test_joining_injections_with_child_injections(cx: &mut App) {
     assert_capture_ranges(
         &syntax_map,
         &buffer,
-        &["field"],
+        &["property"],
         "
         fn a() {
             b!(
@@ -900,7 +900,7 @@ fn test_random_syntax_map_edits_rust_macros(rng: StdRng, cx: &mut App) {
     .repeat(2);
 
     let registry = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
-    let language = Arc::new(rust_lang());
+    let language = rust_lang();
     registry.add(language.clone());
 
     test_random_edits(text, registry, language, rng);
@@ -1133,8 +1133,8 @@ fn check_interpolation(
             check_node_edits(
                 depth,
                 range,
-                old_node.child(i).unwrap(),
-                new_node.child(i).unwrap(),
+                old_node.child(i as u32).unwrap(),
+                new_node.child(i as u32).unwrap(),
                 old_buffer,
                 new_buffer,
                 edits,
@@ -1147,11 +1147,11 @@ fn test_edit_sequence(language_name: &str, steps: &[&str], cx: &mut App) -> (Buf
     let registry = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
     registry.add(Arc::new(elixir_lang()));
     registry.add(Arc::new(heex_lang()));
-    registry.add(Arc::new(rust_lang()));
+    registry.add(rust_lang());
     registry.add(Arc::new(ruby_lang()));
     registry.add(Arc::new(html_lang()));
     registry.add(Arc::new(erb_lang()));
-    registry.add(Arc::new(markdown_lang()));
+    registry.add(markdown_lang());
     registry.add(Arc::new(markdown_inline_lang()));
 
     let language = registry
@@ -1287,35 +1287,6 @@ fn erb_lang() -> Language {
     .unwrap()
 }
 
-fn rust_lang() -> Language {
-    Language::new(
-        LanguageConfig {
-            name: "Rust".into(),
-            matcher: LanguageMatcher {
-                path_suffixes: vec!["rs".to_string()],
-                ..Default::default()
-            },
-            ..Default::default()
-        },
-        Some(tree_sitter_rust::LANGUAGE.into()),
-    )
-    .with_highlights_query(
-        r#"
-            (field_identifier) @field
-            (struct_expression) @struct
-        "#,
-    )
-    .unwrap()
-    .with_injection_query(
-        r#"
-            (macro_invocation
-                (token_tree) @injection.content
-                (#set! injection.language "rust"))
-        "#,
-    )
-    .unwrap()
-}
-
 fn elixir_lang() -> Language {
     Language::new(
         LanguageConfig {
@@ -1425,6 +1396,7 @@ fn assert_capture_ranges(
             actual_ranges.push(capture.node.byte_range());
         }
     }
+    actual_ranges.dedup();
 
     let (text, expected_ranges) = marked_text_ranges(&marked_string.unindent(), false);
     assert_eq!(text, buffer.text());

crates/language/src/text_diff.rs 🔗

@@ -1,25 +1,139 @@
 use crate::{CharClassifier, CharKind, CharScopeContext, LanguageScope};
 use anyhow::{Context, anyhow};
 use imara_diff::{
-    Algorithm, UnifiedDiffBuilder, diff,
-    intern::{InternedInput, Token},
+    Algorithm, Sink, diff,
+    intern::{InternedInput, Interner, Token},
     sources::lines_with_terminator,
 };
-use std::{iter, ops::Range, sync::Arc};
+use std::{fmt::Write, iter, ops::Range, sync::Arc};
 
 const MAX_WORD_DIFF_LEN: usize = 512;
 const MAX_WORD_DIFF_LINE_COUNT: usize = 8;
 
 /// Computes a diff between two strings, returning a unified diff string.
 pub fn unified_diff(old_text: &str, new_text: &str) -> String {
+    unified_diff_with_offsets(old_text, new_text, 0, 0)
+}
+
+/// Computes a diff between two strings, returning a unified diff string with
+/// hunk headers adjusted to reflect the given starting line numbers (1-indexed).
+pub fn unified_diff_with_offsets(
+    old_text: &str,
+    new_text: &str,
+    old_start_line: u32,
+    new_start_line: u32,
+) -> String {
     let input = InternedInput::new(old_text, new_text);
     diff(
         Algorithm::Histogram,
         &input,
-        UnifiedDiffBuilder::new(&input),
+        OffsetUnifiedDiffBuilder::new(&input, old_start_line, new_start_line),
     )
 }
 
+/// A unified diff builder that applies line number offsets to hunk headers.
+struct OffsetUnifiedDiffBuilder<'a> {
+    before: &'a [Token],
+    after: &'a [Token],
+    interner: &'a Interner<&'a str>,
+
+    pos: u32,
+    before_hunk_start: u32,
+    after_hunk_start: u32,
+    before_hunk_len: u32,
+    after_hunk_len: u32,
+
+    old_line_offset: u32,
+    new_line_offset: u32,
+
+    buffer: String,
+    dst: String,
+}
+
+impl<'a> OffsetUnifiedDiffBuilder<'a> {
+    fn new(input: &'a InternedInput<&'a str>, old_line_offset: u32, new_line_offset: u32) -> Self {
+        Self {
+            before_hunk_start: 0,
+            after_hunk_start: 0,
+            before_hunk_len: 0,
+            after_hunk_len: 0,
+            old_line_offset,
+            new_line_offset,
+            buffer: String::with_capacity(8),
+            dst: String::new(),
+            interner: &input.interner,
+            before: &input.before,
+            after: &input.after,
+            pos: 0,
+        }
+    }
+
+    fn print_tokens(&mut self, tokens: &[Token], prefix: char) {
+        for &token in tokens {
+            writeln!(&mut self.buffer, "{prefix}{}", self.interner[token]).unwrap();
+        }
+    }
+
+    fn flush(&mut self) {
+        if self.before_hunk_len == 0 && self.after_hunk_len == 0 {
+            return;
+        }
+
+        let end = (self.pos + 3).min(self.before.len() as u32);
+        self.update_pos(end, end);
+
+        writeln!(
+            &mut self.dst,
+            "@@ -{},{} +{},{} @@",
+            self.before_hunk_start + 1 + self.old_line_offset,
+            self.before_hunk_len,
+            self.after_hunk_start + 1 + self.new_line_offset,
+            self.after_hunk_len,
+        )
+        .unwrap();
+        write!(&mut self.dst, "{}", &self.buffer).unwrap();
+        self.buffer.clear();
+        self.before_hunk_len = 0;
+        self.after_hunk_len = 0;
+    }
+
+    fn update_pos(&mut self, print_to: u32, move_to: u32) {
+        self.print_tokens(&self.before[self.pos as usize..print_to as usize], ' ');
+        let len = print_to - self.pos;
+        self.pos = move_to;
+        self.before_hunk_len += len;
+        self.after_hunk_len += len;
+    }
+}
+
+impl Sink for OffsetUnifiedDiffBuilder<'_> {
+    type Out = String;
+
+    fn process_change(&mut self, before: Range<u32>, after: Range<u32>) {
+        if before.start - self.pos > 6 {
+            self.flush();
+        }
+        if self.before_hunk_len == 0 && self.after_hunk_len == 0 {
+            self.pos = before.start.saturating_sub(3);
+            self.before_hunk_start = self.pos;
+            self.after_hunk_start = after.start.saturating_sub(3);
+        }
+        self.update_pos(before.start, before.end);
+        self.before_hunk_len += before.end - before.start;
+        self.after_hunk_len += after.end - after.start;
+        self.print_tokens(
+            &self.before[before.start as usize..before.end as usize],
+            '-',
+        );
+        self.print_tokens(&self.after[after.start as usize..after.end as usize], '+');
+    }
+
+    fn finish(mut self) -> Self::Out {
+        self.flush();
+        self.dst
+    }
+}
+
 /// Computes a diff between two strings, returning a vector of old and new row
 /// ranges.
 pub fn line_diff(old_text: &str, new_text: &str) -> Vec<(Range<u32>, Range<u32>)> {
@@ -48,7 +162,6 @@ pub fn text_diff(old_text: &str, new_text: &str) -> Vec<(Range<usize>, Arc<str>)
 ///
 /// Returns a tuple of (old_ranges, new_ranges) where each vector contains
 /// the byte ranges of changed words in the respective text.
-/// Whitespace-only changes are excluded from the results.
 pub fn word_diff_ranges(
     old_text: &str,
     new_text: &str,
@@ -62,23 +175,23 @@ pub fn word_diff_ranges(
     let mut new_ranges: Vec<Range<usize>> = Vec::new();
 
     diff_internal(&input, |old_byte_range, new_byte_range, _, _| {
-        for range in split_on_whitespace(old_text, &old_byte_range) {
+        if !old_byte_range.is_empty() {
             if let Some(last) = old_ranges.last_mut()
-                && last.end >= range.start
+                && last.end >= old_byte_range.start
             {
-                last.end = range.end;
+                last.end = old_byte_range.end;
             } else {
-                old_ranges.push(range);
+                old_ranges.push(old_byte_range);
             }
         }
 
-        for range in split_on_whitespace(new_text, &new_byte_range) {
+        if !new_byte_range.is_empty() {
             if let Some(last) = new_ranges.last_mut()
-                && last.end >= range.start
+                && last.end >= new_byte_range.start
             {
-                last.end = range.end;
+                last.end = new_byte_range.end;
             } else {
-                new_ranges.push(range);
+                new_ranges.push(new_byte_range);
             }
         }
     });
@@ -86,50 +199,6 @@ pub fn word_diff_ranges(
     (old_ranges, new_ranges)
 }
 
-fn split_on_whitespace(text: &str, range: &Range<usize>) -> Vec<Range<usize>> {
-    if range.is_empty() {
-        return Vec::new();
-    }
-
-    let slice = &text[range.clone()];
-    let mut ranges = Vec::new();
-    let mut offset = 0;
-
-    for line in slice.lines() {
-        let line_start = offset;
-        let line_end = line_start + line.len();
-        offset = line_end + 1;
-        let trimmed = line.trim();
-
-        if !trimmed.is_empty() {
-            let leading = line.len() - line.trim_start().len();
-            let trailing = line.len() - line.trim_end().len();
-            let trimmed_start = range.start + line_start + leading;
-            let trimmed_end = range.start + line_end - trailing;
-
-            let original_line_start = text[..range.start + line_start]
-                .rfind('\n')
-                .map(|i| i + 1)
-                .unwrap_or(0);
-            let original_line_end = text[range.start + line_start..]
-                .find('\n')
-                .map(|i| range.start + line_start + i)
-                .unwrap_or(text.len());
-            let original_line = &text[original_line_start..original_line_end];
-            let original_trimmed_start =
-                original_line_start + (original_line.len() - original_line.trim_start().len());
-            let original_trimmed_end =
-                original_line_end - (original_line.len() - original_line.trim_end().len());
-
-            if trimmed_start > original_trimmed_start || trimmed_end < original_trimmed_end {
-                ranges.push(trimmed_start..trimmed_end);
-            }
-        }
-    }
-
-    ranges
-}
-
 pub struct DiffOptions {
     pub language_scope: Option<LanguageScope>,
     pub max_word_diff_len: usize,
@@ -372,4 +441,30 @@ mod tests {
         let patch = unified_diff(old_text, new_text);
         assert_eq!(apply_diff_patch(old_text, &patch).unwrap(), new_text);
     }
+
+    #[test]
+    fn test_unified_diff_with_offsets() {
+        let old_text = "foo\nbar\nbaz\n";
+        let new_text = "foo\nBAR\nbaz\n";
+
+        let expected_diff_body = " foo\n-bar\n+BAR\n baz\n";
+
+        let diff_no_offset = unified_diff(old_text, new_text);
+        assert_eq!(
+            diff_no_offset,
+            format!("@@ -1,3 +1,3 @@\n{}", expected_diff_body)
+        );
+
+        let diff_with_offset = unified_diff_with_offsets(old_text, new_text, 9, 11);
+        assert_eq!(
+            diff_with_offset,
+            format!("@@ -10,3 +12,3 @@\n{}", expected_diff_body)
+        );
+
+        let diff_with_offset = unified_diff_with_offsets(old_text, new_text, 99, 104);
+        assert_eq!(
+            diff_with_offset,
+            format!("@@ -100,3 +105,3 @@\n{}", expected_diff_body)
+        );
+    }
 }

crates/language/src/toolchain.rs 🔗

@@ -4,7 +4,10 @@
 //! which is a set of tools used to interact with the projects written in said language.
 //! For example, a Python project can have an associated virtual environment; a Rust project can have a toolchain override.
 
-use std::{path::PathBuf, sync::Arc};
+use std::{
+    path::{Path, PathBuf},
+    sync::Arc,
+};
 
 use async_trait::async_trait;
 use collections::HashMap;
@@ -36,7 +39,7 @@ pub struct Toolchain {
 /// - Only in the subproject they're currently in.
 #[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
 pub enum ToolchainScope {
-    Subproject(WorktreeId, Arc<RelPath>),
+    Subproject(Arc<Path>, Arc<RelPath>),
     Project,
     /// Available in all projects on this box. It wouldn't make sense to show suggestions across machines.
     Global,

crates/language_extension/src/extension_lsp_adapter.rs 🔗

@@ -1,5 +1,5 @@
 use std::ops::Range;
-use std::path::PathBuf;
+use std::path::{Path, PathBuf};
 use std::sync::Arc;
 
 use anyhow::{Context as _, Result};
@@ -174,7 +174,32 @@ impl DynLspInstaller for ExtensionLspAdapter {
                     )
                     .await?;
 
-                let path = self.extension.path_from_extension(command.command.as_ref());
+                // on windows, extensions might produce weird paths
+                // that start with a leading slash due to WASI
+                // requiring that for PWD and friends so account for
+                // that here and try to transform those paths back
+                // to windows paths
+                //
+                // if we don't do this, std will interpret the path as relative,
+                // which changes join behavior
+                let command_path: &Path = if cfg!(windows)
+                    && let Some(command) = command.command.to_str()
+                {
+                    let mut chars = command.chars();
+                    if chars.next().is_some_and(|c| c == '/')
+                        && chars.next().is_some_and(|c| c.is_ascii_alphabetic())
+                        && chars.next().is_some_and(|c| c == ':')
+                        && chars.next().is_some_and(|c| c == '\\' || c == '/')
+                    {
+                        // looks like a windows path with a leading slash, so strip it
+                        command.strip_prefix('/').unwrap().as_ref()
+                    } else {
+                        command.as_ref()
+                    }
+                } else {
+                    command.command.as_ref()
+                };
+                let path = self.extension.path_from_extension(command_path);
 
                 // TODO: This should now be done via the `zed::make_file_executable` function in
                 // Zed extension API, but we're leaving these existing usages in place temporarily
@@ -193,7 +218,32 @@ impl DynLspInstaller for ExtensionLspAdapter {
 
                 Ok(LanguageServerBinary {
                     path,
-                    arguments: command.args.into_iter().map(|arg| arg.into()).collect(),
+                    arguments: command
+                        .args
+                        .into_iter()
+                        .map(|arg| {
+                            // on windows, extensions might produce weird paths
+                            // that start with a leading slash due to WASI
+                            // requiring that for PWD and friends so account for
+                            // that here and try to transform those paths back
+                            // to windows paths
+                            if cfg!(windows) {
+                                let mut chars = arg.chars();
+                                if chars.next().is_some_and(|c| c == '/')
+                                    && chars.next().is_some_and(|c| c.is_ascii_alphabetic())
+                                    && chars.next().is_some_and(|c| c == ':')
+                                    && chars.next().is_some_and(|c| c == '\\' || c == '/')
+                                {
+                                    // looks like a windows path with a leading slash, so strip it
+                                    arg.strip_prefix('/').unwrap().into()
+                                } else {
+                                    arg.into()
+                                }
+                            } else {
+                                arg.into()
+                            }
+                        })
+                        .collect(),
                     env: Some(command.env.into_iter().collect()),
                 })
             })
@@ -245,7 +295,7 @@ impl LspAdapter for ExtensionLspAdapter {
         // We can remove once the following extension versions no longer see any use:
         // - php@0.0.1
         if self.extension.manifest().id.as_ref() == "php" {
-            return HashMap::from_iter([(LanguageName::new("PHP"), "php".into())]);
+            return HashMap::from_iter([(LanguageName::new_static("PHP"), "php".into())]);
         }
 
         self.extension

crates/language_model/Cargo.toml 🔗

@@ -18,6 +18,7 @@ test-support = []
 [dependencies]
 anthropic = { workspace = true, features = ["schemars"] }
 anyhow.workspace = true
+credentials_provider.workspace = true
 base64.workspace = true
 client.workspace = true
 cloud_api_types.workspace = true
@@ -38,9 +39,9 @@ serde.workspace = true
 serde_json.workspace = true
 settings.workspace = true
 smol.workspace = true
-telemetry_events.workspace = true
 thiserror.workspace = true
 util.workspace = true
+zed_env_vars.workspace = true
 
 [dev-dependencies]
 gpui = { workspace = true, features = ["test-support"] }

crates/language_models/src/api_key.rs → crates/language_model/src/api_key.rs 🔗

@@ -2,7 +2,6 @@ use anyhow::{Result, anyhow};
 use credentials_provider::CredentialsProvider;
 use futures::{FutureExt, future};
 use gpui::{AsyncApp, Context, SharedString, Task};
-use language_model::AuthenticateError;
 use std::{
     fmt::{Display, Formatter},
     sync::Arc,
@@ -10,13 +9,16 @@ use std::{
 use util::ResultExt as _;
 use zed_env_vars::EnvVar;
 
+use crate::AuthenticateError;
+
 /// Manages a single API key for a language model provider. API keys either come from environment
 /// variables or the system keychain.
 ///
 /// Keys from the system keychain are associated with a provider URL, and this ensures that they are
 /// only used with that URL.
 pub struct ApiKeyState {
-    url: SharedString,
+    pub url: SharedString,
+    env_var: EnvVar,
     load_status: LoadStatus,
     load_task: Option<future::Shared<Task<()>>>,
 }
@@ -35,9 +37,10 @@ pub struct ApiKey {
 }
 
 impl ApiKeyState {
-    pub fn new(url: SharedString) -> Self {
+    pub fn new(url: SharedString, env_var: EnvVar) -> Self {
         Self {
             url,
+            env_var,
             load_status: LoadStatus::NotPresent,
             load_task: None,
         }
@@ -47,6 +50,10 @@ impl ApiKeyState {
         matches!(self.load_status, LoadStatus::Loaded { .. })
     }
 
+    pub fn env_var_name(&self) -> &SharedString {
+        &self.env_var.name
+    }
+
     pub fn is_from_env_var(&self) -> bool {
         match &self.load_status {
             LoadStatus::Loaded(ApiKey {
@@ -136,14 +143,13 @@ impl ApiKeyState {
     pub fn handle_url_change<Ent: 'static>(
         &mut self,
         url: SharedString,
-        env_var: &EnvVar,
         get_this: impl Fn(&mut Ent) -> &mut Self + Clone + 'static,
         cx: &mut Context<Ent>,
     ) {
         if url != self.url {
             if !self.is_from_env_var() {
                 // loading will continue even though this result task is dropped
-                let _task = self.load_if_needed(url, env_var, get_this, cx);
+                let _task = self.load_if_needed(url, get_this, cx);
             }
         }
     }
@@ -156,7 +162,6 @@ impl ApiKeyState {
     pub fn load_if_needed<Ent: 'static>(
         &mut self,
         url: SharedString,
-        env_var: &EnvVar,
         get_this: impl Fn(&mut Ent) -> &mut Self + Clone + 'static,
         cx: &mut Context<Ent>,
     ) -> Task<Result<(), AuthenticateError>> {
@@ -166,10 +171,10 @@ impl ApiKeyState {
             return Task::ready(Ok(()));
         }
 
-        if let Some(key) = &env_var.value
+        if let Some(key) = &self.env_var.value
             && !key.is_empty()
         {
-            let api_key = ApiKey::from_env(env_var.name.clone(), key);
+            let api_key = ApiKey::from_env(self.env_var.name.clone(), key);
             self.url = url;
             self.load_status = LoadStatus::Loaded(api_key);
             self.load_task = None;

crates/language_model/src/language_model.rs 🔗

@@ -1,3 +1,4 @@
+mod api_key;
 mod model;
 mod rate_limiter;
 mod registry;
@@ -30,6 +31,7 @@ use std::{fmt, io};
 use thiserror::Error;
 use util::serde::is_default;
 
+pub use crate::api_key::{ApiKey, ApiKeyState};
 pub use crate::model::*;
 pub use crate::rate_limiter::*;
 pub use crate::registry::*;
@@ -37,6 +39,7 @@ pub use crate::request::*;
 pub use crate::role::*;
 pub use crate::telemetry::*;
 pub use crate::tool_schema::LanguageModelToolSchemaFormat;
+pub use zed_env_vars::{EnvVar, env_var};
 
 pub const ANTHROPIC_PROVIDER_ID: LanguageModelProviderId =
     LanguageModelProviderId::new("anthropic");
@@ -609,6 +612,11 @@ pub trait LanguageModel: Send + Sync {
         false
     }
 
+    /// Returns whether this model or provider supports streaming tool calls;
+    fn supports_streaming_tools(&self) -> bool {
+        false
+    }
+
     fn tool_input_format(&self) -> LanguageModelToolSchemaFormat {
         LanguageModelToolSchemaFormat::JsonSchema
     }
@@ -707,6 +715,40 @@ pub trait LanguageModel: Send + Sync {
         .boxed()
     }
 
+    fn stream_completion_tool(
+        &self,
+        request: LanguageModelRequest,
+        cx: &AsyncApp,
+    ) -> BoxFuture<'static, Result<LanguageModelToolUse, LanguageModelCompletionError>> {
+        let future = self.stream_completion(request, cx);
+
+        async move {
+            let events = future.await?;
+            let mut events = events.fuse();
+
+            // Iterate through events until we find a complete ToolUse
+            while let Some(event) = events.next().await {
+                match event {
+                    Ok(LanguageModelCompletionEvent::ToolUse(tool_use))
+                        if tool_use.is_input_complete =>
+                    {
+                        return Ok(tool_use);
+                    }
+                    Err(err) => {
+                        return Err(err);
+                    }
+                    _ => {}
+                }
+            }
+
+            // Stream ended without a complete tool use
+            Err(LanguageModelCompletionError::Other(anyhow::anyhow!(
+                "Stream ended without receiving a complete tool use"
+            )))
+        }
+        .boxed()
+    }
+
     fn cache_configuration(&self) -> Option<LanguageModelCacheConfiguration> {
         None
     }
@@ -729,6 +771,21 @@ pub trait LanguageModelExt: LanguageModel {
 }
 impl LanguageModelExt for dyn LanguageModel {}
 
+impl std::fmt::Debug for dyn LanguageModel {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        f.debug_struct("<dyn LanguageModel>")
+            .field("id", &self.id())
+            .field("name", &self.name())
+            .field("provider_id", &self.provider_id())
+            .field("provider_name", &self.provider_name())
+            .field("upstream_provider_name", &self.upstream_provider_name())
+            .field("upstream_provider_id", &self.upstream_provider_id())
+            .field("upstream_provider_id", &self.upstream_provider_id())
+            .field("supports_streaming_tools", &self.supports_streaming_tools())
+            .finish()
+    }
+}
+
 /// An error that occurred when trying to authenticate the language model provider.
 #[derive(Debug, Error)]
 pub enum AuthenticateError {
@@ -740,11 +797,26 @@ pub enum AuthenticateError {
     Other(#[from] anyhow::Error),
 }
 
+/// Either a built-in icon name or a path to an external SVG.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum IconOrSvg {
+    /// A built-in icon from Zed's icon set.
+    Icon(IconName),
+    /// Path to a custom SVG icon file.
+    Svg(SharedString),
+}
+
+impl Default for IconOrSvg {
+    fn default() -> Self {
+        Self::Icon(IconName::ZedAssistant)
+    }
+}
+
 pub trait LanguageModelProvider: 'static {
     fn id(&self) -> LanguageModelProviderId;
     fn name(&self) -> LanguageModelProviderName;
-    fn icon(&self) -> IconName {
-        IconName::ZedAssistant
+    fn icon(&self) -> IconOrSvg {
+        IconOrSvg::default()
     }
     fn default_model(&self, cx: &App) -> Option<Arc<dyn LanguageModel>>;
     fn default_fast_model(&self, cx: &App) -> Option<Arc<dyn LanguageModel>>;
@@ -763,7 +835,7 @@ pub trait LanguageModelProvider: 'static {
     fn reset_credentials(&self, cx: &mut App) -> Task<Result<()>>;
 }
 
-#[derive(Default, Clone)]
+#[derive(Default, Clone, PartialEq, Eq)]
 pub enum ConfigurationViewTargetAgent {
     #[default]
     ZedAgent,

crates/language_model/src/registry.rs 🔗

@@ -2,12 +2,16 @@ use crate::{
     LanguageModel, LanguageModelId, LanguageModelProvider, LanguageModelProviderId,
     LanguageModelProviderState,
 };
-use collections::BTreeMap;
+use collections::{BTreeMap, HashSet};
 use gpui::{App, Context, Entity, EventEmitter, Global, prelude::*};
 use std::{str::FromStr, sync::Arc};
 use thiserror::Error;
 use util::maybe;
 
+/// Function type for checking if a built-in provider should be hidden.
+/// Returns Some(extension_id) if the provider should be hidden when that extension is installed.
+pub type BuiltinProviderHidingFn = Box<dyn Fn(&str) -> Option<&'static str> + Send + Sync>;
+
 pub fn init(cx: &mut App) {
     let registry = cx.new(|_cx| LanguageModelRegistry::default());
     cx.set_global(GlobalLanguageModelRegistry(registry));
@@ -48,6 +52,11 @@ pub struct LanguageModelRegistry {
     thread_summary_model: Option<ConfiguredModel>,
     providers: BTreeMap<LanguageModelProviderId, Arc<dyn LanguageModelProvider>>,
     inline_alternatives: Vec<Arc<dyn LanguageModel>>,
+    /// Set of installed extension IDs that provide language models.
+    /// Used to determine which built-in providers should be hidden.
+    installed_llm_extension_ids: HashSet<Arc<str>>,
+    /// Function to check if a built-in provider should be hidden by an extension.
+    builtin_provider_hiding_fn: Option<BuiltinProviderHidingFn>,
 }
 
 #[derive(Debug)]
@@ -104,6 +113,8 @@ pub enum Event {
     ProviderStateChanged(LanguageModelProviderId),
     AddedProvider(LanguageModelProviderId),
     RemovedProvider(LanguageModelProviderId),
+    /// Emitted when provider visibility changes due to extension install/uninstall.
+    ProvidersChanged,
 }
 
 impl EventEmitter<Event> for LanguageModelRegistry {}
@@ -135,6 +146,11 @@ impl LanguageModelRegistry {
         fake_provider
     }
 
+    #[cfg(any(test, feature = "test-support"))]
+    pub fn fake_model(&self) -> Arc<dyn LanguageModel> {
+        self.default_model.as_ref().unwrap().model.clone()
+    }
+
     pub fn register_provider<T: LanguageModelProvider + LanguageModelProviderState>(
         &mut self,
         provider: Arc<T>,
@@ -178,6 +194,60 @@ impl LanguageModelRegistry {
         providers
     }
 
+    /// Returns providers, filtering out hidden built-in providers.
+    pub fn visible_providers(&self) -> Vec<Arc<dyn LanguageModelProvider>> {
+        self.providers()
+            .into_iter()
+            .filter(|p| !self.should_hide_provider(&p.id()))
+            .collect()
+    }
+
+    /// Sets the function used to check if a built-in provider should be hidden.
+    pub fn set_builtin_provider_hiding_fn(&mut self, hiding_fn: BuiltinProviderHidingFn) {
+        self.builtin_provider_hiding_fn = Some(hiding_fn);
+    }
+
+    /// Called when an extension is installed/loaded.
+    /// If the extension provides language models, track it so we can hide the corresponding built-in.
+    pub fn extension_installed(&mut self, extension_id: Arc<str>, cx: &mut Context<Self>) {
+        if self.installed_llm_extension_ids.insert(extension_id) {
+            cx.emit(Event::ProvidersChanged);
+            cx.notify();
+        }
+    }
+
+    /// Called when an extension is uninstalled/unloaded.
+    pub fn extension_uninstalled(&mut self, extension_id: &str, cx: &mut Context<Self>) {
+        if self.installed_llm_extension_ids.remove(extension_id) {
+            cx.emit(Event::ProvidersChanged);
+            cx.notify();
+        }
+    }
+
+    /// Sync the set of installed LLM extension IDs.
+    pub fn sync_installed_llm_extensions(
+        &mut self,
+        extension_ids: HashSet<Arc<str>>,
+        cx: &mut Context<Self>,
+    ) {
+        if extension_ids != self.installed_llm_extension_ids {
+            self.installed_llm_extension_ids = extension_ids;
+            cx.emit(Event::ProvidersChanged);
+            cx.notify();
+        }
+    }
+
+    /// Returns true if a provider should be hidden from the UI.
+    /// Built-in providers are hidden when their corresponding extension is installed.
+    pub fn should_hide_provider(&self, provider_id: &LanguageModelProviderId) -> bool {
+        if let Some(ref hiding_fn) = self.builtin_provider_hiding_fn {
+            if let Some(extension_id) = hiding_fn(&provider_id.0) {
+                return self.installed_llm_extension_ids.contains(extension_id);
+            }
+        }
+        false
+    }
+
     pub fn configuration_error(
         &self,
         model: Option<ConfiguredModel>,
@@ -411,4 +481,132 @@ mod tests {
         let providers = registry.read(cx).providers();
         assert!(providers.is_empty());
     }
+
+    #[gpui::test]
+    fn test_provider_hiding_on_extension_install(cx: &mut App) {
+        let registry = cx.new(|_| LanguageModelRegistry::default());
+
+        let provider = Arc::new(FakeLanguageModelProvider::default());
+        let provider_id = provider.id();
+
+        registry.update(cx, |registry, cx| {
+            registry.register_provider(provider.clone(), cx);
+
+            registry.set_builtin_provider_hiding_fn(Box::new(|id| {
+                if id == "fake" {
+                    Some("fake-extension")
+                } else {
+                    None
+                }
+            }));
+        });
+
+        let visible = registry.read(cx).visible_providers();
+        assert_eq!(visible.len(), 1);
+        assert_eq!(visible[0].id(), provider_id);
+
+        registry.update(cx, |registry, cx| {
+            registry.extension_installed("fake-extension".into(), cx);
+        });
+
+        let visible = registry.read(cx).visible_providers();
+        assert!(visible.is_empty());
+
+        let all = registry.read(cx).providers();
+        assert_eq!(all.len(), 1);
+    }
+
+    #[gpui::test]
+    fn test_provider_unhiding_on_extension_uninstall(cx: &mut App) {
+        let registry = cx.new(|_| LanguageModelRegistry::default());
+
+        let provider = Arc::new(FakeLanguageModelProvider::default());
+        let provider_id = provider.id();
+
+        registry.update(cx, |registry, cx| {
+            registry.register_provider(provider.clone(), cx);
+
+            registry.set_builtin_provider_hiding_fn(Box::new(|id| {
+                if id == "fake" {
+                    Some("fake-extension")
+                } else {
+                    None
+                }
+            }));
+
+            registry.extension_installed("fake-extension".into(), cx);
+        });
+
+        let visible = registry.read(cx).visible_providers();
+        assert!(visible.is_empty());
+
+        registry.update(cx, |registry, cx| {
+            registry.extension_uninstalled("fake-extension", cx);
+        });
+
+        let visible = registry.read(cx).visible_providers();
+        assert_eq!(visible.len(), 1);
+        assert_eq!(visible[0].id(), provider_id);
+    }
+
+    #[gpui::test]
+    fn test_should_hide_provider(cx: &mut App) {
+        let registry = cx.new(|_| LanguageModelRegistry::default());
+
+        registry.update(cx, |registry, cx| {
+            registry.set_builtin_provider_hiding_fn(Box::new(|id| {
+                if id == "anthropic" {
+                    Some("anthropic")
+                } else if id == "openai" {
+                    Some("openai")
+                } else {
+                    None
+                }
+            }));
+
+            registry.extension_installed("anthropic".into(), cx);
+        });
+
+        let registry_read = registry.read(cx);
+
+        assert!(registry_read.should_hide_provider(&LanguageModelProviderId("anthropic".into())));
+
+        assert!(!registry_read.should_hide_provider(&LanguageModelProviderId("openai".into())));
+
+        assert!(!registry_read.should_hide_provider(&LanguageModelProviderId("unknown".into())));
+    }
+
+    #[gpui::test]
+    fn test_sync_installed_llm_extensions(cx: &mut App) {
+        let registry = cx.new(|_| LanguageModelRegistry::default());
+
+        let provider = Arc::new(FakeLanguageModelProvider::default());
+
+        registry.update(cx, |registry, cx| {
+            registry.register_provider(provider.clone(), cx);
+
+            registry.set_builtin_provider_hiding_fn(Box::new(|id| {
+                if id == "fake" {
+                    Some("fake-extension")
+                } else {
+                    None
+                }
+            }));
+        });
+
+        let mut extension_ids = HashSet::default();
+        extension_ids.insert(Arc::from("fake-extension"));
+
+        registry.update(cx, |registry, cx| {
+            registry.sync_installed_llm_extensions(extension_ids, cx);
+        });
+
+        assert!(registry.read(cx).visible_providers().is_empty());
+
+        registry.update(cx, |registry, cx| {
+            registry.sync_installed_llm_extensions(HashSet::default(), cx);
+        });
+
+        assert_eq!(registry.read(cx).visible_providers().len(), 1);
+    }
 }

crates/language_model/src/request.rs 🔗

@@ -8,6 +8,7 @@ use gpui::{
     App, AppContext as _, DevicePixels, Image, ImageFormat, ObjectFit, SharedString, Size, Task,
     point, px, size,
 };
+use image::GenericImageView as _;
 use image::codecs::png::PngEncoder;
 use serde::{Deserialize, Serialize};
 use util::ResultExt;
@@ -19,7 +20,8 @@ use crate::{LanguageModelToolUse, LanguageModelToolUseId};
 pub struct LanguageModelImage {
     /// A base64-encoded PNG image.
     pub source: SharedString,
-    pub size: Size<DevicePixels>,
+    #[serde(default, skip_serializing_if = "Option::is_none")]
+    pub size: Option<Size<DevicePixels>>,
 }
 
 impl LanguageModelImage {
@@ -61,7 +63,7 @@ impl LanguageModelImage {
         }
 
         Some(Self {
-            size: size(DevicePixels(width?), DevicePixels(height?)),
+            size: Some(size(DevicePixels(width?), DevicePixels(height?))),
             source: SharedString::from(source.to_string()),
         })
     }
@@ -79,11 +81,21 @@ impl std::fmt::Debug for LanguageModelImage {
 /// Anthropic wants uploaded images to be smaller than this in both dimensions.
 const ANTHROPIC_SIZE_LIMIT: f32 = 1568.;
 
+/// Default per-image hard limit (in bytes) for the encoded image payload we send upstream.
+///
+/// NOTE: `LanguageModelImage.source` is base64-encoded PNG bytes (without the `data:` prefix).
+/// This limit is enforced on the encoded PNG bytes *before* base64 encoding.
+const DEFAULT_IMAGE_MAX_BYTES: usize = 5 * 1024 * 1024;
+
+/// Conservative cap on how many times we'll attempt to shrink/re-encode an image to fit
+/// `DEFAULT_IMAGE_MAX_BYTES`.
+const MAX_IMAGE_DOWNSCALE_PASSES: usize = 8;
+
 impl LanguageModelImage {
     pub fn empty() -> Self {
         Self {
             source: "".into(),
-            size: size(DevicePixels(0), DevicePixels(0)),
+            size: None,
         }
     }
 
@@ -111,43 +123,79 @@ impl LanguageModelImage {
             let height = dynamic_image.height();
             let image_size = size(DevicePixels(width as i32), DevicePixels(height as i32));
 
-            let base64_image = {
-                if image_size.width.0 > ANTHROPIC_SIZE_LIMIT as i32
-                    || image_size.height.0 > ANTHROPIC_SIZE_LIMIT as i32
-                {
-                    let new_bounds = ObjectFit::ScaleDown.get_bounds(
-                        gpui::Bounds {
-                            origin: point(px(0.0), px(0.0)),
-                            size: size(px(ANTHROPIC_SIZE_LIMIT), px(ANTHROPIC_SIZE_LIMIT)),
-                        },
-                        image_size,
-                    );
-                    let resized_image = dynamic_image.resize(
-                        new_bounds.size.width.into(),
-                        new_bounds.size.height.into(),
-                        image::imageops::FilterType::Triangle,
-                    );
-
-                    encode_as_base64(data, resized_image)
-                } else {
-                    encode_as_base64(data, dynamic_image)
+            // First apply any provider-specific dimension constraints we know about (Anthropic).
+            let mut processed_image = if image_size.width.0 > ANTHROPIC_SIZE_LIMIT as i32
+                || image_size.height.0 > ANTHROPIC_SIZE_LIMIT as i32
+            {
+                let new_bounds = ObjectFit::ScaleDown.get_bounds(
+                    gpui::Bounds {
+                        origin: point(px(0.0), px(0.0)),
+                        size: size(px(ANTHROPIC_SIZE_LIMIT), px(ANTHROPIC_SIZE_LIMIT)),
+                    },
+                    image_size,
+                );
+                dynamic_image.resize(
+                    new_bounds.size.width.into(),
+                    new_bounds.size.height.into(),
+                    image::imageops::FilterType::Triangle,
+                )
+            } else {
+                dynamic_image
+            };
+
+            // Then enforce a default per-image size cap on the encoded PNG bytes.
+            //
+            // We always send PNG bytes (either original PNG bytes, or re-encoded PNG) base64'd.
+            // The upstream provider limit we want to respect is effectively on the binary image
+            // payload size, so we enforce against the encoded PNG bytes before base64 encoding.
+            let mut encoded_png = encode_png_bytes(&processed_image).log_err()?;
+            for _pass in 0..MAX_IMAGE_DOWNSCALE_PASSES {
+                if encoded_png.len() <= DEFAULT_IMAGE_MAX_BYTES {
+                    break;
+                }
+
+                // Scale down geometrically to converge quickly. We don't know the final PNG size
+                // as a function of pixels, so we iteratively shrink.
+                let (w, h) = processed_image.dimensions();
+                if w <= 1 || h <= 1 {
+                    break;
                 }
+
+                // Shrink by ~15% each pass (0.85). This is a compromise between speed and
+                // preserving image detail.
+                let new_w = ((w as f32) * 0.85).round().max(1.0) as u32;
+                let new_h = ((h as f32) * 0.85).round().max(1.0) as u32;
+
+                processed_image =
+                    processed_image.resize(new_w, new_h, image::imageops::FilterType::Triangle);
+                encoded_png = encode_png_bytes(&processed_image).log_err()?;
+            }
+
+            if encoded_png.len() > DEFAULT_IMAGE_MAX_BYTES {
+                // Still too large after multiple passes; treat as non-convertible for now.
+                // (Provider-specific handling can be introduced later.)
+                return None;
             }
-            .log_err()?;
+
+            // Now base64 encode the PNG bytes.
+            let base64_image = encode_bytes_as_base64(encoded_png.as_slice()).log_err()?;
 
             // SAFETY: The base64 encoder should not produce non-UTF8.
             let source = unsafe { String::from_utf8_unchecked(base64_image) };
 
             Some(LanguageModelImage {
-                size: image_size,
+                size: Some(image_size),
                 source: source.into(),
             })
         })
     }
 
     pub fn estimate_tokens(&self) -> usize {
-        let width = self.size.width.0.unsigned_abs() as usize;
-        let height = self.size.height.0.unsigned_abs() as usize;
+        let Some(size) = self.size.as_ref() else {
+            return 0;
+        };
+        let width = size.width.0.unsigned_abs() as usize;
+        let height = size.height.0.unsigned_abs() as usize;
 
         // From: https://docs.anthropic.com/en/docs/build-with-claude/vision#calculate-image-costs
         // Note that are a lot of conditions on Anthropic's API, and OpenAI doesn't use this,
@@ -160,21 +208,20 @@ impl LanguageModelImage {
     }
 }
 
-fn encode_as_base64(data: Arc<Image>, image: image::DynamicImage) -> Result<Vec<u8>> {
+fn encode_png_bytes(image: &image::DynamicImage) -> Result<Vec<u8>> {
+    let mut png = Vec::new();
+    image.write_with_encoder(PngEncoder::new(&mut png))?;
+    Ok(png)
+}
+
+fn encode_bytes_as_base64(bytes: &[u8]) -> Result<Vec<u8>> {
     let mut base64_image = Vec::new();
     {
         let mut base64_encoder = EncoderWriter::new(
             Cursor::new(&mut base64_image),
             &base64::engine::general_purpose::STANDARD,
         );
-        if data.format() == ImageFormat::Png {
-            base64_encoder.write_all(data.bytes())?;
-        } else {
-            let mut png = Vec::new();
-            image.write_with_encoder(PngEncoder::new(&mut png))?;
-
-            base64_encoder.write_all(png.as_slice())?;
-        }
+        base64_encoder.write_all(bytes)?;
     }
     Ok(base64_image)
 }
@@ -413,6 +460,71 @@ pub struct LanguageModelResponseMessage {
 #[cfg(test)]
 mod tests {
     use super::*;
+    use base64::Engine as _;
+    use gpui::TestAppContext;
+    use image::ImageDecoder as _;
+
+    fn base64_to_png_bytes(base64_png: &str) -> Vec<u8> {
+        base64::engine::general_purpose::STANDARD
+            .decode(base64_png.as_bytes())
+            .expect("base64 should decode")
+    }
+
+    fn png_dimensions(png_bytes: &[u8]) -> (u32, u32) {
+        let decoder =
+            image::codecs::png::PngDecoder::new(Cursor::new(png_bytes)).expect("png should decode");
+        decoder.dimensions()
+    }
+
+    fn make_noisy_png_bytes(width: u32, height: u32) -> Vec<u8> {
+        // Create an RGBA image with per-pixel variance to avoid PNG compressing too well.
+        let mut img = image::RgbaImage::new(width, height);
+        for y in 0..height {
+            for x in 0..width {
+                let r = ((x ^ y) & 0xFF) as u8;
+                let g = ((x.wrapping_mul(31) ^ y.wrapping_mul(17)) & 0xFF) as u8;
+                let b = ((x.wrapping_mul(131) ^ y.wrapping_mul(7)) & 0xFF) as u8;
+                img.put_pixel(x, y, image::Rgba([r, g, b, 0xFF]));
+            }
+        }
+
+        let mut out = Vec::new();
+        image::DynamicImage::ImageRgba8(img)
+            .write_with_encoder(PngEncoder::new(&mut out))
+            .expect("png encoding should succeed");
+        out
+    }
+
+    #[gpui::test]
+    async fn test_from_image_downscales_to_default_5mb_limit(cx: &mut TestAppContext) {
+        // Pick a size that reliably produces a PNG > 5MB when filled with noise.
+        // If this fails (image is too small), bump dimensions.
+        let original_png = make_noisy_png_bytes(4096, 4096);
+        assert!(
+            original_png.len() > DEFAULT_IMAGE_MAX_BYTES,
+            "precondition failed: noisy PNG must exceed DEFAULT_IMAGE_MAX_BYTES"
+        );
+
+        let image = gpui::Image::from_bytes(ImageFormat::Png, original_png);
+        let lm_image = cx
+            .update(|cx| LanguageModelImage::from_image(Arc::new(image), cx))
+            .await
+            .expect("image conversion should succeed");
+
+        let encoded_png = base64_to_png_bytes(lm_image.source.as_ref());
+        assert!(
+            encoded_png.len() <= DEFAULT_IMAGE_MAX_BYTES,
+            "expected encoded PNG <= DEFAULT_IMAGE_MAX_BYTES, got {} bytes",
+            encoded_png.len()
+        );
+
+        // Ensure we actually downscaled in pixels (not just re-encoded).
+        let (w, h) = png_dimensions(&encoded_png);
+        assert!(
+            w < 4096 || h < 4096,
+            "expected image to be downscaled in at least one dimension; got {w}x{h}"
+        );
+    }
 
     #[test]
     fn test_language_model_tool_result_content_deserialization() {
@@ -463,8 +575,9 @@ mod tests {
         match result {
             LanguageModelToolResultContent::Image(image) => {
                 assert_eq!(image.source.as_ref(), "base64encodedimagedata");
-                assert_eq!(image.size.width.0, 100);
-                assert_eq!(image.size.height.0, 200);
+                let size = image.size.expect("size");
+                assert_eq!(size.width.0, 100);
+                assert_eq!(size.height.0, 200);
             }
             _ => panic!("Expected Image variant"),
         }
@@ -483,8 +596,9 @@ mod tests {
         match result {
             LanguageModelToolResultContent::Image(image) => {
                 assert_eq!(image.source.as_ref(), "wrappedimagedata");
-                assert_eq!(image.size.width.0, 50);
-                assert_eq!(image.size.height.0, 75);
+                let size = image.size.expect("size");
+                assert_eq!(size.width.0, 50);
+                assert_eq!(size.height.0, 75);
             }
             _ => panic!("Expected Image variant"),
         }
@@ -503,8 +617,9 @@ mod tests {
         match result {
             LanguageModelToolResultContent::Image(image) => {
                 assert_eq!(image.source.as_ref(), "caseinsensitive");
-                assert_eq!(image.size.width.0, 30);
-                assert_eq!(image.size.height.0, 40);
+                let size = image.size.expect("size");
+                assert_eq!(size.width.0, 30);
+                assert_eq!(size.height.0, 40);
             }
             _ => panic!("Expected Image variant"),
         }
@@ -541,8 +656,9 @@ mod tests {
         match result {
             LanguageModelToolResultContent::Image(image) => {
                 assert_eq!(image.source.as_ref(), "directimage");
-                assert_eq!(image.size.width.0, 200);
-                assert_eq!(image.size.height.0, 300);
+                let size = image.size.expect("size");
+                assert_eq!(size.width.0, 200);
+                assert_eq!(size.height.0, 300);
             }
             _ => panic!("Expected Image variant"),
         }

crates/language_model/src/telemetry.rs 🔗

@@ -1,41 +1,101 @@
 use crate::ANTHROPIC_PROVIDER_ID;
 use anthropic::ANTHROPIC_API_URL;
 use anyhow::{Context as _, anyhow};
-use client::telemetry::Telemetry;
 use gpui::BackgroundExecutor;
 use http_client::{AsyncBody, HttpClient, Method, Request as HttpRequest};
 use std::env;
 use std::sync::Arc;
-use telemetry_events::{AssistantEventData, AssistantKind, AssistantPhase};
 use util::ResultExt;
 
-pub fn report_assistant_event(
-    event: AssistantEventData,
-    telemetry: Option<Arc<Telemetry>>,
-    client: Arc<dyn HttpClient>,
-    model_api_key: Option<String>,
-    executor: &BackgroundExecutor,
+#[derive(Clone, Debug)]
+pub struct AnthropicEventData {
+    pub completion_type: AnthropicCompletionType,
+    pub event: AnthropicEventType,
+    pub language_name: Option<String>,
+    pub message_id: Option<String>,
+}
+
+#[derive(Clone, Debug)]
+pub enum AnthropicCompletionType {
+    Editor,
+    Terminal,
+    Panel,
+}
+
+#[derive(Clone, Debug)]
+pub enum AnthropicEventType {
+    Invoked,
+    Response,
+    Accept,
+    Reject,
+}
+
+impl AnthropicCompletionType {
+    fn as_str(&self) -> &'static str {
+        match self {
+            Self::Editor => "natural_language_completion_in_editor",
+            Self::Terminal => "natural_language_completion_in_terminal",
+            Self::Panel => "conversation_message",
+        }
+    }
+}
+
+impl AnthropicEventType {
+    fn as_str(&self) -> &'static str {
+        match self {
+            Self::Invoked => "invoke",
+            Self::Response => "response",
+            Self::Accept => "accept",
+            Self::Reject => "reject",
+        }
+    }
+}
+
+pub fn report_anthropic_event(
+    model: &Arc<dyn crate::LanguageModel>,
+    event: AnthropicEventData,
+    cx: &gpui::App,
 ) {
-    if let Some(telemetry) = telemetry.as_ref() {
-        telemetry.report_assistant_event(event.clone());
-        if telemetry.metrics_enabled() && event.model_provider == ANTHROPIC_PROVIDER_ID.0 {
-            if let Some(api_key) = model_api_key {
-                executor
-                    .spawn(async move {
-                        report_anthropic_event(event, client, api_key)
-                            .await
-                            .log_err();
-                    })
-                    .detach();
-            } else {
-                log::error!("Cannot send Anthropic telemetry because API key is missing");
-            }
+    let reporter = AnthropicEventReporter::new(model, cx);
+    reporter.report(event);
+}
+
+#[derive(Clone)]
+pub struct AnthropicEventReporter {
+    http_client: Arc<dyn HttpClient>,
+    executor: BackgroundExecutor,
+    api_key: Option<String>,
+    is_anthropic: bool,
+}
+
+impl AnthropicEventReporter {
+    pub fn new(model: &Arc<dyn crate::LanguageModel>, cx: &gpui::App) -> Self {
+        Self {
+            http_client: cx.http_client(),
+            executor: cx.background_executor().clone(),
+            api_key: model.api_key(cx),
+            is_anthropic: model.provider_id() == ANTHROPIC_PROVIDER_ID,
         }
     }
+
+    pub fn report(&self, event: AnthropicEventData) {
+        if !self.is_anthropic {
+            return;
+        }
+        let Some(api_key) = self.api_key.clone() else {
+            return;
+        };
+        let client = self.http_client.clone();
+        self.executor
+            .spawn(async move {
+                send_anthropic_event(event, client, api_key).await.log_err();
+            })
+            .detach();
+    }
 }
 
-async fn report_anthropic_event(
-    event: AssistantEventData,
+async fn send_anthropic_event(
+    event: AnthropicEventData,
     client: Arc<dyn HttpClient>,
     api_key: String,
 ) -> anyhow::Result<()> {
@@ -45,18 +105,10 @@ async fn report_anthropic_event(
         .uri(uri)
         .header("X-Api-Key", api_key)
         .header("Content-Type", "application/json");
-    let serialized_event: serde_json::Value = serde_json::json!({
-        "completion_type": match event.kind {
-            AssistantKind::Inline => "natural_language_completion_in_editor",
-            AssistantKind::InlineTerminal => "natural_language_completion_in_terminal",
-            AssistantKind::Panel => "conversation_message",
-        },
-        "event": match event.phase {
-            AssistantPhase::Response => "response",
-            AssistantPhase::Invoked => "invoke",
-            AssistantPhase::Accepted => "accept",
-            AssistantPhase::Rejected => "reject",
-        },
+
+    let serialized_event = serde_json::json!({
+        "completion_type": event.completion_type.as_str(),
+        "event": event.event.as_str(),
         "metadata": {
             "language_name": event.language_name,
             "message_id": event.message_id,

crates/language_models/Cargo.toml 🔗

@@ -28,6 +28,8 @@ convert_case.workspace = true
 copilot.workspace = true
 credentials_provider.workspace = true
 deepseek = { workspace = true, features = ["schemars"] }
+extension.workspace = true
+extension_host.workspace = true
 fs.workspace = true
 futures.workspace = true
 google_ai = { workspace = true, features = ["schemars"] }
@@ -60,7 +62,6 @@ ui_input.workspace = true
 util.workspace = true
 vercel = { workspace = true, features = ["schemars"] }
 x_ai = { workspace = true, features = ["schemars"] }
-zed_env_vars.workspace = true
 
 [dev-dependencies]
 editor = { workspace = true, features = ["test-support"] }

crates/language_models/src/extension.rs 🔗

@@ -0,0 +1,67 @@
+use collections::HashMap;
+use extension::{
+    ExtensionHostProxy, ExtensionLanguageModelProviderProxy, LanguageModelProviderRegistration,
+};
+use gpui::{App, Entity};
+use language_model::{LanguageModelProviderId, LanguageModelRegistry};
+use std::sync::{Arc, LazyLock};
+
+/// Maps built-in provider IDs to their corresponding extension IDs.
+/// When an extension with this ID is installed, the built-in provider should be hidden.
+static BUILTIN_TO_EXTENSION_MAP: LazyLock<HashMap<&'static str, &'static str>> =
+    LazyLock::new(|| {
+        let mut map = HashMap::default();
+        map.insert("anthropic", "anthropic");
+        map.insert("openai", "openai");
+        map.insert("google", "google-ai");
+        map.insert("openrouter", "openrouter");
+        map.insert("copilot_chat", "copilot-chat");
+        map
+    });
+
+/// Returns the extension ID that should hide the given built-in provider.
+pub fn extension_for_builtin_provider(provider_id: &str) -> Option<&'static str> {
+    BUILTIN_TO_EXTENSION_MAP.get(provider_id).copied()
+}
+
+/// Proxy that registers extension language model providers with the LanguageModelRegistry.
+pub struct LanguageModelProviderRegistryProxy {
+    registry: Entity<LanguageModelRegistry>,
+}
+
+impl LanguageModelProviderRegistryProxy {
+    pub fn new(registry: Entity<LanguageModelRegistry>) -> Self {
+        Self { registry }
+    }
+}
+
+impl ExtensionLanguageModelProviderProxy for LanguageModelProviderRegistryProxy {
+    fn register_language_model_provider(
+        &self,
+        _provider_id: Arc<str>,
+        register_fn: LanguageModelProviderRegistration,
+        cx: &mut App,
+    ) {
+        register_fn(cx);
+    }
+
+    fn unregister_language_model_provider(&self, provider_id: Arc<str>, cx: &mut App) {
+        self.registry.update(cx, |registry, cx| {
+            registry.unregister_provider(LanguageModelProviderId::from(provider_id), cx);
+        });
+    }
+}
+
+/// Initialize the extension language model provider proxy.
+/// This must be called BEFORE extension_host::init to ensure the proxy is available
+/// when extensions try to register their language model providers.
+pub fn init_proxy(cx: &mut App) {
+    let proxy = ExtensionHostProxy::default_global(cx);
+    let registry = LanguageModelRegistry::global(cx);
+
+    registry.update(cx, |registry, _cx| {
+        registry.set_builtin_provider_hiding_fn(Box::new(extension_for_builtin_provider));
+    });
+
+    proxy.register_language_model_provider_proxy(LanguageModelProviderRegistryProxy::new(registry));
+}

crates/language_models/src/language_models.rs 🔗

@@ -7,10 +7,11 @@ use gpui::{App, Context, Entity};
 use language_model::{LanguageModelProviderId, LanguageModelRegistry};
 use provider::deepseek::DeepSeekLanguageModelProvider;
 
-mod api_key;
+pub mod extension;
 pub mod provider;
 mod settings;
-pub mod ui;
+
+pub use crate::extension::init_proxy as init_extension_proxy;
 
 use crate::provider::anthropic::AnthropicLanguageModelProvider;
 use crate::provider::bedrock::BedrockLanguageModelProvider;
@@ -33,6 +34,56 @@ pub fn init(user_store: Entity<UserStore>, client: Arc<Client>, cx: &mut App) {
         register_language_model_providers(registry, user_store, client.clone(), cx);
     });
 
+    // Subscribe to extension store events to track LLM extension installations
+    if let Some(extension_store) = extension_host::ExtensionStore::try_global(cx) {
+        cx.subscribe(&extension_store, {
+            let registry = registry.clone();
+            move |extension_store, event, cx| match event {
+                extension_host::Event::ExtensionInstalled(extension_id) => {
+                    if let Some(manifest) = extension_store
+                        .read(cx)
+                        .extension_manifest_for_id(extension_id)
+                    {
+                        if !manifest.language_model_providers.is_empty() {
+                            registry.update(cx, |registry, cx| {
+                                registry.extension_installed(extension_id.clone(), cx);
+                            });
+                        }
+                    }
+                }
+                extension_host::Event::ExtensionUninstalled(extension_id) => {
+                    registry.update(cx, |registry, cx| {
+                        registry.extension_uninstalled(extension_id, cx);
+                    });
+                }
+                extension_host::Event::ExtensionsUpdated => {
+                    let mut new_ids = HashSet::default();
+                    for (extension_id, entry) in extension_store.read(cx).installed_extensions() {
+                        if !entry.manifest.language_model_providers.is_empty() {
+                            new_ids.insert(extension_id.clone());
+                        }
+                    }
+                    registry.update(cx, |registry, cx| {
+                        registry.sync_installed_llm_extensions(new_ids, cx);
+                    });
+                }
+                _ => {}
+            }
+        })
+        .detach();
+
+        // Initialize with currently installed extensions
+        registry.update(cx, |registry, cx| {
+            let mut initial_ids = HashSet::default();
+            for (extension_id, entry) in extension_store.read(cx).installed_extensions() {
+                if !entry.manifest.language_model_providers.is_empty() {
+                    initial_ids.insert(extension_id.clone());
+                }
+            }
+            registry.sync_installed_llm_extensions(initial_ids, cx);
+        });
+    }
+
     let mut openai_compatible_providers = AllLanguageModelSettings::get_global(cx)
         .openai_compatible
         .keys()

crates/language_models/src/provider/anthropic.rs 🔗

@@ -1,6 +1,6 @@
 use anthropic::{
-    ANTHROPIC_API_URL, AnthropicError, AnthropicModelMode, ContentDelta, Event, ResponseContent,
-    ToolResultContent, ToolResultPart, Usage,
+    ANTHROPIC_API_URL, AnthropicError, AnthropicModelMode, ContentDelta, CountTokensRequest, Event,
+    ResponseContent, ToolResultContent, ToolResultPart, Usage,
 };
 use anyhow::{Result, anyhow};
 use collections::{BTreeMap, HashMap};
@@ -8,25 +8,21 @@ use futures::{FutureExt, Stream, StreamExt, future, future::BoxFuture, stream::B
 use gpui::{AnyView, App, AsyncApp, Context, Entity, Task};
 use http_client::HttpClient;
 use language_model::{
-    AuthenticateError, ConfigurationViewTargetAgent, LanguageModel,
-    LanguageModelCacheConfiguration, LanguageModelCompletionError, LanguageModelId,
-    LanguageModelName, LanguageModelProvider, LanguageModelProviderId, LanguageModelProviderName,
-    LanguageModelProviderState, LanguageModelRequest, LanguageModelToolChoice,
-    LanguageModelToolResultContent, MessageContent, RateLimiter, Role,
+    ApiKeyState, AuthenticateError, ConfigurationViewTargetAgent, EnvVar, IconOrSvg, LanguageModel,
+    LanguageModelCacheConfiguration, LanguageModelCompletionError, LanguageModelCompletionEvent,
+    LanguageModelId, LanguageModelName, LanguageModelProvider, LanguageModelProviderId,
+    LanguageModelProviderName, LanguageModelProviderState, LanguageModelRequest,
+    LanguageModelToolChoice, LanguageModelToolResultContent, LanguageModelToolUse, MessageContent,
+    RateLimiter, Role, StopReason, env_var,
 };
-use language_model::{LanguageModelCompletionEvent, LanguageModelToolUse, StopReason};
 use settings::{Settings, SettingsStore};
 use std::pin::Pin;
 use std::str::FromStr;
 use std::sync::{Arc, LazyLock};
 use strum::IntoEnumIterator;
-use ui::{List, prelude::*};
+use ui::{ButtonLink, ConfiguredApiCard, List, ListBulletItem, prelude::*};
 use ui_input::InputField;
 use util::ResultExt;
-use zed_env_vars::{EnvVar, env_var};
-
-use crate::api_key::ApiKeyState;
-use crate::ui::{ConfiguredApiCard, InstructionListItem};
 
 pub use settings::AnthropicAvailableModel as AvailableModel;
 
@@ -65,12 +61,8 @@ impl State {
 
     fn authenticate(&mut self, cx: &mut Context<Self>) -> Task<Result<(), AuthenticateError>> {
         let api_url = AnthropicLanguageModelProvider::api_url(cx);
-        self.api_key_state.load_if_needed(
-            api_url,
-            &API_KEY_ENV_VAR,
-            |this| &mut this.api_key_state,
-            cx,
-        )
+        self.api_key_state
+            .load_if_needed(api_url, |this| &mut this.api_key_state, cx)
     }
 }
 
@@ -79,17 +71,13 @@ impl AnthropicLanguageModelProvider {
         let state = cx.new(|cx| {
             cx.observe_global::<SettingsStore>(|this: &mut State, cx| {
                 let api_url = Self::api_url(cx);
-                this.api_key_state.handle_url_change(
-                    api_url,
-                    &API_KEY_ENV_VAR,
-                    |this| &mut this.api_key_state,
-                    cx,
-                );
+                this.api_key_state
+                    .handle_url_change(api_url, |this| &mut this.api_key_state, cx);
                 cx.notify();
             })
             .detach();
             State {
-                api_key_state: ApiKeyState::new(Self::api_url(cx)),
+                api_key_state: ApiKeyState::new(Self::api_url(cx), (*API_KEY_ENV_VAR).clone()),
             }
         });
 
@@ -137,8 +125,8 @@ impl LanguageModelProvider for AnthropicLanguageModelProvider {
         PROVIDER_NAME
     }
 
-    fn icon(&self) -> IconName {
-        IconName::AiAnthropic
+    fn icon(&self) -> IconOrSvg {
+        IconOrSvg::Icon(IconName::AiAnthropic)
     }
 
     fn default_model(&self, _cx: &App) -> Option<Arc<dyn LanguageModel>> {
@@ -231,68 +219,215 @@ pub struct AnthropicModel {
     request_limiter: RateLimiter,
 }
 
-pub fn count_anthropic_tokens(
+/// Convert a LanguageModelRequest to an Anthropic CountTokensRequest.
+pub fn into_anthropic_count_tokens_request(
     request: LanguageModelRequest,
-    cx: &App,
-) -> BoxFuture<'static, Result<u64>> {
-    cx.background_spawn(async move {
-        let messages = request.messages;
-        let mut tokens_from_images = 0;
-        let mut string_messages = Vec::with_capacity(messages.len());
-
-        for message in messages {
-            use language_model::MessageContent;
-
-            let mut string_contents = String::new();
-
-            for content in message.content {
-                match content {
-                    MessageContent::Text(text) => {
-                        string_contents.push_str(&text);
-                    }
-                    MessageContent::Thinking { .. } => {
-                        // Thinking blocks are not included in the input token count.
-                    }
-                    MessageContent::RedactedThinking(_) => {
-                        // Thinking blocks are not included in the input token count.
-                    }
-                    MessageContent::Image(image) => {
-                        tokens_from_images += image.estimate_tokens();
-                    }
-                    MessageContent::ToolUse(_tool_use) => {
-                        // TODO: Estimate token usage from tool uses.
-                    }
-                    MessageContent::ToolResult(tool_result) => match &tool_result.content {
-                        LanguageModelToolResultContent::Text(text) => {
-                            string_contents.push_str(text);
+    model: String,
+    mode: AnthropicModelMode,
+) -> CountTokensRequest {
+    let mut new_messages: Vec<anthropic::Message> = Vec::new();
+    let mut system_message = String::new();
+
+    for message in request.messages {
+        if message.contents_empty() {
+            continue;
+        }
+
+        match message.role {
+            Role::User | Role::Assistant => {
+                let anthropic_message_content: Vec<anthropic::RequestContent> = message
+                    .content
+                    .into_iter()
+                    .filter_map(|content| match content {
+                        MessageContent::Text(text) => {
+                            let text = if text.chars().last().is_some_and(|c| c.is_whitespace()) {
+                                text.trim_end().to_string()
+                            } else {
+                                text
+                            };
+                            if !text.is_empty() {
+                                Some(anthropic::RequestContent::Text {
+                                    text,
+                                    cache_control: None,
+                                })
+                            } else {
+                                None
+                            }
                         }
-                        LanguageModelToolResultContent::Image(image) => {
-                            tokens_from_images += image.estimate_tokens();
+                        MessageContent::Thinking {
+                            text: thinking,
+                            signature,
+                        } => {
+                            if !thinking.is_empty() {
+                                Some(anthropic::RequestContent::Thinking {
+                                    thinking,
+                                    signature: signature.unwrap_or_default(),
+                                    cache_control: None,
+                                })
+                            } else {
+                                None
+                            }
+                        }
+                        MessageContent::RedactedThinking(data) => {
+                            if !data.is_empty() {
+                                Some(anthropic::RequestContent::RedactedThinking { data })
+                            } else {
+                                None
+                            }
+                        }
+                        MessageContent::Image(image) => Some(anthropic::RequestContent::Image {
+                            source: anthropic::ImageSource {
+                                source_type: "base64".to_string(),
+                                media_type: "image/png".to_string(),
+                                data: image.source.to_string(),
+                            },
+                            cache_control: None,
+                        }),
+                        MessageContent::ToolUse(tool_use) => {
+                            Some(anthropic::RequestContent::ToolUse {
+                                id: tool_use.id.to_string(),
+                                name: tool_use.name.to_string(),
+                                input: tool_use.input,
+                                cache_control: None,
+                            })
                         }
-                    },
+                        MessageContent::ToolResult(tool_result) => {
+                            Some(anthropic::RequestContent::ToolResult {
+                                tool_use_id: tool_result.tool_use_id.to_string(),
+                                is_error: tool_result.is_error,
+                                content: match tool_result.content {
+                                    LanguageModelToolResultContent::Text(text) => {
+                                        ToolResultContent::Plain(text.to_string())
+                                    }
+                                    LanguageModelToolResultContent::Image(image) => {
+                                        ToolResultContent::Multipart(vec![ToolResultPart::Image {
+                                            source: anthropic::ImageSource {
+                                                source_type: "base64".to_string(),
+                                                media_type: "image/png".to_string(),
+                                                data: image.source.to_string(),
+                                            },
+                                        }])
+                                    }
+                                },
+                                cache_control: None,
+                            })
+                        }
+                    })
+                    .collect();
+                let anthropic_role = match message.role {
+                    Role::User => anthropic::Role::User,
+                    Role::Assistant => anthropic::Role::Assistant,
+                    Role::System => unreachable!("System role should never occur here"),
+                };
+                if let Some(last_message) = new_messages.last_mut()
+                    && last_message.role == anthropic_role
+                {
+                    last_message.content.extend(anthropic_message_content);
+                    continue;
                 }
-            }
 
-            if !string_contents.is_empty() {
-                string_messages.push(tiktoken_rs::ChatCompletionRequestMessage {
-                    role: match message.role {
-                        Role::User => "user".into(),
-                        Role::Assistant => "assistant".into(),
-                        Role::System => "system".into(),
-                    },
-                    content: Some(string_contents),
-                    name: None,
-                    function_call: None,
+                new_messages.push(anthropic::Message {
+                    role: anthropic_role,
+                    content: anthropic_message_content,
                 });
             }
+            Role::System => {
+                if !system_message.is_empty() {
+                    system_message.push_str("\n\n");
+                }
+                system_message.push_str(&message.string_contents());
+            }
+        }
+    }
+
+    CountTokensRequest {
+        model,
+        messages: new_messages,
+        system: if system_message.is_empty() {
+            None
+        } else {
+            Some(anthropic::StringOrContents::String(system_message))
+        },
+        thinking: if request.thinking_allowed
+            && let AnthropicModelMode::Thinking { budget_tokens } = mode
+        {
+            Some(anthropic::Thinking::Enabled { budget_tokens })
+        } else {
+            None
+        },
+        tools: request
+            .tools
+            .into_iter()
+            .map(|tool| anthropic::Tool {
+                name: tool.name,
+                description: tool.description,
+                input_schema: tool.input_schema,
+            })
+            .collect(),
+        tool_choice: request.tool_choice.map(|choice| match choice {
+            LanguageModelToolChoice::Auto => anthropic::ToolChoice::Auto,
+            LanguageModelToolChoice::Any => anthropic::ToolChoice::Any,
+            LanguageModelToolChoice::None => anthropic::ToolChoice::None,
+        }),
+    }
+}
+
+/// Estimate tokens using tiktoken. Used as a fallback when the API is unavailable,
+/// or by providers (like Zed Cloud) that don't have direct Anthropic API access.
+pub fn count_anthropic_tokens_with_tiktoken(request: LanguageModelRequest) -> Result<u64> {
+    let messages = request.messages;
+    let mut tokens_from_images = 0;
+    let mut string_messages = Vec::with_capacity(messages.len());
+
+    for message in messages {
+        let mut string_contents = String::new();
+
+        for content in message.content {
+            match content {
+                MessageContent::Text(text) => {
+                    string_contents.push_str(&text);
+                }
+                MessageContent::Thinking { .. } => {
+                    // Thinking blocks are not included in the input token count.
+                }
+                MessageContent::RedactedThinking(_) => {
+                    // Thinking blocks are not included in the input token count.
+                }
+                MessageContent::Image(image) => {
+                    tokens_from_images += image.estimate_tokens();
+                }
+                MessageContent::ToolUse(_tool_use) => {
+                    // TODO: Estimate token usage from tool uses.
+                }
+                MessageContent::ToolResult(tool_result) => match &tool_result.content {
+                    LanguageModelToolResultContent::Text(text) => {
+                        string_contents.push_str(text);
+                    }
+                    LanguageModelToolResultContent::Image(image) => {
+                        tokens_from_images += image.estimate_tokens();
+                    }
+                },
+            }
         }
 
-        // Tiktoken doesn't yet support these models, so we manually use the
-        // same tokenizer as GPT-4.
-        tiktoken_rs::num_tokens_from_messages("gpt-4", &string_messages)
-            .map(|tokens| (tokens + tokens_from_images) as u64)
-    })
-    .boxed()
+        if !string_contents.is_empty() {
+            string_messages.push(tiktoken_rs::ChatCompletionRequestMessage {
+                role: match message.role {
+                    Role::User => "user".into(),
+                    Role::Assistant => "assistant".into(),
+                    Role::System => "system".into(),
+                },
+                content: Some(string_contents),
+                name: None,
+                function_call: None,
+            });
+        }
+    }
+
+    // Tiktoken doesn't yet support these models, so we manually use the
+    // same tokenizer as GPT-4.
+    tiktoken_rs::num_tokens_from_messages("gpt-4", &string_messages)
+        .map(|tokens| (tokens + tokens_from_images) as u64)
 }
 
 impl AnthropicModel {
@@ -362,6 +497,10 @@ impl LanguageModel for AnthropicModel {
         true
     }
 
+    fn supports_streaming_tools(&self) -> bool {
+        true
+    }
+
     fn supports_tool_choice(&self, choice: LanguageModelToolChoice) -> bool {
         match choice {
             LanguageModelToolChoice::Auto
@@ -394,7 +533,40 @@ impl LanguageModel for AnthropicModel {
         request: LanguageModelRequest,
         cx: &App,
     ) -> BoxFuture<'static, Result<u64>> {
-        count_anthropic_tokens(request, cx)
+        let http_client = self.http_client.clone();
+        let model_id = self.model.request_id().to_string();
+        let mode = self.model.mode();
+
+        let (api_key, api_url) = self.state.read_with(cx, |state, cx| {
+            let api_url = AnthropicLanguageModelProvider::api_url(cx);
+            (
+                state.api_key_state.key(&api_url).map(|k| k.to_string()),
+                api_url.to_string(),
+            )
+        });
+
+        async move {
+            // If no API key, fall back to tiktoken estimation
+            let Some(api_key) = api_key else {
+                return count_anthropic_tokens_with_tiktoken(request);
+            };
+
+            let count_request =
+                into_anthropic_count_tokens_request(request.clone(), model_id, mode);
+
+            match anthropic::count_tokens(http_client.as_ref(), &api_url, &api_key, count_request)
+                .await
+            {
+                Ok(response) => Ok(response.input_tokens),
+                Err(err) => {
+                    log::error!(
+                        "Anthropic count_tokens API failed, falling back to tiktoken: {err:?}"
+                    );
+                    count_anthropic_tokens_with_tiktoken(request)
+                }
+            }
+        }
+        .boxed()
     }
 
     fn stream_completion(
@@ -937,14 +1109,12 @@ impl Render for ConfigurationView {
                 .child(
                     List::new()
                         .child(
-                            InstructionListItem::new(
-                                "Create one by visiting",
-                                Some("Anthropic's settings"),
-                                Some("https://console.anthropic.com/settings/keys")
-                            )
+                            ListBulletItem::new("")
+                                .child(Label::new("Create one by visiting"))
+                                .child(ButtonLink::new("Anthropic's settings", "https://console.anthropic.com/settings/keys"))
                         )
                         .child(
-                            InstructionListItem::text_only("Paste your API key below and hit enter to start using the agent")
+                            ListBulletItem::new("Paste your API key below and hit enter to start using the agent")
                         )
                 )
                 .child(self.api_key_editor.clone())
@@ -953,7 +1123,8 @@ impl Render for ConfigurationView {
                         format!("You can also assign the {API_KEY_ENV_VAR_NAME} environment variable and restart Zed."),
                     )
                     .size(LabelSize::Small)
-                    .color(Color::Muted),
+                    .color(Color::Muted)
+                    .mt_0p5(),
                 )
                 .into_any_element()
         } else {

crates/language_models/src/provider/bedrock.rs 🔗

@@ -2,11 +2,10 @@ use std::pin::Pin;
 use std::str::FromStr;
 use std::sync::Arc;
 
-use crate::ui::{ConfiguredApiCard, InstructionListItem};
 use anyhow::{Context as _, Result, anyhow};
 use aws_config::stalled_stream_protection::StalledStreamProtectionConfig;
 use aws_config::{BehaviorVersion, Region};
-use aws_credential_types::Credentials;
+use aws_credential_types::{Credentials, Token};
 use aws_http_client::AwsHttpClient;
 use bedrock::bedrock_client::Client as BedrockClient;
 use bedrock::bedrock_client::config::timeout::TimeoutConfig;
@@ -31,20 +30,21 @@ use gpui::{
 use gpui_tokio::Tokio;
 use http_client::HttpClient;
 use language_model::{
-    AuthenticateError, LanguageModel, LanguageModelCacheConfiguration,
+    AuthenticateError, EnvVar, IconOrSvg, LanguageModel, LanguageModelCacheConfiguration,
     LanguageModelCompletionError, LanguageModelCompletionEvent, LanguageModelId, LanguageModelName,
     LanguageModelProvider, LanguageModelProviderId, LanguageModelProviderName,
     LanguageModelProviderState, LanguageModelRequest, LanguageModelToolChoice,
     LanguageModelToolResultContent, LanguageModelToolUse, MessageContent, RateLimiter, Role,
-    TokenUsage,
+    TokenUsage, env_var,
 };
 use schemars::JsonSchema;
 use serde::{Deserialize, Serialize};
 use serde_json::Value;
 use settings::{BedrockAvailableModel as AvailableModel, Settings, SettingsStore};
 use smol::lock::OnceCell;
+use std::sync::LazyLock;
 use strum::{EnumIter, IntoEnumIterator, IntoStaticStr};
-use ui::{List, prelude::*};
+use ui::{ButtonLink, ConfiguredApiCard, List, ListBulletItem, prelude::*};
 use ui_input::InputField;
 use util::ResultExt;
 
@@ -55,12 +55,52 @@ actions!(bedrock, [Tab, TabPrev]);
 const PROVIDER_ID: LanguageModelProviderId = LanguageModelProviderId::new("amazon-bedrock");
 const PROVIDER_NAME: LanguageModelProviderName = LanguageModelProviderName::new("Amazon Bedrock");
 
+/// Credentials stored in the keychain for static authentication.
+/// Region is handled separately since it's orthogonal to auth method.
 #[derive(Default, Clone, Deserialize, Serialize, PartialEq, Debug)]
 pub struct BedrockCredentials {
     pub access_key_id: String,
     pub secret_access_key: String,
     pub session_token: Option<String>,
-    pub region: String,
+    pub bearer_token: Option<String>,
+}
+
+/// Resolved authentication configuration for Bedrock.
+/// Settings take priority over UX-provided credentials.
+#[derive(Clone, Debug, PartialEq)]
+pub enum BedrockAuth {
+    /// Use default AWS credential provider chain (IMDSv2, PodIdentity, env vars, etc.)
+    Automatic,
+    /// Use AWS named profile from ~/.aws/credentials or ~/.aws/config
+    NamedProfile { profile_name: String },
+    /// Use AWS SSO profile
+    SingleSignOn { profile_name: String },
+    /// Use IAM credentials (access key + secret + optional session token)
+    IamCredentials {
+        access_key_id: String,
+        secret_access_key: String,
+        session_token: Option<String>,
+    },
+    /// Use Bedrock API Key (bearer token authentication)
+    ApiKey { api_key: String },
+}
+
+impl BedrockCredentials {
+    /// Convert stored credentials to the appropriate auth variant.
+    /// Prefers API key if present, otherwise uses IAM credentials.
+    fn into_auth(self) -> Option<BedrockAuth> {
+        if let Some(api_key) = self.bearer_token.filter(|t| !t.is_empty()) {
+            Some(BedrockAuth::ApiKey { api_key })
+        } else if !self.access_key_id.is_empty() && !self.secret_access_key.is_empty() {
+            Some(BedrockAuth::IamCredentials {
+                access_key_id: self.access_key_id,
+                secret_access_key: self.secret_access_key,
+                session_token: self.session_token.filter(|t| !t.is_empty()),
+            })
+        } else {
+            None
+        }
+    }
 }
 
 #[derive(Default, Clone, Debug, PartialEq)]
@@ -71,6 +111,7 @@ pub struct AmazonBedrockSettings {
     pub profile_name: Option<String>,
     pub role_arn: Option<String>,
     pub authentication_method: Option<BedrockAuthMethod>,
+    pub allow_global: Option<bool>,
 }
 
 #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, EnumIter, IntoStaticStr, JsonSchema)]
@@ -79,6 +120,8 @@ pub enum BedrockAuthMethod {
     NamedProfile,
     #[serde(rename = "sso")]
     SingleSignOn,
+    #[serde(rename = "api_key")]
+    ApiKey,
     /// IMDSv2, PodIdentity, env vars, etc.
     #[serde(rename = "default")]
     Automatic,
@@ -90,6 +133,7 @@ impl From<settings::BedrockAuthMethodContent> for BedrockAuthMethod {
             settings::BedrockAuthMethodContent::SingleSignOn => BedrockAuthMethod::SingleSignOn,
             settings::BedrockAuthMethodContent::Automatic => BedrockAuthMethod::Automatic,
             settings::BedrockAuthMethodContent::NamedProfile => BedrockAuthMethod::NamedProfile,
+            settings::BedrockAuthMethodContent::ApiKey => BedrockAuthMethod::ApiKey,
         }
     }
 }
@@ -130,23 +174,26 @@ impl From<BedrockModelMode> for ModelMode {
 const AMAZON_AWS_URL: &str = "https://amazonaws.com";
 
 // These environment variables all use a `ZED_` prefix because we don't want to overwrite the user's AWS credentials.
-const ZED_BEDROCK_ACCESS_KEY_ID_VAR: &str = "ZED_ACCESS_KEY_ID";
-const ZED_BEDROCK_SECRET_ACCESS_KEY_VAR: &str = "ZED_SECRET_ACCESS_KEY";
-const ZED_BEDROCK_SESSION_TOKEN_VAR: &str = "ZED_SESSION_TOKEN";
-const ZED_AWS_PROFILE_VAR: &str = "ZED_AWS_PROFILE";
-const ZED_BEDROCK_REGION_VAR: &str = "ZED_AWS_REGION";
-const ZED_AWS_CREDENTIALS_VAR: &str = "ZED_AWS_CREDENTIALS";
-const ZED_AWS_ENDPOINT_VAR: &str = "ZED_AWS_ENDPOINT";
+static ZED_BEDROCK_ACCESS_KEY_ID_VAR: LazyLock<EnvVar> = env_var!("ZED_ACCESS_KEY_ID");
+static ZED_BEDROCK_SECRET_ACCESS_KEY_VAR: LazyLock<EnvVar> = env_var!("ZED_SECRET_ACCESS_KEY");
+static ZED_BEDROCK_SESSION_TOKEN_VAR: LazyLock<EnvVar> = env_var!("ZED_SESSION_TOKEN");
+static ZED_AWS_PROFILE_VAR: LazyLock<EnvVar> = env_var!("ZED_AWS_PROFILE");
+static ZED_BEDROCK_REGION_VAR: LazyLock<EnvVar> = env_var!("ZED_AWS_REGION");
+static ZED_AWS_ENDPOINT_VAR: LazyLock<EnvVar> = env_var!("ZED_AWS_ENDPOINT");
+static ZED_BEDROCK_BEARER_TOKEN_VAR: LazyLock<EnvVar> = env_var!("ZED_BEDROCK_BEARER_TOKEN");
 
 pub struct State {
-    credentials: Option<BedrockCredentials>,
+    /// The resolved authentication method. Settings take priority over UX credentials.
+    auth: Option<BedrockAuth>,
+    /// Raw settings from settings.json
     settings: Option<AmazonBedrockSettings>,
+    /// Whether credentials came from environment variables (only relevant for static credentials)
     credentials_from_env: bool,
     _subscription: Subscription,
 }
 
 impl State {
-    fn reset_credentials(&self, cx: &mut Context<Self>) -> Task<Result<()>> {
+    fn reset_auth(&self, cx: &mut Context<Self>) -> Task<Result<()>> {
         let credentials_provider = <dyn CredentialsProvider>::global(cx);
         cx.spawn(async move |this, cx| {
             credentials_provider
@@ -154,19 +201,19 @@ impl State {
                 .await
                 .log_err();
             this.update(cx, |this, cx| {
-                this.credentials = None;
+                this.auth = None;
                 this.credentials_from_env = false;
-                this.settings = None;
                 cx.notify();
             })
         })
     }
 
-    fn set_credentials(
+    fn set_static_credentials(
         &mut self,
         credentials: BedrockCredentials,
         cx: &mut Context<Self>,
     ) -> Task<Result<()>> {
+        let auth = credentials.clone().into_auth();
         let credentials_provider = <dyn CredentialsProvider>::global(cx);
         cx.spawn(async move |this, cx| {
             credentials_provider
@@ -178,50 +225,131 @@ impl State {
                 )
                 .await?;
             this.update(cx, |this, cx| {
-                this.credentials = Some(credentials);
+                this.auth = auth;
+                this.credentials_from_env = false;
                 cx.notify();
             })
         })
     }
 
     fn is_authenticated(&self) -> bool {
-        let derived = self
-            .settings
-            .as_ref()
-            .and_then(|s| s.authentication_method.as_ref());
-        let creds = self.credentials.as_ref();
-
-        derived.is_some() || creds.is_some()
+        self.auth.is_some()
     }
 
+    /// Resolve authentication. Settings take priority over UX-provided credentials.
     fn authenticate(&self, cx: &mut Context<Self>) -> Task<Result<(), AuthenticateError>> {
         if self.is_authenticated() {
             return Task::ready(Ok(()));
         }
 
+        // Step 1: Check if settings specify an auth method (enterprise control)
+        if let Some(settings) = &self.settings {
+            if let Some(method) = &settings.authentication_method {
+                let profile_name = settings
+                    .profile_name
+                    .clone()
+                    .unwrap_or_else(|| "default".to_string());
+
+                let auth = match method {
+                    BedrockAuthMethod::Automatic => BedrockAuth::Automatic,
+                    BedrockAuthMethod::NamedProfile => BedrockAuth::NamedProfile { profile_name },
+                    BedrockAuthMethod::SingleSignOn => BedrockAuth::SingleSignOn { profile_name },
+                    BedrockAuthMethod::ApiKey => {
+                        // ApiKey method means "use static credentials from keychain/env"
+                        // Fall through to load them below
+                        return self.load_static_credentials(cx);
+                    }
+                };
+
+                return cx.spawn(async move |this, cx| {
+                    this.update(cx, |this, cx| {
+                        this.auth = Some(auth);
+                        this.credentials_from_env = false;
+                        cx.notify();
+                    })?;
+                    Ok(())
+                });
+            }
+        }
+
+        // Step 2: No settings auth method - try to load static credentials
+        self.load_static_credentials(cx)
+    }
+
+    /// Load static credentials from environment variables or keychain.
+    fn load_static_credentials(
+        &self,
+        cx: &mut Context<Self>,
+    ) -> Task<Result<(), AuthenticateError>> {
         let credentials_provider = <dyn CredentialsProvider>::global(cx);
         cx.spawn(async move |this, cx| {
-            let (credentials, from_env) =
-                if let Ok(credentials) = std::env::var(ZED_AWS_CREDENTIALS_VAR) {
-                    (credentials, true)
-                } else {
-                    let (_, credentials) = credentials_provider
-                        .read_credentials(AMAZON_AWS_URL, cx)
-                        .await?
-                        .ok_or_else(|| AuthenticateError::CredentialsNotFound)?;
+            // Try environment variables first
+            let (auth, from_env) = if let Some(bearer_token) = &ZED_BEDROCK_BEARER_TOKEN_VAR.value {
+                if !bearer_token.is_empty() {
                     (
-                        String::from_utf8(credentials)
-                            .context("invalid {PROVIDER_NAME} credentials")?,
-                        false,
+                        Some(BedrockAuth::ApiKey {
+                            api_key: bearer_token.to_string(),
+                        }),
+                        true,
                     )
-                };
+                } else {
+                    (None, false)
+                }
+            } else if let Some(access_key_id) = &ZED_BEDROCK_ACCESS_KEY_ID_VAR.value {
+                if let Some(secret_access_key) = &ZED_BEDROCK_SECRET_ACCESS_KEY_VAR.value {
+                    if !access_key_id.is_empty() && !secret_access_key.is_empty() {
+                        let session_token = ZED_BEDROCK_SESSION_TOKEN_VAR
+                            .value
+                            .as_deref()
+                            .filter(|s| !s.is_empty())
+                            .map(|s| s.to_string());
+                        (
+                            Some(BedrockAuth::IamCredentials {
+                                access_key_id: access_key_id.to_string(),
+                                secret_access_key: secret_access_key.to_string(),
+                                session_token,
+                            }),
+                            true,
+                        )
+                    } else {
+                        (None, false)
+                    }
+                } else {
+                    (None, false)
+                }
+            } else {
+                (None, false)
+            };
+
+            // If we got auth from env vars, use it
+            if let Some(auth) = auth {
+                this.update(cx, |this, cx| {
+                    this.auth = Some(auth);
+                    this.credentials_from_env = from_env;
+                    cx.notify();
+                })?;
+                return Ok(());
+            }
+
+            // Try keychain
+            let (_, credentials_bytes) = credentials_provider
+                .read_credentials(AMAZON_AWS_URL, cx)
+                .await?
+                .ok_or(AuthenticateError::CredentialsNotFound)?;
+
+            let credentials_str = String::from_utf8(credentials_bytes)
+                .context("invalid {PROVIDER_NAME} credentials")?;
 
             let credentials: BedrockCredentials =
-                serde_json::from_str(&credentials).context("failed to parse credentials")?;
+                serde_json::from_str(&credentials_str).context("failed to parse credentials")?;
+
+            let auth = credentials
+                .into_auth()
+                .ok_or(AuthenticateError::CredentialsNotFound)?;
 
             this.update(cx, |this, cx| {
-                this.credentials = Some(credentials);
-                this.credentials_from_env = from_env;
+                this.auth = Some(auth);
+                this.credentials_from_env = false;
                 cx.notify();
             })?;
 
@@ -229,15 +357,26 @@ impl State {
         })
     }
 
+    /// Get the resolved region. Checks env var, then settings, then defaults to us-east-1.
     fn get_region(&self) -> String {
-        // Get region - from credentials or directly from settings
-        let credentials_region = self.credentials.as_ref().map(|s| s.region.clone());
-        let settings_region = self.settings.as_ref().and_then(|s| s.region.clone());
-
-        // Use credentials region if available, otherwise use settings region, finally fall back to default
-        credentials_region
-            .or(settings_region)
-            .unwrap_or(String::from("us-east-1"))
+        // Priority: env var > settings > default
+        if let Some(region) = ZED_BEDROCK_REGION_VAR.value.as_deref() {
+            if !region.is_empty() {
+                return region.to_string();
+            }
+        }
+
+        self.settings
+            .as_ref()
+            .and_then(|s| s.region.clone())
+            .unwrap_or_else(|| "us-east-1".to_string())
+    }
+
+    fn get_allow_global(&self) -> bool {
+        self.settings
+            .as_ref()
+            .and_then(|s| s.allow_global)
+            .unwrap_or(false)
     }
 }
 
@@ -250,7 +389,7 @@ pub struct BedrockLanguageModelProvider {
 impl BedrockLanguageModelProvider {
     pub fn new(http_client: Arc<dyn HttpClient>, cx: &mut App) -> Self {
         let state = cx.new(|cx| State {
-            credentials: None,
+            auth: None,
             settings: Some(AllLanguageModelSettings::get_global(cx).bedrock.clone()),
             credentials_from_env: false,
             _subscription: cx.observe_global::<SettingsStore>(|_, cx| {
@@ -259,7 +398,7 @@ impl BedrockLanguageModelProvider {
         });
 
         Self {
-            http_client: AwsHttpClient::new(http_client.clone()),
+            http_client: AwsHttpClient::new(http_client),
             handle: Tokio::handle(cx),
             state,
         }
@@ -287,8 +426,8 @@ impl LanguageModelProvider for BedrockLanguageModelProvider {
         PROVIDER_NAME
     }
 
-    fn icon(&self) -> IconName {
-        IconName::AiBedrock
+    fn icon(&self) -> IconOrSvg {
+        IconOrSvg::Icon(IconName::AiBedrock)
     }
 
     fn default_model(&self, _cx: &App) -> Option<Arc<dyn LanguageModel>> {
@@ -305,7 +444,6 @@ impl LanguageModelProvider for BedrockLanguageModelProvider {
 
         for model in bedrock::Model::iter() {
             if !matches!(model, bedrock::Model::Custom { .. }) {
-                // TODO: Sonnet 3.7 vs. 3.7 Thinking bug is here.
                 models.insert(model.id().to_string(), model);
             }
         }
@@ -359,8 +497,7 @@ impl LanguageModelProvider for BedrockLanguageModelProvider {
     }
 
     fn reset_credentials(&self, cx: &mut App) -> Task<Result<()>> {
-        self.state
-            .update(cx, |state, cx| state.reset_credentials(cx))
+        self.state.update(cx, |state, cx| state.reset_auth(cx))
     }
 }
 
@@ -386,25 +523,11 @@ impl BedrockModel {
     fn get_or_init_client(&self, cx: &AsyncApp) -> anyhow::Result<&BedrockClient> {
         self.client
             .get_or_try_init_blocking(|| {
-                let (auth_method, credentials, endpoint, region, settings) =
-                    cx.read_entity(&self.state, |state, _cx| {
-                        let auth_method = state
-                            .settings
-                            .as_ref()
-                            .and_then(|s| s.authentication_method.clone());
-
-                        let endpoint = state.settings.as_ref().and_then(|s| s.endpoint.clone());
-
-                        let region = state.get_region();
-
-                        (
-                            auth_method,
-                            state.credentials.clone(),
-                            endpoint,
-                            region,
-                            state.settings.clone(),
-                        )
-                    })?;
+                let (auth, endpoint, region) = cx.read_entity(&self.state, |state, _cx| {
+                    let endpoint = state.settings.as_ref().and_then(|s| s.endpoint.clone());
+                    let region = state.get_region();
+                    (state.auth.clone(), endpoint, region)
+                })?;
 
                 let mut config_builder = aws_config::defaults(BehaviorVersion::latest())
                     .stalled_stream_protection(StalledStreamProtectionConfig::disabled())
@@ -418,37 +541,39 @@ impl BedrockModel {
                     config_builder = config_builder.endpoint_url(endpoint_url);
                 }
 
-                match auth_method {
-                    None => {
-                        if let Some(creds) = credentials {
-                            let aws_creds = Credentials::new(
-                                creds.access_key_id,
-                                creds.secret_access_key,
-                                creds.session_token,
-                                None,
-                                "zed-bedrock-provider",
-                            );
-                            config_builder = config_builder.credentials_provider(aws_creds);
-                        }
+                match auth {
+                    Some(BedrockAuth::Automatic) | None => {
+                        // Use default AWS credential provider chain
                     }
-                    Some(BedrockAuthMethod::NamedProfile)
-                    | Some(BedrockAuthMethod::SingleSignOn) => {
-                        // Currently NamedProfile and SSO behave the same way but only the instructions change
-                        // Until we support BearerAuth through SSO, this will not change.
-                        let profile_name = settings
-                            .and_then(|s| s.profile_name)
-                            .unwrap_or_else(|| "default".to_string());
-
+                    Some(BedrockAuth::NamedProfile { profile_name })
+                    | Some(BedrockAuth::SingleSignOn { profile_name }) => {
                         if !profile_name.is_empty() {
                             config_builder = config_builder.profile_name(profile_name);
                         }
                     }
-                    Some(BedrockAuthMethod::Automatic) => {
-                        // Use default credential provider chain
+                    Some(BedrockAuth::IamCredentials {
+                        access_key_id,
+                        secret_access_key,
+                        session_token,
+                    }) => {
+                        let aws_creds = Credentials::new(
+                            access_key_id,
+                            secret_access_key,
+                            session_token,
+                            None,
+                            "zed-bedrock-provider",
+                        );
+                        config_builder = config_builder.credentials_provider(aws_creds);
+                    }
+                    Some(BedrockAuth::ApiKey { api_key }) => {
+                        config_builder = config_builder
+                            .auth_scheme_preference(["httpBearerAuth".into()]) // https://github.com/smithy-lang/smithy-rs/pull/4241
+                            .token_provider(Token::new(api_key, None));
                     }
                 }
 
                 let config = self.handle.block_on(config_builder.load());
+
                 anyhow::Ok(BedrockClient::new(&config))
             })
             .context("initializing Bedrock client")?;
@@ -545,11 +670,13 @@ impl LanguageModel for BedrockModel {
             LanguageModelCompletionError,
         >,
     > {
-        let Ok(region) = cx.read_entity(&self.state, |state, _cx| state.get_region()) else {
+        let Ok((region, allow_global)) = cx.read_entity(&self.state, |state, _cx| {
+            (state.get_region(), state.get_allow_global())
+        }) else {
             return async move { Err(anyhow::anyhow!("App State Dropped").into()) }.boxed();
         };
 
-        let model_id = match self.model.cross_region_inference_id(&region) {
+        let model_id = match self.model.cross_region_inference_id(&region, allow_global) {
             Ok(s) => s,
             Err(e) => {
                 return async move { Err(e.into()) }.boxed();
@@ -1015,7 +1142,7 @@ struct ConfigurationView {
     access_key_id_editor: Entity<InputField>,
     secret_access_key_editor: Entity<InputField>,
     session_token_editor: Entity<InputField>,
-    region_editor: Entity<InputField>,
+    bearer_token_editor: Entity<InputField>,
     state: Entity<State>,
     load_credentials_task: Option<Task<()>>,
     focus_handle: FocusHandle,
@@ -1026,7 +1153,7 @@ impl ConfigurationView {
     const PLACEHOLDER_SECRET_ACCESS_KEY_TEXT: &'static str =
         "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
     const PLACEHOLDER_SESSION_TOKEN_TEXT: &'static str = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
-    const PLACEHOLDER_REGION: &'static str = "us-east-1";
+    const PLACEHOLDER_BEARER_TOKEN_TEXT: &'static str = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
 
     fn new(state: Entity<State>, window: &mut Window, cx: &mut Context<Self>) -> Self {
         let focus_handle = cx.focus_handle();
@@ -1057,9 +1184,9 @@ impl ConfigurationView {
                 .tab_stop(true)
         });
 
-        let region_editor = cx.new(|cx| {
-            InputField::new(window, cx, Self::PLACEHOLDER_REGION)
-                .label("Region")
+        let bearer_token_editor = cx.new(|cx| {
+            InputField::new(window, cx, Self::PLACEHOLDER_BEARER_TOKEN_TEXT)
+                .label("Bedrock API Key")
                 .tab_index(3)
                 .tab_stop(true)
         });
@@ -1086,7 +1213,7 @@ impl ConfigurationView {
             access_key_id_editor,
             secret_access_key_editor,
             session_token_editor,
-            region_editor,
+            bearer_token_editor,
             state,
             load_credentials_task,
             focus_handle,
@@ -1122,25 +1249,30 @@ impl ConfigurationView {
         } else {
             Some(session_token)
         };
-        let region = self.region_editor.read(cx).text(cx).trim().to_string();
-        let region = if region.is_empty() {
-            "us-east-1".to_string()
+        let bearer_token = self
+            .bearer_token_editor
+            .read(cx)
+            .text(cx)
+            .trim()
+            .to_string();
+        let bearer_token = if bearer_token.is_empty() {
+            None
         } else {
-            region
+            Some(bearer_token)
         };
 
         let state = self.state.clone();
         cx.spawn(async move |_, cx| {
             state
                 .update(cx, |state, cx| {
-                    let credentials: BedrockCredentials = BedrockCredentials {
-                        region: region.clone(),
-                        access_key_id: access_key_id.clone(),
-                        secret_access_key: secret_access_key.clone(),
-                        session_token: session_token.clone(),
+                    let credentials = BedrockCredentials {
+                        access_key_id,
+                        secret_access_key,
+                        session_token,
+                        bearer_token,
                     };
 
-                    state.set_credentials(credentials, cx)
+                    state.set_static_credentials(credentials, cx)
                 })?
                 .await
         })
@@ -1154,41 +1286,39 @@ impl ConfigurationView {
             .update(cx, |editor, cx| editor.set_text("", window, cx));
         self.session_token_editor
             .update(cx, |editor, cx| editor.set_text("", window, cx));
-        self.region_editor
+        self.bearer_token_editor
             .update(cx, |editor, cx| editor.set_text("", window, cx));
 
         let state = self.state.clone();
-        cx.spawn(async move |_, cx| {
-            state
-                .update(cx, |state, cx| state.reset_credentials(cx))?
-                .await
-        })
-        .detach_and_log_err(cx);
+        cx.spawn(async move |_, cx| state.update(cx, |state, cx| state.reset_auth(cx))?.await)
+            .detach_and_log_err(cx);
     }
 
     fn should_render_editor(&self, cx: &Context<Self>) -> bool {
         self.state.read(cx).is_authenticated()
     }
 
-    fn on_tab(&mut self, _: &menu::SelectNext, window: &mut Window, _: &mut Context<Self>) {
-        window.focus_next();
+    fn on_tab(&mut self, _: &menu::SelectNext, window: &mut Window, cx: &mut Context<Self>) {
+        window.focus_next(cx);
     }
 
     fn on_tab_prev(
         &mut self,
         _: &menu::SelectPrevious,
         window: &mut Window,
-        _: &mut Context<Self>,
+        cx: &mut Context<Self>,
     ) {
-        window.focus_prev();
+        window.focus_prev(cx);
     }
 }
 
 impl Render for ConfigurationView {
     fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
-        let env_var_set = self.state.read(cx).credentials_from_env;
-        let bedrock_settings = self.state.read(cx).settings.as_ref();
-        let bedrock_method = bedrock_settings
+        let state = self.state.read(cx);
+        let env_var_set = state.credentials_from_env;
+        let auth = state.auth.clone();
+        let settings_auth_method = state
+            .settings
             .as_ref()
             .and_then(|s| s.authentication_method.clone());
 
@@ -1196,34 +1326,62 @@ impl Render for ConfigurationView {
             return div().child(Label::new("Loading credentials...")).into_any();
         }
 
-        let configured_label = if env_var_set {
-            format!(
-                "Access Key ID is set in {ZED_BEDROCK_ACCESS_KEY_ID_VAR}, Secret Key is set in {ZED_BEDROCK_SECRET_ACCESS_KEY_VAR}, Region is set in {ZED_BEDROCK_REGION_VAR} environment variables."
-            )
-        } else {
-            match bedrock_method {
-                Some(BedrockAuthMethod::Automatic) => "You are using automatic credentials.".into(),
-                Some(BedrockAuthMethod::NamedProfile) => "You are using named profile.".into(),
-                Some(BedrockAuthMethod::SingleSignOn) => {
-                    "You are using a single sign on profile.".into()
-                }
-                None => "You are using static credentials.".into(),
+        let configured_label = match &auth {
+            Some(BedrockAuth::Automatic) => {
+                "Using automatic credentials (AWS default chain)".into()
+            }
+            Some(BedrockAuth::NamedProfile { profile_name }) => {
+                format!("Using AWS profile: {profile_name}")
             }
+            Some(BedrockAuth::SingleSignOn { profile_name }) => {
+                format!("Using AWS SSO profile: {profile_name}")
+            }
+            Some(BedrockAuth::IamCredentials { .. }) if env_var_set => {
+                format!(
+                    "Using IAM credentials from {} and {} environment variables",
+                    ZED_BEDROCK_ACCESS_KEY_ID_VAR.name, ZED_BEDROCK_SECRET_ACCESS_KEY_VAR.name
+                )
+            }
+            Some(BedrockAuth::IamCredentials { .. }) => "Using IAM credentials".into(),
+            Some(BedrockAuth::ApiKey { .. }) if env_var_set => {
+                format!(
+                    "Using Bedrock API Key from {} environment variable",
+                    ZED_BEDROCK_BEARER_TOKEN_VAR.name
+                )
+            }
+            Some(BedrockAuth::ApiKey { .. }) => "Using Bedrock API Key".into(),
+            None => "Not authenticated".into(),
         };
 
+        // Determine if credentials can be reset
+        // Settings-derived auth (non-ApiKey) cannot be reset from UI
+        let is_settings_derived = matches!(
+            settings_auth_method,
+            Some(BedrockAuthMethod::Automatic)
+                | Some(BedrockAuthMethod::NamedProfile)
+                | Some(BedrockAuthMethod::SingleSignOn)
+        );
+
         let tooltip_label = if env_var_set {
             Some(format!(
-                "To reset your credentials, unset the {ZED_BEDROCK_ACCESS_KEY_ID_VAR}, {ZED_BEDROCK_SECRET_ACCESS_KEY_VAR}, and {ZED_BEDROCK_REGION_VAR} environment variables."
+                "To reset your credentials, unset the {}, {}, and {} or {} environment variables.",
+                ZED_BEDROCK_ACCESS_KEY_ID_VAR.name,
+                ZED_BEDROCK_SECRET_ACCESS_KEY_VAR.name,
+                ZED_BEDROCK_SESSION_TOKEN_VAR.name,
+                ZED_BEDROCK_BEARER_TOKEN_VAR.name
             ))
-        } else if bedrock_method.is_some() {
-            Some("You cannot reset credentials as they're being derived, check Zed settings to understand how.".to_string())
+        } else if is_settings_derived {
+            Some(
+                "Authentication method is configured in settings. Edit settings.json to change."
+                    .to_string(),
+            )
         } else {
             None
         };
 
         if self.should_render_editor(cx) {
             return ConfiguredApiCard::new(configured_label)
-                .disabled(env_var_set || bedrock_method.is_some())
+                .disabled(env_var_set || is_settings_derived)
                 .on_click(cx.listener(|this, _, window, cx| this.reset_credentials(window, cx)))
                 .when_some(tooltip_label, |this, label| this.tooltip_label(label))
                 .into_any_element();
@@ -1240,24 +1398,20 @@ impl Render for ConfigurationView {
             .child(
                 List::new()
                     .child(
-                        InstructionListItem::new(
-                            "Grant permissions to the strategy you'll use according to the:",
-                            Some("Prerequisites"),
-                            Some("https://docs.aws.amazon.com/bedrock/latest/userguide/inference-prereq.html"),
-                        )
+                        ListBulletItem::new("")
+                            .child(Label::new("Grant permissions to the strategy you'll use according to the:"))
+                            .child(ButtonLink::new("Prerequisites", "https://docs.aws.amazon.com/bedrock/latest/userguide/inference-prereq.html"))
                     )
                     .child(
-                        InstructionListItem::new(
-                            "Select the models you would like access to:",
-                            Some("Bedrock Model Catalog"),
-                            Some("https://us-east-1.console.aws.amazon.com/bedrock/home?region=us-east-1#/modelaccess"),
-                        )
+                        ListBulletItem::new("")
+                            .child(Label::new("Select the models you would like access to:"))
+                            .child(ButtonLink::new("Bedrock Model Catalog", "https://us-east-1.console.aws.amazon.com/bedrock/home?region=us-east-1#/modelaccess"))
                     )
             )
             .child(self.render_static_credentials_ui())
             .child(
                 Label::new(
-                    format!("You can also assign the {ZED_BEDROCK_ACCESS_KEY_ID_VAR}, {ZED_BEDROCK_SECRET_ACCESS_KEY_VAR} AND {ZED_BEDROCK_REGION_VAR} environment variables and restart Zed."),
+                    format!("You can also assign the {}, {} AND {} environment variables (or {} for Bedrock API Key authentication) and restart Zed.", ZED_BEDROCK_ACCESS_KEY_ID_VAR.name, ZED_BEDROCK_SECRET_ACCESS_KEY_VAR.name, ZED_BEDROCK_REGION_VAR.name, ZED_BEDROCK_BEARER_TOKEN_VAR.name),
                 )
                     .size(LabelSize::Small)
                     .color(Color::Muted)
@@ -1265,7 +1419,7 @@ impl Render for ConfigurationView {
             )
             .child(
                 Label::new(
-                    format!("Optionally, if your environment uses AWS CLI profiles, you can set {ZED_AWS_PROFILE_VAR}; if it requires a custom endpoint, you can set {ZED_AWS_ENDPOINT_VAR}; and if it requires a Session Token, you can set {ZED_BEDROCK_SESSION_TOKEN_VAR}."),
+                    format!("Optionally, if your environment uses AWS CLI profiles, you can set {}; if it requires a custom endpoint, you can set {}; and if it requires a Session Token, you can set {}.", ZED_AWS_PROFILE_VAR.name, ZED_AWS_ENDPOINT_VAR.name, ZED_BEDROCK_SESSION_TOKEN_VAR.name),
                 )
                     .size(LabelSize::Small)
                     .color(Color::Muted),
@@ -1287,31 +1441,47 @@ impl ConfigurationView {
             )
             .child(
                 Label::new(
-                    "This method uses your AWS access key ID and secret access key directly.",
+                    "This method uses your AWS access key ID and secret access key, or a Bedrock API Key.",
                 )
             )
             .child(
                 List::new()
-                    .child(InstructionListItem::new(
-                        "Create an IAM user in the AWS console with programmatic access",
-                        Some("IAM Console"),
-                        Some("https://us-east-1.console.aws.amazon.com/iam/home?region=us-east-1#/users"),
-                    ))
-                    .child(InstructionListItem::new(
-                        "Attach the necessary Bedrock permissions to this ",
-                        Some("user"),
-                        Some("https://docs.aws.amazon.com/bedrock/latest/userguide/inference-prereq.html"),
-                    ))
-                    .child(InstructionListItem::text_only(
-                        "Copy the access key ID and secret access key when provided",
-                    ))
-                    .child(InstructionListItem::text_only(
-                        "Enter these credentials below",
-                    )),
+                    .child(
+                        ListBulletItem::new("")
+                            .child(Label::new("For access keys: Create an IAM user in the AWS console with programmatic access"))
+                            .child(ButtonLink::new("IAM Console", "https://us-east-1.console.aws.amazon.com/iam/home?region=us-east-1#/users"))
+                    )
+                    .child(
+                        ListBulletItem::new("")
+                            .child(Label::new("For Bedrock API Keys: Generate an API key from the"))
+                            .child(ButtonLink::new("Bedrock Console", "https://docs.aws.amazon.com/bedrock/latest/userguide/api-keys-use.html"))
+                    )
+                    .child(
+                        ListBulletItem::new("")
+                            .child(Label::new("Attach the necessary Bedrock permissions to this"))
+                            .child(ButtonLink::new("user", "https://docs.aws.amazon.com/bedrock/latest/userguide/inference-prereq.html"))
+                    )
+                    .child(
+                        ListBulletItem::new("Enter either access keys OR a Bedrock API Key below (not both)")
+                    ),
             )
             .child(self.access_key_id_editor.clone())
             .child(self.secret_access_key_editor.clone())
             .child(self.session_token_editor.clone())
-            .child(self.region_editor.clone())
+            .child(
+                Label::new("OR")
+                    .size(LabelSize::Default)
+                    .weight(FontWeight::BOLD)
+                    .my_1(),
+            )
+            .child(self.bearer_token_editor.clone())
+            .child(
+                Label::new(
+                    format!("Region is configured via {} environment variable or settings.json (defaults to us-east-1).", ZED_BEDROCK_REGION_VAR.name),
+                )
+                    .size(LabelSize::Small)
+                    .color(Color::Muted)
+                    .mt_2(),
+            )
     }
 }

crates/language_models/src/provider/cloud.rs 🔗

@@ -19,7 +19,7 @@ use gpui::{AnyElement, AnyView, App, AsyncApp, Context, Entity, Subscription, Ta
 use http_client::http::{HeaderMap, HeaderValue};
 use http_client::{AsyncBody, HttpClient, HttpRequestExt, Method, Response, StatusCode};
 use language_model::{
-    AuthenticateError, LanguageModel, LanguageModelCacheConfiguration,
+    AuthenticateError, IconOrSvg, LanguageModel, LanguageModelCacheConfiguration,
     LanguageModelCompletionError, LanguageModelCompletionEvent, LanguageModelId, LanguageModelName,
     LanguageModelProvider, LanguageModelProviderId, LanguageModelProviderName,
     LanguageModelProviderState, LanguageModelRequest, LanguageModelToolChoice,
@@ -42,7 +42,9 @@ use thiserror::Error;
 use ui::{TintColor, prelude::*};
 use util::{ResultExt as _, maybe};
 
-use crate::provider::anthropic::{AnthropicEventMapper, count_anthropic_tokens, into_anthropic};
+use crate::provider::anthropic::{
+    AnthropicEventMapper, count_anthropic_tokens_with_tiktoken, into_anthropic,
+};
 use crate::provider::google::{GoogleEventMapper, into_google};
 use crate::provider::open_ai::{OpenAiEventMapper, count_open_ai_tokens, into_open_ai};
 use crate::provider::x_ai::count_xai_tokens;
@@ -302,8 +304,8 @@ impl LanguageModelProvider for CloudLanguageModelProvider {
         PROVIDER_NAME
     }
 
-    fn icon(&self) -> IconName {
-        IconName::AiZed
+    fn icon(&self) -> IconOrSvg {
+        IconOrSvg::Icon(IconName::AiZed)
     }
 
     fn default_model(&self, cx: &App) -> Option<Arc<dyn LanguageModel>> {
@@ -602,6 +604,10 @@ impl LanguageModel for CloudLanguageModel {
         self.model.supports_images
     }
 
+    fn supports_streaming_tools(&self) -> bool {
+        self.model.supports_streaming_tools
+    }
+
     fn supports_tool_choice(&self, choice: LanguageModelToolChoice) -> bool {
         match choice {
             LanguageModelToolChoice::Auto
@@ -663,9 +669,9 @@ impl LanguageModel for CloudLanguageModel {
         cx: &App,
     ) -> BoxFuture<'static, Result<u64>> {
         match self.model.provider {
-            cloud_llm_client::LanguageModelProvider::Anthropic => {
-                count_anthropic_tokens(request, cx)
-            }
+            cloud_llm_client::LanguageModelProvider::Anthropic => cx
+                .background_spawn(async move { count_anthropic_tokens_with_tiktoken(request) })
+                .boxed(),
             cloud_llm_client::LanguageModelProvider::OpenAi => {
                 let model = match open_ai::Model::from_id(&self.model.id.0) {
                     Ok(model) => model,

crates/language_models/src/provider/copilot_chat.rs 🔗

@@ -14,23 +14,21 @@ use copilot::{Copilot, Status};
 use futures::future::BoxFuture;
 use futures::stream::BoxStream;
 use futures::{FutureExt, Stream, StreamExt};
-use gpui::{Action, AnyView, App, AsyncApp, Entity, Render, Subscription, Task, svg};
+use gpui::{AnyView, App, AsyncApp, Entity, Subscription, Task};
 use http_client::StatusCode;
 use language::language_settings::all_language_settings;
 use language_model::{
-    AuthenticateError, LanguageModel, LanguageModelCompletionError, LanguageModelCompletionEvent,
-    LanguageModelId, LanguageModelName, LanguageModelProvider, LanguageModelProviderId,
-    LanguageModelProviderName, LanguageModelProviderState, LanguageModelRequest,
-    LanguageModelRequestMessage, LanguageModelToolChoice, LanguageModelToolResultContent,
-    LanguageModelToolSchemaFormat, LanguageModelToolUse, MessageContent, RateLimiter, Role,
-    StopReason, TokenUsage,
+    AuthenticateError, IconOrSvg, LanguageModel, LanguageModelCompletionError,
+    LanguageModelCompletionEvent, LanguageModelId, LanguageModelName, LanguageModelProvider,
+    LanguageModelProviderId, LanguageModelProviderName, LanguageModelProviderState,
+    LanguageModelRequest, LanguageModelRequestMessage, LanguageModelToolChoice,
+    LanguageModelToolResultContent, LanguageModelToolSchemaFormat, LanguageModelToolUse,
+    MessageContent, RateLimiter, Role, StopReason, TokenUsage,
 };
 use settings::SettingsStore;
-use ui::{CommonAnimationExt, prelude::*};
+use ui::prelude::*;
 use util::debug_panic;
 
-use crate::ui::ConfiguredApiCard;
-
 const PROVIDER_ID: LanguageModelProviderId = LanguageModelProviderId::new("copilot_chat");
 const PROVIDER_NAME: LanguageModelProviderName =
     LanguageModelProviderName::new("GitHub Copilot Chat");
@@ -106,8 +104,8 @@ impl LanguageModelProvider for CopilotChatLanguageModelProvider {
         PROVIDER_NAME
     }
 
-    fn icon(&self) -> IconName {
-        IconName::Copilot
+    fn icon(&self) -> IconOrSvg {
+        IconOrSvg::Icon(IconName::Copilot)
     }
 
     fn default_model(&self, cx: &App) -> Option<Arc<dyn LanguageModel>> {
@@ -179,8 +177,18 @@ impl LanguageModelProvider for CopilotChatLanguageModelProvider {
         _: &mut Window,
         cx: &mut App,
     ) -> AnyView {
-        let state = self.state.clone();
-        cx.new(|cx| ConfigurationView::new(state, cx)).into()
+        cx.new(|cx| {
+            copilot::ConfigurationView::new(
+                |cx| {
+                    CopilotChat::global(cx)
+                        .map(|m| m.read(cx).is_authenticated())
+                        .unwrap_or(false)
+                },
+                copilot::ConfigurationMode::Chat,
+                cx,
+            )
+        })
+        .into()
     }
 
     fn reset_credentials(&self, _cx: &mut App) -> Task<Result<()>> {
@@ -1474,92 +1482,3 @@ mod tests {
         );
     }
 }
-struct ConfigurationView {
-    copilot_status: Option<copilot::Status>,
-    state: Entity<State>,
-    _subscription: Option<Subscription>,
-}
-
-impl ConfigurationView {
-    pub fn new(state: Entity<State>, cx: &mut Context<Self>) -> Self {
-        let copilot = Copilot::global(cx);
-
-        Self {
-            copilot_status: copilot.as_ref().map(|copilot| copilot.read(cx).status()),
-            state,
-            _subscription: copilot.as_ref().map(|copilot| {
-                cx.observe(copilot, |this, model, cx| {
-                    this.copilot_status = Some(model.read(cx).status());
-                    cx.notify();
-                })
-            }),
-        }
-    }
-}
-
-impl Render for ConfigurationView {
-    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
-        if self.state.read(cx).is_authenticated(cx) {
-            ConfiguredApiCard::new("Authorized")
-                .button_label("Sign Out")
-                .on_click(|_, window, cx| {
-                    window.dispatch_action(copilot::SignOut.boxed_clone(), cx);
-                })
-                .into_any_element()
-        } else {
-            let loading_icon = Icon::new(IconName::ArrowCircle).with_rotate_animation(4);
-
-            const ERROR_LABEL: &str = "Copilot Chat requires an active GitHub Copilot subscription. Please ensure Copilot is configured and try again, or use a different Assistant provider.";
-
-            match &self.copilot_status {
-                Some(status) => match status {
-                    Status::Starting { task: _ } => h_flex()
-                        .gap_2()
-                        .child(loading_icon)
-                        .child(Label::new("Starting Copilot…"))
-                        .into_any_element(),
-                    Status::SigningIn { prompt: _ }
-                    | Status::SignedOut {
-                        awaiting_signing_in: true,
-                    } => h_flex()
-                        .gap_2()
-                        .child(loading_icon)
-                        .child(Label::new("Signing into Copilot…"))
-                        .into_any_element(),
-                    Status::Error(_) => {
-                        const LABEL: &str = "Copilot had issues starting. Please try restarting it. If the issue persists, try reinstalling Copilot.";
-                        v_flex()
-                            .gap_6()
-                            .child(Label::new(LABEL))
-                            .child(svg().size_8().path(IconName::CopilotError.path()))
-                            .into_any_element()
-                    }
-                    _ => {
-                        const LABEL: &str = "To use Zed's agent with GitHub Copilot, you need to be logged in to GitHub. Note that your GitHub account must have an active Copilot Chat subscription.";
-
-                        v_flex()
-                            .gap_2()
-                            .child(Label::new(LABEL))
-                            .child(
-                                Button::new("sign_in", "Sign in to use GitHub Copilot")
-                                    .full_width()
-                                    .style(ButtonStyle::Outlined)
-                                    .icon_color(Color::Muted)
-                                    .icon(IconName::Github)
-                                    .icon_position(IconPosition::Start)
-                                    .icon_size(IconSize::Small)
-                                    .on_click(|_, window, cx| {
-                                        copilot::initiate_sign_in(window, cx)
-                                    }),
-                            )
-                            .into_any_element()
-                    }
-                },
-                None => v_flex()
-                    .gap_6()
-                    .child(Label::new(ERROR_LABEL))
-                    .into_any_element(),
-            }
-        }
-    }
-}

crates/language_models/src/provider/deepseek.rs 🔗

@@ -7,11 +7,11 @@ use futures::{FutureExt, StreamExt, future, future::BoxFuture, stream::BoxStream
 use gpui::{AnyView, App, AsyncApp, Context, Entity, SharedString, Task, Window};
 use http_client::HttpClient;
 use language_model::{
-    AuthenticateError, LanguageModel, LanguageModelCompletionError, LanguageModelCompletionEvent,
-    LanguageModelId, LanguageModelName, LanguageModelProvider, LanguageModelProviderId,
-    LanguageModelProviderName, LanguageModelProviderState, LanguageModelRequest,
-    LanguageModelToolChoice, LanguageModelToolResultContent, LanguageModelToolUse, MessageContent,
-    RateLimiter, Role, StopReason, TokenUsage,
+    ApiKeyState, AuthenticateError, EnvVar, IconOrSvg, LanguageModel, LanguageModelCompletionError,
+    LanguageModelCompletionEvent, LanguageModelId, LanguageModelName, LanguageModelProvider,
+    LanguageModelProviderId, LanguageModelProviderName, LanguageModelProviderState,
+    LanguageModelRequest, LanguageModelToolChoice, LanguageModelToolResultContent,
+    LanguageModelToolUse, MessageContent, RateLimiter, Role, StopReason, TokenUsage, env_var,
 };
 pub use settings::DeepseekAvailableModel as AvailableModel;
 use settings::{Settings, SettingsStore};
@@ -19,13 +19,9 @@ use std::pin::Pin;
 use std::str::FromStr;
 use std::sync::{Arc, LazyLock};
 
-use ui::{List, prelude::*};
+use ui::{ButtonLink, ConfiguredApiCard, List, ListBulletItem, prelude::*};
 use ui_input::InputField;
 use util::ResultExt;
-use zed_env_vars::{EnvVar, env_var};
-
-use crate::ui::ConfiguredApiCard;
-use crate::{api_key::ApiKeyState, ui::InstructionListItem};
 
 const PROVIDER_ID: LanguageModelProviderId = LanguageModelProviderId::new("deepseek");
 const PROVIDER_NAME: LanguageModelProviderName = LanguageModelProviderName::new("DeepSeek");
@@ -67,12 +63,8 @@ impl State {
 
     fn authenticate(&mut self, cx: &mut Context<Self>) -> Task<Result<(), AuthenticateError>> {
         let api_url = DeepSeekLanguageModelProvider::api_url(cx);
-        self.api_key_state.load_if_needed(
-            api_url,
-            &API_KEY_ENV_VAR,
-            |this| &mut this.api_key_state,
-            cx,
-        )
+        self.api_key_state
+            .load_if_needed(api_url, |this| &mut this.api_key_state, cx)
     }
 }
 
@@ -81,17 +73,13 @@ impl DeepSeekLanguageModelProvider {
         let state = cx.new(|cx| {
             cx.observe_global::<SettingsStore>(|this: &mut State, cx| {
                 let api_url = Self::api_url(cx);
-                this.api_key_state.handle_url_change(
-                    api_url,
-                    &API_KEY_ENV_VAR,
-                    |this| &mut this.api_key_state,
-                    cx,
-                );
+                this.api_key_state
+                    .handle_url_change(api_url, |this| &mut this.api_key_state, cx);
                 cx.notify();
             })
             .detach();
             State {
-                api_key_state: ApiKeyState::new(Self::api_url(cx)),
+                api_key_state: ApiKeyState::new(Self::api_url(cx), (*API_KEY_ENV_VAR).clone()),
             }
         });
 
@@ -139,8 +127,8 @@ impl LanguageModelProvider for DeepSeekLanguageModelProvider {
         PROVIDER_NAME
     }
 
-    fn icon(&self) -> IconName {
-        IconName::AiDeepSeek
+    fn icon(&self) -> IconOrSvg {
+        IconOrSvg::Icon(IconName::AiDeepSeek)
     }
 
     fn default_model(&self, _cx: &App) -> Option<Arc<dyn LanguageModel>> {
@@ -332,9 +320,11 @@ pub fn into_deepseek(
     model: &deepseek::Model,
     max_output_tokens: Option<u64>,
 ) -> deepseek::Request {
-    let is_reasoner = *model == deepseek::Model::Reasoner;
+    let is_reasoner = model == &deepseek::Model::Reasoner;
 
     let mut messages = Vec::new();
+    let mut current_reasoning: Option<String> = None;
+
     for message in request.messages {
         for content in message.content {
             match content {
@@ -343,10 +333,14 @@ pub fn into_deepseek(
                     Role::Assistant => deepseek::RequestMessage::Assistant {
                         content: Some(text),
                         tool_calls: Vec::new(),
+                        reasoning_content: current_reasoning.take(),
                     },
                     Role::System => deepseek::RequestMessage::System { content: text },
                 }),
-                MessageContent::Thinking { .. } => {}
+                MessageContent::Thinking { text, .. } => {
+                    // Accumulate reasoning content for next assistant message
+                    current_reasoning.get_or_insert_default().push_str(&text);
+                }
                 MessageContent::RedactedThinking(_) => {}
                 MessageContent::Image(_) => {}
                 MessageContent::ToolUse(tool_use) => {
@@ -369,6 +363,7 @@ pub fn into_deepseek(
                         messages.push(deepseek::RequestMessage::Assistant {
                             content: None,
                             tool_calls: vec![tool_call],
+                            reasoning_content: current_reasoning.take(),
                         });
                     }
                 }
@@ -625,12 +620,15 @@ impl Render for ConfigurationView {
                 .child(Label::new("To use DeepSeek in Zed, you need an API key:"))
                 .child(
                     List::new()
-                        .child(InstructionListItem::new(
-                            "Get your API key from the",
-                            Some("DeepSeek console"),
-                            Some("https://platform.deepseek.com/api_keys"),
-                        ))
-                        .child(InstructionListItem::text_only(
+                        .child(
+                            ListBulletItem::new("")
+                                .child(Label::new("Get your API key from the"))
+                                .child(ButtonLink::new(
+                                    "DeepSeek console",
+                                    "https://platform.deepseek.com/api_keys",
+                                )),
+                        )
+                        .child(ListBulletItem::new(
                             "Paste your API key below and hit enter to start using the assistant",
                         )),
                 )

crates/language_models/src/provider/google.rs 🔗

@@ -9,12 +9,12 @@ use google_ai::{
 use gpui::{AnyView, App, AsyncApp, Context, Entity, SharedString, Task, Window};
 use http_client::HttpClient;
 use language_model::{
-    AuthenticateError, ConfigurationViewTargetAgent, LanguageModelCompletionError,
+    AuthenticateError, ConfigurationViewTargetAgent, EnvVar, LanguageModelCompletionError,
     LanguageModelCompletionEvent, LanguageModelToolChoice, LanguageModelToolSchemaFormat,
     LanguageModelToolUse, LanguageModelToolUseId, MessageContent, StopReason,
 };
 use language_model::{
-    LanguageModel, LanguageModelId, LanguageModelName, LanguageModelProvider,
+    IconOrSvg, LanguageModel, LanguageModelId, LanguageModelName, LanguageModelProvider,
     LanguageModelProviderId, LanguageModelProviderName, LanguageModelProviderState,
     LanguageModelRequest, RateLimiter, Role,
 };
@@ -28,14 +28,11 @@ use std::sync::{
     atomic::{self, AtomicU64},
 };
 use strum::IntoEnumIterator;
-use ui::{List, prelude::*};
+use ui::{ButtonLink, ConfiguredApiCard, List, ListBulletItem, prelude::*};
 use ui_input::InputField;
 use util::ResultExt;
-use zed_env_vars::EnvVar;
 
-use crate::api_key::ApiKey;
-use crate::api_key::ApiKeyState;
-use crate::ui::{ConfiguredApiCard, InstructionListItem};
+use language_model::{ApiKey, ApiKeyState};
 
 const PROVIDER_ID: LanguageModelProviderId = language_model::GOOGLE_PROVIDER_ID;
 const PROVIDER_NAME: LanguageModelProviderName = language_model::GOOGLE_PROVIDER_NAME;
@@ -87,12 +84,8 @@ impl State {
 
     fn authenticate(&mut self, cx: &mut Context<Self>) -> Task<Result<(), AuthenticateError>> {
         let api_url = GoogleLanguageModelProvider::api_url(cx);
-        self.api_key_state.load_if_needed(
-            api_url,
-            &API_KEY_ENV_VAR,
-            |this| &mut this.api_key_state,
-            cx,
-        )
+        self.api_key_state
+            .load_if_needed(api_url, |this| &mut this.api_key_state, cx)
     }
 }
 
@@ -101,17 +94,13 @@ impl GoogleLanguageModelProvider {
         let state = cx.new(|cx| {
             cx.observe_global::<SettingsStore>(|this: &mut State, cx| {
                 let api_url = Self::api_url(cx);
-                this.api_key_state.handle_url_change(
-                    api_url,
-                    &API_KEY_ENV_VAR,
-                    |this| &mut this.api_key_state,
-                    cx,
-                );
+                this.api_key_state
+                    .handle_url_change(api_url, |this| &mut this.api_key_state, cx);
                 cx.notify();
             })
             .detach();
             State {
-                api_key_state: ApiKeyState::new(Self::api_url(cx)),
+                api_key_state: ApiKeyState::new(Self::api_url(cx), (*API_KEY_ENV_VAR).clone()),
             }
         });
 
@@ -175,8 +164,8 @@ impl LanguageModelProvider for GoogleLanguageModelProvider {
         PROVIDER_NAME
     }
 
-    fn icon(&self) -> IconName {
-        IconName::AiGoogle
+    fn icon(&self) -> IconOrSvg {
+        IconOrSvg::Icon(IconName::AiGoogle)
     }
 
     fn default_model(&self, _cx: &App) -> Option<Arc<dyn LanguageModel>> {
@@ -873,14 +862,14 @@ impl Render for ConfigurationView {
                 })))
                 .child(
                     List::new()
-                        .child(InstructionListItem::new(
-                            "Create one by visiting",
-                            Some("Google AI's console"),
-                            Some("https://aistudio.google.com/app/apikey"),
-                        ))
-                        .child(InstructionListItem::text_only(
-                            "Paste your API key below and hit enter to start using the assistant",
-                        )),
+                        .child(
+                            ListBulletItem::new("")
+                                .child(Label::new("Create one by visiting"))
+                                .child(ButtonLink::new("Google AI's console", "https://aistudio.google.com/app/apikey"))
+                        )
+                        .child(
+                            ListBulletItem::new("Paste your API key below and hit enter to start using the agent")
+                        )
                 )
                 .child(self.api_key_editor.clone())
                 .child(

crates/language_models/src/provider/lmstudio.rs 🔗

@@ -10,7 +10,7 @@ use language_model::{
     StopReason, TokenUsage,
 };
 use language_model::{
-    LanguageModel, LanguageModelId, LanguageModelName, LanguageModelProvider,
+    IconOrSvg, LanguageModel, LanguageModelId, LanguageModelName, LanguageModelProvider,
     LanguageModelProviderId, LanguageModelProviderName, LanguageModelProviderState,
     LanguageModelRequest, RateLimiter, Role,
 };
@@ -20,11 +20,10 @@ use settings::{Settings, SettingsStore};
 use std::pin::Pin;
 use std::str::FromStr;
 use std::{collections::BTreeMap, sync::Arc};
-use ui::{ButtonLike, Indicator, List, prelude::*};
+use ui::{ButtonLike, Indicator, List, ListBulletItem, prelude::*};
 use util::ResultExt;
 
 use crate::AllLanguageModelSettings;
-use crate::ui::InstructionListItem;
 
 const LMSTUDIO_DOWNLOAD_URL: &str = "https://lmstudio.ai/download";
 const LMSTUDIO_CATALOG_URL: &str = "https://lmstudio.ai/models";
@@ -176,8 +175,8 @@ impl LanguageModelProvider for LmStudioLanguageModelProvider {
         PROVIDER_NAME
     }
 
-    fn icon(&self) -> IconName {
-        IconName::AiLmStudio
+    fn icon(&self) -> IconOrSvg {
+        IconOrSvg::Icon(IconName::AiLmStudio)
     }
 
     fn default_model(&self, _: &App) -> Option<Arc<dyn LanguageModel>> {
@@ -686,12 +685,14 @@ impl Render for ConfigurationView {
                 .child(
                     v_flex().gap_1().child(Label::new(lmstudio_intro)).child(
                         List::new()
-                            .child(InstructionListItem::text_only(
+                            .child(ListBulletItem::new(
                                 "LM Studio needs to be running with at least one model downloaded.",
                             ))
-                            .child(InstructionListItem::text_only(
-                                "To get your first model, try running `lms get qwen2.5-coder-7b`",
-                            )),
+                            .child(
+                                ListBulletItem::new("")
+                                    .child(Label::new("To get your first model, try running"))
+                                    .child(Label::new("lms get qwen2.5-coder-7b").inline_code(cx)),
+                            ),
                     ),
                 )
                 .child(

crates/language_models/src/provider/mistral.rs 🔗

@@ -1,31 +1,27 @@
 use anyhow::{Result, anyhow};
 use collections::BTreeMap;
-use fs::Fs;
+
 use futures::{FutureExt, Stream, StreamExt, future, future::BoxFuture, stream::BoxStream};
 use gpui::{AnyView, App, AsyncApp, Context, Entity, Global, SharedString, Task, Window};
 use http_client::HttpClient;
 use language_model::{
-    AuthenticateError, LanguageModel, LanguageModelCompletionError, LanguageModelCompletionEvent,
-    LanguageModelId, LanguageModelName, LanguageModelProvider, LanguageModelProviderId,
-    LanguageModelProviderName, LanguageModelProviderState, LanguageModelRequest,
-    LanguageModelToolChoice, LanguageModelToolResultContent, LanguageModelToolUse, MessageContent,
-    RateLimiter, Role, StopReason, TokenUsage,
+    ApiKeyState, AuthenticateError, EnvVar, IconOrSvg, LanguageModel, LanguageModelCompletionError,
+    LanguageModelCompletionEvent, LanguageModelId, LanguageModelName, LanguageModelProvider,
+    LanguageModelProviderId, LanguageModelProviderName, LanguageModelProviderState,
+    LanguageModelRequest, LanguageModelToolChoice, LanguageModelToolResultContent,
+    LanguageModelToolUse, MessageContent, RateLimiter, Role, StopReason, TokenUsage, env_var,
 };
-use mistral::{CODESTRAL_API_URL, MISTRAL_API_URL, StreamResponse};
+pub use mistral::{CODESTRAL_API_URL, MISTRAL_API_URL, StreamResponse};
 pub use settings::MistralAvailableModel as AvailableModel;
-use settings::{EditPredictionProvider, Settings, SettingsStore, update_settings_file};
+use settings::{Settings, SettingsStore};
 use std::collections::HashMap;
 use std::pin::Pin;
 use std::str::FromStr;
 use std::sync::{Arc, LazyLock};
 use strum::IntoEnumIterator;
-use ui::{List, prelude::*};
+use ui::{ButtonLink, ConfiguredApiCard, List, ListBulletItem, prelude::*};
 use ui_input::InputField;
 use util::ResultExt;
-use zed_env_vars::{EnvVar, env_var};
-
-use crate::ui::ConfiguredApiCard;
-use crate::{api_key::ApiKeyState, ui::InstructionListItem};
 
 const PROVIDER_ID: LanguageModelProviderId = LanguageModelProviderId::new("mistral");
 const PROVIDER_NAME: LanguageModelProviderName = LanguageModelProviderName::new("Mistral");
@@ -44,12 +40,26 @@ pub struct MistralSettings {
 
 pub struct MistralLanguageModelProvider {
     http_client: Arc<dyn HttpClient>,
-    state: Entity<State>,
+    pub state: Entity<State>,
 }
 
 pub struct State {
     api_key_state: ApiKeyState,
-    codestral_api_key_state: ApiKeyState,
+    codestral_api_key_state: Entity<ApiKeyState>,
+}
+
+struct CodestralApiKey(Entity<ApiKeyState>);
+impl Global for CodestralApiKey {}
+
+pub fn codestral_api_key(cx: &mut App) -> Entity<ApiKeyState> {
+    if cx.has_global::<CodestralApiKey>() {
+        cx.global::<CodestralApiKey>().0.clone()
+    } else {
+        let api_key_state = cx
+            .new(|_| ApiKeyState::new(CODESTRAL_API_URL.into(), CODESTRAL_API_KEY_ENV_VAR.clone()));
+        cx.set_global(CodestralApiKey(api_key_state.clone()));
+        api_key_state
+    }
 }
 
 impl State {
@@ -63,39 +73,19 @@ impl State {
             .store(api_url, api_key, |this| &mut this.api_key_state, cx)
     }
 
-    fn set_codestral_api_key(
-        &mut self,
-        api_key: Option<String>,
-        cx: &mut Context<Self>,
-    ) -> Task<Result<()>> {
-        self.codestral_api_key_state.store(
-            CODESTRAL_API_URL.into(),
-            api_key,
-            |this| &mut this.codestral_api_key_state,
-            cx,
-        )
-    }
-
     fn authenticate(&mut self, cx: &mut Context<Self>) -> Task<Result<(), AuthenticateError>> {
         let api_url = MistralLanguageModelProvider::api_url(cx);
-        self.api_key_state.load_if_needed(
-            api_url,
-            &API_KEY_ENV_VAR,
-            |this| &mut this.api_key_state,
-            cx,
-        )
+        self.api_key_state
+            .load_if_needed(api_url, |this| &mut this.api_key_state, cx)
     }
 
     fn authenticate_codestral(
         &mut self,
         cx: &mut Context<Self>,
     ) -> Task<Result<(), AuthenticateError>> {
-        self.codestral_api_key_state.load_if_needed(
-            CODESTRAL_API_URL.into(),
-            &CODESTRAL_API_KEY_ENV_VAR,
-            |this| &mut this.codestral_api_key_state,
-            cx,
-        )
+        self.codestral_api_key_state.update(cx, |state, cx| {
+            state.load_if_needed(CODESTRAL_API_URL.into(), |state| state, cx)
+        })
     }
 }
 
@@ -116,18 +106,14 @@ impl MistralLanguageModelProvider {
         let state = cx.new(|cx| {
             cx.observe_global::<SettingsStore>(|this: &mut State, cx| {
                 let api_url = Self::api_url(cx);
-                this.api_key_state.handle_url_change(
-                    api_url,
-                    &API_KEY_ENV_VAR,
-                    |this| &mut this.api_key_state,
-                    cx,
-                );
+                this.api_key_state
+                    .handle_url_change(api_url, |this| &mut this.api_key_state, cx);
                 cx.notify();
             })
             .detach();
             State {
-                api_key_state: ApiKeyState::new(Self::api_url(cx)),
-                codestral_api_key_state: ApiKeyState::new(CODESTRAL_API_URL.into()),
+                api_key_state: ApiKeyState::new(Self::api_url(cx), (*API_KEY_ENV_VAR).clone()),
+                codestral_api_key_state: codestral_api_key(cx),
             }
         });
 
@@ -142,7 +128,11 @@ impl MistralLanguageModelProvider {
     }
 
     pub fn codestral_api_key(&self, url: &str, cx: &App) -> Option<Arc<str>> {
-        self.state.read(cx).codestral_api_key_state.key(url)
+        self.state
+            .read(cx)
+            .codestral_api_key_state
+            .read(cx)
+            .key(url)
     }
 
     fn create_language_model(&self, model: mistral::Model) -> Arc<dyn LanguageModel> {
@@ -159,7 +149,7 @@ impl MistralLanguageModelProvider {
         &crate::AllLanguageModelSettings::get_global(cx).mistral
     }
 
-    fn api_url(cx: &App) -> SharedString {
+    pub fn api_url(cx: &App) -> SharedString {
         let api_url = &Self::settings(cx).api_url;
         if api_url.is_empty() {
             mistral::MISTRAL_API_URL.into()
@@ -186,8 +176,8 @@ impl LanguageModelProvider for MistralLanguageModelProvider {
         PROVIDER_NAME
     }
 
-    fn icon(&self) -> IconName {
-        IconName::AiMistral
+    fn icon(&self) -> IconOrSvg {
+        IconOrSvg::Icon(IconName::AiMistral)
     }
 
     fn default_model(&self, _cx: &App) -> Option<Arc<dyn LanguageModel>> {
@@ -747,7 +737,6 @@ struct RawToolCall {
 
 struct ConfigurationView {
     api_key_editor: Entity<InputField>,
-    codestral_api_key_editor: Entity<InputField>,
     state: Entity<State>,
     load_credentials_task: Option<Task<()>>,
 }
@@ -756,8 +745,6 @@ impl ConfigurationView {
     fn new(state: Entity<State>, window: &mut Window, cx: &mut Context<Self>) -> Self {
         let api_key_editor =
             cx.new(|cx| InputField::new(window, cx, "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"));
-        let codestral_api_key_editor =
-            cx.new(|cx| InputField::new(window, cx, "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"));
 
         cx.observe(&state, |_, _, cx| {
             cx.notify();
@@ -774,12 +761,6 @@ impl ConfigurationView {
                     // We don't log an error, because "not signed in" is also an error.
                     let _ = task.await;
                 }
-                if let Some(task) = state
-                    .update(cx, |state, cx| state.authenticate_codestral(cx))
-                    .log_err()
-                {
-                    let _ = task.await;
-                }
 
                 this.update(cx, |this, cx| {
                     this.load_credentials_task = None;
@@ -791,7 +772,6 @@ impl ConfigurationView {
 
         Self {
             api_key_editor,
-            codestral_api_key_editor,
             state,
             load_credentials_task,
         }
@@ -829,110 +809,9 @@ impl ConfigurationView {
         .detach_and_log_err(cx);
     }
 
-    fn save_codestral_api_key(
-        &mut self,
-        _: &menu::Confirm,
-        window: &mut Window,
-        cx: &mut Context<Self>,
-    ) {
-        let api_key = self
-            .codestral_api_key_editor
-            .read(cx)
-            .text(cx)
-            .trim()
-            .to_string();
-        if api_key.is_empty() {
-            return;
-        }
-
-        // url changes can cause the editor to be displayed again
-        self.codestral_api_key_editor
-            .update(cx, |editor, cx| editor.set_text("", window, cx));
-
-        let state = self.state.clone();
-        cx.spawn_in(window, async move |_, cx| {
-            state
-                .update(cx, |state, cx| {
-                    state.set_codestral_api_key(Some(api_key), cx)
-                })?
-                .await?;
-            cx.update(|_window, cx| {
-                set_edit_prediction_provider(EditPredictionProvider::Codestral, cx)
-            })
-        })
-        .detach_and_log_err(cx);
-    }
-
-    fn reset_codestral_api_key(&mut self, window: &mut Window, cx: &mut Context<Self>) {
-        self.codestral_api_key_editor
-            .update(cx, |editor, cx| editor.set_text("", window, cx));
-
-        let state = self.state.clone();
-        cx.spawn_in(window, async move |_, cx| {
-            state
-                .update(cx, |state, cx| state.set_codestral_api_key(None, cx))?
-                .await?;
-            cx.update(|_window, cx| set_edit_prediction_provider(EditPredictionProvider::Zed, cx))
-        })
-        .detach_and_log_err(cx);
-    }
-
     fn should_render_api_key_editor(&self, cx: &mut Context<Self>) -> bool {
         !self.state.read(cx).is_authenticated()
     }
-
-    fn render_codestral_api_key_editor(&mut self, cx: &mut Context<Self>) -> AnyElement {
-        let key_state = &self.state.read(cx).codestral_api_key_state;
-        let should_show_editor = !key_state.has_key();
-        let env_var_set = key_state.is_from_env_var();
-        let configured_card_label = if env_var_set {
-            format!("API key set in {CODESTRAL_API_KEY_ENV_VAR_NAME} environment variable")
-        } else {
-            "Codestral API key configured".to_string()
-        };
-
-        if should_show_editor {
-            v_flex()
-                .id("codestral")
-                .size_full()
-                .mt_2()
-                .on_action(cx.listener(Self::save_codestral_api_key))
-                .child(Label::new(
-                    "To use Codestral as an edit prediction provider, \
-                    you need to add a Codestral-specific API key. Follow these steps:",
-                ))
-                .child(
-                    List::new()
-                        .child(InstructionListItem::new(
-                            "Create one by visiting",
-                            Some("the Codestral section of Mistral's console"),
-                            Some("https://console.mistral.ai/codestral"),
-                        ))
-                        .child(InstructionListItem::text_only("Paste your API key below and hit enter")),
-                )
-                .child(self.codestral_api_key_editor.clone())
-                .child(
-                    Label::new(
-                        format!("You can also assign the {CODESTRAL_API_KEY_ENV_VAR_NAME} environment variable and restart Zed."),
-                    )
-                    .size(LabelSize::Small).color(Color::Muted),
-                ).into_any()
-        } else {
-            ConfiguredApiCard::new(configured_card_label)
-                .disabled(env_var_set)
-                .on_click(cx.listener(|this, _, window, cx| this.reset_api_key(window, cx)))
-                .when(env_var_set, |this| {
-                    this.tooltip_label(format!(
-                        "To reset your API key, \
-                            unset the {CODESTRAL_API_KEY_ENV_VAR_NAME} environment variable."
-                    ))
-                })
-                .on_click(
-                    cx.listener(|this, _, window, cx| this.reset_codestral_api_key(window, cx)),
-                )
-                .into_any_element()
-        }
-    }
 }
 
 impl Render for ConfigurationView {
@@ -958,17 +837,17 @@ impl Render for ConfigurationView {
                 .child(Label::new("To use Zed's agent with Mistral, you need to add an API key. Follow these steps:"))
                 .child(
                     List::new()
-                        .child(InstructionListItem::new(
-                            "Create one by visiting",
-                            Some("Mistral's console"),
-                            Some("https://console.mistral.ai/api-keys"),
-                        ))
-                        .child(InstructionListItem::text_only(
-                            "Ensure your Mistral account has credits",
-                        ))
-                        .child(InstructionListItem::text_only(
-                            "Paste your API key below and hit enter to start using the assistant",
-                        )),
+                        .child(
+                            ListBulletItem::new("")
+                                .child(Label::new("Create one by visiting"))
+                                .child(ButtonLink::new("Mistral's console", "https://console.mistral.ai/api-keys"))
+                        )
+                        .child(
+                            ListBulletItem::new("Ensure your Mistral account has credits")
+                        )
+                        .child(
+                            ListBulletItem::new("Paste your API key below and hit enter to start using the assistant")
+                        ),
                 )
                 .child(self.api_key_editor.clone())
                 .child(
@@ -977,7 +856,6 @@ impl Render for ConfigurationView {
                     )
                     .size(LabelSize::Small).color(Color::Muted),
                 )
-                .child(self.render_codestral_api_key_editor(cx))
                 .into_any()
         } else {
             v_flex()
@@ -994,24 +872,11 @@ impl Render for ConfigurationView {
                             ))
                         }),
                 )
-                .child(self.render_codestral_api_key_editor(cx))
                 .into_any()
         }
     }
 }
 
-fn set_edit_prediction_provider(provider: EditPredictionProvider, cx: &mut App) {
-    let fs = <dyn Fs>::global(cx);
-    update_settings_file(fs, cx, move |settings, _| {
-        settings
-            .project
-            .all_languages
-            .features
-            .get_or_insert_default()
-            .edit_prediction_provider = Some(provider);
-    });
-}
-
 #[cfg(test)]
 mod tests {
     use super::*;
@@ -1062,7 +927,7 @@ mod tests {
                     MessageContent::Text("What's in this image?".into()),
                     MessageContent::Image(LanguageModelImage {
                         source: "base64data".into(),
-                        size: Default::default(),
+                        size: None,
                     }),
                 ],
                 cache: false,

crates/language_models/src/provider/ollama.rs 🔗

@@ -5,11 +5,11 @@ use futures::{Stream, TryFutureExt, stream};
 use gpui::{AnyView, App, AsyncApp, Context, CursorStyle, Entity, Task};
 use http_client::HttpClient;
 use language_model::{
-    AuthenticateError, LanguageModel, LanguageModelCompletionError, LanguageModelCompletionEvent,
-    LanguageModelId, LanguageModelName, LanguageModelProvider, LanguageModelProviderId,
-    LanguageModelProviderName, LanguageModelProviderState, LanguageModelRequest,
-    LanguageModelRequestTool, LanguageModelToolChoice, LanguageModelToolUse,
-    LanguageModelToolUseId, MessageContent, RateLimiter, Role, StopReason, TokenUsage,
+    ApiKeyState, AuthenticateError, EnvVar, IconOrSvg, LanguageModel, LanguageModelCompletionError,
+    LanguageModelCompletionEvent, LanguageModelId, LanguageModelName, LanguageModelProvider,
+    LanguageModelProviderId, LanguageModelProviderName, LanguageModelProviderState,
+    LanguageModelRequest, LanguageModelRequestTool, LanguageModelToolChoice, LanguageModelToolUse,
+    LanguageModelToolUseId, MessageContent, RateLimiter, Role, StopReason, TokenUsage, env_var,
 };
 use menu;
 use ollama::{
@@ -22,13 +22,13 @@ use std::pin::Pin;
 use std::sync::LazyLock;
 use std::sync::atomic::{AtomicU64, Ordering};
 use std::{collections::HashMap, sync::Arc};
-use ui::{ButtonLike, ElevationIndex, List, Tooltip, prelude::*};
+use ui::{
+    ButtonLike, ButtonLink, ConfiguredApiCard, ElevationIndex, List, ListBulletItem, Tooltip,
+    prelude::*,
+};
 use ui_input::InputField;
-use zed_env_vars::{EnvVar, env_var};
 
 use crate::AllLanguageModelSettings;
-use crate::api_key::ApiKeyState;
-use crate::ui::{ConfiguredApiCard, InstructionListItem};
 
 const OLLAMA_DOWNLOAD_URL: &str = "https://ollama.com/download";
 const OLLAMA_LIBRARY_URL: &str = "https://ollama.com/library";
@@ -43,6 +43,7 @@ static API_KEY_ENV_VAR: LazyLock<EnvVar> = env_var!(API_KEY_ENV_VAR_NAME);
 #[derive(Default, Debug, Clone, PartialEq)]
 pub struct OllamaSettings {
     pub api_url: String,
+    pub auto_discover: bool,
     pub available_models: Vec<AvailableModel>,
 }
 
@@ -80,12 +81,9 @@ impl State {
 
     fn authenticate(&mut self, cx: &mut Context<Self>) -> Task<Result<(), AuthenticateError>> {
         let api_url = OllamaLanguageModelProvider::api_url(cx);
-        let task = self.api_key_state.load_if_needed(
-            api_url,
-            &API_KEY_ENV_VAR,
-            |this| &mut this.api_key_state,
-            cx,
-        );
+        let task = self
+            .api_key_state
+            .load_if_needed(api_url, |this| &mut this.api_key_state, cx);
 
         // Always try to fetch models - if no API key is needed (local Ollama), it will work
         // If API key is needed and provided, it will work
@@ -185,7 +183,7 @@ impl OllamaLanguageModelProvider {
                     http_client,
                     fetched_models: Default::default(),
                     fetch_model_task: None,
-                    api_key_state: ApiKeyState::new(Self::api_url(cx)),
+                    api_key_state: ApiKeyState::new(Self::api_url(cx), (*API_KEY_ENV_VAR).clone()),
                 }
             }),
         };
@@ -223,8 +221,8 @@ impl LanguageModelProvider for OllamaLanguageModelProvider {
         PROVIDER_NAME
     }
 
-    fn icon(&self) -> IconName {
-        IconName::AiOllama
+    fn icon(&self) -> IconOrSvg {
+        IconOrSvg::Icon(IconName::AiOllama)
     }
 
     fn default_model(&self, _: &App) -> Option<Arc<dyn LanguageModel>> {
@@ -241,40 +239,17 @@ impl LanguageModelProvider for OllamaLanguageModelProvider {
 
     fn provided_models(&self, cx: &App) -> Vec<Arc<dyn LanguageModel>> {
         let mut models: HashMap<String, ollama::Model> = HashMap::new();
+        let settings = OllamaLanguageModelProvider::settings(cx);
 
         // Add models from the Ollama API
-        for model in self.state.read(cx).fetched_models.iter() {
-            models.insert(model.name.clone(), model.clone());
+        if settings.auto_discover {
+            for model in self.state.read(cx).fetched_models.iter() {
+                models.insert(model.name.clone(), model.clone());
+            }
         }
 
         // Override with available models from settings
-        for setting_model in &OllamaLanguageModelProvider::settings(cx).available_models {
-            let setting_base = setting_model.name.split(':').next().unwrap();
-            if let Some(model) = models
-                .values_mut()
-                .find(|m| m.name.split(':').next().unwrap() == setting_base)
-            {
-                model.max_tokens = setting_model.max_tokens;
-                model.display_name = setting_model.display_name.clone();
-                model.keep_alive = setting_model.keep_alive.clone();
-                model.supports_tools = setting_model.supports_tools;
-                model.supports_vision = setting_model.supports_images;
-                model.supports_thinking = setting_model.supports_thinking;
-            } else {
-                models.insert(
-                    setting_model.name.clone(),
-                    ollama::Model {
-                        name: setting_model.name.clone(),
-                        display_name: setting_model.display_name.clone(),
-                        max_tokens: setting_model.max_tokens,
-                        keep_alive: setting_model.keep_alive.clone(),
-                        supports_tools: setting_model.supports_tools,
-                        supports_vision: setting_model.supports_images,
-                        supports_thinking: setting_model.supports_thinking,
-                    },
-                );
-            }
-        }
+        merge_settings_into_models(&mut models, &settings.available_models);
 
         let mut models = models
             .into_values()
@@ -723,7 +698,7 @@ impl ConfigurationView {
         cx.notify();
     }
 
-    fn render_instructions() -> Div {
+    fn render_instructions(cx: &mut Context<Self>) -> Div {
         v_flex()
             .gap_2()
             .child(Label::new(
@@ -733,15 +708,17 @@ impl ConfigurationView {
             .child(Label::new("To use local Ollama:"))
             .child(
                 List::new()
-                    .child(InstructionListItem::new(
-                        "Download and install Ollama from",
-                        Some("ollama.com"),
-                        Some("https://ollama.com/download"),
-                    ))
-                    .child(InstructionListItem::text_only(
-                        "Start Ollama and download a model: `ollama run gpt-oss:20b`",
-                    ))
-                    .child(InstructionListItem::text_only(
+                    .child(
+                        ListBulletItem::new("")
+                            .child(Label::new("Download and install Ollama from"))
+                            .child(ButtonLink::new("ollama.com", "https://ollama.com/download")),
+                    )
+                    .child(
+                        ListBulletItem::new("")
+                            .child(Label::new("Start Ollama and download a model:"))
+                            .child(Label::new("ollama run gpt-oss:20b").inline_code(cx)),
+                    )
+                    .child(ListBulletItem::new(
                         "Click 'Connect' below to start using Ollama in Zed",
                     )),
             )
@@ -830,7 +807,7 @@ impl Render for ConfigurationView {
 
         v_flex()
             .gap_2()
-            .child(Self::render_instructions())
+            .child(Self::render_instructions(cx))
             .child(self.render_api_url_editor(cx))
             .child(self.render_api_key_editor(cx))
             .child(
@@ -918,6 +895,35 @@ impl Render for ConfigurationView {
     }
 }
 
+fn merge_settings_into_models(
+    models: &mut HashMap<String, ollama::Model>,
+    available_models: &[AvailableModel],
+) {
+    for setting_model in available_models {
+        if let Some(model) = models.get_mut(&setting_model.name) {
+            model.max_tokens = setting_model.max_tokens;
+            model.display_name = setting_model.display_name.clone();
+            model.keep_alive = setting_model.keep_alive.clone();
+            model.supports_tools = setting_model.supports_tools;
+            model.supports_vision = setting_model.supports_images;
+            model.supports_thinking = setting_model.supports_thinking;
+        } else {
+            models.insert(
+                setting_model.name.clone(),
+                ollama::Model {
+                    name: setting_model.name.clone(),
+                    display_name: setting_model.display_name.clone(),
+                    max_tokens: setting_model.max_tokens,
+                    keep_alive: setting_model.keep_alive.clone(),
+                    supports_tools: setting_model.supports_tools,
+                    supports_vision: setting_model.supports_images,
+                    supports_thinking: setting_model.supports_thinking,
+                },
+            );
+        }
+    }
+}
+
 fn tool_into_ollama(tool: LanguageModelRequestTool) -> ollama::OllamaTool {
     ollama::OllamaTool::Function {
         function: OllamaFunctionTool {
@@ -927,3 +933,83 @@ fn tool_into_ollama(tool: LanguageModelRequestTool) -> ollama::OllamaTool {
         },
     }
 }
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    #[test]
+    fn test_merge_settings_preserves_display_names_for_similar_models() {
+        // Regression test for https://github.com/zed-industries/zed/issues/43646
+        // When multiple models share the same base name (e.g., qwen2.5-coder:1.5b and qwen2.5-coder:3b),
+        // each model should get its own display_name from settings, not a random one.
+
+        let mut models: HashMap<String, ollama::Model> = HashMap::new();
+        models.insert(
+            "qwen2.5-coder:1.5b".to_string(),
+            ollama::Model {
+                name: "qwen2.5-coder:1.5b".to_string(),
+                display_name: None,
+                max_tokens: 4096,
+                keep_alive: None,
+                supports_tools: None,
+                supports_vision: None,
+                supports_thinking: None,
+            },
+        );
+        models.insert(
+            "qwen2.5-coder:3b".to_string(),
+            ollama::Model {
+                name: "qwen2.5-coder:3b".to_string(),
+                display_name: None,
+                max_tokens: 4096,
+                keep_alive: None,
+                supports_tools: None,
+                supports_vision: None,
+                supports_thinking: None,
+            },
+        );
+
+        let available_models = vec![
+            AvailableModel {
+                name: "qwen2.5-coder:1.5b".to_string(),
+                display_name: Some("QWEN2.5 Coder 1.5B".to_string()),
+                max_tokens: 5000,
+                keep_alive: None,
+                supports_tools: Some(true),
+                supports_images: None,
+                supports_thinking: None,
+            },
+            AvailableModel {
+                name: "qwen2.5-coder:3b".to_string(),
+                display_name: Some("QWEN2.5 Coder 3B".to_string()),
+                max_tokens: 6000,
+                keep_alive: None,
+                supports_tools: Some(true),
+                supports_images: None,
+                supports_thinking: None,
+            },
+        ];
+
+        merge_settings_into_models(&mut models, &available_models);
+
+        let model_1_5b = models
+            .get("qwen2.5-coder:1.5b")
+            .expect("1.5b model missing");
+        let model_3b = models.get("qwen2.5-coder:3b").expect("3b model missing");
+
+        assert_eq!(
+            model_1_5b.display_name,
+            Some("QWEN2.5 Coder 1.5B".to_string()),
+            "1.5b model should have its own display_name"
+        );
+        assert_eq!(model_1_5b.max_tokens, 5000);
+
+        assert_eq!(
+            model_3b.display_name,
+            Some("QWEN2.5 Coder 3B".to_string()),
+            "3b model should have its own display_name"
+        );
+        assert_eq!(model_3b.max_tokens, 6000);
+    }
+}

crates/language_models/src/provider/open_ai.rs 🔗

@@ -5,11 +5,11 @@ use futures::{FutureExt, StreamExt, future, future::BoxFuture};
 use gpui::{AnyView, App, AsyncApp, Context, Entity, SharedString, Task, Window};
 use http_client::HttpClient;
 use language_model::{
-    AuthenticateError, LanguageModel, LanguageModelCompletionError, LanguageModelCompletionEvent,
-    LanguageModelId, LanguageModelName, LanguageModelProvider, LanguageModelProviderId,
-    LanguageModelProviderName, LanguageModelProviderState, LanguageModelRequest,
-    LanguageModelToolChoice, LanguageModelToolResultContent, LanguageModelToolUse, MessageContent,
-    RateLimiter, Role, StopReason, TokenUsage,
+    ApiKeyState, AuthenticateError, EnvVar, IconOrSvg, LanguageModel, LanguageModelCompletionError,
+    LanguageModelCompletionEvent, LanguageModelId, LanguageModelName, LanguageModelProvider,
+    LanguageModelProviderId, LanguageModelProviderName, LanguageModelProviderState,
+    LanguageModelRequest, LanguageModelToolChoice, LanguageModelToolResultContent,
+    LanguageModelToolUse, MessageContent, RateLimiter, Role, StopReason, TokenUsage, env_var,
 };
 use menu;
 use open_ai::{
@@ -20,13 +20,9 @@ use std::pin::Pin;
 use std::str::FromStr as _;
 use std::sync::{Arc, LazyLock};
 use strum::IntoEnumIterator;
-use ui::{List, prelude::*};
+use ui::{ButtonLink, ConfiguredApiCard, List, ListBulletItem, prelude::*};
 use ui_input::InputField;
 use util::ResultExt;
-use zed_env_vars::{EnvVar, env_var};
-
-use crate::ui::ConfiguredApiCard;
-use crate::{api_key::ApiKeyState, ui::InstructionListItem};
 
 const PROVIDER_ID: LanguageModelProviderId = language_model::OPEN_AI_PROVIDER_ID;
 const PROVIDER_NAME: LanguageModelProviderName = language_model::OPEN_AI_PROVIDER_NAME;
@@ -62,12 +58,8 @@ impl State {
 
     fn authenticate(&mut self, cx: &mut Context<Self>) -> Task<Result<(), AuthenticateError>> {
         let api_url = OpenAiLanguageModelProvider::api_url(cx);
-        self.api_key_state.load_if_needed(
-            api_url,
-            &API_KEY_ENV_VAR,
-            |this| &mut this.api_key_state,
-            cx,
-        )
+        self.api_key_state
+            .load_if_needed(api_url, |this| &mut this.api_key_state, cx)
     }
 }
 
@@ -76,17 +68,13 @@ impl OpenAiLanguageModelProvider {
         let state = cx.new(|cx| {
             cx.observe_global::<SettingsStore>(|this: &mut State, cx| {
                 let api_url = Self::api_url(cx);
-                this.api_key_state.handle_url_change(
-                    api_url,
-                    &API_KEY_ENV_VAR,
-                    |this| &mut this.api_key_state,
-                    cx,
-                );
+                this.api_key_state
+                    .handle_url_change(api_url, |this| &mut this.api_key_state, cx);
                 cx.notify();
             })
             .detach();
             State {
-                api_key_state: ApiKeyState::new(Self::api_url(cx)),
+                api_key_state: ApiKeyState::new(Self::api_url(cx), (*API_KEY_ENV_VAR).clone()),
             }
         });
 
@@ -134,8 +122,8 @@ impl LanguageModelProvider for OpenAiLanguageModelProvider {
         PROVIDER_NAME
     }
 
-    fn icon(&self) -> IconName {
-        IconName::AiOpenAi
+    fn icon(&self) -> IconOrSvg {
+        IconOrSvg::Icon(IconName::AiOpenAi)
     }
 
     fn default_model(&self, _cx: &App) -> Option<Arc<dyn LanguageModel>> {
@@ -278,6 +266,7 @@ impl LanguageModel for OpenAiLanguageModel {
             | Model::FiveMini
             | Model::FiveNano
             | Model::FivePointOne
+            | Model::FivePointTwo
             | Model::O1
             | Model::O3
             | Model::O4Mini => true,
@@ -438,7 +427,7 @@ pub fn into_open_ai(
         messages,
         stream,
         stop: request.stop,
-        temperature: request.temperature.unwrap_or(1.0),
+        temperature: request.temperature.or(Some(1.0)),
         max_completion_tokens: max_output_tokens,
         parallel_tool_calls: if supports_parallel_tool_calls && !request.tools.is_empty() {
             // Disable parallel tool calls, as the Agent currently expects a maximum of one per turn.
@@ -675,8 +664,11 @@ pub fn count_open_ai_tokens(
             | Model::O4Mini
             | Model::Five
             | Model::FiveMini
-            | Model::FiveNano => tiktoken_rs::num_tokens_from_messages(model.id(), &messages), // GPT-5.1 doesn't have tiktoken support yet; fall back on gpt-4o tokenizer
-            Model::FivePointOne => tiktoken_rs::num_tokens_from_messages("gpt-5", &messages),
+            | Model::FiveNano => tiktoken_rs::num_tokens_from_messages(model.id(), &messages),
+            // GPT-5.1 and 5.2 don't have dedicated tiktoken support; use gpt-5 tokenizer
+            Model::FivePointOne | Model::FivePointTwo => {
+                tiktoken_rs::num_tokens_from_messages("gpt-5", &messages)
+            }
         }
         .map(|tokens| tokens as u64)
     })
@@ -786,17 +778,17 @@ impl Render for ConfigurationView {
                 .child(Label::new("To use Zed's agent with OpenAI, you need to add an API key. Follow these steps:"))
                 .child(
                     List::new()
-                        .child(InstructionListItem::new(
-                            "Create one by visiting",
-                            Some("OpenAI's console"),
-                            Some("https://platform.openai.com/api-keys"),
-                        ))
-                        .child(InstructionListItem::text_only(
-                            "Ensure your OpenAI account has credits",
-                        ))
-                        .child(InstructionListItem::text_only(
-                            "Paste your API key below and hit enter to start using the assistant",
-                        )),
+                        .child(
+                            ListBulletItem::new("")
+                                .child(Label::new("Create one by visiting"))
+                                .child(ButtonLink::new("OpenAI's console", "https://platform.openai.com/api-keys"))
+                        )
+                        .child(
+                            ListBulletItem::new("Ensure your OpenAI account has credits")
+                        )
+                        .child(
+                            ListBulletItem::new("Paste your API key below and hit enter to start using the agent")
+                        ),
                 )
                 .child(self.api_key_editor.clone())
                 .child(

crates/language_models/src/provider/open_ai_compatible.rs 🔗

@@ -4,10 +4,10 @@ use futures::{FutureExt, StreamExt, future, future::BoxFuture};
 use gpui::{AnyView, App, AsyncApp, Context, Entity, SharedString, Task, Window};
 use http_client::HttpClient;
 use language_model::{
-    AuthenticateError, LanguageModel, LanguageModelCompletionError, LanguageModelCompletionEvent,
-    LanguageModelId, LanguageModelName, LanguageModelProvider, LanguageModelProviderId,
-    LanguageModelProviderName, LanguageModelProviderState, LanguageModelRequest,
-    LanguageModelToolChoice, LanguageModelToolSchemaFormat, RateLimiter,
+    ApiKeyState, AuthenticateError, EnvVar, IconOrSvg, LanguageModel, LanguageModelCompletionError,
+    LanguageModelCompletionEvent, LanguageModelId, LanguageModelName, LanguageModelProvider,
+    LanguageModelProviderId, LanguageModelProviderName, LanguageModelProviderState,
+    LanguageModelRequest, LanguageModelToolChoice, LanguageModelToolSchemaFormat, RateLimiter,
 };
 use menu;
 use open_ai::{ResponseStreamEvent, stream_completion};
@@ -16,9 +16,7 @@ use std::sync::Arc;
 use ui::{ElevationIndex, Tooltip, prelude::*};
 use ui_input::InputField;
 use util::ResultExt;
-use zed_env_vars::EnvVar;
 
-use crate::api_key::ApiKeyState;
 use crate::provider::open_ai::{OpenAiEventMapper, into_open_ai};
 pub use settings::OpenAiCompatibleAvailableModel as AvailableModel;
 pub use settings::OpenAiCompatibleModelCapabilities as ModelCapabilities;
@@ -38,7 +36,6 @@ pub struct OpenAiCompatibleLanguageModelProvider {
 
 pub struct State {
     id: Arc<str>,
-    api_key_env_var: EnvVar,
     api_key_state: ApiKeyState,
     settings: OpenAiCompatibleSettings,
 }
@@ -56,12 +53,8 @@ impl State {
 
     fn authenticate(&mut self, cx: &mut Context<Self>) -> Task<Result<(), AuthenticateError>> {
         let api_url = SharedString::new(self.settings.api_url.clone());
-        self.api_key_state.load_if_needed(
-            api_url,
-            &self.api_key_env_var,
-            |this| &mut this.api_key_state,
-            cx,
-        )
+        self.api_key_state
+            .load_if_needed(api_url, |this| &mut this.api_key_state, cx)
     }
 }
 
@@ -83,7 +76,6 @@ impl OpenAiCompatibleLanguageModelProvider {
                     let api_url = SharedString::new(settings.api_url.as_str());
                     this.api_key_state.handle_url_change(
                         api_url,
-                        &this.api_key_env_var,
                         |this| &mut this.api_key_state,
                         cx,
                     );
@@ -95,8 +87,10 @@ impl OpenAiCompatibleLanguageModelProvider {
             let settings = resolve_settings(&id, cx).cloned().unwrap_or_default();
             State {
                 id: id.clone(),
-                api_key_env_var: EnvVar::new(api_key_env_var_name),
-                api_key_state: ApiKeyState::new(SharedString::new(settings.api_url.as_str())),
+                api_key_state: ApiKeyState::new(
+                    SharedString::new(settings.api_url.as_str()),
+                    EnvVar::new(api_key_env_var_name),
+                ),
                 settings,
             }
         });
@@ -139,8 +133,8 @@ impl LanguageModelProvider for OpenAiCompatibleLanguageModelProvider {
         self.name.clone()
     }
 
-    fn icon(&self) -> IconName {
-        IconName::AiOpenAiCompat
+    fn icon(&self) -> IconOrSvg {
+        IconOrSvg::Icon(IconName::AiOpenAiCompat)
     }
 
     fn default_model(&self, cx: &App) -> Option<Arc<dyn LanguageModel>> {
@@ -437,7 +431,7 @@ impl Render for ConfigurationView {
     fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
         let state = self.state.read(cx);
         let env_var_set = state.api_key_state.is_from_env_var();
-        let env_var_name = &state.api_key_env_var.name;
+        let env_var_name = state.api_key_state.env_var_name();
 
         let api_key_section = if self.should_render_editor(cx) {
             v_flex()

crates/language_models/src/provider/open_router.rs 🔗

@@ -4,11 +4,12 @@ use futures::{FutureExt, Stream, StreamExt, future, future::BoxFuture};
 use gpui::{AnyView, App, AsyncApp, Context, Entity, SharedString, Task};
 use http_client::HttpClient;
 use language_model::{
-    AuthenticateError, LanguageModel, LanguageModelCompletionError, LanguageModelCompletionEvent,
-    LanguageModelId, LanguageModelName, LanguageModelProvider, LanguageModelProviderId,
-    LanguageModelProviderName, LanguageModelProviderState, LanguageModelRequest,
-    LanguageModelToolChoice, LanguageModelToolResultContent, LanguageModelToolSchemaFormat,
-    LanguageModelToolUse, MessageContent, RateLimiter, Role, StopReason, TokenUsage,
+    ApiKeyState, AuthenticateError, EnvVar, IconOrSvg, LanguageModel, LanguageModelCompletionError,
+    LanguageModelCompletionEvent, LanguageModelId, LanguageModelName, LanguageModelProvider,
+    LanguageModelProviderId, LanguageModelProviderName, LanguageModelProviderState,
+    LanguageModelRequest, LanguageModelToolChoice, LanguageModelToolResultContent,
+    LanguageModelToolSchemaFormat, LanguageModelToolUse, MessageContent, RateLimiter, Role,
+    StopReason, TokenUsage, env_var,
 };
 use open_router::{
     Model, ModelMode as OpenRouterModelMode, OPEN_ROUTER_API_URL, ResponseStreamEvent, list_models,
@@ -17,13 +18,9 @@ use settings::{OpenRouterAvailableModel as AvailableModel, Settings, SettingsSto
 use std::pin::Pin;
 use std::str::FromStr as _;
 use std::sync::{Arc, LazyLock};
-use ui::{List, prelude::*};
+use ui::{ButtonLink, ConfiguredApiCard, List, ListBulletItem, prelude::*};
 use ui_input::InputField;
 use util::ResultExt;
-use zed_env_vars::{EnvVar, env_var};
-
-use crate::ui::ConfiguredApiCard;
-use crate::{api_key::ApiKeyState, ui::InstructionListItem};
 
 const PROVIDER_ID: LanguageModelProviderId = LanguageModelProviderId::new("openrouter");
 const PROVIDER_NAME: LanguageModelProviderName = LanguageModelProviderName::new("OpenRouter");
@@ -62,12 +59,9 @@ impl State {
 
     fn authenticate(&mut self, cx: &mut Context<Self>) -> Task<Result<(), AuthenticateError>> {
         let api_url = OpenRouterLanguageModelProvider::api_url(cx);
-        let task = self.api_key_state.load_if_needed(
-            api_url,
-            &API_KEY_ENV_VAR,
-            |this| &mut this.api_key_state,
-            cx,
-        );
+        let task = self
+            .api_key_state
+            .load_if_needed(api_url, |this| &mut this.api_key_state, cx);
 
         cx.spawn(async move |this, cx| {
             let result = task.await;
@@ -135,7 +129,7 @@ impl OpenRouterLanguageModelProvider {
             })
             .detach();
             State {
-                api_key_state: ApiKeyState::new(Self::api_url(cx)),
+                api_key_state: ApiKeyState::new(Self::api_url(cx), (*API_KEY_ENV_VAR).clone()),
                 http_client: http_client.clone(),
                 available_models: Vec::new(),
                 fetch_models_task: None,
@@ -186,8 +180,8 @@ impl LanguageModelProvider for OpenRouterLanguageModelProvider {
         PROVIDER_NAME
     }
 
-    fn icon(&self) -> IconName {
-        IconName::AiOpenRouter
+    fn icon(&self) -> IconOrSvg {
+        IconOrSvg::Icon(IconName::AiOpenRouter)
     }
 
     fn default_model(&self, _cx: &App) -> Option<Arc<dyn LanguageModel>> {
@@ -376,8 +370,8 @@ impl LanguageModel for OpenRouterLanguageModel {
             LanguageModelCompletionError,
         >,
     > {
-        let request = into_open_router(request, &self.model, self.max_output_tokens());
-        let request = self.stream_completion(request, cx);
+        let openrouter_request = into_open_router(request, &self.model, self.max_output_tokens());
+        let request = self.stream_completion(openrouter_request, cx);
         let future = self.request_limiter.stream(async move {
             let response = request.await?;
             Ok(OpenRouterEventMapper::new().map_stream(response))
@@ -391,15 +385,31 @@ pub fn into_open_router(
     model: &Model,
     max_output_tokens: Option<u64>,
 ) -> open_router::Request {
+    // Anthropic models via OpenRouter don't accept reasoning_details being echoed back
+    // in requests - it's an output-only field for them. However, Gemini models require
+    // the thought signatures to be echoed back for proper reasoning chain continuity.
+    // Note: OpenRouter's model API provides an `architecture.tokenizer` field (e.g. "Claude",
+    // "Gemini") which could replace this ID prefix check, but since this is the only place
+    // we need this distinction, we're just using this less invasive check instead.
+    // If we ever have a more formal distionction between the models in the future,
+    // we should revise this to use that instead.
+    let is_anthropic_model = model.id().starts_with("anthropic/");
+
     let mut messages = Vec::new();
     for message in request.messages {
-        let reasoning_details = message.reasoning_details.clone();
+        let reasoning_details_for_message = if is_anthropic_model {
+            None
+        } else {
+            message.reasoning_details.clone()
+        };
+
         for content in message.content {
             match content {
                 MessageContent::Text(text) => add_message_content_part(
                     open_router::MessagePart::Text { text },
                     message.role,
                     &mut messages,
+                    reasoning_details_for_message.clone(),
                 ),
                 MessageContent::Thinking { .. } => {}
                 MessageContent::RedactedThinking(_) => {}
@@ -410,6 +420,7 @@ pub fn into_open_router(
                         },
                         message.role,
                         &mut messages,
+                        reasoning_details_for_message.clone(),
                     );
                 }
                 MessageContent::ToolUse(tool_use) => {
@@ -425,21 +436,15 @@ pub fn into_open_router(
                         },
                     };
 
-                    if let Some(open_router::RequestMessage::Assistant {
-                        tool_calls,
-                        reasoning_details: existing_reasoning,
-                        ..
-                    }) = messages.last_mut()
+                    if let Some(open_router::RequestMessage::Assistant { tool_calls, .. }) =
+                        messages.last_mut()
                     {
                         tool_calls.push(tool_call);
-                        if existing_reasoning.is_none() && reasoning_details.is_some() {
-                            *existing_reasoning = reasoning_details.clone();
-                        }
                     } else {
                         messages.push(open_router::RequestMessage::Assistant {
                             content: None,
                             tool_calls: vec![tool_call],
-                            reasoning_details: reasoning_details.clone(),
+                            reasoning_details: reasoning_details_for_message.clone(),
                         });
                     }
                 }
@@ -515,6 +520,7 @@ fn add_message_content_part(
     new_part: open_router::MessagePart,
     role: Role,
     messages: &mut Vec<open_router::RequestMessage>,
+    reasoning_details: Option<serde_json::Value>,
 ) {
     match (role, messages.last_mut()) {
         (Role::User, Some(open_router::RequestMessage::User { content }))
@@ -538,7 +544,7 @@ fn add_message_content_part(
                 Role::Assistant => open_router::RequestMessage::Assistant {
                     content: Some(open_router::MessageContent::from(vec![new_part])),
                     tool_calls: Vec::new(),
-                    reasoning_details: None,
+                    reasoning_details,
                 },
                 Role::System => open_router::RequestMessage::System {
                     content: open_router::MessageContent::from(vec![new_part]),
@@ -830,17 +836,15 @@ impl Render for ConfigurationView {
                 .child(Label::new("To use Zed's agent with OpenRouter, you need to add an API key. Follow these steps:"))
                 .child(
                     List::new()
-                        .child(InstructionListItem::new(
-                            "Create an API key by visiting",
-                            Some("OpenRouter's console"),
-                            Some("https://openrouter.ai/keys"),
-                        ))
-                        .child(InstructionListItem::text_only(
-                            "Ensure your OpenRouter account has credits",
-                        ))
-                        .child(InstructionListItem::text_only(
-                            "Paste your API key below and hit enter to start using the assistant",
-                        )),
+                        .child(
+                            ListBulletItem::new("")
+                                .child(Label::new("Create an API key by visiting"))
+                                .child(ButtonLink::new("OpenRouter's console", "https://openrouter.ai/keys"))
+                        )
+                        .child(ListBulletItem::new("Ensure your OpenRouter account has credits")
+                        )
+                        .child(ListBulletItem::new("Paste your API key below and hit enter to start using the assistant")
+                        ),
                 )
                 .child(self.api_key_editor.clone())
                 .child(

crates/language_models/src/provider/vercel.rs 🔗

@@ -4,26 +4,20 @@ use futures::{FutureExt, StreamExt, future, future::BoxFuture};
 use gpui::{AnyView, App, AsyncApp, Context, Entity, SharedString, Task, Window};
 use http_client::HttpClient;
 use language_model::{
-    AuthenticateError, LanguageModel, LanguageModelCompletionError, LanguageModelCompletionEvent,
-    LanguageModelId, LanguageModelName, LanguageModelProvider, LanguageModelProviderId,
-    LanguageModelProviderName, LanguageModelProviderState, LanguageModelRequest,
-    LanguageModelToolChoice, RateLimiter, Role,
+    ApiKeyState, AuthenticateError, EnvVar, IconOrSvg, LanguageModel, LanguageModelCompletionError,
+    LanguageModelCompletionEvent, LanguageModelId, LanguageModelName, LanguageModelProvider,
+    LanguageModelProviderId, LanguageModelProviderName, LanguageModelProviderState,
+    LanguageModelRequest, LanguageModelToolChoice, RateLimiter, Role, env_var,
 };
 use open_ai::ResponseStreamEvent;
 pub use settings::VercelAvailableModel as AvailableModel;
 use settings::{Settings, SettingsStore};
 use std::sync::{Arc, LazyLock};
 use strum::IntoEnumIterator;
-use ui::{List, prelude::*};
+use ui::{ButtonLink, ConfiguredApiCard, List, ListBulletItem, prelude::*};
 use ui_input::InputField;
 use util::ResultExt;
 use vercel::{Model, VERCEL_API_URL};
-use zed_env_vars::{EnvVar, env_var};
-
-use crate::{
-    api_key::ApiKeyState,
-    ui::{ConfiguredApiCard, InstructionListItem},
-};
 
 const PROVIDER_ID: LanguageModelProviderId = LanguageModelProviderId::new("vercel");
 const PROVIDER_NAME: LanguageModelProviderName = LanguageModelProviderName::new("Vercel");
@@ -59,12 +53,8 @@ impl State {
 
     fn authenticate(&mut self, cx: &mut Context<Self>) -> Task<Result<(), AuthenticateError>> {
         let api_url = VercelLanguageModelProvider::api_url(cx);
-        self.api_key_state.load_if_needed(
-            api_url,
-            &API_KEY_ENV_VAR,
-            |this| &mut this.api_key_state,
-            cx,
-        )
+        self.api_key_state
+            .load_if_needed(api_url, |this| &mut this.api_key_state, cx)
     }
 }
 
@@ -73,17 +63,13 @@ impl VercelLanguageModelProvider {
         let state = cx.new(|cx| {
             cx.observe_global::<SettingsStore>(|this: &mut State, cx| {
                 let api_url = Self::api_url(cx);
-                this.api_key_state.handle_url_change(
-                    api_url,
-                    &API_KEY_ENV_VAR,
-                    |this| &mut this.api_key_state,
-                    cx,
-                );
+                this.api_key_state
+                    .handle_url_change(api_url, |this| &mut this.api_key_state, cx);
                 cx.notify();
             })
             .detach();
             State {
-                api_key_state: ApiKeyState::new(Self::api_url(cx)),
+                api_key_state: ApiKeyState::new(Self::api_url(cx), (*API_KEY_ENV_VAR).clone()),
             }
         });
 
@@ -131,8 +117,8 @@ impl LanguageModelProvider for VercelLanguageModelProvider {
         PROVIDER_NAME
     }
 
-    fn icon(&self) -> IconName {
-        IconName::AiVZero
+    fn icon(&self) -> IconOrSvg {
+        IconOrSvg::Icon(IconName::AiVZero)
     }
 
     fn default_model(&self, _cx: &App) -> Option<Arc<dyn LanguageModel>> {
@@ -472,14 +458,14 @@ impl Render for ConfigurationView {
                 .child(Label::new("To use Zed's agent with Vercel v0, you need to add an API key. Follow these steps:"))
                 .child(
                     List::new()
-                        .child(InstructionListItem::new(
-                            "Create one by visiting",
-                            Some("Vercel v0's console"),
-                            Some("https://v0.dev/chat/settings/keys"),
-                        ))
-                        .child(InstructionListItem::text_only(
-                            "Paste your API key below and hit enter to start using the agent",
-                        )),
+                        .child(
+                            ListBulletItem::new("")
+                                .child(Label::new("Create one by visiting"))
+                                .child(ButtonLink::new("Vercel v0's console", "https://v0.dev/chat/settings/keys"))
+                        )
+                        .child(
+                            ListBulletItem::new("Paste your API key below and hit enter to start using the agent")
+                        ),
                 )
                 .child(self.api_key_editor.clone())
                 .child(

crates/language_models/src/provider/x_ai.rs 🔗

@@ -4,26 +4,21 @@ use futures::{FutureExt, StreamExt, future, future::BoxFuture};
 use gpui::{AnyView, App, AsyncApp, Context, Entity, Task, Window};
 use http_client::HttpClient;
 use language_model::{
-    AuthenticateError, LanguageModel, LanguageModelCompletionError, LanguageModelCompletionEvent,
-    LanguageModelId, LanguageModelName, LanguageModelProvider, LanguageModelProviderId,
-    LanguageModelProviderName, LanguageModelProviderState, LanguageModelRequest,
-    LanguageModelToolChoice, LanguageModelToolSchemaFormat, RateLimiter, Role,
+    ApiKeyState, AuthenticateError, EnvVar, IconOrSvg, LanguageModel, LanguageModelCompletionError,
+    LanguageModelCompletionEvent, LanguageModelId, LanguageModelName, LanguageModelProvider,
+    LanguageModelProviderId, LanguageModelProviderName, LanguageModelProviderState,
+    LanguageModelRequest, LanguageModelToolChoice, LanguageModelToolSchemaFormat, RateLimiter,
+    Role, env_var,
 };
 use open_ai::ResponseStreamEvent;
 pub use settings::XaiAvailableModel as AvailableModel;
 use settings::{Settings, SettingsStore};
 use std::sync::{Arc, LazyLock};
 use strum::IntoEnumIterator;
-use ui::{List, prelude::*};
+use ui::{ButtonLink, ConfiguredApiCard, List, ListBulletItem, prelude::*};
 use ui_input::InputField;
 use util::ResultExt;
 use x_ai::{Model, XAI_API_URL};
-use zed_env_vars::{EnvVar, env_var};
-
-use crate::{
-    api_key::ApiKeyState,
-    ui::{ConfiguredApiCard, InstructionListItem},
-};
 
 const PROVIDER_ID: LanguageModelProviderId = LanguageModelProviderId::new("x_ai");
 const PROVIDER_NAME: LanguageModelProviderName = LanguageModelProviderName::new("xAI");
@@ -59,12 +54,8 @@ impl State {
 
     fn authenticate(&mut self, cx: &mut Context<Self>) -> Task<Result<(), AuthenticateError>> {
         let api_url = XAiLanguageModelProvider::api_url(cx);
-        self.api_key_state.load_if_needed(
-            api_url,
-            &API_KEY_ENV_VAR,
-            |this| &mut this.api_key_state,
-            cx,
-        )
+        self.api_key_state
+            .load_if_needed(api_url, |this| &mut this.api_key_state, cx)
     }
 }
 
@@ -73,17 +64,13 @@ impl XAiLanguageModelProvider {
         let state = cx.new(|cx| {
             cx.observe_global::<SettingsStore>(|this: &mut State, cx| {
                 let api_url = Self::api_url(cx);
-                this.api_key_state.handle_url_change(
-                    api_url,
-                    &API_KEY_ENV_VAR,
-                    |this| &mut this.api_key_state,
-                    cx,
-                );
+                this.api_key_state
+                    .handle_url_change(api_url, |this| &mut this.api_key_state, cx);
                 cx.notify();
             })
             .detach();
             State {
-                api_key_state: ApiKeyState::new(Self::api_url(cx)),
+                api_key_state: ApiKeyState::new(Self::api_url(cx), (*API_KEY_ENV_VAR).clone()),
             }
         });
 
@@ -131,8 +118,8 @@ impl LanguageModelProvider for XAiLanguageModelProvider {
         PROVIDER_NAME
     }
 
-    fn icon(&self) -> IconName {
-        IconName::AiXAi
+    fn icon(&self) -> IconOrSvg {
+        IconOrSvg::Icon(IconName::AiXAi)
     }
 
     fn default_model(&self, _cx: &App) -> Option<Arc<dyn LanguageModel>> {
@@ -474,14 +461,14 @@ impl Render for ConfigurationView {
                 .child(Label::new("To use Zed's agent with xAI, you need to add an API key. Follow these steps:"))
                 .child(
                     List::new()
-                        .child(InstructionListItem::new(
-                            "Create one by visiting",
-                            Some("xAI console"),
-                            Some("https://console.x.ai/team/default/api-keys"),
-                        ))
-                        .child(InstructionListItem::text_only(
-                            "Paste your API key below and hit enter to start using the agent",
-                        )),
+                        .child(
+                            ListBulletItem::new("")
+                                .child(Label::new("Create one by visiting"))
+                                .child(ButtonLink::new("xAI console", "https://console.x.ai/team/default/api-keys"))
+                        )
+                        .child(
+                            ListBulletItem::new("Paste your API key below and hit enter to start using the agent")
+                        ),
                 )
                 .child(self.api_key_editor.clone())
                 .child(

crates/language_models/src/settings.rs 🔗

@@ -58,6 +58,7 @@ impl settings::Settings for AllLanguageModelSettings {
                 profile_name: bedrock.profile,
                 role_arn: None, // todo(was never a setting for this...)
                 authentication_method: bedrock.authentication_method.map(Into::into),
+                allow_global: bedrock.allow_global,
             },
             deepseek: DeepSeekSettings {
                 api_url: deepseek.api_url.unwrap(),
@@ -77,6 +78,7 @@ impl settings::Settings for AllLanguageModelSettings {
             },
             ollama: OllamaSettings {
                 api_url: ollama.api_url.unwrap(),
+                auto_discover: ollama.auto_discover.unwrap_or(true),
                 available_models: ollama.available_models.unwrap_or_default(),
             },
             open_router: OpenRouterSettings {

crates/language_models/src/ui.rs 🔗

@@ -1,4 +0,0 @@
-pub mod configured_api_card;
-pub mod instruction_list_item;
-pub use configured_api_card::ConfiguredApiCard;
-pub use instruction_list_item::InstructionListItem;

crates/language_models/src/ui/instruction_list_item.rs 🔗

@@ -1,69 +0,0 @@
-use gpui::{AnyElement, IntoElement, ParentElement, SharedString};
-use ui::{ListItem, prelude::*};
-
-/// A reusable list item component for adding LLM provider configuration instructions
-pub struct InstructionListItem {
-    label: SharedString,
-    button_label: Option<SharedString>,
-    button_link: Option<String>,
-}
-
-impl InstructionListItem {
-    pub fn new(
-        label: impl Into<SharedString>,
-        button_label: Option<impl Into<SharedString>>,
-        button_link: Option<impl Into<String>>,
-    ) -> Self {
-        Self {
-            label: label.into(),
-            button_label: button_label.map(|l| l.into()),
-            button_link: button_link.map(|l| l.into()),
-        }
-    }
-
-    pub fn text_only(label: impl Into<SharedString>) -> Self {
-        Self {
-            label: label.into(),
-            button_label: None,
-            button_link: None,
-        }
-    }
-}
-
-impl IntoElement for InstructionListItem {
-    type Element = AnyElement;
-
-    fn into_element(self) -> Self::Element {
-        let item_content = if let (Some(button_label), Some(button_link)) =
-            (self.button_label, self.button_link)
-        {
-            let link = button_link;
-            let unique_id = SharedString::from(format!("{}-button", self.label));
-
-            h_flex()
-                .flex_wrap()
-                .child(Label::new(self.label))
-                .child(
-                    Button::new(unique_id, button_label)
-                        .style(ButtonStyle::Subtle)
-                        .icon(IconName::ArrowUpRight)
-                        .icon_size(IconSize::Small)
-                        .icon_color(Color::Muted)
-                        .on_click(move |_, _window, cx| cx.open_url(&link)),
-                )
-                .into_any_element()
-        } else {
-            Label::new(self.label).into_any_element()
-        };
-
-        ListItem::new("list-item")
-            .selectable(false)
-            .start_slot(
-                Icon::new(IconName::Dash)
-                    .size(IconSize::XSmall)
-                    .color(Color::Hidden),
-            )
-            .child(div().w_full().child(item_content))
-            .into_any_element()
-    }
-}

crates/language_tools/src/lsp_button.rs 🔗

@@ -127,6 +127,16 @@ impl LanguageServerState {
             return menu;
         };
 
+        let server_versions = self
+            .lsp_store
+            .update(cx, |lsp_store, _| {
+                lsp_store
+                    .language_server_statuses()
+                    .map(|(server_id, status)| (server_id, status.server_version.clone()))
+                    .collect::<HashMap<_, _>>()
+            })
+            .unwrap_or_default();
+
         let mut first_button_encountered = false;
         for item in &self.items {
             if let LspMenuItem::ToggleServersButton { restart } = item {
@@ -254,6 +264,22 @@ impl LanguageServerState {
             };
 
             let server_name = server_info.name.clone();
+            let server_version = server_versions
+                .get(&server_info.id)
+                .and_then(|version| version.clone());
+
+            let tooltip_text = match (&server_version, &message) {
+                (None, None) => None,
+                (Some(version), None) => {
+                    Some(SharedString::from(format!("Version: {}", version.as_ref())))
+                }
+                (None, Some(message)) => Some(message.clone()),
+                (Some(version), Some(message)) => Some(SharedString::from(format!(
+                    "Version: {}\n\n{}",
+                    version.as_ref(),
+                    message.as_ref()
+                ))),
+            };
             menu = menu.item(ContextMenuItem::custom_entry(
                 move |_, _| {
                     h_flex()
@@ -355,11 +381,11 @@ impl LanguageServerState {
                         }
                     }
                 },
-                message.map(|server_message| {
+                tooltip_text.map(|tooltip_text| {
                     DocumentationAside::new(
                         DocumentationSide::Right,
-                        DocumentationEdge::Bottom,
-                        Rc::new(move |_| Label::new(server_message.clone()).into_any_element()),
+                        DocumentationEdge::Top,
+                        Rc::new(move |_| Label::new(tooltip_text.clone()).into_any_element()),
                     )
                 }),
             ));

crates/language_tools/src/lsp_log_view.rs 🔗

@@ -125,7 +125,7 @@ pub fn init(on_headless_host: bool, cx: &mut App) {
                     let server_id = server.server_id();
                     let weak_lsp_store = cx.weak_entity();
                     log_store.copilot_log_subscription =
-                        Some(server.on_notification::<copilot::request::LogMessage, _>(
+                        Some(server.on_notification::<lsp::notification::LogMessage, _>(
                             move |params, cx| {
                                 weak_lsp_store
                                     .update(cx, |lsp_store, cx| {
@@ -269,7 +269,7 @@ impl LspLogView {
 
         let focus_handle = cx.focus_handle();
         let focus_subscription = cx.on_focus(&focus_handle, window, |log_view, window, cx| {
-            window.focus(&log_view.editor.focus_handle(cx));
+            window.focus(&log_view.editor.focus_handle(cx), cx);
         });
 
         cx.on_release(|log_view, cx| {
@@ -330,6 +330,8 @@ impl LspLogView {
         let server_info = format!(
             "* Server: {NAME} (id {ID})
 
+* Version: {VERSION}
+
 * Binary: {BINARY}
 
 * Registered workspace folders:
@@ -340,6 +342,12 @@ impl LspLogView {
 * Configuration: {CONFIGURATION}",
             NAME = info.status.name,
             ID = info.id,
+            VERSION = info
+                .status
+                .server_version
+                .as_ref()
+                .map(|version| version.as_ref())
+                .unwrap_or("Unknown"),
             BINARY = info
                 .status
                 .binary
@@ -462,7 +470,7 @@ impl LspLogView {
             self.editor_subscriptions = editor_subscriptions;
             cx.notify();
         }
-        self.editor.read(cx).focus_handle(cx).focus(window);
+        self.editor.read(cx).focus_handle(cx).focus(window, cx);
         self.log_store.update(cx, |log_store, cx| {
             let state = log_store.get_language_server_state(server_id)?;
             state.toggled_log_kind = Some(LogKind::Logs);
@@ -494,7 +502,7 @@ impl LspLogView {
             cx.notify();
         }
 
-        self.editor.read(cx).focus_handle(cx).focus(window);
+        self.editor.read(cx).focus_handle(cx).focus(window, cx);
     }
 
     fn show_trace_for_server(
@@ -528,7 +536,7 @@ impl LspLogView {
             });
             cx.notify();
         }
-        self.editor.read(cx).focus_handle(cx).focus(window);
+        self.editor.read(cx).focus_handle(cx).focus(window, cx);
     }
 
     fn show_rpc_trace_for_server(
@@ -572,7 +580,7 @@ impl LspLogView {
             cx.notify();
         }
 
-        self.editor.read(cx).focus_handle(cx).focus(window);
+        self.editor.read(cx).focus_handle(cx).focus(window, cx);
     }
 
     fn toggle_rpc_trace_for_server(
@@ -660,7 +668,7 @@ impl LspLogView {
         self.editor = editor;
         self.editor_subscriptions = editor_subscriptions;
         cx.notify();
-        self.editor.read(cx).focus_handle(cx).focus(window);
+        self.editor.read(cx).focus_handle(cx).focus(window, cx);
         self.log_store.update(cx, |log_store, cx| {
             let state = log_store.get_language_server_state(server_id)?;
             if let Some(log_kind) = state.toggled_log_kind.take() {
@@ -805,11 +813,13 @@ impl SearchableItem for LspLogView {
     fn update_matches(
         &mut self,
         matches: &[Self::Match],
+        active_match_index: Option<usize>,
         window: &mut Window,
         cx: &mut Context<Self>,
     ) {
-        self.editor
-            .update(cx, |e, cx| e.update_matches(matches, window, cx))
+        self.editor.update(cx, |e, cx| {
+            e.update_matches(matches, active_match_index, window, cx)
+        })
     }
 
     fn query_suggestion(&mut self, window: &mut Window, cx: &mut Context<Self>) -> String {
@@ -937,7 +947,7 @@ impl Render for LspLogToolbarItemView {
             })
             .collect();
 
-        let log_toolbar_view = cx.entity();
+        let log_toolbar_view = cx.weak_entity();
 
         let lsp_menu = PopoverMenu::new("LspLogView")
             .anchor(Corner::TopLeft)
@@ -1021,7 +1031,7 @@ impl Render for LspLogToolbarItemView {
                         .icon_color(Color::Muted),
                 )
                 .menu(move |window, cx| {
-                    let log_toolbar_view = log_toolbar_view.clone();
+                    let log_toolbar_view = log_toolbar_view.upgrade()?;
                     let log_view = log_view.clone();
                     Some(ContextMenu::build(window, cx, move |this, window, _| {
                         this.entry(
@@ -1312,7 +1322,7 @@ impl LspLogToolbarItemView {
                     log_view.show_rpc_trace_for_server(id, window, cx);
                     cx.notify();
                 }
-                window.focus(&log_view.focus_handle);
+                window.focus(&log_view.focus_handle, cx);
             });
         }
         cx.notify();
@@ -1332,6 +1342,7 @@ impl ServerInfo {
             capabilities: server.capabilities(),
             status: LanguageServerStatus {
                 name: server.name(),
+                server_version: server.version(),
                 pending_work: Default::default(),
                 has_pending_diagnostic_updates: false,
                 progress_tokens: Default::default(),

crates/language_tools/src/syntax_tree_view.rs 🔗

@@ -459,7 +459,7 @@ impl SyntaxTreeView {
                                         editor.clear_background_highlights::<Self>(cx);
                                         editor.highlight_background::<Self>(
                                             &[range],
-                                            |theme| {
+                                            |_, theme| {
                                                 theme
                                                     .colors()
                                                     .editor_document_highlight_write_background
@@ -614,13 +614,14 @@ impl SyntaxTreeToolbarItemView {
         let active_layer = buffer_state.active_layer.clone()?;
         let active_buffer = buffer_state.buffer.read(cx).snapshot();
 
-        let view = cx.entity();
+        let view = cx.weak_entity();
         Some(
             PopoverMenu::new("Syntax Tree")
                 .trigger(Self::render_header(&active_layer))
                 .menu(move |window, cx| {
-                    ContextMenu::build(window, cx, |mut menu, window, _| {
+                    ContextMenu::build(window, cx, |mut menu, _, _| {
                         for (layer_ix, layer) in active_buffer.syntax_layers().enumerate() {
+                            let view = view.clone();
                             menu = menu.entry(
                                 format!(
                                     "{} {}",
@@ -628,9 +629,12 @@ impl SyntaxTreeToolbarItemView {
                                     format_node_range(layer.node())
                                 ),
                                 None,
-                                window.handler_for(&view, move |view, window, cx| {
-                                    view.select_layer(layer_ix, window, cx);
-                                }),
+                                move |window, cx| {
+                                    view.update(cx, |view, cx| {
+                                        view.select_layer(layer_ix, window, cx);
+                                    })
+                                    .ok();
+                                },
                             );
                         }
                         menu
@@ -655,7 +659,7 @@ impl SyntaxTreeToolbarItemView {
             buffer_state.active_layer = Some(layer.to_owned());
             view.selected_descendant_ix = None;
             cx.notify();
-            view.focus_handle.focus(window);
+            view.focus_handle.focus(window, cx);
             Some(())
         })
     }

crates/languages/Cargo.toml 🔗

@@ -68,6 +68,7 @@ serde_json.workspace = true
 serde_json_lenient.workspace = true
 settings.workspace = true
 smallvec.workspace = true
+semver.workspace = true
 smol.workspace = true
 snippet.workspace = true
 task.workspace = true

crates/languages/src/c.rs 🔗

@@ -3,7 +3,7 @@ use async_trait::async_trait;
 use futures::StreamExt;
 use gpui::{App, AsyncApp};
 use http_client::github::{AssetKind, GitHubLspBinaryVersion, latest_github_release};
-use http_client::github_download::fetch_github_binary_with_digest_check;
+use http_client::github_download::{GithubBinaryMetadata, download_server_binary};
 pub use language::*;
 use lsp::{InitializeParams, LanguageServerBinary, LanguageServerName};
 use project::lsp_store::clangd_ext;
@@ -85,32 +85,55 @@ impl LspInstaller for CLspAdapter {
         };
 
         let metadata_path = version_dir.join("metadata");
-
-        let binary_path_for_check = binary_path.clone();
-        fetch_github_binary_with_digest_check(
-            &binary_path,
-            &metadata_path,
-            expected_digest,
-            &url,
-            AssetKind::Zip,
-            &container_dir,
-            &*delegate.http_client(),
-            || async move {
+        let metadata = GithubBinaryMetadata::read_from_file(&metadata_path)
+            .await
+            .ok();
+        if let Some(metadata) = metadata {
+            let validity_check = async || {
                 delegate
                     .try_exec(LanguageServerBinary {
-                        path: binary_path_for_check,
+                        path: binary_path.clone(),
                         arguments: vec!["--version".into()],
                         env: None,
                     })
                     .await
                     .inspect_err(|err| {
-                        log::warn!("Unable to run clangd asset, redownloading: {err:#}")
+                        log::warn!("Unable to run {binary_path:?} asset, redownloading: {err:#}",)
                     })
-            },
+            };
+            if let (Some(actual_digest), Some(expected_digest)) =
+                (&metadata.digest, &expected_digest)
+            {
+                if actual_digest == expected_digest {
+                    if validity_check().await.is_ok() {
+                        return Ok(binary);
+                    }
+                } else {
+                    log::info!(
+                        "SHA-256 mismatch for {binary_path:?} asset, downloading new asset. Expected: {expected_digest}, Got: {actual_digest}"
+                    );
+                }
+            } else if validity_check().await.is_ok() {
+                return Ok(binary);
+            }
+        }
+        download_server_binary(
+            &*delegate.http_client(),
+            &url,
+            expected_digest.as_deref(),
+            &container_dir,
+            AssetKind::Zip,
         )
         .await?;
-
         remove_matching(&container_dir, |entry| entry != version_dir).await;
+        GithubBinaryMetadata::write_to_file(
+            &GithubBinaryMetadata {
+                metadata_version: 1,
+                digest: expected_digest,
+            },
+            &metadata_path,
+        )
+        .await?;
 
         Ok(binary)
     }

crates/languages/src/c/injections.scm 🔗

@@ -1,7 +1,6 @@
 ((comment) @injection.content
-  (#match? @injection.content "^(///|//!|/\\*\\*|/\\*!)(.*)")
-  (#set! injection.language "doxygen")
-  (#set! injection.include-children))
+ (#set! injection.language "comment")
+)
 
 (preproc_def
     value: (preproc_arg) @injection.content

crates/languages/src/cpp/brackets.scm 🔗

@@ -1,5 +1,6 @@
 ("(" @open ")" @close)
 ("[" @open "]" @close)
 ("{" @open "}" @close)
+("<" @open ">" @close)
 (("\"" @open "\"" @close) (#set! rainbow.exclude))
 (("'" @open "'" @close) (#set! rainbow.exclude))

crates/languages/src/cpp/injections.scm 🔗

@@ -1,7 +1,6 @@
 ((comment) @injection.content
-  (#match? @injection.content "^(///|//!|/\\*\\*|/\\*!)(.*)")
-  (#set! injection.language "doxygen")
-  (#set! injection.include-children))
+ (#set! injection.language "comment")
+)
 
 (preproc_def
     value: (preproc_arg) @injection.content

crates/languages/src/cpp/textobjects.scm 🔗

@@ -24,6 +24,12 @@
         [(_) ","?]* @class.inside
         "}")) @class.around
 
+(union_specifier
+    body: (_
+        "{"
+        (_)* @class.inside
+        "}")) @class.around
+
 (class_specifier
   body: (_
       "{"

crates/languages/src/css.rs 🔗

@@ -5,6 +5,7 @@ use language::{LspAdapter, LspAdapterDelegate, LspInstaller, Toolchain};
 use lsp::{LanguageServerBinary, LanguageServerName, Uri};
 use node_runtime::{NodeRuntime, VersionStrategy};
 use project::lsp_store::language_server_settings;
+use semver::Version;
 use serde_json::json;
 use std::{
     ffi::OsString,
@@ -32,14 +33,14 @@ impl CssLspAdapter {
 }
 
 impl LspInstaller for CssLspAdapter {
-    type BinaryVersion = String;
+    type BinaryVersion = Version;
 
     async fn fetch_latest_server_version(
         &self,
         _: &dyn LspAdapterDelegate,
         _: bool,
         _: &mut AsyncApp,
-    ) -> Result<String> {
+    ) -> Result<Self::BinaryVersion> {
         self.node
             .npm_package_latest_version("vscode-langservers-extracted")
             .await
@@ -65,11 +66,12 @@ impl LspInstaller for CssLspAdapter {
 
     async fn fetch_server_binary(
         &self,
-        latest_version: String,
+        latest_version: Self::BinaryVersion,
         container_dir: PathBuf,
         _: &dyn LspAdapterDelegate,
     ) -> Result<LanguageServerBinary> {
         let server_path = container_dir.join(SERVER_PATH);
+        let latest_version = latest_version.to_string();
 
         self.node
             .npm_install_packages(
@@ -87,7 +89,7 @@ impl LspInstaller for CssLspAdapter {
 
     async fn check_if_version_installed(
         &self,
-        version: &String,
+        version: &Self::BinaryVersion,
         container_dir: &PathBuf,
         _: &dyn LspAdapterDelegate,
     ) -> Option<LanguageServerBinary> {

crates/languages/src/eslint.rs 🔗

@@ -126,11 +126,11 @@ impl LspInstaller for EsLintLspAdapter {
             }
 
             self.node
-                .run_npm_subcommand(&repo_root, "install", &[])
+                .run_npm_subcommand(Some(&repo_root), "install", &[])
                 .await?;
 
             self.node
-                .run_npm_subcommand(&repo_root, "run-script", &["compile"])
+                .run_npm_subcommand(Some(&repo_root), "run-script", &["compile"])
                 .await?;
         }
 

crates/languages/src/go.rs 🔗

@@ -73,7 +73,9 @@ impl LspInstaller for GoLspAdapter {
                     delegate.show_notification(NOTIFICATION_MESSAGE, cx);
                 })?
             }
-            anyhow::bail!("cannot install gopls");
+            anyhow::bail!(
+                "Could not install the Go language server `gopls`, because `go` was not found."
+            );
         }
 
         let release =

crates/languages/src/go/injections.scm 🔗

@@ -19,360 +19,717 @@
 
 ; INJECT SQL
 (
-	[
-		; var, const or short declaration of raw or interpreted string literal
-		((comment) @comment
-  		.
-    	(expression_list
-     	[
-      		(interpreted_string_literal)
-        	(raw_string_literal)
-        ] @injection.content
-        ))
-
-        ; when passing as a literal element (to struct field eg.)
-		((comment) @comment
-        .
-        (literal_element
-        [
-        	(interpreted_string_literal)
-        	(raw_string_literal)
-        ] @injection.content
-        ))
-
-        ; when passing as a function parameter
-        ((comment) @comment
-        .
-        [
-        	(interpreted_string_literal)
-        	(raw_string_literal)
-        ] @injection.content)
-    ]
+    [
+        (const_spec
+            name: (identifier)
+            "="
+            (comment) @_comment
+            value: (expression_list
+            [
+                (interpreted_string_literal (interpreted_string_literal_content) @injection.content)
+                (raw_string_literal (raw_string_literal_content) @injection.content)
+            ]
+        ))
+
+        (var_spec
+            name: (identifier)
+            "="
+            (comment) @_comment
+            value: (expression_list
+            [
+                (interpreted_string_literal (interpreted_string_literal_content) @injection.content)
+                (raw_string_literal (raw_string_literal_content) @injection.content)
+            ]
+        ))
+
+        (assignment_statement
+        left: (expression_list)
+        "="
+        (comment) @_comment
+        right: (expression_list
+            [
+                (interpreted_string_literal (interpreted_string_literal_content) @injection.content)
+                (raw_string_literal (raw_string_literal_content) @injection.content)
+            ]
+        ))
 
-    (#match? @comment "^\\/\\*\\s*sql\\s*\\*\\/") ; /* sql */ or /*sql*/
-    (#set! injection.language "sql")
+        (short_var_declaration
+        left: (expression_list)
+        ":="
+        (comment) @_comment
+        right: (expression_list
+            [
+                (interpreted_string_literal (interpreted_string_literal_content) @injection.content)
+                (raw_string_literal (raw_string_literal_content) @injection.content)
+            ]
+        ))
+
+        (composite_literal
+            body: (literal_value
+            (keyed_element
+            (comment) @_comment
+            value: (literal_element
+            [
+                (interpreted_string_literal (interpreted_string_literal_content) @injection.content)
+                (raw_string_literal (raw_string_literal_content) @injection.content)
+            ]
+        ))))
+
+        (expression_statement
+            (call_expression
+            (argument_list
+            (comment) @_comment
+            [
+               	(interpreted_string_literal (interpreted_string_literal_content) @injection.content)
+                (raw_string_literal (raw_string_literal_content) @injection.content)
+            ]
+        )))
+    ]
+  (#match? @_comment "^\\/\\*\\s*sql\\s*\\*\\/$")
+  (#set! injection.language "sql")
 )
 
 ; INJECT JSON
 (
-	[
-		; var, const or short declaration of raw or interpreted string literal
-		((comment) @comment
-  		.
-    	(expression_list
-     	[
-      		(interpreted_string_literal)
-        	(raw_string_literal)
-        ] @injection.content
-        ))
-
-        ; when passing as a literal element (to struct field eg.)
-		((comment) @comment
-        .
-        (literal_element
-        [
-        	(interpreted_string_literal)
-        	(raw_string_literal)
-        ] @injection.content
-        ))
-
-        ; when passing as a function parameter
-        ((comment) @comment
-        .
-        [
-        	(interpreted_string_literal)
-        	(raw_string_literal)
-        ] @injection.content)
-    ]
+    [
+        (const_spec
+            name: (identifier)
+            "="
+            (comment) @_comment
+            value: (expression_list
+            [
+                (interpreted_string_literal (interpreted_string_literal_content) @injection.content)
+                (raw_string_literal (raw_string_literal_content) @injection.content)
+            ]
+        ))
 
-    (#match? @comment "^\\/\\*\\s*json\\s*\\*\\/") ; /* json */ or /*json*/
+        (var_spec
+            name: (identifier)
+            "="
+            (comment) @_comment
+            value: (expression_list
+            [
+                (interpreted_string_literal (interpreted_string_literal_content) @injection.content)
+                (raw_string_literal (raw_string_literal_content) @injection.content)
+            ]
+        ))
+
+        (assignment_statement
+        left: (expression_list)
+        "="
+        (comment) @_comment
+        right: (expression_list
+            [
+                (interpreted_string_literal (interpreted_string_literal_content) @injection.content)
+                (raw_string_literal (raw_string_literal_content) @injection.content)
+            ]
+        ))
+
+        (short_var_declaration
+        left: (expression_list)
+        ":="
+        (comment) @_comment
+        right: (expression_list
+            [
+                (interpreted_string_literal (interpreted_string_literal_content) @injection.content)
+                (raw_string_literal (raw_string_literal_content) @injection.content)
+            ]
+        ))
+
+        (composite_literal
+            body: (literal_value
+            (keyed_element
+            (comment) @_comment
+            value: (literal_element
+            [
+                (interpreted_string_literal (interpreted_string_literal_content) @injection.content)
+                (raw_string_literal (raw_string_literal_content) @injection.content)
+            ]
+        ))))
+
+        (expression_statement
+            (call_expression
+            (argument_list
+            (comment) @_comment
+            [
+               	(interpreted_string_literal (interpreted_string_literal_content) @injection.content)
+                (raw_string_literal (raw_string_literal_content) @injection.content)
+            ]
+        )))
+    ]
+    (#match? @_comment "^\\/\\*\\s*json\\s*\\*\\/") ; /* json */ or /*json*/
     (#set! injection.language "json")
 )
 
 ; INJECT YAML
 (
-	[
-		; var, const or short declaration of raw or interpreted string literal
-		((comment) @comment
-  		.
-    	(expression_list
-     	[
-      		(interpreted_string_literal)
-        	(raw_string_literal)
-        ] @injection.content
-        ))
-
-        ; when passing as a literal element (to struct field eg.)
-		((comment) @comment
-        .
-        (literal_element
-        [
-        	(interpreted_string_literal)
-        	(raw_string_literal)
-        ] @injection.content
-        ))
-
-        ; when passing as a function parameter
-        ((comment) @comment
-        .
-        [
-        	(interpreted_string_literal)
-        	(raw_string_literal)
-        ] @injection.content)
-    ]
+    [
+        (const_spec
+            name: (identifier)
+            "="
+            (comment) @_comment
+            value: (expression_list
+            [
+                (interpreted_string_literal (interpreted_string_literal_content) @injection.content)
+                (raw_string_literal (raw_string_literal_content) @injection.content)
+            ]
+        ))
+
+        (var_spec
+            name: (identifier)
+            "="
+            (comment) @_comment
+            value: (expression_list
+            [
+                (interpreted_string_literal (interpreted_string_literal_content) @injection.content)
+                (raw_string_literal (raw_string_literal_content) @injection.content)
+            ]
+        ))
+
+        (assignment_statement
+        left: (expression_list)
+        "="
+        (comment) @_comment
+        right: (expression_list
+            [
+                (interpreted_string_literal (interpreted_string_literal_content) @injection.content)
+                (raw_string_literal (raw_string_literal_content) @injection.content)
+            ]
+        ))
+
+        (short_var_declaration
+        left: (expression_list)
+        ":="
+        (comment) @_comment
+        right: (expression_list
+            [
+                (interpreted_string_literal (interpreted_string_literal_content) @injection.content)
+                (raw_string_literal (raw_string_literal_content) @injection.content)
+            ]
+        ))
 
-    (#match? @comment "^\\/\\*\\s*yaml\\s*\\*\\/") ; /* yaml */ or /*yaml*/
+        (composite_literal
+            body: (literal_value
+            (keyed_element
+            (comment) @_comment
+            value: (literal_element
+            [
+                (interpreted_string_literal (interpreted_string_literal_content) @injection.content)
+                (raw_string_literal (raw_string_literal_content) @injection.content)
+            ]
+        ))))
+
+        (expression_statement
+            (call_expression
+            (argument_list
+            (comment) @_comment
+            [
+               	(interpreted_string_literal (interpreted_string_literal_content) @injection.content)
+                (raw_string_literal (raw_string_literal_content) @injection.content)
+            ]
+        )))
+    ]
+    (#match? @_comment "^\\/\\*\\s*yaml\\s*\\*\\/") ; /* yaml */ or /*yaml*/
     (#set! injection.language "yaml")
 )
 
 ; INJECT XML
 (
-	[
-		; var, const or short declaration of raw or interpreted string literal
-		((comment) @comment
-  		.
-    	(expression_list
-     	[
-      		(interpreted_string_literal)
-        	(raw_string_literal)
-        ] @injection.content
-        ))
-
-        ; when passing as a literal element (to struct field eg.)
-		((comment) @comment
-        .
-        (literal_element
-        [
-        	(interpreted_string_literal)
-        	(raw_string_literal)
-        ] @injection.content
-        ))
-
-        ; when passing as a function parameter
-        ((comment) @comment
-        .
-        [
-        	(interpreted_string_literal)
-        	(raw_string_literal)
-        ] @injection.content)
-    ]
+    [
+        (const_spec
+            name: (identifier)
+            "="
+            (comment) @_comment
+            value: (expression_list
+            [
+                (interpreted_string_literal (interpreted_string_literal_content) @injection.content)
+                (raw_string_literal (raw_string_literal_content) @injection.content)
+            ]
+        ))
+
+        (var_spec
+            name: (identifier)
+            "="
+            (comment) @_comment
+            value: (expression_list
+            [
+                (interpreted_string_literal (interpreted_string_literal_content) @injection.content)
+                (raw_string_literal (raw_string_literal_content) @injection.content)
+            ]
+        ))
+
+        (assignment_statement
+        left: (expression_list)
+        "="
+        (comment) @_comment
+        right: (expression_list
+            [
+                (interpreted_string_literal (interpreted_string_literal_content) @injection.content)
+                (raw_string_literal (raw_string_literal_content) @injection.content)
+            ]
+        ))
+
+        (short_var_declaration
+        left: (expression_list)
+        ":="
+        (comment) @_comment
+        right: (expression_list
+            [
+                (interpreted_string_literal (interpreted_string_literal_content) @injection.content)
+                (raw_string_literal (raw_string_literal_content) @injection.content)
+            ]
+        ))
 
-    (#match? @comment "^\\/\\*\\s*xml\\s*\\*\\/") ; /* xml */ or /*xml*/
+        (composite_literal
+            body: (literal_value
+            (keyed_element
+            (comment) @_comment
+            value: (literal_element
+            [
+                (interpreted_string_literal (interpreted_string_literal_content) @injection.content)
+                (raw_string_literal (raw_string_literal_content) @injection.content)
+            ]
+        ))))
+
+        (expression_statement
+            (call_expression
+            (argument_list
+            (comment) @_comment
+            [
+               	(interpreted_string_literal (interpreted_string_literal_content) @injection.content)
+                (raw_string_literal (raw_string_literal_content) @injection.content)
+            ]
+        )))
+    ]
+    (#match? @_comment "^\\/\\*\\s*xml\\s*\\*\\/") ; /* xml */ or /*xml*/
     (#set! injection.language "xml")
 )
 
 ; INJECT HTML
 (
-	[
-		; var, const or short declaration of raw or interpreted string literal
-		((comment) @comment
-  		.
-    	(expression_list
-     	[
-      		(interpreted_string_literal)
-        	(raw_string_literal)
-        ] @injection.content
-        ))
-
-        ; when passing as a literal element (to struct field eg.)
-		((comment) @comment
-        .
-        (literal_element
-        [
-        	(interpreted_string_literal)
-        	(raw_string_literal)
-        ] @injection.content
-        ))
-
-        ; when passing as a function parameter
-        ((comment) @comment
-        .
-        [
-        	(interpreted_string_literal)
-        	(raw_string_literal)
-        ] @injection.content)
-    ]
+    [
+        (const_spec
+            name: (identifier)
+            "="
+            (comment) @_comment
+            value: (expression_list
+            [
+                (interpreted_string_literal (interpreted_string_literal_content) @injection.content)
+                (raw_string_literal (raw_string_literal_content) @injection.content)
+            ]
+        ))
 
-    (#match? @comment "^\\/\\*\\s*html\\s*\\*\\/") ; /* html */ or /*html*/
+        (var_spec
+            name: (identifier)
+            "="
+            (comment) @_comment
+            value: (expression_list
+            [
+                (interpreted_string_literal (interpreted_string_literal_content) @injection.content)
+                (raw_string_literal (raw_string_literal_content) @injection.content)
+            ]
+        ))
+
+        (assignment_statement
+        left: (expression_list)
+        "="
+        (comment) @_comment
+        right: (expression_list
+            [
+                (interpreted_string_literal (interpreted_string_literal_content) @injection.content)
+                (raw_string_literal (raw_string_literal_content) @injection.content)
+            ]
+        ))
+
+        (short_var_declaration
+        left: (expression_list)
+        ":="
+        (comment) @_comment
+        right: (expression_list
+            [
+                (interpreted_string_literal (interpreted_string_literal_content) @injection.content)
+                (raw_string_literal (raw_string_literal_content) @injection.content)
+            ]
+        ))
+
+        (composite_literal
+            body: (literal_value
+            (keyed_element
+            (comment) @_comment
+            value: (literal_element
+            [
+                (interpreted_string_literal (interpreted_string_literal_content) @injection.content)
+                (raw_string_literal (raw_string_literal_content) @injection.content)
+            ]
+        ))))
+
+        (expression_statement
+            (call_expression
+            (argument_list
+            (comment) @_comment
+            [
+               	(interpreted_string_literal (interpreted_string_literal_content) @injection.content)
+                (raw_string_literal (raw_string_literal_content) @injection.content)
+            ]
+        )))
+    ]
+    (#match? @_comment "^\\/\\*\\s*html\\s*\\*\\/") ; /* html */ or /*html*/
     (#set! injection.language "html")
 )
 
 ; INJECT JS
 (
-	[
-		; var, const or short declaration of raw or interpreted string literal
-		((comment) @comment
-  		.
-    	(expression_list
-     	[
-      		(interpreted_string_literal)
-        	(raw_string_literal)
-        ] @injection.content
-        ))
-
-        ; when passing as a literal element (to struct field eg.)
-		((comment) @comment
-        .
-        (literal_element
-        [
-        	(interpreted_string_literal)
-        	(raw_string_literal)
-        ] @injection.content
-        ))
-
-        ; when passing as a function parameter
-        ((comment) @comment
-        .
-        [
-        	(interpreted_string_literal)
-        	(raw_string_literal)
-        ] @injection.content)
-    ]
+    [
+        (const_spec
+            name: (identifier)
+            "="
+            (comment) @_comment
+            value: (expression_list
+            [
+                (interpreted_string_literal (interpreted_string_literal_content) @injection.content)
+                (raw_string_literal (raw_string_literal_content) @injection.content)
+            ]
+        ))
+
+        (var_spec
+            name: (identifier)
+            "="
+            (comment) @_comment
+            value: (expression_list
+            [
+                (interpreted_string_literal (interpreted_string_literal_content) @injection.content)
+                (raw_string_literal (raw_string_literal_content) @injection.content)
+            ]
+        ))
+
+        (assignment_statement
+        left: (expression_list)
+        "="
+        (comment) @_comment
+        right: (expression_list
+            [
+                (interpreted_string_literal (interpreted_string_literal_content) @injection.content)
+                (raw_string_literal (raw_string_literal_content) @injection.content)
+            ]
+        ))
+
+        (short_var_declaration
+        left: (expression_list)
+        ":="
+        (comment) @_comment
+        right: (expression_list
+            [
+                (interpreted_string_literal (interpreted_string_literal_content) @injection.content)
+                (raw_string_literal (raw_string_literal_content) @injection.content)
+            ]
+        ))
 
-    (#match? @comment "^\\/\\*\\s*js\\s*\\*\\/") ; /* js */ or /*js*/
+        (composite_literal
+            body: (literal_value
+            (keyed_element
+            (comment) @_comment
+            value: (literal_element
+            [
+                (interpreted_string_literal (interpreted_string_literal_content) @injection.content)
+                (raw_string_literal (raw_string_literal_content) @injection.content)
+            ]
+        ))))
+
+        (expression_statement
+            (call_expression
+            (argument_list
+            (comment) @_comment
+            [
+               	(interpreted_string_literal (interpreted_string_literal_content) @injection.content)
+                (raw_string_literal (raw_string_literal_content) @injection.content)
+            ]
+        )))
+    ]
+    (#match? @_comment "^\\/\\*\\s*js\\s*\\*\\/") ; /* js */ or /*js*/
     (#set! injection.language "javascript")
 )
 
+
 ; INJECT CSS
 (
-	[
-		; var, const or short declaration of raw or interpreted string literal
-		((comment) @comment
-  		.
-    	(expression_list
-     	[
-      		(interpreted_string_literal)
-        	(raw_string_literal)
-        ] @injection.content
-        ))
-
-        ; when passing as a literal element (to struct field eg.)
-		((comment) @comment
-        .
-        (literal_element
-        [
-        	(interpreted_string_literal)
-        	(raw_string_literal)
-        ] @injection.content
-        ))
-
-        ; when passing as a function parameter
-        ((comment) @comment
-        .
-        [
-        	(interpreted_string_literal)
-        	(raw_string_literal)
-        ] @injection.content)
-    ]
+    [
+        (const_spec
+            name: (identifier)
+            "="
+            (comment) @_comment
+            value: (expression_list
+            [
+                (interpreted_string_literal (interpreted_string_literal_content) @injection.content)
+                (raw_string_literal (raw_string_literal_content) @injection.content)
+            ]
+        ))
+
+        (var_spec
+            name: (identifier)
+            "="
+            (comment) @_comment
+            value: (expression_list
+            [
+                (interpreted_string_literal (interpreted_string_literal_content) @injection.content)
+                (raw_string_literal (raw_string_literal_content) @injection.content)
+            ]
+        ))
+
+        (assignment_statement
+        left: (expression_list)
+        "="
+        (comment) @_comment
+        right: (expression_list
+            [
+                (interpreted_string_literal (interpreted_string_literal_content) @injection.content)
+                (raw_string_literal (raw_string_literal_content) @injection.content)
+            ]
+        ))
 
-    (#match? @comment "^\\/\\*\\s*css\\s*\\*\\/") ; /* css */ or /*css*/
+        (short_var_declaration
+        left: (expression_list)
+        ":="
+        (comment) @_comment
+        right: (expression_list
+            [
+                (interpreted_string_literal (interpreted_string_literal_content) @injection.content)
+                (raw_string_literal (raw_string_literal_content) @injection.content)
+            ]
+        ))
+
+        (composite_literal
+            body: (literal_value
+            (keyed_element
+            (comment) @_comment
+            value: (literal_element
+            [
+                (interpreted_string_literal (interpreted_string_literal_content) @injection.content)
+                (raw_string_literal (raw_string_literal_content) @injection.content)
+            ]
+        ))))
+
+        (expression_statement
+            (call_expression
+            (argument_list
+            (comment) @_comment
+            [
+               	(interpreted_string_literal (interpreted_string_literal_content) @injection.content)
+                (raw_string_literal (raw_string_literal_content) @injection.content)
+            ]
+        )))
+    ]
+    (#match? @_comment "^\\/\\*\\s*css\\s*\\*\\/") ; /* css */ or /*css*/
     (#set! injection.language "css")
 )
 
+
 ; INJECT LUA
 (
-	[
-		; var, const or short declaration of raw or interpreted string literal
-		((comment) @comment
-  		.
-    	(expression_list
-     	[
-      		(interpreted_string_literal)
-        	(raw_string_literal)
-        ] @injection.content
-        ))
-
-        ; when passing as a literal element (to struct field eg.)
-		((comment) @comment
-        .
-        (literal_element
-        [
-        	(interpreted_string_literal)
-        	(raw_string_literal)
-        ] @injection.content
-        ))
-
-        ; when passing as a function parameter
-        ((comment) @comment
-        .
-        [
-        	(interpreted_string_literal)
-        	(raw_string_literal)
-        ] @injection.content)
-    ]
+    [
+        (const_spec
+            name: (identifier)
+            "="
+            (comment) @_comment
+            value: (expression_list
+            [
+                (interpreted_string_literal (interpreted_string_literal_content) @injection.content)
+                (raw_string_literal (raw_string_literal_content) @injection.content)
+            ]
+        ))
+
+        (var_spec
+            name: (identifier)
+            "="
+            (comment) @_comment
+            value: (expression_list
+            [
+                (interpreted_string_literal (interpreted_string_literal_content) @injection.content)
+                (raw_string_literal (raw_string_literal_content) @injection.content)
+            ]
+        ))
+
+        (assignment_statement
+        left: (expression_list)
+        "="
+        (comment) @_comment
+        right: (expression_list
+            [
+                (interpreted_string_literal (interpreted_string_literal_content) @injection.content)
+                (raw_string_literal (raw_string_literal_content) @injection.content)
+            ]
+        ))
+
+        (short_var_declaration
+        left: (expression_list)
+        ":="
+        (comment) @_comment
+        right: (expression_list
+            [
+                (interpreted_string_literal (interpreted_string_literal_content) @injection.content)
+                (raw_string_literal (raw_string_literal_content) @injection.content)
+            ]
+        ))
 
-    (#match? @comment "^\\/\\*\\s*lua\\s*\\*\\/") ; /* lua */ or /*lua*/
+        (composite_literal
+            body: (literal_value
+            (keyed_element
+            (comment) @_comment
+            value: (literal_element
+            [
+                (interpreted_string_literal (interpreted_string_literal_content) @injection.content)
+                (raw_string_literal (raw_string_literal_content) @injection.content)
+            ]
+        ))))
+
+        (expression_statement
+            (call_expression
+            (argument_list
+            (comment) @_comment
+            [
+               	(interpreted_string_literal (interpreted_string_literal_content) @injection.content)
+                (raw_string_literal (raw_string_literal_content) @injection.content)
+            ]
+        )))
+    ]
+    (#match? @_comment "^\\/\\*\\s*lua\\s*\\*\\/") ; /* lua */ or /*lua*/
     (#set! injection.language "lua")
 )
 
 ; INJECT BASH
 (
-	[
-		; var, const or short declaration of raw or interpreted string literal
-		((comment) @comment
-  		.
-    	(expression_list
-     	[
-      		(interpreted_string_literal)
-        	(raw_string_literal)
-        ] @injection.content
-        ))
-
-        ; when passing as a literal element (to struct field eg.)
-		((comment) @comment
-        .
-        (literal_element
-        [
-        	(interpreted_string_literal)
-        	(raw_string_literal)
-        ] @injection.content
-        ))
-
-        ; when passing as a function parameter
-        ((comment) @comment
-        .
-        [
-        	(interpreted_string_literal)
-        	(raw_string_literal)
-        ] @injection.content)
-    ]
+    [
+        (const_spec
+            name: (identifier)
+            "="
+            (comment) @_comment
+            value: (expression_list
+            [
+                (interpreted_string_literal (interpreted_string_literal_content) @injection.content)
+                (raw_string_literal (raw_string_literal_content) @injection.content)
+            ]
+        ))
+
+        (var_spec
+            name: (identifier)
+            "="
+            (comment) @_comment
+            value: (expression_list
+            [
+                (interpreted_string_literal (interpreted_string_literal_content) @injection.content)
+                (raw_string_literal (raw_string_literal_content) @injection.content)
+            ]
+        ))
+
+        (assignment_statement
+        left: (expression_list)
+        "="
+        (comment) @_comment
+        right: (expression_list
+            [
+                (interpreted_string_literal (interpreted_string_literal_content) @injection.content)
+                (raw_string_literal (raw_string_literal_content) @injection.content)
+            ]
+        ))
+
+        (short_var_declaration
+        left: (expression_list)
+        ":="
+        (comment) @_comment
+        right: (expression_list
+            [
+                (interpreted_string_literal (interpreted_string_literal_content) @injection.content)
+                (raw_string_literal (raw_string_literal_content) @injection.content)
+            ]
+        ))
 
-    (#match? @comment "^\\/\\*\\s*bash\\s*\\*\\/") ; /* bash */ or /*bash*/
+        (composite_literal
+            body: (literal_value
+            (keyed_element
+            (comment) @_comment
+            value: (literal_element
+            [
+                (interpreted_string_literal (interpreted_string_literal_content) @injection.content)
+                (raw_string_literal (raw_string_literal_content) @injection.content)
+            ]
+        ))))
+
+        (expression_statement
+            (call_expression
+            (argument_list
+            (comment) @_comment
+            [
+               	(interpreted_string_literal (interpreted_string_literal_content) @injection.content)
+                (raw_string_literal (raw_string_literal_content) @injection.content)
+            ]
+        )))
+    ]
+    (#match? @_comment "^\\/\\*\\s*bash\\s*\\*\\/") ; /* bash */ or /*bash*/
     (#set! injection.language "bash")
 )
 
 ; INJECT CSV
 (
-	[
-		; var, const or short declaration of raw or interpreted string literal
-		((comment) @comment
-  		.
-    	(expression_list
-     	[
-      		(interpreted_string_literal)
-        	(raw_string_literal)
-        ] @injection.content
-        ))
-
-        ; when passing as a literal element (to struct field eg.)
-		((comment) @comment
-        .
-        (literal_element
-        [
-        	(interpreted_string_literal)
-        	(raw_string_literal)
-        ] @injection.content
-        ))
-
-        ; when passing as a function parameter
-        ((comment) @comment
-        .
-        [
-        	(interpreted_string_literal)
-        	(raw_string_literal)
-        ] @injection.content)
-    ]
+    [
+        (const_spec
+            name: (identifier)
+            "="
+            (comment) @_comment
+            value: (expression_list
+            [
+                (interpreted_string_literal (interpreted_string_literal_content) @injection.content)
+                (raw_string_literal (raw_string_literal_content) @injection.content)
+            ]
+        ))
 
-    (#match? @comment "^\\/\\*\\s*csv\\s*\\*\\/") ; /* csv */ or /*csv*/
+        (var_spec
+            name: (identifier)
+            "="
+            (comment) @_comment
+            value: (expression_list
+            [
+                (interpreted_string_literal (interpreted_string_literal_content) @injection.content)
+                (raw_string_literal (raw_string_literal_content) @injection.content)
+            ]
+        ))
+
+        (assignment_statement
+        left: (expression_list)
+        "="
+        (comment) @_comment
+        right: (expression_list
+            [
+                (interpreted_string_literal (interpreted_string_literal_content) @injection.content)
+                (raw_string_literal (raw_string_literal_content) @injection.content)
+            ]
+        ))
+
+        (short_var_declaration
+        left: (expression_list)
+        ":="
+        (comment) @_comment
+        right: (expression_list
+            [
+                (interpreted_string_literal (interpreted_string_literal_content) @injection.content)
+                (raw_string_literal (raw_string_literal_content) @injection.content)
+            ]
+        ))
+
+        ((comment) @_comment
+            value: (literal_element
+            [
+                (interpreted_string_literal (interpreted_string_literal_content) @injection.content)
+                (raw_string_literal (raw_string_literal_content) @injection.content)
+            ]
+        ))
+
+        (argument_list
+            (comment) @_comment
+            [
+               	(interpreted_string_literal (interpreted_string_literal_content) @injection.content)
+                (raw_string_literal (raw_string_literal_content) @injection.content)
+            ]
+        )
+    ]
+    (#match? @_comment "^\\/\\*\\s*csv\\s*\\*\\/") ; /* csv */ or /*csv */
     (#set! injection.language "csv")
 )

crates/languages/src/javascript/highlights.scm 🔗

@@ -2,6 +2,40 @@
 
 (identifier) @variable
 
+(call_expression
+  function: (member_expression
+    object: (identifier) @type.builtin
+    (#any-of?
+      @type.builtin
+      "Promise"
+      "Array"
+      "Object"
+      "Map"
+      "Set"
+      "WeakMap"
+      "WeakSet"
+      "Date"
+      "Error"
+      "TypeError"
+      "RangeError"
+      "SyntaxError"
+      "ReferenceError"
+      "EvalError"
+      "URIError"
+      "RegExp"
+      "Function"
+      "Number"
+      "String"
+      "Boolean"
+      "Symbol"
+      "BigInt"
+      "Proxy"
+      "ArrayBuffer"
+      "DataView"
+    )
+  )
+)
+
 ; Properties
 
 (property_identifier) @property
@@ -18,6 +52,12 @@
   function: (member_expression
       property: [(property_identifier) (private_property_identifier)] @function.method))
 
+(new_expression
+  constructor: (identifier) @type)
+
+(nested_type_identifier
+  module: (identifier) @type)
+
 ; Function and method definitions
 
 (function_expression
@@ -47,10 +87,45 @@
   left: (identifier) @function
   right: [(function_expression) (arrow_function)])
 
+; Parameters
+
+(required_parameter
+  (identifier) @variable.parameter)
+
+(required_parameter
+  (_
+    ([
+      (identifier)
+      (shorthand_property_identifier_pattern)
+    ]) @variable.parameter))
+
+(optional_parameter
+  (identifier) @variable.parameter)
+
+(optional_parameter
+  (_
+    ([
+      (identifier)
+      (shorthand_property_identifier_pattern)
+    ]) @variable.parameter))
+
+(catch_clause
+  parameter: (identifier) @variable.parameter)
+
+(index_signature
+  name: (identifier) @variable.parameter)
+
+(arrow_function
+  parameter: (identifier) @variable.parameter)
+
 ; Special identifiers
+;
+(class_declaration
+  (type_identifier) @type.class)
+
+(extends_clause
+  value: (identifier) @type.class)
 
-((identifier) @type
- (#match? @type "^[A-Z]"))
 (type_identifier) @type
 (predefined_type) @type.builtin
 
@@ -251,6 +326,34 @@
 (jsx_closing_element (identifier) @tag.jsx (#match? @tag.jsx "^[a-z][^.]*$"))
 (jsx_self_closing_element (identifier) @tag.jsx (#match? @tag.jsx "^[a-z][^.]*$"))
 
+(jsx_opening_element
+  [
+    (identifier) @type
+    (member_expression
+      object: (identifier) @type
+      property: (property_identifier) @type
+    )
+  ]
+)
+(jsx_closing_element
+  [
+    (identifier) @type
+    (member_expression
+      object: (identifier) @type
+      property: (property_identifier) @type
+    )
+  ]
+)
+(jsx_self_closing_element
+  [
+    (identifier) @type
+    (member_expression
+      object: (identifier) @type
+      property: (property_identifier) @type
+    )
+  ]
+)
+
 (jsx_attribute (property_identifier) @attribute.jsx)
 (jsx_opening_element (["<" ">"]) @punctuation.bracket.jsx)
 (jsx_closing_element (["</" ">"]) @punctuation.bracket.jsx)

crates/languages/src/javascript/injections.scm 🔗

@@ -83,3 +83,46 @@
   arguments: (arguments (template_string (string_fragment) @injection.content
                               (#set! injection.language "isograph")))
 )
+
+; Parse the contents of strings and tagged template
+; literals with leading ECMAScript comments:
+; '/* html */' or '/*html*/'
+(
+  ((comment) @_ecma_comment [
+    (string (string_fragment) @injection.content)
+    (template_string (string_fragment) @injection.content)
+  ])
+  (#match? @_ecma_comment "^\\/\\*\\s*html\\s*\\*\\/")
+  (#set! injection.language "html")
+)
+
+; '/* sql */' or '/*sql*/'
+(
+  ((comment) @_ecma_comment [
+    (string (string_fragment) @injection.content)
+    (template_string (string_fragment) @injection.content)
+  ])
+  (#match? @_ecma_comment "^\\/\\*\\s*sql\\s*\\*\\/")
+  (#set! injection.language "sql")
+)
+
+; '/* gql */' or '/*gql*/'
+; '/* graphql */' or '/*graphql*/'
+(
+  ((comment) @_ecma_comment [
+    (string (string_fragment) @injection.content)
+    (template_string (string_fragment) @injection.content)
+  ])
+  (#match? @_ecma_comment "^\\/\\*\\s*(gql|graphql)\\s*\\*\\/")
+  (#set! injection.language "graphql")
+)
+
+; '/* css */' or '/*css*/'
+(
+  ((comment) @_ecma_comment [
+    (string (string_fragment) @injection.content)
+    (template_string (string_fragment) @injection.content)
+  ])
+  (#match? @_ecma_comment "^\\/\\*\\s*(css)\\s*\\*\\/")
+  (#set! injection.language "css")
+)

crates/languages/src/javascript/textobjects.scm 🔗

@@ -18,13 +18,47 @@
         (_)* @function.inside
         "}")) @function.around
 
-(arrow_function
+((arrow_function
     body: (statement_block
         "{"
         (_)* @function.inside
         "}")) @function.around
+ (#not-has-parent? @function.around variable_declarator))
 
-(arrow_function) @function.around
+; Arrow function in variable declaration - capture the full declaration
+([
+    (lexical_declaration
+        (variable_declarator
+            value: (arrow_function
+                body: (statement_block
+                    "{"
+                    (_)* @function.inside
+                    "}"))))
+    (variable_declaration
+        (variable_declarator
+            value: (arrow_function
+                body: (statement_block
+                    "{"
+                    (_)* @function.inside
+                    "}"))))
+]) @function.around
+
+; Arrow function in variable declaration (captures body for expression-bodied arrows)
+([
+    (lexical_declaration
+        (variable_declarator
+            value: (arrow_function
+                body: (_) @function.inside)))
+    (variable_declaration
+        (variable_declarator
+            value: (arrow_function
+                body: (_) @function.inside)))
+]) @function.around
+
+; Catch-all for arrow functions in other contexts (callbacks, etc.)
+((arrow_function
+    body: (_) @function.inside) @function.around
+ (#not-has-parent? @function.around variable_declarator))
 
 (generator_function
     body: (_

crates/languages/src/json.rs 🔗

@@ -7,12 +7,13 @@ use futures::StreamExt;
 use gpui::{App, AsyncApp, Task};
 use http_client::github::{GitHubLspBinaryVersion, latest_github_release};
 use language::{
-    ContextProvider, LanguageName, LocalFile as _, LspAdapter, LspAdapterDelegate, LspInstaller,
-    Toolchain,
+    ContextProvider, LanguageName, LanguageRegistry, LocalFile as _, LspAdapter,
+    LspAdapterDelegate, LspInstaller, Toolchain,
 };
 use lsp::{LanguageServerBinary, LanguageServerName, Uri};
 use node_runtime::{NodeRuntime, VersionStrategy};
 use project::lsp_store::language_server_settings;
+use semver::Version;
 use serde_json::{Value, json};
 use smol::{
     fs::{self},
@@ -129,26 +130,27 @@ fn server_binary_arguments(server_path: &Path) -> Vec<OsString> {
 }
 
 pub struct JsonLspAdapter {
+    languages: Arc<LanguageRegistry>,
     node: NodeRuntime,
 }
 
 impl JsonLspAdapter {
     const PACKAGE_NAME: &str = "vscode-langservers-extracted";
 
-    pub fn new(node: NodeRuntime) -> Self {
-        Self { node }
+    pub fn new(languages: Arc<LanguageRegistry>, node: NodeRuntime) -> Self {
+        Self { languages, node }
     }
 }
 
 impl LspInstaller for JsonLspAdapter {
-    type BinaryVersion = String;
+    type BinaryVersion = Version;
 
     async fn fetch_latest_server_version(
         &self,
         _: &dyn LspAdapterDelegate,
         _: bool,
         _: &mut AsyncApp,
-    ) -> Result<String> {
+    ) -> Result<Self::BinaryVersion> {
         self.node
             .npm_package_latest_version(Self::PACKAGE_NAME)
             .await
@@ -174,7 +176,7 @@ impl LspInstaller for JsonLspAdapter {
 
     async fn check_if_version_installed(
         &self,
-        version: &String,
+        version: &Self::BinaryVersion,
         container_dir: &PathBuf,
         _: &dyn LspAdapterDelegate,
     ) -> Option<LanguageServerBinary> {
@@ -203,11 +205,12 @@ impl LspInstaller for JsonLspAdapter {
 
     async fn fetch_server_binary(
         &self,
-        latest_version: String,
+        latest_version: Self::BinaryVersion,
         container_dir: PathBuf,
         _: &dyn LspAdapterDelegate,
     ) -> Result<LanguageServerBinary> {
         let server_path = container_dir.join(SERVER_PATH);
+        let latest_version = latest_version.to_string();
 
         self.node
             .npm_install_packages(
@@ -255,7 +258,7 @@ impl LspAdapter for JsonLspAdapter {
         cx: &mut AsyncApp,
     ) -> Result<Value> {
         let mut config = cx.update(|cx| {
-            let schemas = json_schema_store::all_schema_file_associations(cx);
+            let schemas = json_schema_store::all_schema_file_associations(&self.languages, cx);
 
             // This can be viewed via `dev: open language server logs` -> `json-language-server` ->
             // `Server Info`
@@ -285,8 +288,8 @@ impl LspAdapter for JsonLspAdapter {
 
     fn language_ids(&self) -> HashMap<LanguageName, String> {
         [
-            (LanguageName::new("JSON"), "json".into()),
-            (LanguageName::new("JSONC"), "jsonc".into()),
+            (LanguageName::new_static("JSON"), "json".into()),
+            (LanguageName::new_static("JSONC"), "jsonc".into()),
         ]
         .into_iter()
         .collect()

crates/languages/src/json/config.toml 🔗

@@ -4,9 +4,10 @@ path_suffixes = ["json", "flake.lock"]
 line_comments = ["// "]
 autoclose_before = ",]}"
 brackets = [
-    { start = "{", end = "}", close = true, newline = true },
-    { start = "[", end = "]", close = true, newline = true },
-    { start = "\"", end = "\"", close = true, newline = false, not_in = ["string"] },
+    { start = "{", end = "}", close = true, surround = true, newline = true },
+    { start = "[", end = "]", close = true, surround = true, newline = true },
+    { start = "(", end = ")", close = true, surround = true, newline = false },
+    { start = "\"", end = "\"", close = true, surround = true, newline = false, not_in = ["string"] },
 ]
 tab_size = 2
 prettier_parser_name = "json"

crates/languages/src/jsonc/config.toml 🔗

@@ -1,12 +1,13 @@
 name = "JSONC"
 grammar = "jsonc"
-path_suffixes = ["jsonc", "bun.lock", "tsconfig.json", "pyrightconfig.json"]
+path_suffixes = ["jsonc", "bun.lock", "devcontainer.json", "pyrightconfig.json", "tsconfig.json"]
 line_comments = ["// "]
 autoclose_before = ",]}"
 brackets = [
-    { start = "{", end = "}", close = true, newline = true },
-    { start = "[", end = "]", close = true, newline = true },
-    { start = "\"", end = "\"", close = true, newline = false, not_in = ["string"] },
+    { start = "{", end = "}", close = true, surround = true, newline = true },
+    { start = "[", end = "]", close = true, surround = true, newline = true },
+    { start = "(", end = ")", close = true, surround = true, newline = false },
+    { start = "\"", end = "\"", close = true, surround = true, newline = false, not_in = ["string"] },
 ]
 tab_size = 2
 prettier_parser_name = "jsonc"

crates/languages/src/lib.rs 🔗

@@ -89,7 +89,7 @@ pub fn init(languages: Arc<LanguageRegistry>, fs: Arc<dyn Fs>, node: NodeRuntime
     let go_context_provider = Arc::new(go::GoContextProvider);
     let go_lsp_adapter = Arc::new(go::GoLspAdapter);
     let json_context_provider = Arc::new(JsonTaskProvider);
-    let json_lsp_adapter = Arc::new(json::JsonLspAdapter::new(node.clone()));
+    let json_lsp_adapter = Arc::new(json::JsonLspAdapter::new(languages.clone(), node.clone()));
     let node_version_lsp_adapter = Arc::new(json::NodeVersionAdapter);
     let py_lsp_adapter = Arc::new(python::PyLspAdapter::new());
     let ty_lsp_adapter = Arc::new(python::TyLspAdapter::new(fs.clone()));
@@ -283,7 +283,6 @@ pub fn init(languages: Arc<LanguageRegistry>, fs: Arc<dyn Fs>, node: NodeRuntime
         "CSS",
         "ERB",
         "HTML+ERB",
-        "HTML/ERB",
         "HEEX",
         "HTML",
         "JavaScript",

crates/languages/src/markdown/config.toml 🔗

@@ -20,8 +20,16 @@ rewrap_prefixes = [
     ">\\s*",
     "[-*+]\\s+\\[[\\sx]\\]\\s+"
 ]
+unordered_list = ["- ", "* ", "+ "]
+ordered_list = [{ pattern = "(\\d+)\\. ", format = "{1}. " }]
+task_list = { prefixes = ["- [ ] ", "- [x] ", "- [X] "], continuation = "- [ ] " }
 
 auto_indent_on_paste = false
 auto_indent_using_last_non_empty_line = false
 tab_size = 2
+decrease_indent_patterns = [
+  { pattern = "^\\s*-",    valid_after = ["list_item"] },
+  { pattern = "^\\s*\\d",    valid_after = ["list_item"] },
+  { pattern = "^\\s*",    valid_after = ["list_item"] },
+]
 prettier_parser_name = "markdown"

crates/languages/src/python.rs 🔗

@@ -19,15 +19,18 @@ use pet_core::python_environment::{PythonEnvironment, PythonEnvironmentKind};
 use pet_virtualenv::is_virtualenv_dir;
 use project::Fs;
 use project::lsp_store::language_server_settings;
+use semver::Version;
 use serde::{Deserialize, Serialize};
 use serde_json::{Value, json};
 use settings::Settings;
 use smol::lock::OnceCell;
-use std::cmp::Ordering;
+use std::cmp::{Ordering, Reverse};
 use std::env::consts;
+use std::process::Stdio;
 use terminal::terminal_settings::TerminalSettings;
 use util::command::new_smol_command;
 use util::fs::{make_file_executable, remove_matching};
+use util::paths::PathStyle;
 use util::rel_path::RelPath;
 
 use http_client::github_download::{GithubBinaryMetadata, download_server_binary};
@@ -100,9 +103,41 @@ impl FromStr for TestRunner {
 /// The problem with it is that Pyright adjusts the sort text based on previous resolutions (items for which we've issued `completion/resolve` call have their sortText adjusted),
 /// which - long story short - makes completion items list non-stable. Pyright probably relies on VSCode's implementation detail.
 /// see https://github.com/microsoft/pyright/blob/95ef4e103b9b2f129c9320427e51b73ea7cf78bd/packages/pyright-internal/src/languageService/completionProvider.ts#LL2873
+///
+/// upd 02.12.25:
+/// Decided to ignore Pyright's sortText() completely and to manually sort all entries
 fn process_pyright_completions(items: &mut [lsp::CompletionItem]) {
     for item in items {
-        item.sort_text.take();
+        let is_dunder = item.label.starts_with("__") && item.label.ends_with("__");
+
+        let visibility_priority = if is_dunder {
+            '3'
+        } else if item.label.starts_with("__") {
+            '2' // private non-dunder
+        } else if item.label.starts_with('_') {
+            '1' // protected
+        } else {
+            '0' // public
+        };
+
+        // Kind priority within same visibility level
+        let kind_priority = match item.kind {
+            Some(lsp::CompletionItemKind::ENUM_MEMBER) => '0',
+            Some(lsp::CompletionItemKind::FIELD) => '1',
+            Some(lsp::CompletionItemKind::PROPERTY) => '2',
+            Some(lsp::CompletionItemKind::VARIABLE) => '3',
+            Some(lsp::CompletionItemKind::CONSTANT) => '4',
+            Some(lsp::CompletionItemKind::METHOD) => '5',
+            Some(lsp::CompletionItemKind::FUNCTION) => '5',
+            Some(lsp::CompletionItemKind::CLASS) => '6',
+            Some(lsp::CompletionItemKind::MODULE) => '7',
+            _ => '8',
+        };
+
+        item.sort_text = Some(format!(
+            "{}{}{}",
+            visibility_priority, kind_priority, item.label
+        ));
     }
 }
 
@@ -247,7 +282,7 @@ impl LspInstaller for TyLspAdapter {
         _: &mut AsyncApp,
     ) -> Result<Self::BinaryVersion> {
         let release =
-            latest_github_release("astral-sh/ty", true, true, delegate.http_client()).await?;
+            latest_github_release("astral-sh/ty", true, false, delegate.http_client()).await?;
         let (_, asset_name) = Self::build_asset_name()?;
         let asset = release
             .assets
@@ -261,6 +296,23 @@ impl LspInstaller for TyLspAdapter {
         })
     }
 
+    async fn check_if_user_installed(
+        &self,
+        delegate: &dyn LspAdapterDelegate,
+        _: Option<Toolchain>,
+        _: &AsyncApp,
+    ) -> Option<LanguageServerBinary> {
+        let Some(ty_bin) = delegate.which(Self::SERVER_NAME.as_ref()).await else {
+            return None;
+        };
+        let env = delegate.shell_env().await;
+        Some(LanguageServerBinary {
+            path: ty_bin,
+            env: Some(env),
+            arguments: vec!["server".into()],
+        })
+    }
+
     async fn fetch_server_binary(
         &self,
         latest_version: Self::BinaryVersion,
@@ -588,14 +640,14 @@ impl LspAdapter for PyrightLspAdapter {
 }
 
 impl LspInstaller for PyrightLspAdapter {
-    type BinaryVersion = String;
+    type BinaryVersion = Version;
 
     async fn fetch_latest_server_version(
         &self,
         _: &dyn LspAdapterDelegate,
         _: bool,
         _: &mut AsyncApp,
-    ) -> Result<String> {
+    ) -> Result<Self::BinaryVersion> {
         self.node
             .npm_package_latest_version(Self::SERVER_NAME.as_ref())
             .await
@@ -639,6 +691,7 @@ impl LspInstaller for PyrightLspAdapter {
         delegate: &dyn LspAdapterDelegate,
     ) -> Result<LanguageServerBinary> {
         let server_path = container_dir.join(Self::SERVER_PATH);
+        let latest_version = latest_version.to_string();
 
         self.node
             .npm_install_packages(
@@ -870,7 +923,7 @@ impl ContextProvider for PythonContextProvider {
 
 fn selected_test_runner(location: Option<&Arc<dyn language::File>>, cx: &App) -> TestRunner {
     const TEST_RUNNER_VARIABLE: &str = "TEST_RUNNER";
-    language_settings(Some(LanguageName::new("Python")), location, cx)
+    language_settings(Some(LanguageName::new_static("Python")), location, cx)
         .tasks
         .variables
         .get(TEST_RUNNER_VARIABLE)
@@ -884,7 +937,7 @@ impl PythonContextProvider {
         variables: &task::TaskVariables,
     ) -> Option<(VariableName, String)> {
         let python_module_name =
-            python_module_name_from_relative_path(variables.get(&VariableName::RelativeFile)?);
+            python_module_name_from_relative_path(variables.get(&VariableName::RelativeFile)?)?;
 
         let unittest_class_name =
             variables.get(&VariableName::Custom(Cow::Borrowed("_unittest_class_name")));
@@ -941,9 +994,10 @@ impl PythonContextProvider {
         &self,
         variables: &task::TaskVariables,
     ) -> Result<(VariableName, String)> {
-        let python_module_name = python_module_name_from_relative_path(
-            variables.get(&VariableName::RelativeFile).unwrap_or(""),
-        );
+        let python_module_name = variables
+            .get(&VariableName::RelativeFile)
+            .and_then(|module| python_module_name_from_relative_path(module))
+            .unwrap_or_default();
 
         let module_target = (PYTHON_MODULE_NAME_TASK_VARIABLE.clone(), python_module_name);
 
@@ -951,12 +1005,15 @@ impl PythonContextProvider {
     }
 }
 
-fn python_module_name_from_relative_path(relative_path: &str) -> String {
-    let path_with_dots = relative_path.replace('/', ".");
-    path_with_dots
-        .strip_suffix(".py")
-        .unwrap_or(&path_with_dots)
-        .to_string()
+fn python_module_name_from_relative_path(relative_path: &str) -> Option<String> {
+    let rel_path = RelPath::new(relative_path.as_ref(), PathStyle::local()).ok()?;
+    let path_with_dots = rel_path.display(PathStyle::Posix).replace('/', ".");
+    Some(
+        path_with_dots
+            .strip_suffix(".py")
+            .map(ToOwned::to_owned)
+            .unwrap_or(path_with_dots),
+    )
 }
 
 fn is_python_env_global(k: &PythonEnvironmentKind) -> bool {
@@ -1064,13 +1121,45 @@ fn get_venv_parent_dir(env: &PythonEnvironment) -> Option<PathBuf> {
     venv.parent().map(|parent| parent.to_path_buf())
 }
 
-fn wr_distance(wr: &PathBuf, venv: Option<&PathBuf>) -> usize {
+// How far is this venv from the root of our current project?
+#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
+enum SubprojectDistance {
+    WithinSubproject(Reverse<usize>),
+    WithinWorktree(Reverse<usize>),
+    NotInWorktree,
+}
+
+fn wr_distance(
+    wr: &PathBuf,
+    subroot_relative_path: &RelPath,
+    venv: Option<&PathBuf>,
+) -> SubprojectDistance {
     if let Some(venv) = venv
         && let Ok(p) = venv.strip_prefix(wr)
     {
-        p.components().count()
+        if subroot_relative_path.components().next().is_some()
+            && let Ok(distance) = p
+                .strip_prefix(subroot_relative_path.as_std_path())
+                .map(|p| p.components().count())
+        {
+            SubprojectDistance::WithinSubproject(Reverse(distance))
+        } else {
+            SubprojectDistance::WithinWorktree(Reverse(p.components().count()))
+        }
     } else {
-        usize::MAX
+        SubprojectDistance::NotInWorktree
+    }
+}
+
+fn micromamba_shell_name(kind: ShellKind) -> &'static str {
+    match kind {
+        ShellKind::Csh => "csh",
+        ShellKind::Fish => "fish",
+        ShellKind::Nushell => "nu",
+        ShellKind::PowerShell => "powershell",
+        ShellKind::Cmd => "cmd.exe",
+        // default / catch-all:
+        _ => "posix",
     }
 }
 
@@ -1133,11 +1222,14 @@ impl ToolchainLister for PythonToolchainProvider {
                     });
 
             // Compare project paths against worktree root
-            let proj_ordering = || {
-                let lhs_project = lhs.project.clone().or_else(|| get_venv_parent_dir(lhs));
-                let rhs_project = rhs.project.clone().or_else(|| get_venv_parent_dir(rhs));
-                wr_distance(&wr, lhs_project.as_ref()).cmp(&wr_distance(&wr, rhs_project.as_ref()))
-            };
+            let proj_ordering =
+                || {
+                    let lhs_project = lhs.project.clone().or_else(|| get_venv_parent_dir(lhs));
+                    let rhs_project = rhs.project.clone().or_else(|| get_venv_parent_dir(rhs));
+                    wr_distance(&wr, &subroot_relative_path, lhs_project.as_ref()).cmp(
+                        &wr_distance(&wr, &subroot_relative_path, rhs_project.as_ref()),
+                    )
+                };
 
             // Compare environment priorities
             let priority_ordering = || env_priority(lhs.kind).cmp(&env_priority(rhs.kind));
@@ -1237,24 +1329,28 @@ impl ToolchainLister for PythonToolchainProvider {
                     .as_option()
                     .map(|venv| venv.conda_manager)
                     .unwrap_or(settings::CondaManager::Auto);
-
                 let manager = match conda_manager {
                     settings::CondaManager::Conda => "conda",
                     settings::CondaManager::Mamba => "mamba",
                     settings::CondaManager::Micromamba => "micromamba",
-                    settings::CondaManager::Auto => {
-                        // When auto, prefer the detected manager or fall back to conda
-                        toolchain
-                            .environment
-                            .manager
-                            .as_ref()
-                            .and_then(|m| m.executable.file_name())
-                            .and_then(|name| name.to_str())
-                            .filter(|name| matches!(*name, "conda" | "mamba" | "micromamba"))
-                            .unwrap_or("conda")
-                    }
+                    settings::CondaManager::Auto => toolchain
+                        .environment
+                        .manager
+                        .as_ref()
+                        .and_then(|m| m.executable.file_name())
+                        .and_then(|name| name.to_str())
+                        .filter(|name| matches!(*name, "conda" | "mamba" | "micromamba"))
+                        .unwrap_or("conda"),
                 };
 
+                // Activate micromamba shell in the child shell
+                // [required for micromamba]
+                if manager == "micromamba" {
+                    let shell = micromamba_shell_name(shell);
+                    activation_script
+                        .push(format!(r#"eval "$({manager} shell hook --shell {shell})""#));
+                }
+
                 if let Some(name) = &toolchain.environment.name {
                     activation_script.push(format!("{manager} activate {name}"));
                 } else {
@@ -1284,7 +1380,7 @@ impl ToolchainLister for PythonToolchainProvider {
                     ShellKind::Fish => Some(format!("\"{pyenv}\" shell - fish {version}")),
                     ShellKind::Posix => Some(format!("\"{pyenv}\" shell - sh {version}")),
                     ShellKind::Nushell => Some(format!("^\"{pyenv}\" shell - nu {version}")),
-                    ShellKind::PowerShell => None,
+                    ShellKind::PowerShell | ShellKind::Pwsh => None,
                     ShellKind::Csh => None,
                     ShellKind::Tcsh => None,
                     ShellKind::Cmd => None,
@@ -1337,7 +1433,7 @@ async fn venv_to_toolchain(venv: PythonEnvironment, fs: &dyn Fs) -> Option<Toolc
             .to_str()?
             .to_owned()
             .into(),
-        language_name: LanguageName::new("Python"),
+        language_name: LanguageName::new_static("Python"),
         as_json: serde_json::to_value(data).ok()?,
     })
 }
@@ -1964,14 +2060,14 @@ impl LspAdapter for BasedPyrightLspAdapter {
 }
 
 impl LspInstaller for BasedPyrightLspAdapter {
-    type BinaryVersion = String;
+    type BinaryVersion = Version;
 
     async fn fetch_latest_server_version(
         &self,
         _: &dyn LspAdapterDelegate,
         _: bool,
         _: &mut AsyncApp,
-    ) -> Result<String> {
+    ) -> Result<Self::BinaryVersion> {
         self.node
             .npm_package_latest_version(Self::SERVER_NAME.as_ref())
             .await
@@ -2016,6 +2112,7 @@ impl LspInstaller for BasedPyrightLspAdapter {
         delegate: &dyn LspAdapterDelegate,
     ) -> Result<LanguageServerBinary> {
         let server_path = container_dir.join(Self::SERVER_PATH);
+        let latest_version = latest_version.to_string();
 
         self.node
             .npm_install_packages(
@@ -2077,6 +2174,119 @@ pub(crate) struct RuffLspAdapter {
     fs: Arc<dyn Fs>,
 }
 
+impl RuffLspAdapter {
+    fn convert_ruff_schema(raw_schema: &serde_json::Value) -> serde_json::Value {
+        let Some(schema_object) = raw_schema.as_object() else {
+            return raw_schema.clone();
+        };
+
+        let mut root_properties = serde_json::Map::new();
+
+        for (key, value) in schema_object {
+            let parts: Vec<&str> = key.split('.').collect();
+
+            if parts.is_empty() {
+                continue;
+            }
+
+            let mut current = &mut root_properties;
+
+            for (i, part) in parts.iter().enumerate() {
+                let is_last = i == parts.len() - 1;
+
+                if is_last {
+                    let mut schema_entry = serde_json::Map::new();
+
+                    if let Some(doc) = value.get("doc").and_then(|d| d.as_str()) {
+                        schema_entry.insert(
+                            "markdownDescription".to_string(),
+                            serde_json::Value::String(doc.to_string()),
+                        );
+                    }
+
+                    if let Some(default_val) = value.get("default") {
+                        schema_entry.insert("default".to_string(), default_val.clone());
+                    }
+
+                    if let Some(value_type) = value.get("value_type").and_then(|v| v.as_str()) {
+                        if value_type.contains('|') {
+                            let enum_values: Vec<serde_json::Value> = value_type
+                                .split('|')
+                                .map(|s| s.trim().trim_matches('"'))
+                                .filter(|s| !s.is_empty())
+                                .map(|s| serde_json::Value::String(s.to_string()))
+                                .collect();
+
+                            if !enum_values.is_empty() {
+                                schema_entry
+                                    .insert("type".to_string(), serde_json::json!("string"));
+                                schema_entry.insert(
+                                    "enum".to_string(),
+                                    serde_json::Value::Array(enum_values),
+                                );
+                            }
+                        } else if value_type.starts_with("list[") {
+                            schema_entry.insert("type".to_string(), serde_json::json!("array"));
+                            if let Some(item_type) = value_type
+                                .strip_prefix("list[")
+                                .and_then(|s| s.strip_suffix(']'))
+                            {
+                                let json_type = match item_type {
+                                    "str" => "string",
+                                    "int" => "integer",
+                                    "bool" => "boolean",
+                                    _ => "string",
+                                };
+                                schema_entry.insert(
+                                    "items".to_string(),
+                                    serde_json::json!({"type": json_type}),
+                                );
+                            }
+                        } else if value_type.starts_with("dict[") {
+                            schema_entry.insert("type".to_string(), serde_json::json!("object"));
+                        } else {
+                            let json_type = match value_type {
+                                "bool" => "boolean",
+                                "int" | "usize" => "integer",
+                                "str" => "string",
+                                _ => "string",
+                            };
+                            schema_entry.insert(
+                                "type".to_string(),
+                                serde_json::Value::String(json_type.to_string()),
+                            );
+                        }
+                    }
+
+                    current.insert(part.to_string(), serde_json::Value::Object(schema_entry));
+                } else {
+                    let next_current = current
+                        .entry(part.to_string())
+                        .or_insert_with(|| {
+                            serde_json::json!({
+                                "type": "object",
+                                "properties": {}
+                            })
+                        })
+                        .as_object_mut()
+                        .expect("should be an object")
+                        .entry("properties")
+                        .or_insert_with(|| serde_json::json!({}))
+                        .as_object_mut()
+                        .expect("properties should be an object");
+
+                    current = next_current;
+                }
+            }
+        }
+
+        serde_json::json!({
+            "type": "object",
+            "properties": root_properties
+        })
+    }
+}
+
 #[cfg(target_os = "macos")]
 impl RuffLspAdapter {
     const GITHUB_ASSET_KIND: AssetKind = AssetKind::TarGz;
@@ -2129,6 +2339,36 @@ impl LspAdapter for RuffLspAdapter {
     fn name(&self) -> LanguageServerName {
         Self::SERVER_NAME
     }
+
+    async fn initialization_options_schema(
+        self: Arc<Self>,
+        language_server_binary: &LanguageServerBinary,
+    ) -> Option<serde_json::Value> {
+        let mut command = util::command::new_smol_command(&language_server_binary.path);
+        command
+            .args(&["config", "--output-format", "json"])
+            .stdout(Stdio::piped())
+            .stderr(Stdio::piped());
+        let cmd = command
+            .spawn()
+            .map_err(|e| log::debug!("failed to spawn command {command:?}: {e}"))
+            .ok()?;
+        let output = cmd
+            .output()
+            .await
+            .map_err(|e| log::debug!("failed to execute command {command:?}: {e}"))
+            .ok()?;
+        if !output.status.success() {
+            return None;
+        }
+
+        let raw_schema: serde_json::Value = serde_json::from_slice(output.stdout.as_slice())
+            .map_err(|e| log::debug!("failed to parse ruff's JSON schema output: {e}"))
+            .ok()?;
+
+        let converted_schema = Self::convert_ruff_schema(&raw_schema);
+        Some(converted_schema)
+    }
 }
 
 impl LspInstaller for RuffLspAdapter {
@@ -2311,6 +2551,8 @@ mod tests {
     use settings::SettingsStore;
     use std::num::NonZeroU32;
 
+    use crate::python::python_module_name_from_relative_path;
+
     #[gpui::test]
     async fn test_python_autoindent(cx: &mut TestAppContext) {
         cx.executor().set_block_on_ticks(usize::MAX..=usize::MAX);
@@ -2439,4 +2681,180 @@ mod tests {
             buffer
         });
     }
+
+    #[test]
+    fn test_python_module_name_from_relative_path() {
+        assert_eq!(
+            python_module_name_from_relative_path("foo/bar.py"),
+            Some("foo.bar".to_string())
+        );
+        assert_eq!(
+            python_module_name_from_relative_path("foo/bar"),
+            Some("foo.bar".to_string())
+        );
+        if cfg!(windows) {
+            assert_eq!(
+                python_module_name_from_relative_path("foo\\bar.py"),
+                Some("foo.bar".to_string())
+            );
+            assert_eq!(
+                python_module_name_from_relative_path("foo\\bar"),
+                Some("foo.bar".to_string())
+            );
+        } else {
+            assert_eq!(
+                python_module_name_from_relative_path("foo\\bar.py"),
+                Some("foo\\bar".to_string())
+            );
+            assert_eq!(
+                python_module_name_from_relative_path("foo\\bar"),
+                Some("foo\\bar".to_string())
+            );
+        }
+    }
+
+    #[test]
+    fn test_convert_ruff_schema() {
+        use super::RuffLspAdapter;
+
+        let raw_schema = serde_json::json!({
+            "line-length": {
+                "doc": "The line length to use when enforcing long-lines violations",
+                "default": "88",
+                "value_type": "int",
+                "scope": null,
+                "example": "line-length = 120",
+                "deprecated": null
+            },
+            "lint.select": {
+                "doc": "A list of rule codes or prefixes to enable",
+                "default": "[\"E4\", \"E7\", \"E9\", \"F\"]",
+                "value_type": "list[RuleSelector]",
+                "scope": null,
+                "example": "select = [\"E4\", \"E7\", \"E9\", \"F\", \"B\", \"Q\"]",
+                "deprecated": null
+            },
+            "lint.isort.case-sensitive": {
+                "doc": "Sort imports taking into account case sensitivity.",
+                "default": "false",
+                "value_type": "bool",
+                "scope": null,
+                "example": "case-sensitive = true",
+                "deprecated": null
+            },
+            "format.quote-style": {
+                "doc": "Configures the preferred quote character for strings.",
+                "default": "\"double\"",
+                "value_type": "\"double\" | \"single\" | \"preserve\"",
+                "scope": null,
+                "example": "quote-style = \"single\"",
+                "deprecated": null
+            }
+        });
+
+        let converted = RuffLspAdapter::convert_ruff_schema(&raw_schema);
+
+        assert!(converted.is_object());
+        assert_eq!(
+            converted.get("type").and_then(|v| v.as_str()),
+            Some("object")
+        );
+
+        let properties = converted
+            .get("properties")
+            .expect("should have properties")
+            .as_object()
+            .expect("properties should be an object");
+
+        assert!(properties.contains_key("line-length"));
+        assert!(properties.contains_key("lint"));
+        assert!(properties.contains_key("format"));
+
+        let line_length = properties
+            .get("line-length")
+            .expect("should have line-length")
+            .as_object()
+            .expect("line-length should be an object");
+
+        assert_eq!(
+            line_length.get("type").and_then(|v| v.as_str()),
+            Some("integer")
+        );
+        assert_eq!(
+            line_length.get("default").and_then(|v| v.as_str()),
+            Some("88")
+        );
+
+        let lint = properties
+            .get("lint")
+            .expect("should have lint")
+            .as_object()
+            .expect("lint should be an object");
+
+        let lint_props = lint
+            .get("properties")
+            .expect("lint should have properties")
+            .as_object()
+            .expect("lint properties should be an object");
+
+        assert!(lint_props.contains_key("select"));
+        assert!(lint_props.contains_key("isort"));
+
+        let select = lint_props.get("select").expect("should have select");
+        assert_eq!(select.get("type").and_then(|v| v.as_str()), Some("array"));
+
+        let isort = lint_props
+            .get("isort")
+            .expect("should have isort")
+            .as_object()
+            .expect("isort should be an object");
+
+        let isort_props = isort
+            .get("properties")
+            .expect("isort should have properties")
+            .as_object()
+            .expect("isort properties should be an object");
+
+        let case_sensitive = isort_props
+            .get("case-sensitive")
+            .expect("should have case-sensitive");
+
+        assert_eq!(
+            case_sensitive.get("type").and_then(|v| v.as_str()),
+            Some("boolean")
+        );
+        assert!(case_sensitive.get("markdownDescription").is_some());
+
+        let format = properties
+            .get("format")
+            .expect("should have format")
+            .as_object()
+            .expect("format should be an object");
+
+        let format_props = format
+            .get("properties")
+            .expect("format should have properties")
+            .as_object()
+            .expect("format properties should be an object");
+
+        let quote_style = format_props
+            .get("quote-style")
+            .expect("should have quote-style");
+
+        assert_eq!(
+            quote_style.get("type").and_then(|v| v.as_str()),
+            Some("string")
+        );
+
+        let enum_values = quote_style
+            .get("enum")
+            .expect("should have enum")
+            .as_array()
+            .expect("enum should be an array");
+
+        assert_eq!(enum_values.len(), 3);
+        assert!(enum_values.contains(&serde_json::json!("double")));
+        assert!(enum_values.contains(&serde_json::json!("single")));
+        assert!(enum_values.contains(&serde_json::json!("preserve")));
+    }
 }

crates/languages/src/python/injections.scm 🔗

@@ -1,3 +1,34 @@
 ((comment) @injection.content
  (#set! injection.language "comment")
 )
+
+; SQL -----------------------------------------------------------------------------
+(
+    [
+        ; function calls
+        (call
+            [
+                (attribute attribute: (identifier) @function_name)
+                (identifier) @function_name
+            ]
+            arguments: (argument_list
+                (comment) @comment
+                (string
+                    (string_content) @injection.content
+                )
+        ))
+
+        ; string variables
+        ((comment) @comment
+            .
+            (expression_statement
+                (assignment
+                    right: (string
+                        (string_content) @injection.content
+                    )
+                )
+        ))
+    ]
+    (#match? @comment "^(#|#\\s+)(?i:sql)\\s*$")
+    (#set! injection.language "sql")
+)

crates/languages/src/rust.rs 🔗

@@ -5,7 +5,7 @@ use futures::StreamExt;
 use gpui::{App, AppContext, AsyncApp, SharedString, Task};
 use http_client::github::AssetKind;
 use http_client::github::{GitHubLspBinaryVersion, latest_github_release};
-use http_client::github_download::fetch_github_binary_with_digest_check;
+use http_client::github_download::{GithubBinaryMetadata, download_server_binary};
 pub use language::*;
 use lsp::{InitializeParams, LanguageServerBinary};
 use project::lsp_store::rust_analyzer_ext::CARGO_DIAGNOSTICS_SOURCE_NAME;
@@ -18,6 +18,7 @@ use smol::fs::{self};
 use std::cmp::Reverse;
 use std::fmt::Display;
 use std::ops::Range;
+use std::process::Stdio;
 use std::{
     borrow::Cow,
     path::{Path, PathBuf},
@@ -66,6 +67,68 @@ enum LibcType {
 }
 
 impl RustLspAdapter {
+    fn convert_rust_analyzer_schema(raw_schema: &serde_json::Value) -> serde_json::Value {
+        let Some(schema_array) = raw_schema.as_array() else {
+            return raw_schema.clone();
+        };
+
+        let mut root_properties = serde_json::Map::new();
+
+        for item in schema_array {
+            if let Some(props) = item.get("properties").and_then(|p| p.as_object()) {
+                for (key, value) in props {
+                    let parts: Vec<&str> = key.split('.').collect();
+
+                    if parts.is_empty() {
+                        continue;
+                    }
+
+                    let parts_to_process = if parts.first() == Some(&"rust-analyzer") {
+                        &parts[1..]
+                    } else {
+                        &parts[..]
+                    };
+
+                    if parts_to_process.is_empty() {
+                        continue;
+                    }
+
+                    let mut current = &mut root_properties;
+
+                    for (i, part) in parts_to_process.iter().enumerate() {
+                        let is_last = i == parts_to_process.len() - 1;
+
+                        if is_last {
+                            current.insert(part.to_string(), value.clone());
+                        } else {
+                            let next_current = current
+                                .entry(part.to_string())
+                                .or_insert_with(|| {
+                                    serde_json::json!({
+                                        "type": "object",
+                                        "properties": {}
+                                    })
+                                })
+                                .as_object_mut()
+                                .expect("should be an object")
+                                .entry("properties")
+                                .or_insert_with(|| serde_json::json!({}))
+                                .as_object_mut()
+                                .expect("properties should be an object");
+
+                            current = next_current;
+                        }
+                    }
+                }
+            }
+        }
+
+        serde_json::json!({
+            "type": "object",
+            "properties": root_properties
+        })
+    }
+
     #[cfg(target_os = "linux")]
     async fn determine_libc_type() -> LibcType {
         use futures::pin_mut;
@@ -355,7 +418,7 @@ impl LspAdapter for RustLspAdapter {
                         | lsp::CompletionTextEdit::Edit(lsp::TextEdit { new_text, .. }),
                     ) = completion.text_edit.as_ref()
                     && let Ok(mut snippet) = snippet::Snippet::parse(new_text)
-                    && !snippet.tabstops.is_empty()
+                    && snippet.tabstops.len() > 1
                 {
                     label = String::new();
 
@@ -375,16 +438,20 @@ impl LspAdapter for RustLspAdapter {
                         let start_pos = range.start as usize;
                         let end_pos = range.end as usize;
 
-                        label.push_str(&snippet.text[text_pos..end_pos]);
-                        text_pos = end_pos;
+                        label.push_str(&snippet.text[text_pos..start_pos]);
 
                         if start_pos == end_pos {
                             let caret_start = label.len();
                             label.push('…');
                             runs.push((caret_start..label.len(), HighlightId::TABSTOP_INSERT_ID));
                         } else {
-                            runs.push((start_pos..end_pos, HighlightId::TABSTOP_REPLACE_ID));
+                            let label_start = label.len();
+                            label.push_str(&snippet.text[start_pos..end_pos]);
+                            let label_end = label.len();
+                            runs.push((label_start..label_end, HighlightId::TABSTOP_REPLACE_ID));
                         }
+
+                        text_pos = end_pos;
                     }
 
                     label.push_str(&snippet.text[text_pos..]);
@@ -417,7 +484,9 @@ impl LspAdapter for RustLspAdapter {
                             0..label.rfind('(').unwrap_or(completion.label.len()),
                             highlight_id,
                         ));
-                    } else if detail_left.is_none() {
+                    } else if detail_left.is_none()
+                        && kind != Some(lsp::CompletionItemKind::SNIPPET)
+                    {
                         return None;
                     }
                 }
@@ -442,6 +511,37 @@ impl LspAdapter for RustLspAdapter {
         Some(label)
     }
 
+    async fn initialization_options_schema(
+        self: Arc<Self>,
+        language_server_binary: &LanguageServerBinary,
+    ) -> Option<serde_json::Value> {
+        let mut command = util::command::new_smol_command(&language_server_binary.path);
+        command
+            .arg("--print-config-schema")
+            .stdout(Stdio::piped())
+            .stderr(Stdio::piped());
+        let cmd = command
+            .spawn()
+            .map_err(|e| log::debug!("failed to spawn command {command:?}: {e}"))
+            .ok()?;
+        let output = cmd
+            .output()
+            .await
+            .map_err(|e| log::debug!("failed to execute command {command:?}: {e}"))
+            .ok()?;
+        if !output.status.success() {
+            return None;
+        }
+
+        let raw_schema: serde_json::Value = serde_json::from_slice(output.stdout.as_slice())
+            .map_err(|e| log::debug!("failed to parse rust-analyzer's JSON schema output: {e}"))
+            .ok()?;
+
+        // Convert rust-analyzer's array-based schema format to nested JSON Schema
+        let converted_schema = Self::convert_rust_analyzer_schema(&raw_schema);
+        Some(converted_schema)
+    }
+
     async fn label_for_symbol(
         &self,
         name: &str,
@@ -574,34 +674,64 @@ impl LspInstaller for RustLspAdapter {
             AssetKind::Zip => destination_path.clone().join("rust-analyzer.exe"), // zip contains a .exe
         };
 
-        let metadata_path = destination_path.with_extension("metadata");
+        let binary = LanguageServerBinary {
+            path: server_path.clone(),
+            env: None,
+            arguments: Default::default(),
+        };
 
-        let server_path_for_check = server_path.clone();
-        fetch_github_binary_with_digest_check(
-            &server_path,
-            &metadata_path,
-            expected_digest,
-            &url,
-            Self::GITHUB_ASSET_KIND,
-            &destination_path,
-            &*delegate.http_client(),
-            || async move {
+        let metadata_path = destination_path.with_extension("metadata");
+        let metadata = GithubBinaryMetadata::read_from_file(&metadata_path)
+            .await
+            .ok();
+        if let Some(metadata) = metadata {
+            let validity_check = async || {
                 delegate
                     .try_exec(LanguageServerBinary {
-                        path: server_path_for_check,
+                        path: server_path.clone(),
                         arguments: vec!["--version".into()],
                         env: None,
                     })
                     .await
                     .inspect_err(|err| {
-                        log::warn!("Unable to run rust-analyzer asset, redownloading: {err:#}")
+                        log::warn!("Unable to run {server_path:?} asset, redownloading: {err:#}",)
                     })
-            },
+            };
+            if let (Some(actual_digest), Some(expected_digest)) =
+                (&metadata.digest, &expected_digest)
+            {
+                if actual_digest == expected_digest {
+                    if validity_check().await.is_ok() {
+                        return Ok(binary);
+                    }
+                } else {
+                    log::info!(
+                        "SHA-256 mismatch for {destination_path:?} asset, downloading new asset. Expected: {expected_digest}, Got: {actual_digest}"
+                    );
+                }
+            } else if validity_check().await.is_ok() {
+                return Ok(binary);
+            }
+        }
+
+        download_server_binary(
+            &*delegate.http_client(),
+            &url,
+            expected_digest.as_deref(),
+            &destination_path,
+            Self::GITHUB_ASSET_KIND,
         )
         .await?;
-
         make_file_executable(&server_path).await?;
         remove_matching(&container_dir, |path| path != destination_path).await;
+        GithubBinaryMetadata::write_to_file(
+            &GithubBinaryMetadata {
+                metadata_version: 1,
+                digest: expected_digest,
+            },
+            &metadata_path,
+        )
+        .await?;
 
         Ok(LanguageServerBinary {
             path: server_path,
@@ -852,7 +982,7 @@ impl ContextProvider for RustContextProvider {
                     RUST_BIN_REQUIRED_FEATURES_FLAG_TASK_VARIABLE.template_value(),
                     RUST_BIN_REQUIRED_FEATURES_TASK_VARIABLE.template_value(),
                 ],
-                cwd: Some("$ZED_DIRNAME".to_owned()),
+                cwd: Some(RUST_MANIFEST_DIRNAME_TASK_VARIABLE.template_value()),
                 tags: vec!["rust-main".to_owned()],
                 ..TaskTemplate::default()
             },
@@ -874,14 +1004,14 @@ impl ContextProvider for RustContextProvider {
                 label: "Run".into(),
                 command: "cargo".into(),
                 args: run_task_args,
-                cwd: Some("$ZED_DIRNAME".to_owned()),
+                cwd: Some(RUST_MANIFEST_DIRNAME_TASK_VARIABLE.template_value()),
                 ..TaskTemplate::default()
             },
             TaskTemplate {
                 label: "Clean".into(),
                 command: "cargo".into(),
                 args: vec!["clean".into()],
-                cwd: Some("$ZED_DIRNAME".to_owned()),
+                cwd: Some(RUST_MANIFEST_DIRNAME_TASK_VARIABLE.template_value()),
                 ..TaskTemplate::default()
             },
         ];
@@ -1096,9 +1226,11 @@ fn package_name_from_pkgid(pkgid: &str) -> Option<&str> {
 }
 
 async fn get_cached_server_binary(container_dir: PathBuf) -> Option<LanguageServerBinary> {
-    maybe!(async {
+    let binary_result = maybe!(async {
         let mut last = None;
-        let mut entries = fs::read_dir(&container_dir).await?;
+        let mut entries = fs::read_dir(&container_dir)
+            .await
+            .with_context(|| format!("listing {container_dir:?}"))?;
         while let Some(entry) = entries.next().await {
             let path = entry?.path();
             if path.extension().is_some_and(|ext| ext == "metadata") {
@@ -1107,20 +1239,34 @@ async fn get_cached_server_binary(container_dir: PathBuf) -> Option<LanguageServ
             last = Some(path);
         }
 
-        let path = last.context("no cached binary")?;
+        let path = match last {
+            Some(last) => last,
+            None => return Ok(None),
+        };
         let path = match RustLspAdapter::GITHUB_ASSET_KIND {
             AssetKind::TarGz | AssetKind::Gz => path, // Tar and gzip extract in place.
             AssetKind::Zip => path.join("rust-analyzer.exe"), // zip contains a .exe
         };
 
-        anyhow::Ok(LanguageServerBinary {
+        anyhow::Ok(Some(LanguageServerBinary {
             path,
             env: None,
-            arguments: Default::default(),
-        })
+            arguments: Vec::new(),
+        }))
     })
-    .await
-    .log_err()
+    .await;
+
+    match binary_result {
+        Ok(Some(binary)) => Some(binary),
+        Ok(None) => {
+            log::info!("No cached rust-analyzer binary found");
+            None
+        }
+        Err(e) => {
+            log::error!("Failed to look up cached rust-analyzer binary: {e:#}");
+            None
+        }
+    }
 }
 
 fn test_fragment(variables: &TaskVariables, path: &Path, stem: &str) -> String {
@@ -1546,6 +1692,78 @@ mod tests {
                 ],
             ))
         );
+
+        // Postfix completion without actual tabstops (only implicit final $0)
+        // The label should use completion.label so it can be filtered by "ref"
+        let ref_completion = adapter
+            .label_for_completion(
+                &lsp::CompletionItem {
+                    kind: Some(lsp::CompletionItemKind::SNIPPET),
+                    label: "ref".to_string(),
+                    filter_text: Some("ref".to_string()),
+                    label_details: Some(CompletionItemLabelDetails {
+                        detail: None,
+                        description: Some("&expr".to_string()),
+                    }),
+                    detail: Some("&expr".to_string()),
+                    insert_text_format: Some(lsp::InsertTextFormat::SNIPPET),
+                    text_edit: Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
+                        range: lsp::Range::default(),
+                        new_text: "&String::new()".to_string(),
+                    })),
+                    ..Default::default()
+                },
+                &language,
+            )
+            .await;
+        assert!(
+            ref_completion.is_some(),
+            "ref postfix completion should have a label"
+        );
+        let ref_label = ref_completion.unwrap();
+        let filter_text = &ref_label.text[ref_label.filter_range.clone()];
+        assert!(
+            filter_text.contains("ref"),
+            "filter range text '{filter_text}' should contain 'ref' for filtering to work",
+        );
+
+        // Test for correct range calculation with mixed empty and non-empty tabstops.(See https://github.com/zed-industries/zed/issues/44825)
+        let res = adapter
+            .label_for_completion(
+                &lsp::CompletionItem {
+                    kind: Some(lsp::CompletionItemKind::STRUCT),
+                    label: "Particles".to_string(),
+                    insert_text_format: Some(lsp::InsertTextFormat::SNIPPET),
+                    text_edit: Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
+                        range: lsp::Range::default(),
+                        new_text: "Particles { pos_x: $1, pos_y: $2, vel_x: $3, vel_y: $4, acc_x: ${5:()}, acc_y: ${6:()}, mass: $7 }$0".to_string(),
+                    })),
+                    ..Default::default()
+                },
+                &language,
+            )
+            .await
+            .unwrap();
+
+        assert_eq!(
+            res,
+            CodeLabel::new(
+                "Particles { pos_x: …, pos_y: …, vel_x: …, vel_y: …, acc_x: (), acc_y: (), mass: … }".to_string(),
+                0..9,
+                vec![
+                    (19..22, HighlightId::TABSTOP_INSERT_ID),
+                    (31..34, HighlightId::TABSTOP_INSERT_ID),
+                    (43..46, HighlightId::TABSTOP_INSERT_ID),
+                    (55..58, HighlightId::TABSTOP_INSERT_ID),
+                    (67..69, HighlightId::TABSTOP_REPLACE_ID),
+                    (78..80, HighlightId::TABSTOP_REPLACE_ID),
+                    (88..91, HighlightId::TABSTOP_INSERT_ID),
+                    (0..9, highlight_type),
+                    (60..65, highlight_field),
+                    (71..76, highlight_field),
+                ],
+            )
+        );
     }
 
     #[gpui::test]
@@ -1788,4 +2006,90 @@ mod tests {
         );
         check([], "/project/src/main.rs", "--");
     }
+
+    #[test]
+    fn test_convert_rust_analyzer_schema() {
+        let raw_schema = serde_json::json!([
+            {
+                "title": "Assist",
+                "properties": {
+                    "rust-analyzer.assist.emitMustUse": {
+                        "markdownDescription": "Insert #[must_use] when generating `as_` methods for enum variants.",
+                        "default": false,
+                        "type": "boolean"
+                    }
+                }
+            },
+            {
+                "title": "Assist",
+                "properties": {
+                    "rust-analyzer.assist.expressionFillDefault": {
+                        "markdownDescription": "Placeholder expression to use for missing expressions in assists.",
+                        "default": "todo",
+                        "type": "string"
+                    }
+                }
+            },
+            {
+                "title": "Cache Priming",
+                "properties": {
+                    "rust-analyzer.cachePriming.enable": {
+                        "markdownDescription": "Warm up caches on project load.",
+                        "default": true,
+                        "type": "boolean"
+                    }
+                }
+            }
+        ]);
+
+        let converted = RustLspAdapter::convert_rust_analyzer_schema(&raw_schema);
+
+        assert_eq!(
+            converted.get("type").and_then(|v| v.as_str()),
+            Some("object")
+        );
+
+        let properties = converted
+            .pointer("/properties")
+            .expect("should have properties")
+            .as_object()
+            .expect("properties should be object");
+
+        assert!(properties.contains_key("assist"));
+        assert!(properties.contains_key("cachePriming"));
+        assert!(!properties.contains_key("rust-analyzer"));
+
+        let assist_props = properties
+            .get("assist")
+            .expect("should have assist")
+            .pointer("/properties")
+            .expect("assist should have properties")
+            .as_object()
+            .expect("assist properties should be object");
+
+        assert!(assist_props.contains_key("emitMustUse"));
+        assert!(assist_props.contains_key("expressionFillDefault"));
+
+        let emit_must_use = assist_props
+            .get("emitMustUse")
+            .expect("should have emitMustUse");
+        assert_eq!(
+            emit_must_use.get("type").and_then(|v| v.as_str()),
+            Some("boolean")
+        );
+        assert_eq!(
+            emit_must_use.get("default").and_then(|v| v.as_bool()),
+            Some(false)
+        );
+
+        let cache_priming_props = properties
+            .get("cachePriming")
+            .expect("should have cachePriming")
+            .pointer("/properties")
+            .expect("cachePriming should have properties")
+            .as_object()
+            .expect("cachePriming properties should be object");
+
+        assert!(cache_priming_props.contains_key("enable"));
+    }
 }

crates/languages/src/tailwind.rs 🔗

@@ -6,6 +6,7 @@ use language::{LanguageName, LspAdapter, LspAdapterDelegate, LspInstaller, Toolc
 use lsp::{LanguageServerBinary, LanguageServerName, Uri};
 use node_runtime::{NodeRuntime, VersionStrategy};
 use project::lsp_store::language_server_settings;
+use semver::Version;
 use serde_json::{Value, json};
 use std::{
     ffi::OsString,
@@ -39,14 +40,14 @@ impl TailwindLspAdapter {
 }
 
 impl LspInstaller for TailwindLspAdapter {
-    type BinaryVersion = String;
+    type BinaryVersion = Version;
 
     async fn fetch_latest_server_version(
         &self,
         _: &dyn LspAdapterDelegate,
         _: bool,
         _: &mut AsyncApp,
-    ) -> Result<String> {
+    ) -> Result<Self::BinaryVersion> {
         self.node
             .npm_package_latest_version(Self::PACKAGE_NAME)
             .await
@@ -70,11 +71,12 @@ impl LspInstaller for TailwindLspAdapter {
 
     async fn fetch_server_binary(
         &self,
-        latest_version: String,
+        latest_version: Self::BinaryVersion,
         container_dir: PathBuf,
         _: &dyn LspAdapterDelegate,
     ) -> Result<LanguageServerBinary> {
         let server_path = container_dir.join(SERVER_PATH);
+        let latest_version = latest_version.to_string();
 
         self.node
             .npm_install_packages(
@@ -92,7 +94,7 @@ impl LspInstaller for TailwindLspAdapter {
 
     async fn check_if_version_installed(
         &self,
-        version: &String,
+        version: &Self::BinaryVersion,
         container_dir: &PathBuf,
         _: &dyn LspAdapterDelegate,
     ) -> Option<LanguageServerBinary> {
@@ -140,13 +142,6 @@ impl LspAdapter for TailwindLspAdapter {
     ) -> Result<Option<serde_json::Value>> {
         Ok(Some(json!({
             "provideFormatter": true,
-            "userLanguages": {
-                "html": "html",
-                "css": "css",
-                "javascript": "javascript",
-                "typescript": "typescript",
-                "typescriptreact": "typescriptreact",
-            },
         })))
     }
 
@@ -167,28 +162,49 @@ impl LspAdapter for TailwindLspAdapter {
             tailwind_user_settings["emmetCompletions"] = Value::Bool(true);
         }
 
+        if tailwind_user_settings.get("includeLanguages").is_none() {
+            tailwind_user_settings["includeLanguages"] = json!({
+                "html": "html",
+                "css": "css",
+                "javascript": "javascript",
+                "typescript": "typescript",
+                "typescriptreact": "typescriptreact",
+            });
+        }
+
         Ok(json!({
-            "tailwindCSS": tailwind_user_settings,
+            "tailwindCSS": tailwind_user_settings
         }))
     }
 
     fn language_ids(&self) -> HashMap<LanguageName, String> {
         HashMap::from_iter([
-            (LanguageName::new("Astro"), "astro".to_string()),
-            (LanguageName::new("HTML"), "html".to_string()),
-            (LanguageName::new("Gleam"), "html".to_string()),
-            (LanguageName::new("CSS"), "css".to_string()),
-            (LanguageName::new("JavaScript"), "javascript".to_string()),
-            (LanguageName::new("TypeScript"), "typescript".to_string()),
-            (LanguageName::new("TSX"), "typescriptreact".to_string()),
-            (LanguageName::new("Svelte"), "svelte".to_string()),
-            (LanguageName::new("Elixir"), "phoenix-heex".to_string()),
-            (LanguageName::new("HEEX"), "phoenix-heex".to_string()),
-            (LanguageName::new("ERB"), "erb".to_string()),
-            (LanguageName::new("HTML+ERB"), "erb".to_string()),
-            (LanguageName::new("HTML/ERB"), "erb".to_string()),
-            (LanguageName::new("PHP"), "php".to_string()),
-            (LanguageName::new("Vue.js"), "vue".to_string()),
+            (LanguageName::new_static("Astro"), "astro".to_string()),
+            (LanguageName::new_static("HTML"), "html".to_string()),
+            (LanguageName::new_static("Gleam"), "html".to_string()),
+            (LanguageName::new_static("CSS"), "css".to_string()),
+            (
+                LanguageName::new_static("JavaScript"),
+                "javascript".to_string(),
+            ),
+            (
+                LanguageName::new_static("TypeScript"),
+                "typescript".to_string(),
+            ),
+            (
+                LanguageName::new_static("TSX"),
+                "typescriptreact".to_string(),
+            ),
+            (LanguageName::new_static("Svelte"), "svelte".to_string()),
+            (
+                LanguageName::new_static("Elixir"),
+                "phoenix-heex".to_string(),
+            ),
+            (LanguageName::new_static("HEEX"), "phoenix-heex".to_string()),
+            (LanguageName::new_static("ERB"), "erb".to_string()),
+            (LanguageName::new_static("HTML+ERB"), "erb".to_string()),
+            (LanguageName::new_static("PHP"), "php".to_string()),
+            (LanguageName::new_static("Vue.js"), "vue".to_string()),
         ])
     }
 }

crates/languages/src/tsx/highlights.scm 🔗

@@ -2,6 +2,40 @@
 
 (identifier) @variable
 
+(call_expression
+  function: (member_expression
+    object: (identifier) @type.builtin
+    (#any-of?
+      @type.builtin
+      "Promise"
+      "Array"
+      "Object"
+      "Map"
+      "Set"
+      "WeakMap"
+      "WeakSet"
+      "Date"
+      "Error"
+      "TypeError"
+      "RangeError"
+      "SyntaxError"
+      "ReferenceError"
+      "EvalError"
+      "URIError"
+      "RegExp"
+      "Function"
+      "Number"
+      "String"
+      "Boolean"
+      "Symbol"
+      "BigInt"
+      "Proxy"
+      "ArrayBuffer"
+      "DataView"
+    )
+  )
+)
+
 ; Properties
 
 (property_identifier) @property
@@ -18,6 +52,12 @@
   function: (member_expression
     property: [(property_identifier) (private_property_identifier)] @function.method))
 
+(new_expression
+  constructor: (identifier) @type)
+
+(nested_type_identifier
+  module: (identifier) @type)
+
 ; Function and method definitions
 
 (function_expression
@@ -47,13 +87,68 @@
   left: (identifier) @function
   right: [(function_expression) (arrow_function)])
 
+; Parameters
+
+(required_parameter
+  (identifier) @variable.parameter)
+
+(required_parameter
+  (_
+    ([
+      (identifier)
+      (shorthand_property_identifier_pattern)
+    ]) @variable.parameter))
+
+(optional_parameter
+  (identifier) @variable.parameter)
+
+(optional_parameter
+  (_
+    ([
+      (identifier)
+      (shorthand_property_identifier_pattern)
+    ]) @variable.parameter))
+
+(catch_clause
+  parameter: (identifier) @variable.parameter)
+
+(index_signature
+  name: (identifier) @variable.parameter)
+
+(arrow_function
+  parameter: (identifier) @variable.parameter)
+
+(type_predicate
+  name: (identifier) @variable.parameter)
+
 ; Special identifiers
 
-((identifier) @type
- (#match? @type "^[A-Z]"))
+(type_annotation) @type
 (type_identifier) @type
 (predefined_type) @type.builtin
 
+(type_alias_declaration
+  (type_identifier) @type)
+
+(type_alias_declaration
+  value: (_
+    (type_identifier) @type))
+
+(interface_declaration
+  (type_identifier) @type)
+
+(class_declaration
+  (type_identifier) @type.class)
+
+(extends_clause
+  value: (identifier) @type.class)
+
+(extends_type_clause
+  type: (type_identifier) @type)
+
+(implements_clause
+  (type_identifier) @type)
+
 ([
   (identifier)
   (shorthand_property_identifier)
@@ -231,8 +326,42 @@
   "<" @punctuation.bracket
   ">" @punctuation.bracket)
 
+(type_parameters
+  "<" @punctuation.bracket
+  ">" @punctuation.bracket)
+
 (decorator "@" @punctuation.special)
 
+(union_type
+  ("|") @punctuation.special)
+
+(intersection_type
+  ("&") @punctuation.special)
+
+(type_annotation
+  (":") @punctuation.special)
+
+(index_signature
+  (":") @punctuation.special)
+
+(type_predicate_annotation
+  (":") @punctuation.special)
+
+(public_field_definition
+  ("?") @punctuation.special)
+
+(property_signature
+  ("?") @punctuation.special)
+
+(method_signature
+  ("?") @punctuation.special)
+
+(optional_parameter
+  ([
+    "?"
+    ":"
+  ]) @punctuation.special)
+
 ; Keywords
 
 [ "abstract"
@@ -257,6 +386,34 @@
 (jsx_closing_element (identifier) @tag.jsx (#match? @tag.jsx "^[a-z][^.]*$"))
 (jsx_self_closing_element (identifier) @tag.jsx (#match? @tag.jsx "^[a-z][^.]*$"))
 
+(jsx_opening_element
+  [
+    (identifier) @type
+    (member_expression
+      object: (identifier) @type
+      property: (property_identifier) @type
+    )
+  ]
+)
+(jsx_closing_element
+  [
+    (identifier) @type
+    (member_expression
+      object: (identifier) @type
+      property: (property_identifier) @type
+    )
+  ]
+)
+(jsx_self_closing_element
+  [
+    (identifier) @type
+    (member_expression
+      object: (identifier) @type
+      property: (property_identifier) @type
+    )
+  ]
+)
+
 (jsx_attribute (property_identifier) @attribute.jsx)
 (jsx_opening_element (["<" ">"]) @punctuation.bracket.jsx)
 (jsx_closing_element (["</" ">"]) @punctuation.bracket.jsx)

crates/languages/src/tsx/injections.scm 🔗

@@ -83,3 +83,46 @@
   arguments: (arguments (template_string (string_fragment) @injection.content
                               (#set! injection.language "isograph")))
 )
+
+; Parse the contents of strings and tagged template
+; literals with leading ECMAScript comments:
+; '/* html */' or '/*html*/'
+(
+  ((comment) @_ecma_comment [
+    (string (string_fragment) @injection.content)
+    (template_string (string_fragment) @injection.content)
+  ])
+  (#match? @_ecma_comment "^\\/\\*\\s*html\\s*\\*\\/")
+  (#set! injection.language "html")
+)
+
+; '/* sql */' or '/*sql*/'
+(
+  ((comment) @_ecma_comment [
+    (string (string_fragment) @injection.content)
+    (template_string (string_fragment) @injection.content)
+  ])
+  (#match? @_ecma_comment "^\\/\\*\\s*sql\\s*\\*\\/")
+  (#set! injection.language "sql")
+)
+
+; '/* gql */' or '/*gql*/'
+; '/* graphql */' or '/*graphql*/'
+(
+  ((comment) @_ecma_comment [
+    (string (string_fragment) @injection.content)
+    (template_string (string_fragment) @injection.content)
+  ])
+  (#match? @_ecma_comment "^\\/\\*\\s*(gql|graphql)\\s*\\*\\/")
+  (#set! injection.language "graphql")
+)
+
+; '/* css */' or '/*css*/'
+(
+  ((comment) @_ecma_comment [
+    (string (string_fragment) @injection.content)
+    (template_string (string_fragment) @injection.content)
+  ])
+  (#match? @_ecma_comment "^\\/\\*\\s*(css)\\s*\\*\\/")
+  (#set! injection.language "css")
+)

crates/languages/src/tsx/textobjects.scm 🔗

@@ -18,13 +18,47 @@
         (_)* @function.inside
         "}")) @function.around
 
-(arrow_function
+((arrow_function
     body: (statement_block
         "{"
         (_)* @function.inside
         "}")) @function.around
+ (#not-has-parent? @function.around variable_declarator))
 
-(arrow_function) @function.around
+; Arrow function in variable declaration - capture the full declaration
+([
+    (lexical_declaration
+        (variable_declarator
+            value: (arrow_function
+                body: (statement_block
+                    "{"
+                    (_)* @function.inside
+                    "}"))))
+    (variable_declaration
+        (variable_declarator
+            value: (arrow_function
+                body: (statement_block
+                    "{"
+                    (_)* @function.inside
+                    "}"))))
+]) @function.around
+
+; Arrow function in variable declaration (expression body fallback)
+([
+    (lexical_declaration
+        (variable_declarator
+            value: (arrow_function
+                body: (_) @function.inside)))
+    (variable_declaration
+        (variable_declarator
+            value: (arrow_function
+                body: (_) @function.inside)))
+]) @function.around
+
+; Catch-all for arrow functions in other contexts (callbacks, etc.)
+((arrow_function
+    body: (_) @function.inside) @function.around
+ (#not-has-parent? @function.around variable_declarator))
 (function_signature) @function.around
 
 (generator_function

crates/languages/src/typescript.rs 🔗

@@ -12,6 +12,7 @@ use language::{
 use lsp::{CodeActionKind, LanguageServerBinary, LanguageServerName, Uri};
 use node_runtime::{NodeRuntime, VersionStrategy};
 use project::{Fs, lsp_store::language_server_settings};
+use semver::Version;
 use serde_json::{Value, json};
 use smol::lock::RwLock;
 use std::{
@@ -111,8 +112,7 @@ impl PackageJsonData {
                     "--".to_owned(),
                     "vitest".to_owned(),
                     "run".to_owned(),
-                    "--poolOptions.forks.minForks=0".to_owned(),
-                    "--poolOptions.forks.maxForks=1".to_owned(),
+                    "--no-file-parallelism".to_owned(),
                     VariableName::File.template_value(),
                 ],
                 cwd: Some(TYPESCRIPT_VITEST_PACKAGE_PATH_VARIABLE.template_value()),
@@ -130,8 +130,7 @@ impl PackageJsonData {
                     "--".to_owned(),
                     "vitest".to_owned(),
                     "run".to_owned(),
-                    "--poolOptions.forks.minForks=0".to_owned(),
-                    "--poolOptions.forks.maxForks=1".to_owned(),
+                    "--no-file-parallelism".to_owned(),
                     "--testNamePattern".to_owned(),
                     format!(
                         "\"{}\"",
@@ -599,14 +598,19 @@ pub struct TypeScriptLspAdapter {
 }
 
 impl TypeScriptLspAdapter {
-    const OLD_SERVER_PATH: &'static str = "node_modules/typescript-language-server/lib/cli.js";
-    const NEW_SERVER_PATH: &'static str = "node_modules/typescript-language-server/lib/cli.mjs";
-    const SERVER_NAME: LanguageServerName =
-        LanguageServerName::new_static("typescript-language-server");
+    const OLD_SERVER_PATH: &str = "node_modules/typescript-language-server/lib/cli.js";
+    const NEW_SERVER_PATH: &str = "node_modules/typescript-language-server/lib/cli.mjs";
+
     const PACKAGE_NAME: &str = "typescript";
+    const SERVER_PACKAGE_NAME: &str = "typescript-language-server";
+
+    const SERVER_NAME: LanguageServerName =
+        LanguageServerName::new_static(Self::SERVER_PACKAGE_NAME);
+
     pub fn new(node: NodeRuntime, fs: Arc<dyn Fs>) -> Self {
         TypeScriptLspAdapter { fs, node }
     }
+
     async fn tsdk_path(&self, adapter: &Arc<dyn LspAdapterDelegate>) -> Option<&'static str> {
         let is_yarn = adapter
             .read_text_file(RelPath::unix(".yarn/sdks/typescript/lib/typescript.js").unwrap())
@@ -632,8 +636,8 @@ impl TypeScriptLspAdapter {
 }
 
 pub struct TypeScriptVersions {
-    typescript_version: String,
-    server_version: String,
+    typescript_version: Version,
+    server_version: Version,
 }
 
 impl LspInstaller for TypeScriptLspAdapter {
@@ -644,48 +648,63 @@ impl LspInstaller for TypeScriptLspAdapter {
         _: &dyn LspAdapterDelegate,
         _: bool,
         _: &mut AsyncApp,
-    ) -> Result<TypeScriptVersions> {
+    ) -> Result<Self::BinaryVersion> {
         Ok(TypeScriptVersions {
-            typescript_version: self.node.npm_package_latest_version("typescript").await?,
+            typescript_version: self
+                .node
+                .npm_package_latest_version(Self::PACKAGE_NAME)
+                .await?,
             server_version: self
                 .node
-                .npm_package_latest_version("typescript-language-server")
+                .npm_package_latest_version(Self::SERVER_PACKAGE_NAME)
                 .await?,
         })
     }
 
     async fn check_if_version_installed(
         &self,
-        version: &TypeScriptVersions,
+        version: &Self::BinaryVersion,
         container_dir: &PathBuf,
         _: &dyn LspAdapterDelegate,
     ) -> Option<LanguageServerBinary> {
         let server_path = container_dir.join(Self::NEW_SERVER_PATH);
 
-        let should_install_language_server = self
+        if self
             .node
             .should_install_npm_package(
                 Self::PACKAGE_NAME,
                 &server_path,
                 container_dir,
-                VersionStrategy::Latest(version.typescript_version.as_str()),
+                VersionStrategy::Latest(&version.typescript_version),
             )
-            .await;
+            .await
+        {
+            return None;
+        }
 
-        if should_install_language_server {
-            None
-        } else {
-            Some(LanguageServerBinary {
-                path: self.node.binary_path().await.ok()?,
-                env: None,
-                arguments: typescript_server_binary_arguments(&server_path),
-            })
+        if self
+            .node
+            .should_install_npm_package(
+                Self::SERVER_PACKAGE_NAME,
+                &server_path,
+                container_dir,
+                VersionStrategy::Latest(&version.server_version),
+            )
+            .await
+        {
+            return None;
         }
+
+        Some(LanguageServerBinary {
+            path: self.node.binary_path().await.ok()?,
+            env: None,
+            arguments: typescript_server_binary_arguments(&server_path),
+        })
     }
 
     async fn fetch_server_binary(
         &self,
-        latest_version: TypeScriptVersions,
+        latest_version: Self::BinaryVersion,
         container_dir: PathBuf,
         _: &dyn LspAdapterDelegate,
     ) -> Result<LanguageServerBinary> {
@@ -697,11 +716,11 @@ impl LspInstaller for TypeScriptLspAdapter {
                 &[
                     (
                         Self::PACKAGE_NAME,
-                        latest_version.typescript_version.as_str(),
+                        &latest_version.typescript_version.to_string(),
                     ),
                     (
-                        "typescript-language-server",
-                        latest_version.server_version.as_str(),
+                        Self::SERVER_PACKAGE_NAME,
+                        &latest_version.server_version.to_string(),
                     ),
                 ],
             )
@@ -822,9 +841,9 @@ impl LspAdapter for TypeScriptLspAdapter {
 
     fn language_ids(&self) -> HashMap<LanguageName, String> {
         HashMap::from_iter([
-            (LanguageName::new("TypeScript"), "typescript".into()),
-            (LanguageName::new("JavaScript"), "javascript".into()),
-            (LanguageName::new("TSX"), "typescriptreact".into()),
+            (LanguageName::new_static("TypeScript"), "typescript".into()),
+            (LanguageName::new_static("JavaScript"), "javascript".into()),
+            (LanguageName::new_static("TSX"), "typescriptreact".into()),
         ])
     }
 }

crates/languages/src/typescript/highlights.scm 🔗

@@ -2,13 +2,69 @@
 
 (identifier) @variable
 
+(call_expression
+  function: (member_expression
+    object: (identifier) @type.builtin
+    (#any-of?
+      @type.builtin
+      "Promise"
+      "Array"
+      "Object"
+      "Map"
+      "Set"
+      "WeakMap"
+      "WeakSet"
+      "Date"
+      "Error"
+      "TypeError"
+      "RangeError"
+      "SyntaxError"
+      "ReferenceError"
+      "EvalError"
+      "URIError"
+      "RegExp"
+      "Function"
+      "Number"
+      "String"
+      "Boolean"
+      "Symbol"
+      "BigInt"
+      "Proxy"
+      "ArrayBuffer"
+      "DataView"
+    )
+  )
+)
+
 ; Special identifiers
 
-((identifier) @type
- (#match? @type "^[A-Z]"))
+(type_annotation) @type
+
 (type_identifier) @type
 (predefined_type) @type.builtin
 
+(type_alias_declaration
+  (type_identifier) @type)
+
+(type_alias_declaration
+  value: (_
+    (type_identifier) @type))
+
+(interface_declaration
+  (type_identifier) @type)
+
+(class_declaration
+  (type_identifier) @type.class)
+
+(extends_clause
+  value: (identifier) @type.class)
+
+(extends_type_clause
+  type: (type_identifier) @type)
+
+(implements_clause
+  (type_identifier) @type)
+
 ;; Enables ts-pretty-errors
 ;; The Lsp returns "snippets" of typescript, which are not valid typescript in totality,
 ;; but should still be highlighted
@@ -83,6 +139,12 @@
   function: (member_expression
     property: [(property_identifier) (private_property_identifier)] @function.method))
 
+(new_expression
+  constructor: (identifier) @type)
+
+(nested_type_identifier
+  module: (identifier) @type)
+
 ; Function and method definitions
 
 (function_expression
@@ -114,6 +176,40 @@
 
 (arrow_function) @function
 
+; Parameters
+
+(required_parameter
+  (identifier) @variable.parameter)
+
+(required_parameter
+  (_
+    ([
+      (identifier)
+      (shorthand_property_identifier_pattern)
+    ]) @variable.parameter))
+
+(optional_parameter
+  (identifier) @variable.parameter)
+
+(optional_parameter
+  (_
+    ([
+      (identifier)
+      (shorthand_property_identifier_pattern)
+    ]) @variable.parameter))
+
+(catch_clause
+  parameter: (identifier) @variable.parameter)
+
+(index_signature
+  name: (identifier) @variable.parameter)
+
+(arrow_function
+  parameter: (identifier) @variable.parameter)
+
+(type_predicate
+  name: (identifier) @variable.parameter)
+
 ; Literals
 
 (this) @variable.special
@@ -244,8 +340,42 @@
   "<" @punctuation.bracket
   ">" @punctuation.bracket)
 
+(type_parameters
+  "<" @punctuation.bracket
+  ">" @punctuation.bracket)
+
 (decorator "@" @punctuation.special)
 
+(union_type
+  ("|") @punctuation.special)
+
+(intersection_type
+  ("&") @punctuation.special)
+
+(type_annotation
+  (":") @punctuation.special)
+
+(index_signature
+  (":") @punctuation.special)
+
+(type_predicate_annotation
+  (":") @punctuation.special)
+
+(public_field_definition
+  ("?") @punctuation.special)
+
+(property_signature
+  ("?") @punctuation.special)
+
+(method_signature
+  ("?") @punctuation.special)
+
+(optional_parameter
+  ([
+    "?"
+    ":"
+  ]) @punctuation.special)
+
 ; Keywords
 
 [

crates/languages/src/typescript/injections.scm 🔗

@@ -124,3 +124,46 @@
       ]
     )))
   (#set! injection.language "css"))
+
+; Parse the contents of strings and tagged template
+; literals with leading ECMAScript comments:
+; '/* html */' or '/*html*/'
+(
+  ((comment) @_ecma_comment [
+    (string (string_fragment) @injection.content)
+    (template_string (string_fragment) @injection.content)
+  ])
+  (#match? @_ecma_comment "^\\/\\*\\s*html\\s*\\*\\/")
+  (#set! injection.language "html")
+)
+
+; '/* sql */' or '/*sql*/'
+(
+  ((comment) @_ecma_comment [
+    (string (string_fragment) @injection.content)
+    (template_string (string_fragment) @injection.content)
+  ])
+  (#match? @_ecma_comment "^\\/\\*\\s*sql\\s*\\*\\/")
+  (#set! injection.language "sql")
+)
+
+; '/* gql */' or '/*gql*/'
+; '/* graphql */' or '/*graphql*/'
+(
+  ((comment) @_ecma_comment [
+    (string (string_fragment) @injection.content)
+    (template_string (string_fragment) @injection.content)
+  ])
+  (#match? @_ecma_comment "^\\/\\*\\s*(gql|graphql)\\s*\\*\\/")
+  (#set! injection.language "graphql")
+)
+
+; '/* css */' or '/*css*/'
+(
+  ((comment) @_ecma_comment [
+    (string (string_fragment) @injection.content)
+    (template_string (string_fragment) @injection.content)
+  ])
+  (#match? @_ecma_comment "^\\/\\*\\s*(css)\\s*\\*\\/")
+  (#set! injection.language "css")
+)

crates/languages/src/typescript/textobjects.scm 🔗

@@ -18,13 +18,48 @@
         (_)* @function.inside
         "}")) @function.around
 
-(arrow_function
+((arrow_function
     body: (statement_block
         "{"
         (_)* @function.inside
         "}")) @function.around
+ (#not-has-parent? @function.around variable_declarator))
 
-(arrow_function) @function.around
+; Arrow function in variable declaration - capture the full declaration
+([
+    (lexical_declaration
+        (variable_declarator
+            value: (arrow_function
+                body: (statement_block
+                    "{"
+                    (_)* @function.inside
+                    "}"))))
+    (variable_declaration
+        (variable_declarator
+            value: (arrow_function
+                body: (statement_block
+                    "{"
+                    (_)* @function.inside
+                    "}"))))
+]) @function.around
+
+; Arrow function in variable declaration - capture body as @function.inside
+; (for statement blocks, the more specific pattern above captures just the contents)
+([
+    (lexical_declaration
+        (variable_declarator
+            value: (arrow_function
+                body: (_) @function.inside)))
+    (variable_declaration
+        (variable_declarator
+            value: (arrow_function
+                body: (_) @function.inside)))
+]) @function.around
+
+; Catch-all for arrow functions in other contexts (callbacks, etc.)
+((arrow_function
+    body: (_) @function.inside) @function.around
+ (#not-has-parent? @function.around variable_declarator))
 (function_signature) @function.around
 
 (generator_function

crates/languages/src/vtsls.rs 🔗

@@ -2,12 +2,17 @@ use anyhow::Result;
 use async_trait::async_trait;
 use collections::HashMap;
 use gpui::AsyncApp;
-use language::{LanguageName, LspAdapter, LspAdapterDelegate, LspInstaller, Toolchain};
+use language::{
+    LanguageName, LspAdapter, LspAdapterDelegate, LspInstaller, PromptResponseContext, Toolchain,
+};
 use lsp::{CodeActionKind, LanguageServerBinary, LanguageServerName, Uri};
 use node_runtime::{NodeRuntime, VersionStrategy};
 use project::{Fs, lsp_store::language_server_settings};
 use regex::Regex;
+use semver::Version;
 use serde_json::Value;
+use serde_json::json;
+use settings::update_settings_file;
 use std::{
     ffi::OsString,
     path::{Path, PathBuf},
@@ -15,6 +20,11 @@ use std::{
 };
 use util::{ResultExt, maybe, merge_json_value_into};
 
+const ACTION_ALWAYS: &str = "Always";
+const ACTION_NEVER: &str = "Never";
+const UPDATE_IMPORTS_MESSAGE_PATTERN: &str = "Update imports for";
+const VTSLS_SERVER_NAME: &str = "vtsls";
+
 fn typescript_server_binary_arguments(server_path: &Path) -> Vec<OsString> {
     vec![server_path.into(), "--stdio".into()]
 }
@@ -74,8 +84,8 @@ impl VtslsLspAdapter {
 }
 
 pub struct TypeScriptVersions {
-    typescript_version: String,
-    server_version: String,
+    typescript_version: Version,
+    server_version: Version,
 }
 
 const SERVER_NAME: LanguageServerName = LanguageServerName::new_static("vtsls");
@@ -88,7 +98,7 @@ impl LspInstaller for VtslsLspAdapter {
         _: &dyn LspAdapterDelegate,
         _: bool,
         _: &mut AsyncApp,
-    ) -> Result<TypeScriptVersions> {
+    ) -> Result<Self::BinaryVersion> {
         Ok(TypeScriptVersions {
             typescript_version: self.node.npm_package_latest_version("typescript").await?,
             server_version: self
@@ -115,12 +125,15 @@ impl LspInstaller for VtslsLspAdapter {
 
     async fn fetch_server_binary(
         &self,
-        latest_version: TypeScriptVersions,
+        latest_version: Self::BinaryVersion,
         container_dir: PathBuf,
         _: &dyn LspAdapterDelegate,
     ) -> Result<LanguageServerBinary> {
         let server_path = container_dir.join(Self::SERVER_PATH);
 
+        let typescript_version = latest_version.typescript_version.to_string();
+        let server_version = latest_version.server_version.to_string();
+
         let mut packages_to_install = Vec::new();
 
         if self
@@ -133,7 +146,7 @@ impl LspInstaller for VtslsLspAdapter {
             )
             .await
         {
-            packages_to_install.push((Self::PACKAGE_NAME, latest_version.server_version.as_str()));
+            packages_to_install.push((Self::PACKAGE_NAME, server_version.as_str()));
         }
 
         if self
@@ -146,10 +159,7 @@ impl LspInstaller for VtslsLspAdapter {
             )
             .await
         {
-            packages_to_install.push((
-                Self::TYPESCRIPT_PACKAGE_NAME,
-                latest_version.typescript_version.as_str(),
-            ));
+            packages_to_install.push((Self::TYPESCRIPT_PACKAGE_NAME, typescript_version.as_str()));
         }
 
         self.node
@@ -296,11 +306,58 @@ impl LspAdapter for VtslsLspAdapter {
 
     fn language_ids(&self) -> HashMap<LanguageName, String> {
         HashMap::from_iter([
-            (LanguageName::new("TypeScript"), "typescript".into()),
-            (LanguageName::new("JavaScript"), "javascript".into()),
-            (LanguageName::new("TSX"), "typescriptreact".into()),
+            (LanguageName::new_static("TypeScript"), "typescript".into()),
+            (LanguageName::new_static("JavaScript"), "javascript".into()),
+            (LanguageName::new_static("TSX"), "typescriptreact".into()),
         ])
     }
+
+    fn process_prompt_response(&self, context: &PromptResponseContext, cx: &mut AsyncApp) {
+        let selected_title = context.selected_action.title.as_str();
+        let is_preference_response =
+            selected_title == ACTION_ALWAYS || selected_title == ACTION_NEVER;
+        if !is_preference_response {
+            return;
+        }
+
+        if context.message.contains(UPDATE_IMPORTS_MESSAGE_PATTERN) {
+            let setting_value = match selected_title {
+                ACTION_ALWAYS => "always",
+                ACTION_NEVER => "never",
+                _ => return,
+            };
+
+            let settings = json!({
+                "typescript": {
+                    "updateImportsOnFileMove": {
+                        "enabled": setting_value
+                    }
+                },
+                "javascript": {
+                    "updateImportsOnFileMove": {
+                        "enabled": setting_value
+                    }
+                }
+            });
+
+            let _ = cx.update(|cx| {
+                update_settings_file(self.fs.clone(), cx, move |content, _| {
+                    let lsp_settings = content
+                        .project
+                        .lsp
+                        .0
+                        .entry(VTSLS_SERVER_NAME.into())
+                        .or_default();
+
+                    if let Some(existing) = &mut lsp_settings.settings {
+                        merge_json_value_into(settings, existing);
+                    } else {
+                        lsp_settings.settings = Some(settings);
+                    }
+                });
+            });
+        }
+    }
 }
 
 async fn get_cached_ts_server_binary(

crates/languages/src/yaml.rs 🔗

@@ -7,6 +7,7 @@ use language::{
 use lsp::{LanguageServerBinary, LanguageServerName, Uri};
 use node_runtime::{NodeRuntime, VersionStrategy};
 use project::lsp_store::language_server_settings;
+use semver::Version;
 use serde_json::Value;
 use settings::{Settings, SettingsLocation};
 use std::{
@@ -35,14 +36,14 @@ impl YamlLspAdapter {
 }
 
 impl LspInstaller for YamlLspAdapter {
-    type BinaryVersion = String;
+    type BinaryVersion = Version;
 
     async fn fetch_latest_server_version(
         &self,
         _: &dyn LspAdapterDelegate,
         _: bool,
         _: &mut AsyncApp,
-    ) -> Result<String> {
+    ) -> Result<Self::BinaryVersion> {
         self.node
             .npm_package_latest_version("yaml-language-server")
             .await
@@ -66,7 +67,7 @@ impl LspInstaller for YamlLspAdapter {
 
     async fn fetch_server_binary(
         &self,
-        latest_version: String,
+        latest_version: Self::BinaryVersion,
         container_dir: PathBuf,
         _: &dyn LspAdapterDelegate,
     ) -> Result<LanguageServerBinary> {
@@ -75,7 +76,7 @@ impl LspInstaller for YamlLspAdapter {
         self.node
             .npm_install_packages(
                 &container_dir,
-                &[(Self::PACKAGE_NAME, latest_version.as_str())],
+                &[(Self::PACKAGE_NAME, &latest_version.to_string())],
             )
             .await?;
 
@@ -88,7 +89,7 @@ impl LspInstaller for YamlLspAdapter {
 
     async fn check_if_version_installed(
         &self,
-        version: &String,
+        version: &Self::BinaryVersion,
         container_dir: &PathBuf,
         _: &dyn LspAdapterDelegate,
     ) -> Option<LanguageServerBinary> {

crates/languages/src/yaml/config.toml 🔗

@@ -1,6 +1,6 @@
 name = "YAML"
 grammar = "yaml"
-path_suffixes = ["yml", "yaml", "pixi.lock", "clang-format", "clangd"]
+path_suffixes = ["yml", "yaml", "pixi.lock", "clang-format", "clangd", "bst"]
 line_comments = ["# "]
 autoclose_before = ",]}"
 brackets = [

crates/livekit_client/examples/test_app.rs 🔗

@@ -378,7 +378,7 @@ impl Render for LivekitWindow {
                             .when_some(state.audio_output_stream.as_ref(), |el, state| {
                                 el.child(
                                     button()
-                                        .id(SharedString::from(identity.0.clone()))
+                                        .id(identity.0.clone())
                                         .child(if state.0.is_enabled() {
                                             "Deafen"
                                         } else {

crates/livekit_client/src/livekit_client/playback/source.rs 🔗

@@ -47,14 +47,17 @@ impl LiveKitStream {
         );
         let (queue_input, queue_output) = rodio::queue::queue(true);
         // spawn rtc stream
-        let receiver_task = executor.spawn({
-            async move {
-                while let Some(frame) = stream.next().await {
-                    let samples = frame_to_samplesbuffer(frame);
-                    queue_input.append(samples);
+        let receiver_task = executor.spawn_with_priority(
+            gpui::Priority::Realtime(gpui::RealtimePriority::Audio),
+            {
+                async move {
+                    while let Some(frame) = stream.next().await {
+                        let samples = frame_to_samplesbuffer(frame);
+                        queue_input.append(samples);
+                    }
                 }
-            }
-        });
+            },
+        );
 
         LiveKitStream {
             _receiver_task: receiver_task,

crates/lsp/src/lsp.rs 🔗

@@ -89,6 +89,7 @@ pub struct LanguageServer {
     outbound_tx: channel::Sender<String>,
     notification_tx: channel::Sender<NotificationSerializer>,
     name: LanguageServerName,
+    version: Option<SharedString>,
     process_name: Arc<str>,
     binary: LanguageServerBinary,
     capabilities: RwLock<ServerCapabilities>,
@@ -331,14 +332,13 @@ impl LanguageServer {
         };
         let root_uri = Uri::from_file_path(&working_dir)
             .map_err(|()| anyhow!("{working_dir:?} is not a valid URI"))?;
-
         log::info!(
-            "starting language server process. binary path: {:?}, working directory: {:?}, args: {:?}",
+            "starting language server process. binary path: \
+            {:?}, working directory: {:?}, args: {:?}",
             binary.path,
             working_dir,
             &binary.arguments
         );
-
         let mut command = util::command::new_smol_command(&binary.path);
         command
             .current_dir(working_dir)
@@ -348,6 +348,7 @@ impl LanguageServer {
             .stdout(Stdio::piped())
             .stderr(Stdio::piped())
             .kill_on_drop(true);
+
         let mut server = command
             .spawn()
             .with_context(|| format!("failed to spawn command {command:?}",))?;
@@ -501,6 +502,7 @@ impl LanguageServer {
             response_handlers,
             io_handlers,
             name: server_name,
+            version: None,
             process_name: binary
                 .path
                 .file_name()
@@ -882,7 +884,9 @@ impl LanguageServer {
                 window: Some(WindowClientCapabilities {
                     work_done_progress: Some(true),
                     show_message: Some(ShowMessageRequestClientCapabilities {
-                        message_action_item: None,
+                        message_action_item: Some(MessageActionItemCapabilities {
+                            additional_properties_support: Some(true),
+                        }),
                     }),
                     ..WindowClientCapabilities::default()
                 }),
@@ -923,6 +927,7 @@ impl LanguageServer {
                     )
                 })?;
             if let Some(info) = response.server_info {
+                self.version = info.version.map(SharedString::from);
                 self.process_name = info.name.into();
             }
             self.capabilities = RwLock::new(response.capabilities);
@@ -1153,6 +1158,11 @@ impl LanguageServer {
         self.name.clone()
     }
 
+    /// Get the version of the running language server.
+    pub fn version(&self) -> Option<SharedString> {
+        self.version.clone()
+    }
+
     pub fn process_name(&self) -> &str {
         &self.process_name
     }

crates/markdown/examples/markdown_as_child.rs 🔗

@@ -54,11 +54,11 @@ impl Render for HelloWorld {
                 ..Default::default()
             },
             code_block: StyleRefinement {
-                text: Some(gpui::TextStyleRefinement {
+                text: gpui::TextStyleRefinement {
                     font_family: Some("Zed Mono".into()),
                     background_color: Some(cx.theme().colors().editor_background),
                     ..Default::default()
-                }),
+                },
                 margin: gpui::EdgesRefinement {
                     top: Some(Length::Definite(rems(4.).into())),
                     left: Some(Length::Definite(rems(4.).into())),

crates/markdown/src/markdown.rs 🔗

@@ -7,6 +7,7 @@ use gpui::HitboxBehavior;
 use language::LanguageName;
 use log::Level;
 pub use path_range::{LineCol, PathWithRange};
+use ui::Checkbox;
 
 use std::borrow::Cow;
 use std::iter;
@@ -21,9 +22,9 @@ use collections::{HashMap, HashSet};
 use gpui::{
     AnyElement, App, BorderStyle, Bounds, ClipboardItem, CursorStyle, DispatchPhase, Edges, Entity,
     FocusHandle, Focusable, FontStyle, FontWeight, GlobalElementId, Hitbox, Hsla, Image,
-    ImageFormat, KeyContext, Length, MouseDownEvent, MouseEvent, MouseMoveEvent, MouseUpEvent,
-    Point, ScrollHandle, Stateful, StrikethroughStyle, StyleRefinement, StyledText, Task,
-    TextLayout, TextRun, TextStyle, TextStyleRefinement, actions, img, point, quad,
+    ImageFormat, KeyContext, Length, MouseButton, MouseDownEvent, MouseEvent, MouseMoveEvent,
+    MouseUpEvent, Point, ScrollHandle, Stateful, StrikethroughStyle, StyleRefinement, StyledText,
+    Task, TextLayout, TextRun, TextStyle, TextStyleRefinement, actions, img, point, quad,
 };
 use language::{Language, LanguageRegistry, Rope};
 use parser::CodeBlockMetadata;
@@ -69,6 +70,7 @@ pub struct MarkdownStyle {
     pub heading_level_styles: Option<HeadingLevelStyles>,
     pub height_is_multiple_of_line_height: bool,
     pub prevent_mouse_interaction: bool,
+    pub table_columns_min_size: bool,
 }
 
 impl Default for MarkdownStyle {
@@ -90,6 +92,7 @@ impl Default for MarkdownStyle {
             heading_level_styles: None,
             height_is_multiple_of_line_height: false,
             prevent_mouse_interaction: false,
+            table_columns_min_size: false,
         }
     }
 }
@@ -109,6 +112,7 @@ pub struct Markdown {
     options: Options,
     copied_code_blocks: HashSet<ElementId>,
     code_block_scroll_handles: HashMap<usize, ScrollHandle>,
+    context_menu_selected_text: Option<String>,
 }
 
 struct Options {
@@ -178,6 +182,7 @@ impl Markdown {
             },
             copied_code_blocks: HashSet::default(),
             code_block_scroll_handles: HashMap::default(),
+            context_menu_selected_text: None,
         };
         this.parse(cx);
         this
@@ -202,6 +207,7 @@ impl Markdown {
             },
             copied_code_blocks: HashSet::default(),
             code_block_scroll_handles: HashMap::default(),
+            context_menu_selected_text: None,
         };
         this.parse(cx);
         this
@@ -250,7 +256,7 @@ impl Markdown {
         self.autoscroll_request = None;
         self.pending_parse = None;
         self.should_reparse = false;
-        self.parsed_markdown = ParsedMarkdown::default();
+        // Don't clear parsed_markdown here - keep existing content visible until new parse completes
         self.parse(cx);
     }
 
@@ -286,6 +292,14 @@ impl Markdown {
         }
     }
 
+    pub fn selected_text(&self) -> Option<String> {
+        if self.selection.end <= self.selection.start {
+            None
+        } else {
+            Some(self.source[self.selection.start..self.selection.end].to_string())
+        }
+    }
+
     fn copy(&self, text: &RenderedText, _: &mut Window, cx: &mut Context<Self>) {
         if self.selection.end <= self.selection.start {
             return;
@@ -294,7 +308,11 @@ impl Markdown {
         cx.write_to_clipboard(ClipboardItem::new_string(text));
     }
 
-    fn copy_as_markdown(&self, _: &mut Window, cx: &mut Context<Self>) {
+    fn copy_as_markdown(&mut self, _: &mut Window, cx: &mut Context<Self>) {
+        if let Some(text) = self.context_menu_selected_text.take() {
+            cx.write_to_clipboard(ClipboardItem::new_string(text));
+            return;
+        }
         if self.selection.end <= self.selection.start {
             return;
         }
@@ -302,6 +320,10 @@ impl Markdown {
         cx.write_to_clipboard(ClipboardItem::new_string(text));
     }
 
+    fn capture_selection_for_context_menu(&mut self) {
+        self.context_menu_selected_text = self.selected_text();
+    }
+
     fn parse(&mut self, cx: &mut Context<Self>) {
         if self.source.is_empty() {
             return;
@@ -421,28 +443,72 @@ impl Focusable for Markdown {
     }
 }
 
-#[derive(Copy, Clone, Default, Debug)]
+#[derive(Debug, Default, Clone)]
+enum SelectMode {
+    #[default]
+    Character,
+    Word(Range<usize>),
+    Line(Range<usize>),
+    All,
+}
+
+#[derive(Clone, Default)]
 struct Selection {
     start: usize,
     end: usize,
     reversed: bool,
     pending: bool,
+    mode: SelectMode,
 }
 
 impl Selection {
-    fn set_head(&mut self, head: usize) {
-        if head < self.tail() {
-            if !self.reversed {
-                self.end = self.start;
-                self.reversed = true;
+    fn set_head(&mut self, head: usize, rendered_text: &RenderedText) {
+        match &self.mode {
+            SelectMode::Character => {
+                if head < self.tail() {
+                    if !self.reversed {
+                        self.end = self.start;
+                        self.reversed = true;
+                    }
+                    self.start = head;
+                } else {
+                    if self.reversed {
+                        self.start = self.end;
+                        self.reversed = false;
+                    }
+                    self.end = head;
+                }
             }
-            self.start = head;
-        } else {
-            if self.reversed {
-                self.start = self.end;
+            SelectMode::Word(original_range) | SelectMode::Line(original_range) => {
+                let head_range = if matches!(self.mode, SelectMode::Word(_)) {
+                    rendered_text.surrounding_word_range(head)
+                } else {
+                    rendered_text.surrounding_line_range(head)
+                };
+
+                if head < original_range.start {
+                    self.start = head_range.start;
+                    self.end = original_range.end;
+                    self.reversed = true;
+                } else if head >= original_range.end {
+                    self.start = original_range.start;
+                    self.end = head_range.end;
+                    self.reversed = false;
+                } else {
+                    self.start = original_range.start;
+                    self.end = original_range.end;
+                    self.reversed = false;
+                }
+            }
+            SelectMode::All => {
+                self.start = 0;
+                self.end = rendered_text
+                    .lines
+                    .last()
+                    .map(|line| line.source_end)
+                    .unwrap_or(0);
                 self.reversed = false;
             }
-            self.end = head;
         }
     }
 
@@ -531,7 +597,7 @@ impl MarkdownElement {
         window: &mut Window,
         cx: &mut App,
     ) {
-        let selection = self.markdown.read(cx).selection;
+        let selection = self.markdown.read(cx).selection.clone();
         let selection_start = rendered_text.position_for_source_index(selection.start);
         let selection_end = rendered_text.position_for_source_index(selection.end);
         if let Some(((start_position, start_line_height), (end_position, end_line_height))) =
@@ -618,6 +684,19 @@ impl MarkdownElement {
 
         let on_open_url = self.on_url_click.take();
 
+        self.on_mouse_event(window, cx, {
+            let hitbox = hitbox.clone();
+            move |markdown, event: &MouseDownEvent, phase, window, _| {
+                if phase.capture()
+                    && event.button == MouseButton::Right
+                    && hitbox.is_hovered(window)
+                {
+                    // Capture selected text so it survives until menu item is clicked
+                    markdown.capture_selection_for_context_menu();
+                }
+            }
+        });
+
         self.on_mouse_event(window, cx, {
             let rendered_text = rendered_text.clone();
             let hitbox = hitbox.clone();
@@ -631,26 +710,42 @@ impl MarkdownElement {
                                 match rendered_text.source_index_for_position(event.position) {
                                     Ok(ix) | Err(ix) => ix,
                                 };
-                            let range = if event.click_count == 2 {
-                                rendered_text.surrounding_word_range(source_index)
-                            } else if event.click_count == 3 {
-                                rendered_text.surrounding_line_range(source_index)
-                            } else {
-                                source_index..source_index
+                            let (range, mode) = match event.click_count {
+                                1 => {
+                                    let range = source_index..source_index;
+                                    (range, SelectMode::Character)
+                                }
+                                2 => {
+                                    let range = rendered_text.surrounding_word_range(source_index);
+                                    (range.clone(), SelectMode::Word(range))
+                                }
+                                3 => {
+                                    let range = rendered_text.surrounding_line_range(source_index);
+                                    (range.clone(), SelectMode::Line(range))
+                                }
+                                _ => {
+                                    let range = 0..rendered_text
+                                        .lines
+                                        .last()
+                                        .map(|line| line.source_end)
+                                        .unwrap_or(0);
+                                    (range, SelectMode::All)
+                                }
                             };
                             markdown.selection = Selection {
                                 start: range.start,
                                 end: range.end,
                                 reversed: false,
                                 pending: true,
+                                mode,
                             };
-                            window.focus(&markdown.focus_handle);
+                            window.focus(&markdown.focus_handle, cx);
                         }
 
                         window.prevent_default();
                         cx.notify();
                     }
-                } else if phase.capture() {
+                } else if phase.capture() && event.button == MouseButton::Left {
                     markdown.selection = Selection::default();
                     markdown.pressed_link = None;
                     cx.notify();
@@ -671,7 +766,7 @@ impl MarkdownElement {
                     {
                         Ok(ix) | Err(ix) => ix,
                     };
-                    markdown.selection.set_head(source_index);
+                    markdown.selection.set_head(source_index, &rendered_text);
                     markdown.autoscroll_request = Some(source_index);
                     cx.notify();
                 } else {
@@ -795,7 +890,7 @@ impl Element for MarkdownElement {
         let mut code_block_ids = HashSet::default();
 
         let mut current_img_block_range: Option<Range<usize>> = None;
-        for (range, event) in parsed_markdown.events.iter() {
+        for (index, (range, event)) in parsed_markdown.events.iter().enumerate() {
             // Skip alt text for images that rendered
             if let Some(current_img_block_range) = &current_img_block_range
                 && current_img_block_range.end > range.end
@@ -837,8 +932,7 @@ impl Element for MarkdownElement {
 
                             heading.style().refine(&self.style.heading);
 
-                            let text_style =
-                                self.style.heading.text_style().clone().unwrap_or_default();
+                            let text_style = self.style.heading.text_style().clone();
 
                             builder.push_text_style(text_style);
                             builder.push_div(heading, range, markdown_end);
@@ -932,10 +1026,7 @@ impl Element for MarkdownElement {
                                             }
                                         });
 
-                                    if let Some(code_block_text_style) = &self.style.code_block.text
-                                    {
-                                        builder.push_text_style(code_block_text_style.to_owned());
-                                    }
+                                    builder.push_text_style(self.style.code_block.text.to_owned());
                                     builder.push_code_block(language);
                                     builder.push_div(code_block, range, markdown_end);
                                 }
@@ -945,13 +1036,29 @@ impl Element for MarkdownElement {
                         MarkdownTag::HtmlBlock => builder.push_div(div(), range, markdown_end),
                         MarkdownTag::List(bullet_index) => {
                             builder.push_list(*bullet_index);
-                            builder.push_div(div().pl_4(), range, markdown_end);
+                            builder.push_div(div().pl_2p5(), range, markdown_end);
                         }
                         MarkdownTag::Item => {
-                            let bullet = if let Some(bullet_index) = builder.next_bullet_index() {
-                                format!("{}.", bullet_index)
+                            let bullet = if let Some((_, MarkdownEvent::TaskListMarker(checked))) =
+                                parsed_markdown.events.get(index.saturating_add(1))
+                            {
+                                let source = &parsed_markdown.source()[range.clone()];
+
+                                Checkbox::new(
+                                    ElementId::Name(source.to_string().into()),
+                                    if *checked {
+                                        ToggleState::Selected
+                                    } else {
+                                        ToggleState::Unselected
+                                    },
+                                )
+                                .fill()
+                                .visualization_only(true)
+                                .into_any_element()
+                            } else if let Some(bullet_index) = builder.next_bullet_index() {
+                                div().child(format!("{}.", bullet_index)).into_any_element()
                             } else {
-                                "•".to_string()
+                                div().child("•").into_any_element()
                             };
                             builder.push_div(
                                 div()
@@ -998,15 +1105,23 @@ impl Element for MarkdownElement {
                         }
                         MarkdownTag::MetadataBlock(_) => {}
                         MarkdownTag::Table(alignments) => {
-                            builder.table_alignments = alignments.clone();
+                            builder.table.start(alignments.clone());
 
+                            let column_count = alignments.len();
                             builder.push_div(
                                 div()
                                     .id(("table", range.start))
-                                    .min_w_0()
+                                    .grid()
+                                    .grid_cols(column_count as u16)
+                                    .when(self.style.table_columns_min_size, |this| {
+                                        this.grid_cols_min_content(column_count as u16)
+                                    })
+                                    .when(!self.style.table_columns_min_size, |this| {
+                                        this.grid_cols(column_count as u16)
+                                    })
                                     .size_full()
                                     .mb_2()
-                                    .border_1()
+                                    .border(px(1.5))
                                     .border_color(cx.theme().colors().border)
                                     .rounded_sm()
                                     .overflow_hidden(),
@@ -1015,38 +1130,33 @@ impl Element for MarkdownElement {
                             );
                         }
                         MarkdownTag::TableHead => {
-                            let column_count = builder.table_alignments.len();
-
-                            builder.push_div(
-                                div()
-                                    .grid()
-                                    .grid_cols(column_count as u16)
-                                    .bg(cx.theme().colors().title_bar_background),
-                                range,
-                                markdown_end,
-                            );
+                            builder.table.start_head();
                             builder.push_text_style(TextStyleRefinement {
                                 font_weight: Some(FontWeight::SEMIBOLD),
                                 ..Default::default()
                             });
                         }
                         MarkdownTag::TableRow => {
-                            let column_count = builder.table_alignments.len();
-
-                            builder.push_div(
-                                div().grid().grid_cols(column_count as u16),
-                                range,
-                                markdown_end,
-                            );
+                            builder.table.start_row();
                         }
                         MarkdownTag::TableCell => {
+                            let is_header = builder.table.in_head;
+                            let row_index = builder.table.row_index;
+                            let col_index = builder.table.col_index;
+
                             builder.push_div(
                                 div()
-                                    .min_w_0()
-                                    .border(px(0.5))
+                                    .when(col_index > 0, |this| this.border_l_1())
+                                    .when(row_index > 0, |this| this.border_t_1())
                                     .border_color(cx.theme().colors().border)
                                     .px_1()
-                                    .py_0p5(),
+                                    .py_0p5()
+                                    .when(is_header, |this| {
+                                        this.bg(cx.theme().colors().title_bar_background)
+                                    })
+                                    .when(!is_header && row_index % 2 == 1, |this| {
+                                        this.bg(cx.theme().colors().panel_background)
+                                    }),
                                 range,
                                 markdown_end,
                             );
@@ -1074,9 +1184,7 @@ impl Element for MarkdownElement {
 
                         builder.pop_div();
                         builder.pop_code_block();
-                        if self.style.code_block.text.is_some() {
-                            builder.pop_text_style();
-                        }
+                        builder.pop_text_style();
 
                         if let CodeBlockRenderer::Default {
                             copy_button: true, ..
@@ -1162,17 +1270,18 @@ impl Element for MarkdownElement {
                     }
                     MarkdownTagEnd::Table => {
                         builder.pop_div();
-                        builder.table_alignments.clear();
+                        builder.table.end();
                     }
                     MarkdownTagEnd::TableHead => {
-                        builder.pop_div();
                         builder.pop_text_style();
+                        builder.table.end_head();
                     }
                     MarkdownTagEnd::TableRow => {
-                        builder.pop_div();
+                        builder.table.end_row();
                     }
                     MarkdownTagEnd::TableCell => {
                         builder.pop_div();
+                        builder.table.end_cell();
                     }
                     _ => log::debug!("unsupported markdown tag end: {:?}", tag),
                 },
@@ -1202,6 +1311,15 @@ impl Element for MarkdownElement {
                     builder.push_text(html, range.clone());
                 }
                 MarkdownEvent::InlineHtml => {
+                    let html = &parsed_markdown.source[range.clone()];
+                    if html.starts_with("<code>") {
+                        builder.push_text_style(self.style.inline_code.clone());
+                        continue;
+                    }
+                    if html.trim_end().starts_with("</code>") {
+                        builder.pop_text_style();
+                        continue;
+                    }
                     builder.push_text(&parsed_markdown.source[range.clone()], range.clone());
                 }
                 MarkdownEvent::Rule => {
@@ -1217,6 +1335,9 @@ impl Element for MarkdownElement {
                 }
                 MarkdownEvent::SoftBreak => builder.push_text(" ", range.clone()),
                 MarkdownEvent::HardBreak => builder.push_text("\n", range.clone()),
+                MarkdownEvent::TaskListMarker(_) => {
+                    // handled inside the `MarkdownTag::Item` case
+                }
                 _ => log::debug!("unsupported markdown event {:?}", event),
             }
         }
@@ -1317,7 +1438,7 @@ fn apply_heading_style(
         };
 
         if let Some(style) = style_opt {
-            heading.style().text = Some(style.clone());
+            heading.style().text = style.clone();
         }
     }
 
@@ -1423,6 +1544,50 @@ impl ParentElement for AnyDiv {
     }
 }
 
+#[derive(Default)]
+struct TableState {
+    alignments: Vec<Alignment>,
+    in_head: bool,
+    row_index: usize,
+    col_index: usize,
+}
+
+impl TableState {
+    fn start(&mut self, alignments: Vec<Alignment>) {
+        self.alignments = alignments;
+        self.in_head = false;
+        self.row_index = 0;
+        self.col_index = 0;
+    }
+
+    fn end(&mut self) {
+        self.alignments.clear();
+        self.in_head = false;
+        self.row_index = 0;
+        self.col_index = 0;
+    }
+
+    fn start_head(&mut self) {
+        self.in_head = true;
+    }
+
+    fn end_head(&mut self) {
+        self.in_head = false;
+    }
+
+    fn start_row(&mut self) {
+        self.col_index = 0;
+    }
+
+    fn end_row(&mut self) {
+        self.row_index += 1;
+    }
+
+    fn end_cell(&mut self) {
+        self.col_index += 1;
+    }
+}
+
 struct MarkdownElementBuilder {
     div_stack: Vec<AnyDiv>,
     rendered_lines: Vec<RenderedLine>,
@@ -1434,7 +1599,7 @@ struct MarkdownElementBuilder {
     text_style_stack: Vec<TextStyleRefinement>,
     code_block_stack: Vec<Option<Arc<Language>>>,
     list_stack: Vec<ListStackEntry>,
-    table_alignments: Vec<Alignment>,
+    table: TableState,
     syntax_theme: Arc<SyntaxTheme>,
 }
 
@@ -1470,7 +1635,7 @@ impl MarkdownElementBuilder {
             text_style_stack: Vec::new(),
             code_block_stack: Vec::new(),
             list_stack: Vec::new(),
-            table_alignments: Vec::new(),
+            table: TableState::default(),
             syntax_theme,
         }
     }
@@ -1804,7 +1969,7 @@ impl RenderedText {
     }
 
     fn text_for_range(&self, range: Range<usize>) -> String {
-        let mut ret = vec![];
+        let mut accumulator = String::new();
 
         for line in self.lines.iter() {
             if range.start > line.source_end {
@@ -1829,9 +1994,12 @@ impl RenderedText {
             }
             .min(text.len());
 
-            ret.push(text[start..end].to_string());
+            accumulator.push_str(&text[start..end]);
+            accumulator.push('\n');
         }
-        ret.join("\n")
+        // Remove trailing newline
+        accumulator.pop();
+        accumulator
     }
 
     fn link_for_position(&self, position: Point<Pixels>) -> Option<&RenderedLink> {
@@ -1918,6 +2086,178 @@ mod tests {
         rendered.text
     }
 
+    #[gpui::test]
+    fn test_surrounding_word_range(cx: &mut TestAppContext) {
+        let rendered = render_markdown("Hello world tesεζ", cx);
+
+        // Test word selection for "Hello"
+        let word_range = rendered.surrounding_word_range(2); // Simulate click on 'l' in "Hello"
+        let selected_text = rendered.text_for_range(word_range);
+        assert_eq!(selected_text, "Hello");
+
+        // Test word selection for "world"
+        let word_range = rendered.surrounding_word_range(7); // Simulate click on 'o' in "world"
+        let selected_text = rendered.text_for_range(word_range);
+        assert_eq!(selected_text, "world");
+
+        // Test word selection for "tesεζ"
+        let word_range = rendered.surrounding_word_range(14); // Simulate click on 's' in "tesεζ"
+        let selected_text = rendered.text_for_range(word_range);
+        assert_eq!(selected_text, "tesεζ");
+
+        // Test word selection at word boundary (space)
+        let word_range = rendered.surrounding_word_range(5); // Simulate click on space between "Hello" and "world", expect highlighting word to the left
+        let selected_text = rendered.text_for_range(word_range);
+        assert_eq!(selected_text, "Hello");
+    }
+
+    #[gpui::test]
+    fn test_surrounding_line_range(cx: &mut TestAppContext) {
+        let rendered = render_markdown("First line\n\nSecond line\n\nThird lineεζ", cx);
+
+        // Test getting line range for first line
+        let line_range = rendered.surrounding_line_range(5); // Simulate click somewhere in first line
+        let selected_text = rendered.text_for_range(line_range);
+        assert_eq!(selected_text, "First line");
+
+        // Test getting line range for second line
+        let line_range = rendered.surrounding_line_range(13); // Simulate click at beginning in second line
+        let selected_text = rendered.text_for_range(line_range);
+        assert_eq!(selected_text, "Second line");
+
+        // Test getting line range for third line
+        let line_range = rendered.surrounding_line_range(37); // Simulate click at end of third line with multi-byte chars
+        let selected_text = rendered.text_for_range(line_range);
+        assert_eq!(selected_text, "Third lineεζ");
+    }
+
+    #[gpui::test]
+    fn test_selection_head_movement(cx: &mut TestAppContext) {
+        let rendered = render_markdown("Hello world test", cx);
+
+        let mut selection = Selection {
+            start: 5,
+            end: 5,
+            reversed: false,
+            pending: false,
+            mode: SelectMode::Character,
+        };
+
+        // Test forward selection
+        selection.set_head(10, &rendered);
+        assert_eq!(selection.start, 5);
+        assert_eq!(selection.end, 10);
+        assert!(!selection.reversed);
+        assert_eq!(selection.tail(), 5);
+
+        // Test backward selection
+        selection.set_head(2, &rendered);
+        assert_eq!(selection.start, 2);
+        assert_eq!(selection.end, 5);
+        assert!(selection.reversed);
+        assert_eq!(selection.tail(), 5);
+
+        // Test forward selection again from reversed state
+        selection.set_head(15, &rendered);
+        assert_eq!(selection.start, 5);
+        assert_eq!(selection.end, 15);
+        assert!(!selection.reversed);
+        assert_eq!(selection.tail(), 5);
+    }
+
+    #[gpui::test]
+    fn test_word_selection_drag(cx: &mut TestAppContext) {
+        let rendered = render_markdown("Hello world test", cx);
+
+        // Start with a simulated double-click on "world" (index 6-10)
+        let word_range = rendered.surrounding_word_range(7); // Click on 'o' in "world"
+        let mut selection = Selection {
+            start: word_range.start,
+            end: word_range.end,
+            reversed: false,
+            pending: true,
+            mode: SelectMode::Word(word_range),
+        };
+
+        // Drag forward to "test" - should expand selection to include "test"
+        selection.set_head(13, &rendered); // Index in "test"
+        assert_eq!(selection.start, 6); // Start of "world"
+        assert_eq!(selection.end, 16); // End of "test"
+        assert!(!selection.reversed);
+        let selected_text = rendered.text_for_range(selection.start..selection.end);
+        assert_eq!(selected_text, "world test");
+
+        // Drag backward to "Hello" - should expand selection to include "Hello"
+        selection.set_head(2, &rendered); // Index in "Hello"
+        assert_eq!(selection.start, 0); // Start of "Hello"
+        assert_eq!(selection.end, 11); // End of "world" (original selection)
+        assert!(selection.reversed);
+        let selected_text = rendered.text_for_range(selection.start..selection.end);
+        assert_eq!(selected_text, "Hello world");
+
+        // Drag back within original word - should revert to original selection
+        selection.set_head(8, &rendered); // Back within "world"
+        assert_eq!(selection.start, 6); // Start of "world"
+        assert_eq!(selection.end, 11); // End of "world"
+        assert!(!selection.reversed);
+        let selected_text = rendered.text_for_range(selection.start..selection.end);
+        assert_eq!(selected_text, "world");
+    }
+
+    #[gpui::test]
+    fn test_selection_with_markdown_formatting(cx: &mut TestAppContext) {
+        let rendered = render_markdown(
+            "This is **bold** text, this is *italic* text, use `code` here",
+            cx,
+        );
+        let word_range = rendered.surrounding_word_range(10); // Inside "bold"
+        let selected_text = rendered.text_for_range(word_range);
+        assert_eq!(selected_text, "bold");
+
+        let word_range = rendered.surrounding_word_range(32); // Inside "italic"
+        let selected_text = rendered.text_for_range(word_range);
+        assert_eq!(selected_text, "italic");
+
+        let word_range = rendered.surrounding_word_range(51); // Inside "code"
+        let selected_text = rendered.text_for_range(word_range);
+        assert_eq!(selected_text, "code");
+    }
+
+    #[gpui::test]
+    fn test_all_selection(cx: &mut TestAppContext) {
+        let rendered = render_markdown("Hello world\n\nThis is a test\n\nwith multiple lines", cx);
+
+        let total_length = rendered
+            .lines
+            .last()
+            .map(|line| line.source_end)
+            .unwrap_or(0);
+
+        let mut selection = Selection {
+            start: 0,
+            end: total_length,
+            reversed: false,
+            pending: true,
+            mode: SelectMode::All,
+        };
+
+        selection.set_head(5, &rendered); // Try to set head in middle
+        assert_eq!(selection.start, 0);
+        assert_eq!(selection.end, total_length);
+        assert!(!selection.reversed);
+
+        selection.set_head(25, &rendered); // Try to set head near end
+        assert_eq!(selection.start, 0);
+        assert_eq!(selection.end, total_length);
+        assert!(!selection.reversed);
+
+        let selected_text = rendered.text_for_range(selection.start..selection.end);
+        assert_eq!(
+            selected_text,
+            "Hello world\nThis is a test\nwith multiple lines"
+        );
+    }
+
     #[test]
     fn test_escape() {
         assert_eq!(Markdown::escape("hello `world`"), "hello \\`world\\`");

crates/markdown_preview/Cargo.toml 🔗

@@ -37,3 +37,4 @@ workspace.workspace = true
 
 [dev-dependencies]
 editor = { workspace = true, features = ["test-support"] }
+language = { workspace = true, features = ["test-support"] }

crates/markdown_preview/src/markdown_parser.rs 🔗

@@ -1467,9 +1467,7 @@ mod tests {
     use ParsedMarkdownListItemType::*;
     use core::panic;
     use gpui::{AbsoluteLength, BackgroundExecutor, DefiniteLength};
-    use language::{
-        HighlightId, Language, LanguageConfig, LanguageMatcher, LanguageRegistry, tree_sitter_rust,
-    };
+    use language::{HighlightId, LanguageRegistry};
     use pretty_assertions::assert_eq;
 
     async fn parse(input: &str) -> ParsedMarkdown {
@@ -3053,7 +3051,7 @@ fn main() {
     #[gpui::test]
     async fn test_code_block_with_language(executor: BackgroundExecutor) {
         let language_registry = Arc::new(LanguageRegistry::test(executor.clone()));
-        language_registry.add(rust_lang());
+        language_registry.add(language::rust_lang());
 
         let parsed = parse_markdown(
             "\
@@ -3079,21 +3077,6 @@ fn main() {
         );
     }
 
-    fn rust_lang() -> Arc<Language> {
-        Arc::new(Language::new(
-            LanguageConfig {
-                name: "Rust".into(),
-                matcher: LanguageMatcher {
-                    path_suffixes: vec!["rs".into()],
-                    ..Default::default()
-                },
-                collapsed_placeholder: " /* ... */ ".to_string(),
-                ..Default::default()
-            },
-            Some(tree_sitter_rust::LANGUAGE.into()),
-        ))
-    }
-
     fn h1(contents: MarkdownParagraph, source_range: Range<usize>) -> ParsedMarkdownElement {
         ParsedMarkdownElement::Heading(ParsedMarkdownHeading {
             source_range,

crates/markdown_preview/src/markdown_preview.rs 🔗

@@ -11,9 +11,19 @@ actions!(
     markdown,
     [
         /// Scrolls up by one page in the markdown preview.
-        MovePageUp,
+        #[action(deprecated_aliases = ["markdown::MovePageUp"])]
+        ScrollPageUp,
         /// Scrolls down by one page in the markdown preview.
-        MovePageDown,
+        #[action(deprecated_aliases = ["markdown::MovePageDown"])]
+        ScrollPageDown,
+        /// Scrolls up by approximately one visual line.
+        ScrollUp,
+        /// Scrolls down by approximately one visual line.
+        ScrollDown,
+        /// Scrolls up by one markdown element in the markdown preview
+        ScrollUpByItem,
+        /// Scrolls down by one markdown element in the markdown preview
+        ScrollDownByItem,
         /// Opens a markdown preview for the current file.
         OpenPreview,
         /// Opens a markdown preview in a split pane.

crates/markdown_preview/src/markdown_preview_view.rs 🔗

@@ -1,3 +1,4 @@
+use std::cmp::min;
 use std::sync::Arc;
 use std::time::Duration;
 use std::{ops::Range, path::PathBuf};
@@ -20,11 +21,12 @@ use workspace::{Pane, Workspace};
 use crate::markdown_elements::ParsedMarkdownElement;
 use crate::markdown_renderer::CheckboxClickedEvent;
 use crate::{
-    MovePageDown, MovePageUp, OpenFollowingPreview, OpenPreview, OpenPreviewToTheSide,
+    OpenFollowingPreview, OpenPreview, OpenPreviewToTheSide, ScrollPageDown, ScrollPageUp,
     markdown_elements::ParsedMarkdown,
     markdown_parser::parse_markdown,
     markdown_renderer::{RenderContext, render_markdown_block},
 };
+use crate::{ScrollDown, ScrollDownByItem, ScrollUp, ScrollUpByItem};
 
 const REPARSE_DEBOUNCE: Duration = Duration::from_millis(200);
 
@@ -94,7 +96,7 @@ impl MarkdownPreviewView {
                         pane.add_item(Box::new(view.clone()), false, false, None, window, cx)
                     }
                 });
-                editor.focus_handle(cx).focus(window);
+                editor.focus_handle(cx).focus(window, cx);
                 cx.notify();
             }
         });
@@ -368,7 +370,7 @@ impl MarkdownPreviewView {
                     cx,
                     |selections| selections.select_ranges(vec![selection]),
                 );
-                window.focus(&editor.focus_handle(cx));
+                window.focus(&editor.focus_handle(cx), cx);
             });
         }
     }
@@ -425,7 +427,7 @@ impl MarkdownPreviewView {
         !(current_block.is_list_item() && next_block.map(|b| b.is_list_item()).unwrap_or(false))
     }
 
-    fn scroll_page_up(&mut self, _: &MovePageUp, _window: &mut Window, cx: &mut Context<Self>) {
+    fn scroll_page_up(&mut self, _: &ScrollPageUp, _window: &mut Window, cx: &mut Context<Self>) {
         let viewport_height = self.list_state.viewport_bounds().size.height;
         if viewport_height.is_zero() {
             return;
@@ -435,7 +437,12 @@ impl MarkdownPreviewView {
         cx.notify();
     }
 
-    fn scroll_page_down(&mut self, _: &MovePageDown, _window: &mut Window, cx: &mut Context<Self>) {
+    fn scroll_page_down(
+        &mut self,
+        _: &ScrollPageDown,
+        _window: &mut Window,
+        cx: &mut Context<Self>,
+    ) {
         let viewport_height = self.list_state.viewport_bounds().size.height;
         if viewport_height.is_zero() {
             return;
@@ -444,6 +451,56 @@ impl MarkdownPreviewView {
         self.list_state.scroll_by(viewport_height);
         cx.notify();
     }
+
+    fn scroll_up(&mut self, _: &ScrollUp, window: &mut Window, cx: &mut Context<Self>) {
+        let scroll_top = self.list_state.logical_scroll_top();
+        if let Some(bounds) = self.list_state.bounds_for_item(scroll_top.item_ix) {
+            let item_height = bounds.size.height;
+            // Scroll no more than the rough equivalent of a large headline
+            let max_height = window.rem_size() * 2;
+            let scroll_height = min(item_height, max_height);
+            self.list_state.scroll_by(-scroll_height);
+        }
+        cx.notify();
+    }
+
+    fn scroll_down(&mut self, _: &ScrollDown, window: &mut Window, cx: &mut Context<Self>) {
+        let scroll_top = self.list_state.logical_scroll_top();
+        if let Some(bounds) = self.list_state.bounds_for_item(scroll_top.item_ix) {
+            let item_height = bounds.size.height;
+            // Scroll no more than the rough equivalent of a large headline
+            let max_height = window.rem_size() * 2;
+            let scroll_height = min(item_height, max_height);
+            self.list_state.scroll_by(scroll_height);
+        }
+        cx.notify();
+    }
+
+    fn scroll_up_by_item(
+        &mut self,
+        _: &ScrollUpByItem,
+        _window: &mut Window,
+        cx: &mut Context<Self>,
+    ) {
+        let scroll_top = self.list_state.logical_scroll_top();
+        if let Some(bounds) = self.list_state.bounds_for_item(scroll_top.item_ix) {
+            self.list_state.scroll_by(-bounds.size.height);
+        }
+        cx.notify();
+    }
+
+    fn scroll_down_by_item(
+        &mut self,
+        _: &ScrollDownByItem,
+        _window: &mut Window,
+        cx: &mut Context<Self>,
+    ) {
+        let scroll_top = self.list_state.logical_scroll_top();
+        if let Some(bounds) = self.list_state.bounds_for_item(scroll_top.item_ix) {
+            self.list_state.scroll_by(bounds.size.height);
+        }
+        cx.notify();
+    }
 }
 
 impl Focusable for MarkdownPreviewView {
@@ -496,6 +553,10 @@ impl Render for MarkdownPreviewView {
             .track_focus(&self.focus_handle(cx))
             .on_action(cx.listener(MarkdownPreviewView::scroll_page_up))
             .on_action(cx.listener(MarkdownPreviewView::scroll_page_down))
+            .on_action(cx.listener(MarkdownPreviewView::scroll_up))
+            .on_action(cx.listener(MarkdownPreviewView::scroll_down))
+            .on_action(cx.listener(MarkdownPreviewView::scroll_up_by_item))
+            .on_action(cx.listener(MarkdownPreviewView::scroll_down_by_item))
             .size_full()
             .bg(cx.theme().colors().editor_background)
             .p_4()
@@ -524,7 +585,7 @@ impl Render for MarkdownPreviewView {
                                                         if e.checked() { "[x]" } else { "[ ]" };
 
                                                     editor.edit(
-                                                        vec![(
+                                                        [(
                                                             MultiBufferOffset(
                                                                 e.source_range().start,
                                                             )

crates/markdown_preview/src/markdown_renderer.rs 🔗

@@ -9,7 +9,7 @@ use gpui::{
     AbsoluteLength, AnyElement, App, AppContext as _, ClipboardItem, Context, Div, Element,
     ElementId, Entity, HighlightStyle, Hsla, ImageSource, InteractiveText, IntoElement, Keystroke,
     Modifiers, ParentElement, Render, Resource, SharedString, Styled, StyledText, TextStyle,
-    WeakEntity, Window, div, img, rems,
+    WeakEntity, Window, div, img, px, rems,
 };
 use settings::Settings;
 use std::{
@@ -75,8 +75,10 @@ impl RenderContext {
 
         let settings = ThemeSettings::get_global(cx);
         let buffer_font_family = settings.buffer_font.family.clone();
+        let buffer_font_features = settings.buffer_font.features.clone();
         let mut buffer_text_style = window.text_style();
         buffer_text_style.font_family = buffer_font_family.clone();
+        buffer_text_style.font_features = buffer_font_features;
         buffer_text_style.font_size = AbsoluteLength::from(settings.buffer_font_size(cx));
 
         RenderContext {
@@ -519,8 +521,8 @@ fn render_markdown_table(parsed: &ParsedMarkdownTable, cx: &mut RenderContext) -
                 .children(render_markdown_text(&cell.children, cx))
                 .px_2()
                 .py_1()
-                .border_1()
-                .size_full()
+                .when(col_idx > 0, |this| this.border_l_1())
+                .when(row_idx > 0, |this| this.border_t_1())
                 .border_color(cx.border_color)
                 .when(cell.is_header, |this| {
                     this.bg(cx.title_bar_background_color)
@@ -550,8 +552,8 @@ fn render_markdown_table(parsed: &ParsedMarkdownTable, cx: &mut RenderContext) -
             }
 
             let empty_cell = div()
-                .border_1()
-                .size_full()
+                .when(col_idx > 0, |this| this.border_l_1())
+                .when(row_idx > 0, |this| this.border_t_1())
                 .border_color(cx.border_color)
                 .when(row_idx % 2 == 1, |this| this.bg(cx.panel_background_color));
 
@@ -560,7 +562,7 @@ fn render_markdown_table(parsed: &ParsedMarkdownTable, cx: &mut RenderContext) -
         }
     }
 
-    cx.with_common_p(div())
+    cx.with_common_p(v_flex().items_start())
         .when_some(parsed.caption.as_ref(), |this, caption| {
             this.children(render_markdown_text(caption, cx))
         })
@@ -568,8 +570,10 @@ fn render_markdown_table(parsed: &ParsedMarkdownTable, cx: &mut RenderContext) -
             div()
                 .grid()
                 .grid_cols(max_column_count as u16)
-                .border_1()
+                .border(px(1.5))
                 .border_color(cx.border_color)
+                .rounded_sm()
+                .overflow_hidden()
                 .children(cells),
         )
         .into_any()
@@ -633,8 +637,14 @@ fn render_markdown_code_block(
         .tooltip(Tooltip::text("Copy code block"))
         .visible_on_hover("markdown-block");
 
+    let font = gpui::Font {
+        family: cx.buffer_font_family.clone(),
+        features: cx.buffer_text_style.font_features.clone(),
+        ..Default::default()
+    };
+
     cx.with_common_p(div())
-        .font_family(cx.buffer_font_family.clone())
+        .font(font)
         .px_3()
         .py_3()
         .bg(cx.code_block_background_color)

crates/migrator/src/migrations.rs 🔗

@@ -153,3 +153,21 @@ pub(crate) mod m_2025_11_25 {
 
     pub(crate) use settings::remove_context_server_source;
 }
+
+pub(crate) mod m_2025_12_01 {
+    mod settings;
+
+    pub(crate) use settings::SETTINGS_PATTERNS;
+}
+
+pub(crate) mod m_2025_12_08 {
+    mod keymap;
+
+    pub(crate) use keymap::KEYMAP_PATTERNS;
+}
+
+pub(crate) mod m_2025_12_15 {
+    mod settings;
+
+    pub(crate) use settings::SETTINGS_PATTERNS;
+}

crates/migrator/src/migrations/m_2025_12_01/settings.rs 🔗

@@ -0,0 +1,55 @@
+use std::ops::Range;
+use tree_sitter::{Query, QueryMatch};
+
+use crate::MigrationPatterns;
+use crate::patterns::SETTINGS_NESTED_KEY_VALUE_PATTERN;
+
+pub const SETTINGS_PATTERNS: MigrationPatterns = &[(
+    SETTINGS_NESTED_KEY_VALUE_PATTERN,
+    rename_enable_preview_from_code_navigation_setting,
+)];
+
+fn rename_enable_preview_from_code_navigation_setting(
+    contents: &str,
+    mat: &QueryMatch,
+    query: &Query,
+) -> Option<(Range<usize>, String)> {
+    if !is_enable_preview_from_code_navigation(contents, mat, query) {
+        return None;
+    }
+
+    let setting_name_ix = query.capture_index_for_name("setting_name")?;
+    let setting_name_range = mat
+        .nodes_for_capture_index(setting_name_ix)
+        .next()?
+        .byte_range();
+
+    Some((
+        setting_name_range,
+        "enable_keep_preview_on_code_navigation".to_string(),
+    ))
+}
+
+fn is_enable_preview_from_code_navigation(contents: &str, mat: &QueryMatch, query: &Query) -> bool {
+    let parent_key_ix = match query.capture_index_for_name("parent_key") {
+        Some(ix) => ix,
+        None => return false,
+    };
+    let parent_range = match mat.nodes_for_capture_index(parent_key_ix).next() {
+        Some(node) => node.byte_range(),
+        None => return false,
+    };
+    if contents.get(parent_range) != Some("preview_tabs") {
+        return false;
+    }
+
+    let setting_name_ix = match query.capture_index_for_name("setting_name") {
+        Some(ix) => ix,
+        None => return false,
+    };
+    let setting_name_range = match mat.nodes_for_capture_index(setting_name_ix).next() {
+        Some(node) => node.byte_range(),
+        None => return false,
+    };
+    contents.get(setting_name_range) == Some("enable_preview_from_code_navigation")
+}

crates/migrator/src/migrations/m_2025_12_08/keymap.rs 🔗

@@ -0,0 +1,33 @@
+use collections::HashMap;
+use std::{ops::Range, sync::LazyLock};
+use tree_sitter::{Query, QueryMatch};
+
+use crate::MigrationPatterns;
+use crate::patterns::KEYMAP_ACTION_STRING_PATTERN;
+
+pub const KEYMAP_PATTERNS: MigrationPatterns =
+    &[(KEYMAP_ACTION_STRING_PATTERN, replace_string_action)];
+
+fn replace_string_action(
+    contents: &str,
+    mat: &QueryMatch,
+    query: &Query,
+) -> Option<(Range<usize>, String)> {
+    let action_name_ix = query.capture_index_for_name("action_name")?;
+    let action_name_node = mat.nodes_for_capture_index(action_name_ix).next()?;
+    let action_name_range = action_name_node.byte_range();
+    let action_name = contents.get(action_name_range.clone())?;
+
+    if let Some(new_action_name) = STRING_REPLACE.get(&action_name) {
+        return Some((action_name_range, new_action_name.to_string()));
+    }
+
+    None
+}
+
+static STRING_REPLACE: LazyLock<HashMap<&str, &str>> = LazyLock::new(|| {
+    HashMap::from_iter([(
+        "editor::AcceptPartialEditPrediction",
+        "editor::AcceptNextWordEditPrediction",
+    )])
+});

crates/migrator/src/migrations/m_2025_12_15/settings.rs 🔗

@@ -0,0 +1,52 @@
+use std::ops::Range;
+use tree_sitter::{Query, QueryMatch};
+
+use crate::MigrationPatterns;
+use crate::patterns::SETTINGS_NESTED_KEY_VALUE_PATTERN;
+
+pub const SETTINGS_PATTERNS: MigrationPatterns = &[(
+    SETTINGS_NESTED_KEY_VALUE_PATTERN,
+    rename_restore_on_startup_values,
+)];
+
+fn rename_restore_on_startup_values(
+    contents: &str,
+    mat: &QueryMatch,
+    query: &Query,
+) -> Option<(Range<usize>, String)> {
+    if !is_restore_on_startup_setting(contents, mat, query) {
+        return None;
+    }
+
+    let setting_value_ix = query.capture_index_for_name("setting_value")?;
+    let setting_value_range = mat
+        .nodes_for_capture_index(setting_value_ix)
+        .next()?
+        .byte_range();
+    let setting_value = contents.get(setting_value_range.clone())?;
+
+    // The value includes quotes, so we check for the quoted string
+    let new_value = match setting_value.trim() {
+        "\"none\"" => "\"empty_tab\"",
+        "\"welcome\"" => "\"launchpad\"",
+        _ => return None,
+    };
+
+    Some((setting_value_range, new_value.to_string()))
+}
+
+fn is_restore_on_startup_setting(contents: &str, mat: &QueryMatch, query: &Query) -> bool {
+    // Check that the parent key is "workspace" (since restore_on_startup is under workspace settings)
+    // Actually, restore_on_startup can be at the root level too, so we need to handle both cases
+    // The SETTINGS_NESTED_KEY_VALUE_PATTERN captures parent_key and setting_name
+
+    let setting_name_ix = match query.capture_index_for_name("setting_name") {
+        Some(ix) => ix,
+        None => return false,
+    };
+    let setting_name_range = match mat.nodes_for_capture_index(setting_name_ix).next() {
+        Some(node) => node.byte_range(),
+        None => return false,
+    };
+    contents.get(setting_name_range) == Some("restore_on_startup")
+}

crates/migrator/src/migrator.rs 🔗

@@ -139,6 +139,10 @@ pub fn migrate_keymap(text: &str) -> Result<Option<String>> {
             migrations::m_2025_04_15::KEYMAP_PATTERNS,
             &KEYMAP_QUERY_2025_04_15,
         ),
+        MigrationType::TreeSitter(
+            migrations::m_2025_12_08::KEYMAP_PATTERNS,
+            &KEYMAP_QUERY_2025_12_08,
+        ),
     ];
     run_migrations(text, migrations)
 }
@@ -219,11 +223,19 @@ pub fn migrate_settings(text: &str) -> Result<Option<String>> {
             migrations::m_2025_11_12::SETTINGS_PATTERNS,
             &SETTINGS_QUERY_2025_11_12,
         ),
+        MigrationType::TreeSitter(
+            migrations::m_2025_12_01::SETTINGS_PATTERNS,
+            &SETTINGS_QUERY_2025_12_01,
+        ),
         MigrationType::TreeSitter(
             migrations::m_2025_11_20::SETTINGS_PATTERNS,
             &SETTINGS_QUERY_2025_11_20,
         ),
         MigrationType::Json(migrations::m_2025_11_25::remove_context_server_source),
+        MigrationType::TreeSitter(
+            migrations::m_2025_12_15::SETTINGS_PATTERNS,
+            &SETTINGS_QUERY_2025_12_15,
+        ),
     ];
     run_migrations(text, migrations)
 }
@@ -346,10 +358,22 @@ define_query!(
     SETTINGS_QUERY_2025_11_12,
     migrations::m_2025_11_12::SETTINGS_PATTERNS
 );
+define_query!(
+    SETTINGS_QUERY_2025_12_01,
+    migrations::m_2025_12_01::SETTINGS_PATTERNS
+);
 define_query!(
     SETTINGS_QUERY_2025_11_20,
     migrations::m_2025_11_20::SETTINGS_PATTERNS
 );
+define_query!(
+    KEYMAP_QUERY_2025_12_08,
+    migrations::m_2025_12_08::KEYMAP_PATTERNS
+);
+define_query!(
+    SETTINGS_QUERY_2025_12_15,
+    migrations::m_2025_12_15::SETTINGS_PATTERNS
+);
 
 // custom query
 static EDIT_PREDICTION_SETTINGS_MIGRATION_QUERY: LazyLock<Query> = LazyLock::new(|| {
@@ -2262,6 +2286,54 @@ mod tests {
         );
     }
 
+    #[test]
+    fn test_remove_context_server_source() {
+        assert_migrate_settings(
+            &r#"
+            {
+                "context_servers": {
+                    "extension_server": {
+                        "source": "extension",
+                        "settings": {
+                            "foo": "bar"
+                        }
+                    },
+                    "custom_server": {
+                        "source": "custom",
+                        "command": "foo",
+                        "args": ["bar"],
+                        "env": {
+                            "FOO": "BAR"
+                        }
+                    },
+                }
+            }
+            "#
+            .unindent(),
+            Some(
+                &r#"
+                {
+                    "context_servers": {
+                        "extension_server": {
+                            "settings": {
+                                "foo": "bar"
+                            }
+                        },
+                        "custom_server": {
+                            "command": "foo",
+                            "args": ["bar"],
+                            "env": {
+                                "FOO": "BAR"
+                            }
+                        },
+                    }
+                }
+                "#
+                .unindent(),
+            ),
+        );
+    }
+
     #[test]
     fn test_project_panel_open_file_on_paste_migration() {
         assert_migrate_settings(
@@ -2308,25 +2380,14 @@ mod tests {
     }
 
     #[test]
-    fn test_remove_context_server_source() {
+    fn test_enable_preview_from_code_navigation_migration() {
         assert_migrate_settings(
             &r#"
             {
-                "context_servers": {
-                    "extension_server": {
-                        "source": "extension",
-                        "settings": {
-                            "foo": "bar"
-                        }
-                    },
-                    "custom_server": {
-                        "source": "custom",
-                        "command": "foo",
-                        "args": ["bar"],
-                        "env": {
-                            "FOO": "BAR"
-                        }
-                    },
+                "other_setting_1": 1,
+                "preview_tabs": {
+                    "other_setting_2": 2,
+                    "enable_preview_from_code_navigation": false
                 }
             }
             "#
@@ -2334,19 +2395,35 @@ mod tests {
             Some(
                 &r#"
                 {
-                    "context_servers": {
-                        "extension_server": {
-                            "settings": {
-                                "foo": "bar"
-                            }
-                        },
-                        "custom_server": {
-                            "command": "foo",
-                            "args": ["bar"],
-                            "env": {
-                                "FOO": "BAR"
-                            }
-                        },
+                    "other_setting_1": 1,
+                    "preview_tabs": {
+                        "other_setting_2": 2,
+                        "enable_keep_preview_on_code_navigation": false
+                    }
+                }
+                "#
+                .unindent(),
+            ),
+        );
+
+        assert_migrate_settings(
+            &r#"
+            {
+                "other_setting_1": 1,
+                "preview_tabs": {
+                    "other_setting_2": 2,
+                    "enable_preview_from_code_navigation": true
+                }
+            }
+            "#
+            .unindent(),
+            Some(
+                &r#"
+                {
+                    "other_setting_1": 1,
+                    "preview_tabs": {
+                        "other_setting_2": 2,
+                        "enable_keep_preview_on_code_navigation": true
                     }
                 }
                 "#

crates/mistral/src/mistral.rs 🔗

@@ -155,15 +155,15 @@ impl Model {
     pub fn max_token_count(&self) -> u64 {
         match self {
             Self::CodestralLatest => 256000,
-            Self::MistralLargeLatest => 131000,
+            Self::MistralLargeLatest => 256000,
             Self::MistralMediumLatest => 128000,
             Self::MistralSmallLatest => 32000,
-            Self::MagistralMediumLatest => 40000,
-            Self::MagistralSmallLatest => 40000,
+            Self::MagistralMediumLatest => 128000,
+            Self::MagistralSmallLatest => 128000,
             Self::OpenMistralNemo => 131000,
             Self::OpenCodestralMamba => 256000,
-            Self::DevstralMediumLatest => 128000,
-            Self::DevstralSmallLatest => 262144,
+            Self::DevstralMediumLatest => 256000,
+            Self::DevstralSmallLatest => 256000,
             Self::Pixtral12BLatest => 128000,
             Self::PixtralLargeLatest => 128000,
             Self::Custom { max_tokens, .. } => *max_tokens,

crates/multi_buffer/Cargo.toml 🔗

@@ -42,6 +42,8 @@ sum_tree.workspace = true
 text.workspace = true
 theme.workspace = true
 tree-sitter.workspace = true
+ztracing.workspace = true
+tracing.workspace = true
 util.workspace = true
 
 [dev-dependencies]
@@ -56,3 +58,6 @@ settings = { workspace = true, features = ["test-support"] }
 text = { workspace = true, features = ["test-support"] }
 util = { workspace = true, features = ["test-support"] }
 zlog.workspace = true
+
+[package.metadata.cargo-machete]
+ignored = ["tracing"]

crates/multi_buffer/src/multi_buffer.rs 🔗

@@ -19,9 +19,9 @@ use gpui::{App, Context, Entity, EntityId, EventEmitter, WeakEntity};
 use itertools::Itertools;
 use language::{
     AutoindentMode, BracketMatch, Buffer, BufferChunks, BufferRow, BufferSnapshot, Capability,
-    CharClassifier, CharKind, CharScopeContext, Chunk, CursorShape, DiagnosticEntryRef, DiskState,
-    File, IndentGuideSettings, IndentSize, Language, LanguageScope, OffsetRangeExt, OffsetUtf16,
-    Outline, OutlineItem, Point, PointUtf16, Selection, TextDimension, TextObject, ToOffset as _,
+    CharClassifier, CharKind, CharScopeContext, Chunk, CursorShape, DiagnosticEntryRef, File,
+    IndentGuideSettings, IndentSize, Language, LanguageScope, OffsetRangeExt, OffsetUtf16, Outline,
+    OutlineItem, Point, PointUtf16, Selection, TextDimension, TextObject, ToOffset as _,
     ToPoint as _, TransactionId, TreeSitterOptions, Unclipped,
     language_settings::{LanguageSettings, language_settings},
 };
@@ -41,7 +41,7 @@ use std::{
     io,
     iter::{self, FromIterator},
     mem,
-    ops::{self, AddAssign, Range, RangeBounds, Sub, SubAssign},
+    ops::{self, AddAssign, ControlFlow, Range, RangeBounds, Sub, SubAssign},
     rc::Rc,
     str,
     sync::Arc,
@@ -55,6 +55,7 @@ use text::{
 };
 use theme::SyntaxTheme;
 use util::post_inc;
+use ztracing::instrument;
 
 pub use self::path_key::PathKey;
 
@@ -115,7 +116,7 @@ pub enum Event {
         transaction_id: TransactionId,
     },
     Reloaded,
-    LanguageChanged(BufferId),
+    LanguageChanged(BufferId, bool),
     Reparsed(BufferId),
     Saved,
     FileHandleChanged,
@@ -1202,6 +1203,7 @@ impl MultiBuffer {
     }
 
     /// Returns an up-to-date snapshot of the MultiBuffer.
+    #[ztracing::instrument(skip_all)]
     pub fn snapshot(&self, cx: &App) -> MultiBufferSnapshot {
         self.sync(cx);
         self.snapshot.borrow().clone()
@@ -1672,6 +1674,7 @@ impl MultiBuffer {
         self.insert_excerpts_after(ExcerptId::max(), buffer, ranges, cx)
     }
 
+    #[instrument(skip_all)]
     fn merge_excerpt_ranges<'a>(
         expanded_ranges: impl IntoIterator<Item = &'a ExcerptRange<Point>> + 'a,
     ) -> (Vec<ExcerptRange<Point>>, Vec<usize>) {
@@ -1908,6 +1911,7 @@ impl MultiBuffer {
         cx.notify();
     }
 
+    #[ztracing::instrument(skip_all)]
     pub fn excerpts_for_buffer(
         &self,
         buffer_id: BufferId,
@@ -2262,6 +2266,7 @@ impl MultiBuffer {
         cx: &mut Context<Self>,
     ) {
         use language::BufferEvent;
+        let buffer_id = buffer.read(cx).remote_id();
         cx.emit(match event {
             BufferEvent::Edited => Event::Edited {
                 edited_buffer: Some(buffer),
@@ -2270,8 +2275,10 @@ impl MultiBuffer {
             BufferEvent::Saved => Event::Saved,
             BufferEvent::FileHandleChanged => Event::FileHandleChanged,
             BufferEvent::Reloaded => Event::Reloaded,
-            BufferEvent::LanguageChanged => Event::LanguageChanged(buffer.read(cx).remote_id()),
-            BufferEvent::Reparsed => Event::Reparsed(buffer.read(cx).remote_id()),
+            BufferEvent::LanguageChanged(has_language) => {
+                Event::LanguageChanged(buffer_id, *has_language)
+            }
+            BufferEvent::Reparsed => Event::Reparsed(buffer_id),
             BufferEvent::DiagnosticsUpdated => Event::DiagnosticsUpdated,
             BufferEvent::CapabilityChanged => {
                 self.capability = buffer.read(cx).capability();
@@ -2643,9 +2650,8 @@ impl MultiBuffer {
         for range in ranges {
             let range = range.to_point(&snapshot);
             let start = snapshot.point_to_offset(Point::new(range.start.row, 0));
-            let end = snapshot.point_to_offset(Point::new(range.end.row + 1, 0));
-            let start = start.saturating_sub_usize(1);
-            let end = snapshot.len().min(end + 1usize);
+            let end = (snapshot.point_to_offset(Point::new(range.end.row + 1, 0)) + 1usize)
+                .min(snapshot.len());
             cursor.seek(&start, Bias::Right);
             while let Some(item) = cursor.item() {
                 if *cursor.start() >= end {
@@ -2902,6 +2908,7 @@ impl MultiBuffer {
         cx.notify();
     }
 
+    #[ztracing::instrument(skip_all)]
     fn sync(&self, cx: &App) {
         let changed = self.buffer_changed_since_sync.replace(false);
         if !changed {
@@ -2987,7 +2994,7 @@ impl MultiBuffer {
             *is_dirty |= buffer.is_dirty();
             *has_deleted_file |= buffer
                 .file()
-                .is_some_and(|file| file.disk_state() == DiskState::Deleted);
+                .is_some_and(|file| file.disk_state().is_deleted());
             *has_conflict |= buffer.has_conflict();
         }
         if edited {
@@ -4498,6 +4505,7 @@ impl MultiBufferSnapshot {
         self.convert_dimension(point, text::BufferSnapshot::point_utf16_to_point)
     }
 
+    #[instrument(skip_all)]
     pub fn point_to_offset(&self, point: Point) -> MultiBufferOffset {
         self.convert_dimension(point, text::BufferSnapshot::point_to_offset)
     }
@@ -4551,6 +4559,7 @@ impl MultiBufferSnapshot {
         }
     }
 
+    #[instrument(skip_all)]
     fn convert_dimension<MBR1, MBR2, BR1, BR2>(
         &self,
         key: MBR1,
@@ -4633,7 +4642,24 @@ impl MultiBufferSnapshot {
         cx: &App,
     ) -> BTreeMap<MultiBufferRow, IndentSize> {
         let mut result = BTreeMap::new();
+        self.suggested_indents_callback(
+            rows,
+            |row, indent| {
+                result.insert(row, indent);
+                ControlFlow::Continue(())
+            },
+            cx,
+        );
+        result
+    }
 
+    // move this to be a generator once those are a thing
+    pub fn suggested_indents_callback(
+        &self,
+        rows: impl IntoIterator<Item = u32>,
+        mut cb: impl FnMut(MultiBufferRow, IndentSize) -> ControlFlow<()>,
+        cx: &App,
+    ) {
         let mut rows_for_excerpt = Vec::new();
         let mut cursor = self.cursor::<Point, Point>();
         let mut rows = rows.into_iter().peekable();
@@ -4677,16 +4703,17 @@ impl MultiBufferSnapshot {
             let buffer_indents = region
                 .buffer
                 .suggested_indents(buffer_rows, single_indent_size);
-            let multibuffer_indents = buffer_indents.into_iter().map(|(row, indent)| {
-                (
+            for (row, indent) in buffer_indents {
+                if cb(
                     MultiBufferRow(start_multibuffer_row + row - start_buffer_row),
                     indent,
                 )
-            });
-            result.extend(multibuffer_indents);
+                .is_break()
+                {
+                    return;
+                }
+            }
         }
-
-        result
     }
 
     pub fn indent_size_for_line(&self, row: MultiBufferRow) -> IndentSize {
@@ -5616,6 +5643,7 @@ impl MultiBufferSnapshot {
     /// excerpt
     ///
     /// Can optionally pass a range_filter to filter the ranges of brackets to consider
+    #[ztracing::instrument(skip_all)]
     pub fn innermost_enclosing_bracket_ranges<T: ToOffset>(
         &self,
         range: Range<T>,
@@ -6448,12 +6476,13 @@ impl MultiBufferSnapshot {
     }
 
     /// Returns the excerpt for the given id. The returned excerpt is guaranteed
-    /// to have the same excerpt id as the one passed in, with the exception of
-    /// `ExcerptId::max()`.
+    /// to have the latest excerpt id for the one passed in and will also remap
+    /// `ExcerptId::max()` to the corresponding excertp ID.
     ///
     /// Callers of this function should generally use the resulting excerpt's `id` field
     /// afterwards.
     fn excerpt(&self, excerpt_id: ExcerptId) -> Option<&Excerpt> {
+        let excerpt_id = self.latest_excerpt_id(excerpt_id);
         let mut cursor = self.excerpts.cursor::<Option<&Locator>>(());
         let locator = self.excerpt_locator_for_id(excerpt_id);
         cursor.seek(&Some(locator), Bias::Left);
@@ -6712,6 +6741,10 @@ impl MultiBufferSnapshot {
             prev_transform = Some(item);
         }
     }
+
+    pub fn diff_for_buffer_id(&self, buffer_id: BufferId) -> Option<&BufferDiffSnapshot> {
+        self.diffs.get(&buffer_id).map(|diff| &diff.diff)
+    }
 }
 
 impl<'a, MBD, BD> MultiBufferCursor<'a, MBD, BD>
@@ -6719,6 +6752,7 @@ where
     MBD: MultiBufferDimension + Ord + Sub + ops::AddAssign<<MBD as Sub>::Output>,
     BD: TextDimension + AddAssign<<MBD as Sub>::Output>,
 {
+    #[instrument(skip_all)]
     fn seek(&mut self, position: &MBD) {
         let position = OutputDimension(*position);
         self.cached_region.take();

crates/multi_buffer/src/multi_buffer_tests.rs 🔗

@@ -4711,6 +4711,19 @@ async fn test_word_diff_simple_replacement(cx: &mut TestAppContext) {
     assert_eq!(word_diffs, vec!["world", "bar", "WORLD", "BAR"]);
 }
 
+#[gpui::test]
+async fn test_word_diff_white_space(cx: &mut TestAppContext) {
+    let settings_store = cx.update(|cx| SettingsStore::test(cx));
+    cx.set_global(settings_store);
+
+    let base_text = "hello world foo bar\n";
+    let modified_text = "    hello world foo bar\n";
+
+    let word_diffs = collect_word_diffs(base_text, modified_text, cx);
+
+    assert_eq!(word_diffs, vec!["    "]);
+}
+
 #[gpui::test]
 async fn test_word_diff_consecutive_modified_lines(cx: &mut TestAppContext) {
     let settings_store = cx.update(|cx| SettingsStore::test(cx));

crates/multi_buffer/src/path_key.rs 🔗

@@ -1,448 +1,448 @@
-use std::{mem, ops::Range, sync::Arc};

-

-use collections::HashSet;

-use gpui::{App, AppContext, Context, Entity};

-use itertools::Itertools;

-use language::{Buffer, BufferSnapshot};

-use rope::Point;

-use text::{Bias, BufferId, OffsetRangeExt, locator::Locator};

-use util::{post_inc, rel_path::RelPath};

-

-use crate::{

-    Anchor, ExcerptId, ExcerptRange, ExpandExcerptDirection, MultiBuffer, build_excerpt_ranges,

-};

-

-#[derive(PartialEq, Eq, Ord, PartialOrd, Clone, Hash, Debug)]

-pub struct PathKey {

-    // Used by the derived PartialOrd & Ord

-    pub sort_prefix: Option<u64>,

-    pub path: Arc<RelPath>,

-}

-

-impl PathKey {

-    pub fn with_sort_prefix(sort_prefix: u64, path: Arc<RelPath>) -> Self {

-        Self {

-            sort_prefix: Some(sort_prefix),

-            path,

-        }

-    }

-

-    pub fn for_buffer(buffer: &Entity<Buffer>, cx: &App) -> Self {

-        if let Some(file) = buffer.read(cx).file() {

-            Self::with_sort_prefix(file.worktree_id(cx).to_proto(), file.path().clone())

-        } else {

-            Self {

-                sort_prefix: None,

-                path: RelPath::unix(&buffer.entity_id().to_string())

-                    .unwrap()

-                    .into_arc(),

-            }

-        }

-    }

-}

-

-impl MultiBuffer {

-    pub fn paths(&self) -> impl Iterator<Item = PathKey> + '_ {

-        self.excerpts_by_path.keys().cloned()

-    }

-

-    pub fn path_for_excerpt(&self, excerpt_id: ExcerptId) -> Option<&PathKey> {

-        self.paths_by_excerpt.get(&excerpt_id)

-    }

-

-    pub fn remove_excerpts_for_path(&mut self, path: PathKey, cx: &mut Context<Self>) {

-        if let Some(to_remove) = self.excerpts_by_path.remove(&path) {

-            self.remove_excerpts(to_remove, cx)

-        }

-    }

-

-    pub fn location_for_path(&self, path: &PathKey, cx: &App) -> Option<Anchor> {

-        let excerpt_id = self.excerpts_by_path.get(path)?.first()?;

-        let snapshot = self.read(cx);

-        let excerpt = snapshot.excerpt(*excerpt_id)?;

-        Some(Anchor::in_buffer(excerpt.id, excerpt.range.context.start))

-    }

-

-    pub fn excerpt_paths(&self) -> impl Iterator<Item = &PathKey> {

-        self.excerpts_by_path.keys()

-    }

-

-    pub fn excerpts_with_paths(&self) -> impl Iterator<Item = (&PathKey, &ExcerptId)> {

-        self.excerpts_by_path

-            .iter()

-            .flat_map(|(key, ex_ids)| ex_ids.iter().map(move |id| (key, id)))

-    }

-

-    pub fn excerpts_for_path(&self, path: &PathKey) -> impl '_ + Iterator<Item = ExcerptId> {

-        self.excerpts_by_path

-            .get(path)

-            .into_iter()

-            .flatten()

-            .copied()

-    }

-

-    /// Sets excerpts, returns `true` if at least one new excerpt was added.

-    pub fn set_excerpts_for_path(

-        &mut self,

-        path: PathKey,

-        buffer: Entity<Buffer>,

-        ranges: impl IntoIterator<Item = Range<Point>>,

-        context_line_count: u32,

-        cx: &mut Context<Self>,

-    ) -> (Vec<Range<Anchor>>, bool) {

-        let buffer_snapshot = buffer.read(cx).snapshot();

-        let excerpt_ranges = build_excerpt_ranges(ranges, context_line_count, &buffer_snapshot);

-

-        let (new, counts) = Self::merge_excerpt_ranges(&excerpt_ranges);

-        self.set_merged_excerpt_ranges_for_path(

-            path,

-            buffer,

-            excerpt_ranges,

-            &buffer_snapshot,

-            new,

-            counts,

-            cx,

-        )

-    }

-

-    pub fn set_excerpt_ranges_for_path(

-        &mut self,

-        path: PathKey,

-        buffer: Entity<Buffer>,

-        buffer_snapshot: &BufferSnapshot,

-        excerpt_ranges: Vec<ExcerptRange<Point>>,

-        cx: &mut Context<Self>,

-    ) -> (Vec<Range<Anchor>>, bool) {

-        let (new, counts) = Self::merge_excerpt_ranges(&excerpt_ranges);

-        self.set_merged_excerpt_ranges_for_path(

-            path,

-            buffer,

-            excerpt_ranges,

-            buffer_snapshot,

-            new,

-            counts,

-            cx,

-        )

-    }

-

-    pub fn set_anchored_excerpts_for_path(

-        &self,

-        path_key: PathKey,

-        buffer: Entity<Buffer>,

-        ranges: Vec<Range<text::Anchor>>,

-        context_line_count: u32,

-        cx: &Context<Self>,

-    ) -> impl Future<Output = Vec<Range<Anchor>>> + use<> {

-        let buffer_snapshot = buffer.read(cx).snapshot();

-        let multi_buffer = cx.weak_entity();

-        let mut app = cx.to_async();

-        async move {

-            let snapshot = buffer_snapshot.clone();

-            let (excerpt_ranges, new, counts) = app

-                .background_spawn(async move {

-                    let ranges = ranges.into_iter().map(|range| range.to_point(&snapshot));

-                    let excerpt_ranges =

-                        build_excerpt_ranges(ranges, context_line_count, &snapshot);

-                    let (new, counts) = Self::merge_excerpt_ranges(&excerpt_ranges);

-                    (excerpt_ranges, new, counts)

-                })

-                .await;

-

-            multi_buffer

-                .update(&mut app, move |multi_buffer, cx| {

-                    let (ranges, _) = multi_buffer.set_merged_excerpt_ranges_for_path(

-                        path_key,

-                        buffer,

-                        excerpt_ranges,

-                        &buffer_snapshot,

-                        new,

-                        counts,

-                        cx,

-                    );

-                    ranges

-                })

-                .ok()

-                .unwrap_or_default()

-        }

-    }

-

-    pub fn remove_excerpts_for_buffer(&mut self, buffer: BufferId, cx: &mut Context<Self>) {

-        self.remove_excerpts(

-            self.excerpts_for_buffer(buffer, cx)

-                .into_iter()

-                .map(|(excerpt, _)| excerpt),

-            cx,

-        );

-    }

-

-    pub(super) fn expand_excerpts_with_paths(

-        &mut self,

-        ids: impl IntoIterator<Item = ExcerptId>,

-        line_count: u32,

-        direction: ExpandExcerptDirection,

-        cx: &mut Context<Self>,

-    ) {

-        let grouped = ids

-            .into_iter()

-            .chunk_by(|id| self.paths_by_excerpt.get(id).cloned())

-            .into_iter()

-            .filter_map(|(k, v)| Some((k?, v.into_iter().collect::<Vec<_>>())))

-            .collect::<Vec<_>>();

-        let snapshot = self.snapshot(cx);

-

-        for (path, ids) in grouped.into_iter() {

-            let Some(excerpt_ids) = self.excerpts_by_path.get(&path) else {

-                continue;

-            };

-

-            let ids_to_expand = HashSet::from_iter(ids);

-            let mut excerpt_id_ = None;

-            let expanded_ranges = excerpt_ids.iter().filter_map(|excerpt_id| {

-                let excerpt = snapshot.excerpt(*excerpt_id)?;

-                let excerpt_id = excerpt.id;

-                if excerpt_id_.is_none() {

-                    excerpt_id_ = Some(excerpt_id);

-                }

-

-                let mut context = excerpt.range.context.to_point(&excerpt.buffer);

-                if ids_to_expand.contains(&excerpt_id) {

-                    match direction {

-                        ExpandExcerptDirection::Up => {

-                            context.start.row = context.start.row.saturating_sub(line_count);

-                            context.start.column = 0;

-                        }

-                        ExpandExcerptDirection::Down => {

-                            context.end.row =

-                                (context.end.row + line_count).min(excerpt.buffer.max_point().row);

-                            context.end.column = excerpt.buffer.line_len(context.end.row);

-                        }

-                        ExpandExcerptDirection::UpAndDown => {

-                            context.start.row = context.start.row.saturating_sub(line_count);

-                            context.start.column = 0;

-                            context.end.row =

-                                (context.end.row + line_count).min(excerpt.buffer.max_point().row);

-                            context.end.column = excerpt.buffer.line_len(context.end.row);

-                        }

-                    }

-                }

-

-                Some(ExcerptRange {

-                    context,

-                    primary: excerpt.range.primary.to_point(&excerpt.buffer),

-                })

-            });

-            let mut merged_ranges: Vec<ExcerptRange<Point>> = Vec::new();

-            for range in expanded_ranges {

-                if let Some(last_range) = merged_ranges.last_mut()

-                    && last_range.context.end >= range.context.start

-                {

-                    last_range.context.end = range.context.end;

-                    continue;

-                }

-                merged_ranges.push(range)

-            }

-            let Some(excerpt_id) = excerpt_id_ else {

-                continue;

-            };

-            let Some(buffer_id) = &snapshot.buffer_id_for_excerpt(excerpt_id) else {

-                continue;

-            };

-

-            let Some(buffer) = self.buffers.get(buffer_id).map(|b| b.buffer.clone()) else {

-                continue;

-            };

-

-            let buffer_snapshot = buffer.read(cx).snapshot();

-            self.update_path_excerpts(path.clone(), buffer, &buffer_snapshot, merged_ranges, cx);

-        }

-    }

-

-    /// Sets excerpts, returns `true` if at least one new excerpt was added.

-    fn set_merged_excerpt_ranges_for_path(

-        &mut self,

-        path: PathKey,

-        buffer: Entity<Buffer>,

-        ranges: Vec<ExcerptRange<Point>>,

-        buffer_snapshot: &BufferSnapshot,

-        new: Vec<ExcerptRange<Point>>,

-        counts: Vec<usize>,

-        cx: &mut Context<Self>,

-    ) -> (Vec<Range<Anchor>>, bool) {

-        let (excerpt_ids, added_a_new_excerpt) =

-            self.update_path_excerpts(path, buffer, buffer_snapshot, new, cx);

-

-        let mut result = Vec::new();

-        let mut ranges = ranges.into_iter();

-        for (excerpt_id, range_count) in excerpt_ids.into_iter().zip(counts.into_iter()) {

-            for range in ranges.by_ref().take(range_count) {

-                let range = Anchor::range_in_buffer(

-                    excerpt_id,

-                    buffer_snapshot.anchor_before(&range.primary.start)

-                        ..buffer_snapshot.anchor_after(&range.primary.end),

-                );

-                result.push(range)

-            }

-        }

-        (result, added_a_new_excerpt)

-    }

-

-    pub fn update_path_excerpts(

-        &mut self,

-        path: PathKey,

-        buffer: Entity<Buffer>,

-        buffer_snapshot: &BufferSnapshot,

-        new: Vec<ExcerptRange<Point>>,

-        cx: &mut Context<Self>,

-    ) -> (Vec<ExcerptId>, bool) {

-        let mut insert_after = self

-            .excerpts_by_path

-            .range(..path.clone())

-            .next_back()

-            .and_then(|(_, value)| value.last().copied())

-            .unwrap_or(ExcerptId::min());

-

-        let existing = self

-            .excerpts_by_path

-            .get(&path)

-            .cloned()

-            .unwrap_or_default();

-        let mut new_iter = new.iter().cloned().peekable();

-        let mut existing_iter = existing.into_iter().peekable();

-

-        let mut excerpt_ids = Vec::new();

-        let mut to_remove = Vec::new();

-        let mut to_insert: Vec<(ExcerptId, ExcerptRange<Point>)> = Vec::new();

-        let mut added_a_new_excerpt = false;

-        let snapshot = self.snapshot(cx);

-

-        let mut next_excerpt_id =

-            // is this right? What if we remove the last excerpt, then we might reallocate with a wrong mapping?

-            if let Some(last_entry) = self.snapshot.borrow().excerpt_ids.last() {

-                last_entry.id.0 + 1

-            } else {

-                1

-            };

-

-        let mut next_excerpt_id = move || ExcerptId(post_inc(&mut next_excerpt_id));

-

-        let mut excerpts_cursor = snapshot.excerpts.cursor::<Option<&Locator>>(());

-        excerpts_cursor.next();

-

-        loop {

-            let existing = if let Some(&existing_id) = existing_iter.peek() {

-                let locator = snapshot.excerpt_locator_for_id(existing_id);

-                excerpts_cursor.seek_forward(&Some(locator), Bias::Left);

-                if let Some(excerpt) = excerpts_cursor.item() {

-                    if excerpt.buffer_id != buffer_snapshot.remote_id() {

-                        to_remove.push(existing_id);

-                        existing_iter.next();

-                        continue;

-                    }

-                    Some((existing_id, excerpt.range.context.to_point(buffer_snapshot)))

-                } else {

-                    None

-                }

-            } else {

-                None

-            };

-

-            let new = new_iter.peek();

-            if let Some((last_id, last)) = to_insert.last_mut() {

-                if let Some(new) = new

-                    && last.context.end >= new.context.start

-                {

-                    last.context.end = last.context.end.max(new.context.end);

-                    excerpt_ids.push(*last_id);

-                    new_iter.next();

-                    continue;

-                }

-                if let Some((existing_id, existing_range)) = &existing

-                    && last.context.end >= existing_range.start

-                {

-                    last.context.end = last.context.end.max(existing_range.end);

-                    to_remove.push(*existing_id);

-                    self.snapshot

-                        .get_mut()

-                        .replaced_excerpts

-                        .insert(*existing_id, *last_id);

-                    existing_iter.next();

-                    continue;

-                }

-            }

-

-            match (new, existing) {

-                (None, None) => break,

-                (None, Some((existing_id, _))) => {

-                    existing_iter.next();

-                    to_remove.push(existing_id);

-                    continue;

-                }

-                (Some(_), None) => {

-                    added_a_new_excerpt = true;

-                    let new_id = next_excerpt_id();

-                    excerpt_ids.push(new_id);

-                    to_insert.push((new_id, new_iter.next().unwrap()));

-                    continue;

-                }

-                (Some(new), Some((_, existing_range))) => {

-                    if existing_range.end < new.context.start {

-                        let existing_id = existing_iter.next().unwrap();

-                        to_remove.push(existing_id);

-                        continue;

-                    } else if existing_range.start > new.context.end {

-                        let new_id = next_excerpt_id();

-                        excerpt_ids.push(new_id);

-                        to_insert.push((new_id, new_iter.next().unwrap()));

-                        continue;

-                    }

-

-                    if existing_range.start == new.context.start

-                        && existing_range.end == new.context.end

-                    {

-                        self.insert_excerpts_with_ids_after(

-                            insert_after,

-                            buffer.clone(),

-                            mem::take(&mut to_insert),

-                            cx,

-                        );

-                        insert_after = existing_iter.next().unwrap();

-                        excerpt_ids.push(insert_after);

-                        new_iter.next();

-                    } else {

-                        let existing_id = existing_iter.next().unwrap();

-                        let new_id = next_excerpt_id();

-                        self.snapshot

-                            .get_mut()

-                            .replaced_excerpts

-                            .insert(existing_id, new_id);

-                        to_remove.push(existing_id);

-                        let mut range = new_iter.next().unwrap();

-                        range.context.start = range.context.start.min(existing_range.start);

-                        range.context.end = range.context.end.max(existing_range.end);

-                        excerpt_ids.push(new_id);

-                        to_insert.push((new_id, range));

-                    }

-                }

-            };

-        }

-

-        self.insert_excerpts_with_ids_after(insert_after, buffer, to_insert, cx);

-        // todo(lw): There is a logic bug somewhere that causes the to_remove vector to be not ordered correctly

-        to_remove.sort_by_cached_key(|&id| snapshot.excerpt_locator_for_id(id));

-        self.remove_excerpts(to_remove, cx);

-

-        if excerpt_ids.is_empty() {

-            self.excerpts_by_path.remove(&path);

-        } else {

-            for excerpt_id in &excerpt_ids {

-                self.paths_by_excerpt.insert(*excerpt_id, path.clone());

-            }

-            let snapshot = &*self.snapshot.get_mut();

-            let mut excerpt_ids: Vec<_> = excerpt_ids.iter().dedup().cloned().collect();

-            excerpt_ids.sort_by_cached_key(|&id| snapshot.excerpt_locator_for_id(id));

-            self.excerpts_by_path.insert(path.clone(), excerpt_ids);

-        }

-

-        (excerpt_ids, added_a_new_excerpt)

-    }

-}

+use std::{mem, ops::Range, sync::Arc};
+
+use collections::HashSet;
+use gpui::{App, AppContext, Context, Entity};
+use itertools::Itertools;
+use language::{Buffer, BufferSnapshot};
+use rope::Point;
+use text::{Bias, BufferId, OffsetRangeExt, locator::Locator};
+use util::{post_inc, rel_path::RelPath};
+use ztracing::instrument;
+
+use crate::{
+    Anchor, ExcerptId, ExcerptRange, ExpandExcerptDirection, MultiBuffer, build_excerpt_ranges,
+};
+
+#[derive(PartialEq, Eq, Ord, PartialOrd, Clone, Hash, Debug)]
+pub struct PathKey {
+    // Used by the derived PartialOrd & Ord
+    pub sort_prefix: Option<u64>,
+    pub path: Arc<RelPath>,
+}
+
+impl PathKey {
+    pub fn with_sort_prefix(sort_prefix: u64, path: Arc<RelPath>) -> Self {
+        Self {
+            sort_prefix: Some(sort_prefix),
+            path,
+        }
+    }
+
+    pub fn for_buffer(buffer: &Entity<Buffer>, cx: &App) -> Self {
+        if let Some(file) = buffer.read(cx).file() {
+            Self::with_sort_prefix(file.worktree_id(cx).to_proto(), file.path().clone())
+        } else {
+            Self {
+                sort_prefix: None,
+                path: RelPath::unix(&buffer.entity_id().to_string())
+                    .unwrap()
+                    .into_arc(),
+            }
+        }
+    }
+}
+
+impl MultiBuffer {
+    pub fn paths(&self) -> impl Iterator<Item = &PathKey> + '_ {
+        self.excerpts_by_path.keys()
+    }
+
+    pub fn excerpts_for_path(&self, path: &PathKey) -> impl '_ + Iterator<Item = ExcerptId> {
+        self.excerpts_by_path
+            .get(path)
+            .map(|excerpts| excerpts.as_slice())
+            .unwrap_or(&[])
+            .iter()
+            .copied()
+    }
+
+    pub fn path_for_excerpt(&self, excerpt: ExcerptId) -> Option<PathKey> {
+        self.paths_by_excerpt.get(&excerpt).cloned()
+    }
+
+    pub fn remove_excerpts_for_path(&mut self, path: PathKey, cx: &mut Context<Self>) {
+        if let Some(to_remove) = self.excerpts_by_path.remove(&path) {
+            self.remove_excerpts(to_remove, cx)
+        }
+    }
+
+    pub fn buffer_for_path(&self, path: &PathKey, cx: &App) -> Option<Entity<Buffer>> {
+        let excerpt_id = self.excerpts_by_path.get(path)?.first()?;
+        let snapshot = self.read(cx);
+        let excerpt = snapshot.excerpt(*excerpt_id)?;
+        self.buffer(excerpt.buffer_id)
+    }
+
+    pub fn location_for_path(&self, path: &PathKey, cx: &App) -> Option<Anchor> {
+        let excerpt_id = self.excerpts_by_path.get(path)?.first()?;
+        let snapshot = self.read(cx);
+        let excerpt = snapshot.excerpt(*excerpt_id)?;
+        Some(Anchor::in_buffer(excerpt.id, excerpt.range.context.start))
+    }
+
+    /// Sets excerpts, returns `true` if at least one new excerpt was added.
+    #[instrument(skip_all)]
+    pub fn set_excerpts_for_path(
+        &mut self,
+        path: PathKey,
+        buffer: Entity<Buffer>,
+        ranges: impl IntoIterator<Item = Range<Point>>,
+        context_line_count: u32,
+        cx: &mut Context<Self>,
+    ) -> (Vec<Range<Anchor>>, bool) {
+        let buffer_snapshot = buffer.read(cx).snapshot();
+        let excerpt_ranges = build_excerpt_ranges(ranges, context_line_count, &buffer_snapshot);
+
+        let (new, counts) = Self::merge_excerpt_ranges(&excerpt_ranges);
+        self.set_merged_excerpt_ranges_for_path(
+            path,
+            buffer,
+            excerpt_ranges,
+            &buffer_snapshot,
+            new,
+            counts,
+            cx,
+        )
+    }
+
+    pub fn set_excerpt_ranges_for_path(
+        &mut self,
+        path: PathKey,
+        buffer: Entity<Buffer>,
+        buffer_snapshot: &BufferSnapshot,
+        excerpt_ranges: Vec<ExcerptRange<Point>>,
+        cx: &mut Context<Self>,
+    ) -> (Vec<Range<Anchor>>, bool) {
+        let (new, counts) = Self::merge_excerpt_ranges(&excerpt_ranges);
+        self.set_merged_excerpt_ranges_for_path(
+            path,
+            buffer,
+            excerpt_ranges,
+            buffer_snapshot,
+            new,
+            counts,
+            cx,
+        )
+    }
+
+    pub fn set_anchored_excerpts_for_path(
+        &self,
+        path_key: PathKey,
+        buffer: Entity<Buffer>,
+        ranges: Vec<Range<text::Anchor>>,
+        context_line_count: u32,
+        cx: &Context<Self>,
+    ) -> impl Future<Output = Vec<Range<Anchor>>> + use<> {
+        let buffer_snapshot = buffer.read(cx).snapshot();
+        let multi_buffer = cx.weak_entity();
+        let mut app = cx.to_async();
+        async move {
+            let snapshot = buffer_snapshot.clone();
+            let (excerpt_ranges, new, counts) = app
+                .background_spawn(async move {
+                    let ranges = ranges.into_iter().map(|range| range.to_point(&snapshot));
+                    let excerpt_ranges =
+                        build_excerpt_ranges(ranges, context_line_count, &snapshot);
+                    let (new, counts) = Self::merge_excerpt_ranges(&excerpt_ranges);
+                    (excerpt_ranges, new, counts)
+                })
+                .await;
+
+            multi_buffer
+                .update(&mut app, move |multi_buffer, cx| {
+                    let (ranges, _) = multi_buffer.set_merged_excerpt_ranges_for_path(
+                        path_key,
+                        buffer,
+                        excerpt_ranges,
+                        &buffer_snapshot,
+                        new,
+                        counts,
+                        cx,
+                    );
+                    ranges
+                })
+                .ok()
+                .unwrap_or_default()
+        }
+    }
+
+    pub fn remove_excerpts_for_buffer(&mut self, buffer: BufferId, cx: &mut Context<Self>) {
+        self.remove_excerpts(
+            self.excerpts_for_buffer(buffer, cx)
+                .into_iter()
+                .map(|(excerpt, _)| excerpt),
+            cx,
+        );
+    }
+
+    pub(super) fn expand_excerpts_with_paths(
+        &mut self,
+        ids: impl IntoIterator<Item = ExcerptId>,
+        line_count: u32,
+        direction: ExpandExcerptDirection,
+        cx: &mut Context<Self>,
+    ) {
+        let grouped = ids
+            .into_iter()
+            .chunk_by(|id| self.paths_by_excerpt.get(id).cloned())
+            .into_iter()
+            .filter_map(|(k, v)| Some((k?, v.into_iter().collect::<Vec<_>>())))
+            .collect::<Vec<_>>();
+        let snapshot = self.snapshot(cx);
+
+        for (path, ids) in grouped.into_iter() {
+            let Some(excerpt_ids) = self.excerpts_by_path.get(&path) else {
+                continue;
+            };
+
+            let ids_to_expand = HashSet::from_iter(ids);
+            let mut excerpt_id_ = None;
+            let expanded_ranges = excerpt_ids.iter().filter_map(|excerpt_id| {
+                let excerpt = snapshot.excerpt(*excerpt_id)?;
+                let excerpt_id = excerpt.id;
+                if excerpt_id_.is_none() {
+                    excerpt_id_ = Some(excerpt_id);
+                }
+
+                let mut context = excerpt.range.context.to_point(&excerpt.buffer);
+                if ids_to_expand.contains(&excerpt_id) {
+                    match direction {
+                        ExpandExcerptDirection::Up => {
+                            context.start.row = context.start.row.saturating_sub(line_count);
+                            context.start.column = 0;
+                        }
+                        ExpandExcerptDirection::Down => {
+                            context.end.row =
+                                (context.end.row + line_count).min(excerpt.buffer.max_point().row);
+                            context.end.column = excerpt.buffer.line_len(context.end.row);
+                        }
+                        ExpandExcerptDirection::UpAndDown => {
+                            context.start.row = context.start.row.saturating_sub(line_count);
+                            context.start.column = 0;
+                            context.end.row =
+                                (context.end.row + line_count).min(excerpt.buffer.max_point().row);
+                            context.end.column = excerpt.buffer.line_len(context.end.row);
+                        }
+                    }
+                }
+
+                Some(ExcerptRange {
+                    context,
+                    primary: excerpt.range.primary.to_point(&excerpt.buffer),
+                })
+            });
+            let mut merged_ranges: Vec<ExcerptRange<Point>> = Vec::new();
+            for range in expanded_ranges {
+                if let Some(last_range) = merged_ranges.last_mut()
+                    && last_range.context.end >= range.context.start
+                {
+                    last_range.context.end = range.context.end;
+                    continue;
+                }
+                merged_ranges.push(range)
+            }
+            let Some(excerpt_id) = excerpt_id_ else {
+                continue;
+            };
+            let Some(buffer_id) = &snapshot.buffer_id_for_excerpt(excerpt_id) else {
+                continue;
+            };
+
+            let Some(buffer) = self.buffers.get(buffer_id).map(|b| b.buffer.clone()) else {
+                continue;
+            };
+
+            let buffer_snapshot = buffer.read(cx).snapshot();
+            self.update_path_excerpts(path.clone(), buffer, &buffer_snapshot, merged_ranges, cx);
+        }
+    }
+
+    /// Sets excerpts, returns `true` if at least one new excerpt was added.
+    fn set_merged_excerpt_ranges_for_path(
+        &mut self,
+        path: PathKey,
+        buffer: Entity<Buffer>,
+        ranges: Vec<ExcerptRange<Point>>,
+        buffer_snapshot: &BufferSnapshot,
+        new: Vec<ExcerptRange<Point>>,
+        counts: Vec<usize>,
+        cx: &mut Context<Self>,
+    ) -> (Vec<Range<Anchor>>, bool) {
+        let (excerpt_ids, added_a_new_excerpt) =
+            self.update_path_excerpts(path, buffer, buffer_snapshot, new, cx);
+
+        let mut result = Vec::new();
+        let mut ranges = ranges.into_iter();
+        for (excerpt_id, range_count) in excerpt_ids.into_iter().zip(counts.into_iter()) {
+            for range in ranges.by_ref().take(range_count) {
+                let range = Anchor::range_in_buffer(
+                    excerpt_id,
+                    buffer_snapshot.anchor_before(&range.primary.start)
+                        ..buffer_snapshot.anchor_after(&range.primary.end),
+                );
+                result.push(range)
+            }
+        }
+        (result, added_a_new_excerpt)
+    }
+
+    pub fn update_path_excerpts(
+        &mut self,
+        path: PathKey,
+        buffer: Entity<Buffer>,
+        buffer_snapshot: &BufferSnapshot,
+        new: Vec<ExcerptRange<Point>>,
+        cx: &mut Context<Self>,
+    ) -> (Vec<ExcerptId>, bool) {
+        let mut insert_after = self
+            .excerpts_by_path
+            .range(..path.clone())
+            .next_back()
+            .and_then(|(_, value)| value.last().copied())
+            .unwrap_or(ExcerptId::min());
+
+        let existing = self
+            .excerpts_by_path
+            .get(&path)
+            .cloned()
+            .unwrap_or_default();
+        let mut new_iter = new.into_iter().peekable();
+        let mut existing_iter = existing.into_iter().peekable();
+
+        let mut excerpt_ids = Vec::new();
+        let mut to_remove = Vec::new();
+        let mut to_insert: Vec<(ExcerptId, ExcerptRange<Point>)> = Vec::new();
+        let mut added_a_new_excerpt = false;
+        let snapshot = self.snapshot(cx);
+
+        let mut next_excerpt_id =
+            // todo(lw): is this right? What if we remove the last excerpt, then we might reallocate with a wrong mapping?
+            if let Some(last_entry) = self.snapshot.borrow().excerpt_ids.last() {
+                last_entry.id.0 + 1
+            } else {
+                1
+            };
+
+        let mut next_excerpt_id = move || ExcerptId(post_inc(&mut next_excerpt_id));
+
+        let mut excerpts_cursor = snapshot.excerpts.cursor::<Option<&Locator>>(());
+        excerpts_cursor.next();
+
+        loop {
+            let existing = if let Some(&existing_id) = existing_iter.peek() {
+                let locator = snapshot.excerpt_locator_for_id(existing_id);
+                excerpts_cursor.seek_forward(&Some(locator), Bias::Left);
+                if let Some(excerpt) = excerpts_cursor.item() {
+                    if excerpt.buffer_id != buffer_snapshot.remote_id() {
+                        to_remove.push(existing_id);
+                        existing_iter.next();
+                        continue;
+                    }
+                    Some((existing_id, excerpt.range.context.to_point(buffer_snapshot)))
+                } else {
+                    None
+                }
+            } else {
+                None
+            };
+
+            let new = new_iter.peek();
+            if let Some((last_id, last)) = to_insert.last_mut() {
+                if let Some(new) = new
+                    && last.context.end >= new.context.start
+                {
+                    last.context.end = last.context.end.max(new.context.end);
+                    excerpt_ids.push(*last_id);
+                    new_iter.next();
+                    continue;
+                }
+                if let Some((existing_id, existing_range)) = &existing
+                    && last.context.end >= existing_range.start
+                {
+                    last.context.end = last.context.end.max(existing_range.end);
+                    to_remove.push(*existing_id);
+                    self.snapshot
+                        .get_mut()
+                        .replaced_excerpts
+                        .insert(*existing_id, *last_id);
+                    existing_iter.next();
+                    continue;
+                }
+            }
+
+            match (new, existing) {
+                (None, None) => break,
+                (None, Some((existing_id, _))) => {
+                    existing_iter.next();
+                    to_remove.push(existing_id);
+                    continue;
+                }
+                (Some(_), None) => {
+                    added_a_new_excerpt = true;
+                    let new_id = next_excerpt_id();
+                    excerpt_ids.push(new_id);
+                    to_insert.push((new_id, new_iter.next().unwrap()));
+                    continue;
+                }
+                (Some(new), Some((_, existing_range))) => {
+                    if existing_range.end < new.context.start {
+                        let existing_id = existing_iter.next().unwrap();
+                        to_remove.push(existing_id);
+                        continue;
+                    } else if existing_range.start > new.context.end {
+                        let new_id = next_excerpt_id();
+                        excerpt_ids.push(new_id);
+                        to_insert.push((new_id, new_iter.next().unwrap()));
+                        continue;
+                    }
+
+                    if existing_range.start == new.context.start
+                        && existing_range.end == new.context.end
+                    {
+                        self.insert_excerpts_with_ids_after(
+                            insert_after,
+                            buffer.clone(),
+                            mem::take(&mut to_insert),
+                            cx,
+                        );
+                        insert_after = existing_iter.next().unwrap();
+                        excerpt_ids.push(insert_after);
+                        new_iter.next();
+                    } else {
+                        let existing_id = existing_iter.next().unwrap();
+                        let new_id = next_excerpt_id();
+                        self.snapshot
+                            .get_mut()
+                            .replaced_excerpts
+                            .insert(existing_id, new_id);
+                        to_remove.push(existing_id);
+                        let mut range = new_iter.next().unwrap();
+                        range.context.start = range.context.start.min(existing_range.start);
+                        range.context.end = range.context.end.max(existing_range.end);
+                        excerpt_ids.push(new_id);
+                        to_insert.push((new_id, range));
+                    }
+                }
+            };
+        }
+
+        self.insert_excerpts_with_ids_after(insert_after, buffer, to_insert, cx);
+        // todo(lw): There is a logic bug somewhere that causes the to_remove vector to be not ordered correctly
+        to_remove.sort_by_cached_key(|&id| snapshot.excerpt_locator_for_id(id));
+        self.remove_excerpts(to_remove, cx);
+
+        if excerpt_ids.is_empty() {
+            self.excerpts_by_path.remove(&path);
+        } else {
+            for excerpt_id in &excerpt_ids {
+                self.paths_by_excerpt.insert(*excerpt_id, path.clone());
+            }
+            let snapshot = &*self.snapshot.get_mut();
+            let mut excerpt_ids: Vec<_> = excerpt_ids.iter().dedup().cloned().collect();
+            excerpt_ids.sort_by_cached_key(|&id| snapshot.excerpt_locator_for_id(id));
+            self.excerpts_by_path.insert(path, excerpt_ids);
+        }
+
+        (excerpt_ids, added_a_new_excerpt)
+    }
+}

crates/node_runtime/src/node_runtime.rs 🔗

@@ -32,9 +32,9 @@ pub struct NodeBinaryOptions {
 
 pub enum VersionStrategy<'a> {
     /// Install if current version doesn't match pinned version
-    Pin(&'a str),
+    Pin(&'a Version),
     /// Install if current version is older than latest version
-    Latest(&'a str),
+    Latest(&'a Version),
 }
 
 #[derive(Clone)]
@@ -206,14 +206,14 @@ impl NodeRuntime {
 
     pub async fn run_npm_subcommand(
         &self,
-        directory: &Path,
+        directory: Option<&Path>,
         subcommand: &str,
         args: &[&str],
     ) -> Result<Output> {
         let http = self.0.lock().await.http.clone();
         self.instance()
             .await
-            .run_npm_subcommand(Some(directory), http.proxy(), subcommand, args)
+            .run_npm_subcommand(directory, http.proxy(), subcommand, args)
             .await
     }
 
@@ -221,14 +221,14 @@ impl NodeRuntime {
         &self,
         local_package_directory: &Path,
         name: &str,
-    ) -> Result<Option<String>> {
+    ) -> Result<Option<Version>> {
         self.instance()
             .await
             .npm_package_installed_version(local_package_directory, name)
             .await
     }
 
-    pub async fn npm_package_latest_version(&self, name: &str) -> Result<String> {
+    pub async fn npm_package_latest_version(&self, name: &str) -> Result<Version> {
         let http = self.0.lock().await.http.clone();
         let output = self
             .instance()
@@ -271,19 +271,22 @@ impl NodeRuntime {
             .map(|(name, version)| format!("{name}@{version}"))
             .collect();
 
-        let mut arguments: Vec<_> = packages.iter().map(|p| p.as_str()).collect();
-        arguments.extend_from_slice(&[
-            "--save-exact",
-            "--fetch-retry-mintimeout",
-            "2000",
-            "--fetch-retry-maxtimeout",
-            "5000",
-            "--fetch-timeout",
-            "5000",
-        ]);
+        let arguments: Vec<_> = packages
+            .iter()
+            .map(|p| p.as_str())
+            .chain([
+                "--save-exact",
+                "--fetch-retry-mintimeout",
+                "2000",
+                "--fetch-retry-maxtimeout",
+                "5000",
+                "--fetch-timeout",
+                "5000",
+            ])
+            .collect();
 
         // This is also wrong because the directory is wrong.
-        self.run_npm_subcommand(directory, "install", &arguments)
+        self.run_npm_subcommand(Some(directory), "install", &arguments)
             .await?;
         Ok(())
     }
@@ -311,23 +314,9 @@ impl NodeRuntime {
             return true;
         };
 
-        let Some(installed_version) = Version::parse(&installed_version).log_err() else {
-            return true;
-        };
-
         match version_strategy {
-            VersionStrategy::Pin(pinned_version) => {
-                let Some(pinned_version) = Version::parse(pinned_version).log_err() else {
-                    return true;
-                };
-                installed_version != pinned_version
-            }
-            VersionStrategy::Latest(latest_version) => {
-                let Some(latest_version) = Version::parse(latest_version).log_err() else {
-                    return true;
-                };
-                installed_version < latest_version
-            }
+            VersionStrategy::Pin(pinned_version) => &installed_version != pinned_version,
+            VersionStrategy::Latest(latest_version) => &installed_version < latest_version,
         }
     }
 }
@@ -342,12 +331,12 @@ enum ArchiveType {
 pub struct NpmInfo {
     #[serde(default)]
     dist_tags: NpmInfoDistTags,
-    versions: Vec<String>,
+    versions: Vec<Version>,
 }
 
 #[derive(Debug, Deserialize, Default)]
 pub struct NpmInfoDistTags {
-    latest: Option<String>,
+    latest: Option<Version>,
 }
 
 #[async_trait::async_trait]
@@ -367,7 +356,7 @@ trait NodeRuntimeTrait: Send + Sync {
         &self,
         local_package_directory: &Path,
         name: &str,
-    ) -> Result<Option<String>>;
+    ) -> Result<Option<Version>>;
 }
 
 #[derive(Clone)]
@@ -559,7 +548,10 @@ impl NodeRuntimeTrait for ManagedNodeRuntime {
             command.env("PATH", env_path);
             command.env(NODE_CA_CERTS_ENV_VAR, node_ca_certs);
             command.arg(npm_file).arg(subcommand);
-            command.args(["--cache".into(), self.installation_path.join("cache")]);
+            command.arg(format!(
+                "--cache={}",
+                self.installation_path.join("cache").display()
+            ));
             command.args([
                 "--userconfig".into(),
                 self.installation_path.join("blank_user_npmrc"),
@@ -598,7 +590,7 @@ impl NodeRuntimeTrait for ManagedNodeRuntime {
         &self,
         local_package_directory: &Path,
         name: &str,
-    ) -> Result<Option<String>> {
+    ) -> Result<Option<Version>> {
         read_package_installed_version(local_package_directory.join("node_modules"), name).await
     }
 }
@@ -703,7 +695,10 @@ impl NodeRuntimeTrait for SystemNodeRuntime {
             .env("PATH", path)
             .env(NODE_CA_CERTS_ENV_VAR, node_ca_certs)
             .arg(subcommand)
-            .args(["--cache".into(), self.scratch_dir.join("cache")])
+            .arg(format!(
+                "--cache={}",
+                self.scratch_dir.join("cache").display()
+            ))
             .args(args);
         configure_npm_command(&mut command, directory, proxy);
         let output = command.output().await?;
@@ -720,7 +715,7 @@ impl NodeRuntimeTrait for SystemNodeRuntime {
         &self,
         local_package_directory: &Path,
         name: &str,
-    ) -> Result<Option<String>> {
+    ) -> Result<Option<Version>> {
         read_package_installed_version(local_package_directory.join("node_modules"), name).await
         // todo: allow returning a globally installed version (requires callers not to hard-code the path)
     }
@@ -729,7 +724,7 @@ impl NodeRuntimeTrait for SystemNodeRuntime {
 pub async fn read_package_installed_version(
     node_module_directory: PathBuf,
     name: &str,
-) -> Result<Option<String>> {
+) -> Result<Option<Version>> {
     let package_json_path = node_module_directory.join(name).join("package.json");
 
     let mut file = match fs::File::open(package_json_path).await {
@@ -745,7 +740,7 @@ pub async fn read_package_installed_version(
 
     #[derive(Deserialize)]
     struct PackageJson {
-        version: String,
+        version: Version,
     }
 
     let mut contents = String::new();
@@ -782,7 +777,7 @@ impl NodeRuntimeTrait for UnavailableNodeRuntime {
         &self,
         _local_package_directory: &Path,
         _: &str,
-    ) -> Result<Option<String>> {
+    ) -> Result<Option<Version>> {
         bail!("{}", self.error_message)
     }
 }

crates/notifications/src/status_toast.rs 🔗

@@ -137,7 +137,8 @@ impl Render for StatusToast {
                 let handle = self.this_handle.clone();
                 this.child(
                     IconButton::new("dismiss", IconName::Close)
-                        .icon_size(IconSize::XSmall)
+                        .shape(ui::IconButtonShape::Square)
+                        .icon_size(IconSize::Small)
                         .icon_color(Color::Muted)
                         .tooltip(Tooltip::text("Dismiss"))
                         .on_click(move |_click_event, _window, cx| {

crates/onboarding/Cargo.toml 🔗

@@ -22,7 +22,6 @@ db.workspace = true
 documented.workspace = true
 fs.workspace = true
 fuzzy.workspace = true
-git.workspace = true
 gpui.workspace = true
 menu.workspace = true
 notifications.workspace = true

crates/onboarding/src/basics_page.rs 🔗

@@ -3,6 +3,7 @@ use std::sync::Arc;
 use client::TelemetrySettings;
 use fs::Fs;
 use gpui::{Action, App, IntoElement};
+use project::project_settings::ProjectSettings;
 use settings::{BaseKeymap, Settings, update_settings_file};
 use theme::{
     Appearance, SystemAppearance, ThemeAppearanceMode, ThemeName, ThemeRegistry, ThemeSelection,
@@ -10,8 +11,8 @@ use theme::{
 };
 use ui::{
     Divider, ParentElement as _, StatefulInteractiveElement, SwitchField, TintColor,
-    ToggleButtonGroup, ToggleButtonGroupSize, ToggleButtonSimple, ToggleButtonWithIcon, prelude::*,
-    rems_from_px,
+    ToggleButtonGroup, ToggleButtonGroupSize, ToggleButtonSimple, ToggleButtonWithIcon, Tooltip,
+    prelude::*, rems_from_px,
 };
 use vim_mode_setting::VimModeSetting;
 
@@ -409,6 +410,48 @@ fn render_vim_mode_switch(tab_index: &mut isize, cx: &mut App) -> impl IntoEleme
     })
 }
 
+fn render_worktree_auto_trust_switch(tab_index: &mut isize, cx: &mut App) -> impl IntoElement {
+    let toggle_state = if ProjectSettings::get_global(cx).session.trust_all_worktrees {
+        ui::ToggleState::Selected
+    } else {
+        ui::ToggleState::Unselected
+    };
+
+    let tooltip_description = "Zed can only allow services like language servers, project settings, and MCP servers to run after you mark a new project as trusted.";
+
+    SwitchField::new(
+        "onboarding-auto-trust-worktrees",
+        Some("Trust All Projects By Default"),
+        Some("Automatically mark all new projects as trusted to unlock all Zed's features".into()),
+        toggle_state,
+        {
+            let fs = <dyn Fs>::global(cx);
+            move |&selection, _, cx| {
+                let trust = match selection {
+                    ToggleState::Selected => true,
+                    ToggleState::Unselected => false,
+                    ToggleState::Indeterminate => {
+                        return;
+                    }
+                };
+                update_settings_file(fs.clone(), cx, move |setting, _| {
+                    setting.session.get_or_insert_default().trust_all_worktrees = Some(trust);
+                });
+
+                telemetry::event!(
+                    "Welcome Page Worktree Auto Trust Toggled",
+                    options = if trust { "on" } else { "off" }
+                );
+            }
+        },
+    )
+    .tab_index({
+        *tab_index += 1;
+        *tab_index - 1
+    })
+    .tooltip(Tooltip::text(tooltip_description))
+}
+
 fn render_setting_import_button(
     tab_index: isize,
     label: SharedString,
@@ -481,6 +524,7 @@ pub(crate) fn render_basics_page(cx: &mut App) -> impl IntoElement {
         .child(render_base_keymap_section(&mut tab_index, cx))
         .child(render_import_settings_section(&mut tab_index, cx))
         .child(render_vim_mode_switch(&mut tab_index, cx))
+        .child(render_worktree_auto_trust_switch(&mut tab_index, cx))
         .child(Divider::horizontal().color(ui::DividerColor::BorderVariant))
         .child(render_telemetry_section(&mut tab_index, cx))
 }

crates/onboarding/src/onboarding.rs 🔗

@@ -1,5 +1,4 @@
-pub use crate::welcome::ShowWelcome;
-use crate::{multibuffer_hint::MultibufferHint, welcome::WelcomePage};
+use crate::multibuffer_hint::MultibufferHint;
 use client::{Client, UserStore, zed_urls};
 use db::kvp::KEY_VALUE_STORE;
 use fs::Fs;
@@ -17,6 +16,8 @@ use ui::{
     Divider, KeyBinding, ParentElement as _, StatefulInteractiveElement, Vector, VectorName,
     WithScrollbar as _, prelude::*, rems_from_px,
 };
+pub use workspace::welcome::ShowWelcome;
+use workspace::welcome::WelcomePage;
 use workspace::{
     AppState, Workspace, WorkspaceId,
     dock::DockPosition,
@@ -24,12 +25,12 @@ use workspace::{
     notifications::NotifyResultExt as _,
     open_new, register_serializable_item, with_active_or_new_workspace,
 };
+use zed_actions::OpenOnboarding;
 
 mod base_keymap_picker;
 mod basics_page;
 pub mod multibuffer_hint;
 mod theme_preview;
-mod welcome;
 
 /// Imports settings from Visual Studio Code.
 #[derive(Copy, Clone, Debug, Default, PartialEq, Deserialize, JsonSchema, Action)]
@@ -52,14 +53,6 @@ pub struct ImportCursorSettings {
 pub const FIRST_OPEN: &str = "first_open";
 pub const DOCS_URL: &str = "https://zed.dev/docs/";
 
-actions!(
-    zed,
-    [
-        /// Opens the onboarding view.
-        OpenOnboarding
-    ]
-);
-
 actions!(
     onboarding,
     [
@@ -121,7 +114,8 @@ pub fn init(cx: &mut App) {
                     if let Some(existing) = existing {
                         workspace.activate_item(&existing, true, true, window, cx);
                     } else {
-                        let settings_page = WelcomePage::new(window, cx);
+                        let settings_page = cx
+                            .new(|cx| WelcomePage::new(workspace.weak_handle(), false, window, cx));
                         workspace.add_item_to_active_pane(
                             Box::new(settings_page),
                             None,
@@ -196,7 +190,7 @@ pub fn show_onboarding_view(app_state: Arc<AppState>, cx: &mut App) -> Task<anyh
                 let onboarding_page = Onboarding::new(workspace, cx);
                 workspace.add_item_to_center(Box::new(onboarding_page.clone()), window, cx);
 
-                window.focus(&onboarding_page.focus_handle(cx));
+                window.focus(&onboarding_page.focus_handle(cx), cx);
 
                 cx.notify();
             };
@@ -283,11 +277,11 @@ impl Render for Onboarding {
             .on_action(Self::handle_sign_in)
             .on_action(Self::handle_open_account)
             .on_action(cx.listener(|_, _: &menu::SelectNext, window, cx| {
-                window.focus_next();
+                window.focus_next(cx);
                 cx.notify();
             }))
             .on_action(cx.listener(|_, _: &menu::SelectPrevious, window, cx| {
-                window.focus_prev();
+                window.focus_prev(cx);
                 cx.notify();
             }))
             .child(
@@ -427,7 +421,9 @@ fn go_to_welcome_page(cx: &mut App) {
             if let Some(idx) = idx {
                 pane.activate_item(idx, true, true, window, cx);
             } else {
-                let item = Box::new(WelcomePage::new(window, cx));
+                let item = Box::new(
+                    cx.new(|cx| WelcomePage::new(workspace.weak_handle(), false, window, cx)),
+                );
                 pane.add_item(item, true, true, Some(onboarding_idx), window, cx);
             }
 

crates/onboarding/src/welcome.rs 🔗

@@ -1,443 +0,0 @@
-use gpui::{
-    Action, App, Context, Entity, EventEmitter, FocusHandle, Focusable, InteractiveElement,
-    ParentElement, Render, Styled, Task, Window, actions,
-};
-use menu::{SelectNext, SelectPrevious};
-use ui::{ButtonLike, Divider, DividerColor, KeyBinding, Vector, VectorName, prelude::*};
-use workspace::{
-    NewFile, Open,
-    item::{Item, ItemEvent},
-    with_active_or_new_workspace,
-};
-use zed_actions::{Extensions, OpenSettings, agent, command_palette};
-
-use crate::{Onboarding, OpenOnboarding};
-
-actions!(
-    zed,
-    [
-        /// Show the Zed welcome screen
-        ShowWelcome
-    ]
-);
-
-const CONTENT: (Section<4>, Section<3>) = (
-    Section {
-        title: "Get Started",
-        entries: [
-            SectionEntry {
-                icon: IconName::Plus,
-                title: "New File",
-                action: &NewFile,
-            },
-            SectionEntry {
-                icon: IconName::FolderOpen,
-                title: "Open Project",
-                action: &Open,
-            },
-            SectionEntry {
-                icon: IconName::CloudDownload,
-                title: "Clone Repository",
-                action: &git::Clone,
-            },
-            SectionEntry {
-                icon: IconName::ListCollapse,
-                title: "Open Command Palette",
-                action: &command_palette::Toggle,
-            },
-        ],
-    },
-    Section {
-        title: "Configure",
-        entries: [
-            SectionEntry {
-                icon: IconName::Settings,
-                title: "Open Settings",
-                action: &OpenSettings,
-            },
-            SectionEntry {
-                icon: IconName::ZedAssistant,
-                title: "View AI Settings",
-                action: &agent::OpenSettings,
-            },
-            SectionEntry {
-                icon: IconName::Blocks,
-                title: "Explore Extensions",
-                action: &Extensions {
-                    category_filter: None,
-                    id: None,
-                },
-            },
-        ],
-    },
-);
-
-struct Section<const COLS: usize> {
-    title: &'static str,
-    entries: [SectionEntry; COLS],
-}
-
-impl<const COLS: usize> Section<COLS> {
-    fn render(self, index_offset: usize, focus: &FocusHandle, cx: &mut App) -> impl IntoElement {
-        v_flex()
-            .min_w_full()
-            .child(
-                h_flex()
-                    .px_1()
-                    .mb_2()
-                    .gap_2()
-                    .child(
-                        Label::new(self.title.to_ascii_uppercase())
-                            .buffer_font(cx)
-                            .color(Color::Muted)
-                            .size(LabelSize::XSmall),
-                    )
-                    .child(Divider::horizontal().color(DividerColor::BorderVariant)),
-            )
-            .children(
-                self.entries
-                    .iter()
-                    .enumerate()
-                    .map(|(index, entry)| entry.render(index_offset + index, focus, cx)),
-            )
-    }
-}
-
-struct SectionEntry {
-    icon: IconName,
-    title: &'static str,
-    action: &'static dyn Action,
-}
-
-impl SectionEntry {
-    fn render(&self, button_index: usize, focus: &FocusHandle, cx: &App) -> impl IntoElement {
-        ButtonLike::new(("onboarding-button-id", button_index))
-            .tab_index(button_index as isize)
-            .full_width()
-            .size(ButtonSize::Medium)
-            .child(
-                h_flex()
-                    .w_full()
-                    .justify_between()
-                    .child(
-                        h_flex()
-                            .gap_2()
-                            .child(
-                                Icon::new(self.icon)
-                                    .color(Color::Muted)
-                                    .size(IconSize::XSmall),
-                            )
-                            .child(Label::new(self.title)),
-                    )
-                    .child(
-                        KeyBinding::for_action_in(self.action, focus, cx).size(rems_from_px(12.)),
-                    ),
-            )
-            .on_click(|_, window, cx| window.dispatch_action(self.action.boxed_clone(), cx))
-    }
-}
-
-pub struct WelcomePage {
-    focus_handle: FocusHandle,
-}
-
-impl WelcomePage {
-    fn select_next(&mut self, _: &SelectNext, window: &mut Window, cx: &mut Context<Self>) {
-        window.focus_next();
-        cx.notify();
-    }
-
-    fn select_previous(&mut self, _: &SelectPrevious, window: &mut Window, cx: &mut Context<Self>) {
-        window.focus_prev();
-        cx.notify();
-    }
-}
-
-impl Render for WelcomePage {
-    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
-        let (first_section, second_section) = CONTENT;
-        let first_section_entries = first_section.entries.len();
-        let last_index = first_section_entries + second_section.entries.len();
-
-        h_flex()
-            .size_full()
-            .justify_center()
-            .overflow_hidden()
-            .bg(cx.theme().colors().editor_background)
-            .key_context("Welcome")
-            .track_focus(&self.focus_handle(cx))
-            .on_action(cx.listener(Self::select_previous))
-            .on_action(cx.listener(Self::select_next))
-            .child(
-                h_flex()
-                    .px_12()
-                    .py_40()
-                    .size_full()
-                    .relative()
-                    .max_w(px(1100.))
-                    .child(
-                        div()
-                            .size_full()
-                            .max_w_128()
-                            .mx_auto()
-                            .child(
-                                h_flex()
-                                    .w_full()
-                                    .justify_center()
-                                    .gap_4()
-                                    .child(Vector::square(VectorName::ZedLogo, rems(2.)))
-                                    .child(
-                                        div().child(Headline::new("Welcome to Zed")).child(
-                                            Label::new("The editor for what's next")
-                                                .size(LabelSize::Small)
-                                                .color(Color::Muted)
-                                                .italic(),
-                                        ),
-                                    ),
-                            )
-                            .child(
-                                v_flex()
-                                    .mt_10()
-                                    .gap_6()
-                                    .child(first_section.render(
-                                        Default::default(),
-                                        &self.focus_handle,
-                                        cx,
-                                    ))
-                                    .child(second_section.render(
-                                        first_section_entries,
-                                        &self.focus_handle,
-                                        cx,
-                                    ))
-                                    .child(
-                                        h_flex()
-                                            .w_full()
-                                            .pt_4()
-                                            .justify_center()
-                                            // We call this a hack
-                                            .rounded_b_xs()
-                                            .border_t_1()
-                                            .border_color(cx.theme().colors().border.opacity(0.6))
-                                            .border_dashed()
-                                            .child(
-                                                    Button::new("welcome-exit", "Return to Setup")
-                                                        .tab_index(last_index as isize)
-                                                        .full_width()
-                                                        .label_size(LabelSize::XSmall)
-                                                        .on_click(|_, window, cx| {
-                                                            window.dispatch_action(
-                                                                OpenOnboarding.boxed_clone(),
-                                                                cx,
-                                                            );
-
-                                                            with_active_or_new_workspace(cx, |workspace, window, cx| {
-                                                                let Some((welcome_id, welcome_idx)) = workspace
-                                                                    .active_pane()
-                                                                    .read(cx)
-                                                                    .items()
-                                                                    .enumerate()
-                                                                    .find_map(|(idx, item)| {
-                                                                        let _ = item.downcast::<WelcomePage>()?;
-                                                                        Some((item.item_id(), idx))
-                                                                    })
-                                                                else {
-                                                                    return;
-                                                                };
-
-                                                                workspace.active_pane().update(cx, |pane, cx| {
-                                                                    // Get the index here to get around the borrow checker
-                                                                    let idx = pane.items().enumerate().find_map(
-                                                                        |(idx, item)| {
-                                                                            let _ =
-                                                                                item.downcast::<Onboarding>()?;
-                                                                            Some(idx)
-                                                                        },
-                                                                    );
-
-                                                                    if let Some(idx) = idx {
-                                                                        pane.activate_item(
-                                                                            idx, true, true, window, cx,
-                                                                        );
-                                                                    } else {
-                                                                        let item =
-                                                                            Box::new(Onboarding::new(workspace, cx));
-                                                                        pane.add_item(
-                                                                            item,
-                                                                            true,
-                                                                            true,
-                                                                            Some(welcome_idx),
-                                                                            window,
-                                                                            cx,
-                                                                        );
-                                                                    }
-
-                                                                    pane.remove_item(
-                                                                        welcome_id,
-                                                                        false,
-                                                                        false,
-                                                                        window,
-                                                                        cx,
-                                                                    );
-                                                                });
-                                                            });
-                                                        }),
-                                                ),
-                                    ),
-                            ),
-                    ),
-            )
-    }
-}
-
-impl WelcomePage {
-    pub fn new(window: &mut Window, cx: &mut App) -> Entity<Self> {
-        cx.new(|cx| {
-            let focus_handle = cx.focus_handle();
-            cx.on_focus(&focus_handle, window, |_, _, cx| cx.notify())
-                .detach();
-
-            WelcomePage { focus_handle }
-        })
-    }
-}
-
-impl EventEmitter<ItemEvent> for WelcomePage {}
-
-impl Focusable for WelcomePage {
-    fn focus_handle(&self, _: &App) -> gpui::FocusHandle {
-        self.focus_handle.clone()
-    }
-}
-
-impl Item for WelcomePage {
-    type Event = ItemEvent;
-
-    fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
-        "Welcome".into()
-    }
-
-    fn telemetry_event_text(&self) -> Option<&'static str> {
-        Some("New Welcome Page Opened")
-    }
-
-    fn show_toolbar(&self) -> bool {
-        false
-    }
-
-    fn to_item_events(event: &Self::Event, mut f: impl FnMut(workspace::item::ItemEvent)) {
-        f(*event)
-    }
-}
-
-impl workspace::SerializableItem for WelcomePage {
-    fn serialized_item_kind() -> &'static str {
-        "WelcomePage"
-    }
-
-    fn cleanup(
-        workspace_id: workspace::WorkspaceId,
-        alive_items: Vec<workspace::ItemId>,
-        _window: &mut Window,
-        cx: &mut App,
-    ) -> Task<gpui::Result<()>> {
-        workspace::delete_unloaded_items(
-            alive_items,
-            workspace_id,
-            "welcome_pages",
-            &persistence::WELCOME_PAGES,
-            cx,
-        )
-    }
-
-    fn deserialize(
-        _project: Entity<project::Project>,
-        _workspace: gpui::WeakEntity<workspace::Workspace>,
-        workspace_id: workspace::WorkspaceId,
-        item_id: workspace::ItemId,
-        window: &mut Window,
-        cx: &mut App,
-    ) -> Task<gpui::Result<Entity<Self>>> {
-        if persistence::WELCOME_PAGES
-            .get_welcome_page(item_id, workspace_id)
-            .ok()
-            .is_some_and(|is_open| is_open)
-        {
-            window.spawn(cx, async move |cx| cx.update(WelcomePage::new))
-        } else {
-            Task::ready(Err(anyhow::anyhow!("No welcome page to deserialize")))
-        }
-    }
-
-    fn serialize(
-        &mut self,
-        workspace: &mut workspace::Workspace,
-        item_id: workspace::ItemId,
-        _closing: bool,
-        _window: &mut Window,
-        cx: &mut Context<Self>,
-    ) -> Option<Task<gpui::Result<()>>> {
-        let workspace_id = workspace.database_id()?;
-        Some(cx.background_spawn(async move {
-            persistence::WELCOME_PAGES
-                .save_welcome_page(item_id, workspace_id, true)
-                .await
-        }))
-    }
-
-    fn should_serialize(&self, event: &Self::Event) -> bool {
-        event == &ItemEvent::UpdateTab
-    }
-}
-
-mod persistence {
-    use db::{
-        query,
-        sqlez::{domain::Domain, thread_safe_connection::ThreadSafeConnection},
-        sqlez_macros::sql,
-    };
-    use workspace::WorkspaceDb;
-
-    pub struct WelcomePagesDb(ThreadSafeConnection);
-
-    impl Domain for WelcomePagesDb {
-        const NAME: &str = stringify!(WelcomePagesDb);
-
-        const MIGRATIONS: &[&str] = (&[sql!(
-                    CREATE TABLE welcome_pages (
-                        workspace_id INTEGER,
-                        item_id INTEGER UNIQUE,
-                        is_open INTEGER DEFAULT FALSE,
-
-                        PRIMARY KEY(workspace_id, item_id),
-                        FOREIGN KEY(workspace_id) REFERENCES workspaces(workspace_id)
-                        ON DELETE CASCADE
-                    ) STRICT;
-        )]);
-    }
-
-    db::static_connection!(WELCOME_PAGES, WelcomePagesDb, [WorkspaceDb]);
-
-    impl WelcomePagesDb {
-        query! {
-            pub async fn save_welcome_page(
-                item_id: workspace::ItemId,
-                workspace_id: workspace::WorkspaceId,
-                is_open: bool
-            ) -> Result<()> {
-                INSERT OR REPLACE INTO welcome_pages(item_id, workspace_id, is_open)
-                VALUES (?, ?, ?)
-            }
-        }
-
-        query! {
-            pub fn get_welcome_page(
-                item_id: workspace::ItemId,
-                workspace_id: workspace::WorkspaceId
-            ) -> Result<bool> {
-                SELECT is_open
-                FROM welcome_pages
-                WHERE item_id = ? AND workspace_id = ?
-            }
-        }
-    }
-}

crates/open_ai/src/open_ai.rs 🔗

@@ -87,6 +87,8 @@ pub enum Model {
     FiveNano,
     #[serde(rename = "gpt-5.1")]
     FivePointOne,
+    #[serde(rename = "gpt-5.2")]
+    FivePointTwo,
     #[serde(rename = "custom")]
     Custom {
         name: String,
@@ -123,6 +125,7 @@ impl Model {
             "gpt-5-mini" => Ok(Self::FiveMini),
             "gpt-5-nano" => Ok(Self::FiveNano),
             "gpt-5.1" => Ok(Self::FivePointOne),
+            "gpt-5.2" => Ok(Self::FivePointTwo),
             invalid_id => anyhow::bail!("invalid model id '{invalid_id}'"),
         }
     }
@@ -145,6 +148,7 @@ impl Model {
             Self::FiveMini => "gpt-5-mini",
             Self::FiveNano => "gpt-5-nano",
             Self::FivePointOne => "gpt-5.1",
+            Self::FivePointTwo => "gpt-5.2",
             Self::Custom { name, .. } => name,
         }
     }
@@ -167,6 +171,7 @@ impl Model {
             Self::FiveMini => "gpt-5-mini",
             Self::FiveNano => "gpt-5-nano",
             Self::FivePointOne => "gpt-5.1",
+            Self::FivePointTwo => "gpt-5.2",
             Self::Custom {
                 name, display_name, ..
             } => display_name.as_ref().unwrap_or(name),
@@ -191,6 +196,7 @@ impl Model {
             Self::FiveMini => 272_000,
             Self::FiveNano => 272_000,
             Self::FivePointOne => 400_000,
+            Self::FivePointTwo => 400_000,
             Self::Custom { max_tokens, .. } => *max_tokens,
         }
     }
@@ -216,6 +222,7 @@ impl Model {
             Self::FiveMini => Some(128_000),
             Self::FiveNano => Some(128_000),
             Self::FivePointOne => Some(128_000),
+            Self::FivePointTwo => Some(128_000),
         }
     }
 
@@ -244,6 +251,7 @@ impl Model {
             | Self::Five
             | Self::FiveMini
             | Self::FivePointOne
+            | Self::FivePointTwo
             | Self::FiveNano => true,
             Self::O1 | Self::O3 | Self::O3Mini | Self::O4Mini | Model::Custom { .. } => false,
         }
@@ -266,7 +274,8 @@ pub struct Request {
     pub max_completion_tokens: Option<u64>,
     #[serde(default, skip_serializing_if = "Vec::is_empty")]
     pub stop: Vec<String>,
-    pub temperature: f32,
+    #[serde(default, skip_serializing_if = "Option::is_none")]
+    pub temperature: Option<f32>,
     #[serde(default, skip_serializing_if = "Option::is_none")]
     pub tool_choice: Option<ToolChoice>,
     /// Whether to enable parallel function calling during tool use.

crates/outline/src/outline.rs 🔗

@@ -311,7 +311,7 @@ impl PickerDelegate for OutlineViewDelegate {
                     |s| s.select_ranges([rows.start..rows.start]),
                 );
                 active_editor.clear_row_highlights::<OutlineRowHighlights>();
-                window.focus(&active_editor.focus_handle(cx));
+                window.focus(&active_editor.focus_handle(cx), cx);
             }
         });
 
@@ -391,7 +391,6 @@ mod tests {
     use super::*;
     use gpui::{TestAppContext, VisualTestContext};
     use indoc::indoc;
-    use language::{Language, LanguageConfig, LanguageMatcher};
     use project::{FakeFs, Project};
     use serde_json::json;
     use util::{path, rel_path::rel_path};
@@ -418,7 +417,9 @@ mod tests {
         .await;
 
         let project = Project::test(fs, [path!("/dir").as_ref()], cx).await;
-        project.read_with(cx, |project, _| project.languages().add(rust_lang()));
+        project.read_with(cx, |project, _| {
+            project.languages().add(language::rust_lang())
+        });
 
         let (workspace, cx) =
             cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
@@ -581,89 +582,6 @@ mod tests {
         })
     }
 
-    fn rust_lang() -> Arc<Language> {
-        Arc::new(
-            Language::new(
-                LanguageConfig {
-                    name: "Rust".into(),
-                    matcher: LanguageMatcher {
-                        path_suffixes: vec!["rs".to_string()],
-                        ..Default::default()
-                    },
-                    ..Default::default()
-                },
-                Some(tree_sitter_rust::LANGUAGE.into()),
-            )
-            .with_outline_query(
-                r#"(struct_item
-            (visibility_modifier)? @context
-            "struct" @context
-            name: (_) @name) @item
-
-        (enum_item
-            (visibility_modifier)? @context
-            "enum" @context
-            name: (_) @name) @item
-
-        (enum_variant
-            (visibility_modifier)? @context
-            name: (_) @name) @item
-
-        (impl_item
-            "impl" @context
-            trait: (_)? @name
-            "for"? @context
-            type: (_) @name) @item
-
-        (trait_item
-            (visibility_modifier)? @context
-            "trait" @context
-            name: (_) @name) @item
-
-        (function_item
-            (visibility_modifier)? @context
-            (function_modifiers)? @context
-            "fn" @context
-            name: (_) @name) @item
-
-        (function_signature_item
-            (visibility_modifier)? @context
-            (function_modifiers)? @context
-            "fn" @context
-            name: (_) @name) @item
-
-        (macro_definition
-            . "macro_rules!" @context
-            name: (_) @name) @item
-
-        (mod_item
-            (visibility_modifier)? @context
-            "mod" @context
-            name: (_) @name) @item
-
-        (type_item
-            (visibility_modifier)? @context
-            "type" @context
-            name: (_) @name) @item
-
-        (associated_type
-            "type" @context
-            name: (_) @name) @item
-
-        (const_item
-            (visibility_modifier)? @context
-            "const" @context
-            name: (_) @name) @item
-
-        (field_declaration
-            (visibility_modifier)? @context
-            name: (_) @name) @item
-"#,
-            )
-            .unwrap(),
-        )
-    }
-
     #[track_caller]
     fn assert_single_caret_at_row(
         editor: &Entity<Editor>,

crates/outline_panel/src/outline_panel.rs 🔗

@@ -75,6 +75,16 @@ actions!(
         OpenSelectedEntry,
         /// Reveals the selected item in the system file manager.
         RevealInFileManager,
+        /// Scroll half a page upwards
+        ScrollUp,
+        /// Scroll half a page downwards
+        ScrollDown,
+        /// Scroll until the cursor displays at the center
+        ScrollCursorCenter,
+        /// Scroll until the cursor displays at the top
+        ScrollCursorTop,
+        /// Scroll until the cursor displays at the bottom
+        ScrollCursorBottom,
         /// Selects the parent of the current entry.
         SelectParent,
         /// Toggles the pin status of the active editor.
@@ -100,6 +110,7 @@ pub struct OutlinePanel {
     active: bool,
     pinned: bool,
     scroll_handle: UniformListScrollHandle,
+    rendered_entries_len: usize,
     context_menu: Option<(Entity<ContextMenu>, Point<Pixels>, Subscription)>,
     focus_handle: FocusHandle,
     pending_serialization: Task<Option<()>>,
@@ -839,6 +850,7 @@ impl OutlinePanel {
                 fs: workspace.app_state().fs.clone(),
                 max_width_item_index: None,
                 scroll_handle,
+                rendered_entries_len: 0,
                 focus_handle,
                 filter_editor,
                 fs_entries: Vec::new(),
@@ -986,9 +998,9 @@ impl OutlinePanel {
 
     fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
         if self.filter_editor.focus_handle(cx).is_focused(window) {
-            self.focus_handle.focus(window);
+            self.focus_handle.focus(window, cx);
         } else {
-            self.filter_editor.focus_handle(cx).focus(window);
+            self.filter_editor.focus_handle(cx).focus(window, cx);
         }
 
         if self.context_menu.is_some() {
@@ -1141,14 +1153,78 @@ impl OutlinePanel {
                 }
 
                 if change_focus {
-                    active_editor.focus_handle(cx).focus(window);
+                    active_editor.focus_handle(cx).focus(window, cx);
                 } else {
-                    self.focus_handle.focus(window);
+                    self.focus_handle.focus(window, cx);
                 }
             }
         }
     }
 
+    fn scroll_up(&mut self, _: &ScrollUp, window: &mut Window, cx: &mut Context<Self>) {
+        for _ in 0..self.rendered_entries_len / 2 {
+            window.dispatch_action(SelectPrevious.boxed_clone(), cx);
+        }
+    }
+
+    fn scroll_down(&mut self, _: &ScrollDown, window: &mut Window, cx: &mut Context<Self>) {
+        for _ in 0..self.rendered_entries_len / 2 {
+            window.dispatch_action(SelectNext.boxed_clone(), cx);
+        }
+    }
+
+    fn scroll_cursor_center(
+        &mut self,
+        _: &ScrollCursorCenter,
+        _: &mut Window,
+        cx: &mut Context<Self>,
+    ) {
+        if let Some(selected_entry) = self.selected_entry() {
+            let index = self
+                .cached_entries
+                .iter()
+                .position(|cached_entry| &cached_entry.entry == selected_entry);
+            if let Some(index) = index {
+                self.scroll_handle
+                    .scroll_to_item_strict(index, ScrollStrategy::Center);
+                cx.notify();
+            }
+        }
+    }
+
+    fn scroll_cursor_top(&mut self, _: &ScrollCursorTop, _: &mut Window, cx: &mut Context<Self>) {
+        if let Some(selected_entry) = self.selected_entry() {
+            let index = self
+                .cached_entries
+                .iter()
+                .position(|cached_entry| &cached_entry.entry == selected_entry);
+            if let Some(index) = index {
+                self.scroll_handle
+                    .scroll_to_item_strict(index, ScrollStrategy::Top);
+                cx.notify();
+            }
+        }
+    }
+
+    fn scroll_cursor_bottom(
+        &mut self,
+        _: &ScrollCursorBottom,
+        _: &mut Window,
+        cx: &mut Context<Self>,
+    ) {
+        if let Some(selected_entry) = self.selected_entry() {
+            let index = self
+                .cached_entries
+                .iter()
+                .position(|cached_entry| &cached_entry.entry == selected_entry);
+            if let Some(index) = index {
+                self.scroll_handle
+                    .scroll_to_item_strict(index, ScrollStrategy::Bottom);
+                cx.notify();
+            }
+        }
+    }
+
     fn select_next(&mut self, _: &SelectNext, window: &mut Window, cx: &mut Context<Self>) {
         if let Some(entry_to_select) = self.selected_entry().and_then(|selected_entry| {
             self.cached_entries
@@ -1382,7 +1458,7 @@ impl OutlinePanel {
                     Box::new(zed_actions::workspace::CopyRelativePath),
                 )
         });
-        window.focus(&context_menu.focus_handle(cx));
+        window.focus(&context_menu.focus_handle(cx), cx);
         let subscription = cx.subscribe(&context_menu, |outline_panel, _, _: &DismissEvent, cx| {
             outline_panel.context_menu.take();
             cx.notify();
@@ -2610,7 +2686,7 @@ impl OutlinePanel {
             })
             .when(
                 is_active && self.focus_handle.contains_focused(window, cx),
-                |div| div.border_color(Color::Selected.color(cx)),
+                |div| div.border_color(cx.theme().colors().panel_focused_border),
             )
     }
 
@@ -4463,7 +4539,7 @@ impl OutlinePanel {
         cx: &mut Context<Self>,
     ) {
         if focus {
-            self.focus_handle.focus(window);
+            self.focus_handle.focus(window, cx);
         }
         let ix = self
             .cached_entries
@@ -4578,6 +4654,7 @@ impl OutlinePanel {
                     "entries",
                     items_len,
                     cx.processor(move |outline_panel, range: Range<usize>, window, cx| {
+                        outline_panel.rendered_entries_len = range.end - range.start;
                         let entries = outline_panel.cached_entries.get(range);
                         entries
                             .map(|entries| entries.to_vec())
@@ -4970,7 +5047,12 @@ impl Render for OutlinePanel {
             .key_context(self.dispatch_context(window, cx))
             .on_action(cx.listener(Self::open_selected_entry))
             .on_action(cx.listener(Self::cancel))
+            .on_action(cx.listener(Self::scroll_up))
+            .on_action(cx.listener(Self::scroll_down))
             .on_action(cx.listener(Self::select_next))
+            .on_action(cx.listener(Self::scroll_cursor_center))
+            .on_action(cx.listener(Self::scroll_cursor_top))
+            .on_action(cx.listener(Self::scroll_cursor_bottom))
             .on_action(cx.listener(Self::select_previous))
             .on_action(cx.listener(Self::select_first))
             .on_action(cx.listener(Self::select_last))
@@ -5220,7 +5302,7 @@ impl GenerationState {
 mod tests {
     use db::indoc;
     use gpui::{TestAppContext, VisualTestContext, WindowHandle};
-    use language::{Language, LanguageConfig, LanguageMatcher, tree_sitter_rust};
+    use language::rust_lang;
     use pretty_assertions::assert_eq;
     use project::FakeFs;
     use search::{
@@ -5243,9 +5325,7 @@ mod tests {
         let root = path!("/rust-analyzer");
         populate_with_test_ra_project(&fs, root).await;
         let project = Project::test(fs.clone(), [Path::new(root)], cx).await;
-        project.read_with(cx, |project, _| {
-            project.languages().add(Arc::new(rust_lang()))
-        });
+        project.read_with(cx, |project, _| project.languages().add(rust_lang()));
         let workspace = add_outline_panel(&project, cx).await;
         let cx = &mut VisualTestContext::from_window(*workspace, cx);
         let outline_panel = outline_panel(&workspace, cx);
@@ -5478,9 +5558,7 @@ mod tests {
         let root = path!("/rust-analyzer");
         populate_with_test_ra_project(&fs, root).await;
         let project = Project::test(fs.clone(), [Path::new(root)], cx).await;
-        project.read_with(cx, |project, _| {
-            project.languages().add(Arc::new(rust_lang()))
-        });
+        project.read_with(cx, |project, _| project.languages().add(rust_lang()));
         let workspace = add_outline_panel(&project, cx).await;
         let cx = &mut VisualTestContext::from_window(*workspace, cx);
         let outline_panel = outline_panel(&workspace, cx);
@@ -5617,9 +5695,7 @@ mod tests {
         let root = path!("/rust-analyzer");
         populate_with_test_ra_project(&fs, root).await;
         let project = Project::test(fs.clone(), [Path::new(root)], cx).await;
-        project.read_with(cx, |project, _| {
-            project.languages().add(Arc::new(rust_lang()))
-        });
+        project.read_with(cx, |project, _| project.languages().add(rust_lang()));
         let workspace = add_outline_panel(&project, cx).await;
         let cx = &mut VisualTestContext::from_window(*workspace, cx);
         let outline_panel = outline_panel(&workspace, cx);
@@ -5816,7 +5892,8 @@ mod tests {
                     outline_panel.selected_entry(),
                     cx,
                 ),
-                "fn_lifetime_fn.rs  <==== selected"
+                "outline: pub(super) fn hints
+outline: fn hints_lifetimes_named  <==== selected"
             );
             assert_eq!(
                 selected_row_text(&new_active_editor, cx),
@@ -6029,24 +6106,7 @@ struct OutlineEntryExcerpt {
         )
         .await;
         let project = Project::test(fs.clone(), [Path::new(root)], cx).await;
-        project.read_with(cx, |project, _| {
-            project.languages().add(Arc::new(
-                rust_lang()
-                    .with_outline_query(
-                        r#"
-                (struct_item
-                    (visibility_modifier)? @context
-                    "struct" @context
-                    name: (_) @name) @item
-
-                (field_declaration
-                    (visibility_modifier)? @context
-                    name: (_) @name) @item
-"#,
-                    )
-                    .unwrap(),
-            ))
-        });
+        project.read_with(cx, |project, _| project.languages().add(rust_lang()));
         let workspace = add_outline_panel(&project, cx).await;
         let cx = &mut VisualTestContext::from_window(*workspace, cx);
         let outline_panel = outline_panel(&workspace, cx);
@@ -6601,11 +6661,13 @@ outline: struct OutlineEntryExcerpt
                 format!(
                     r#"frontend-project/
   public/lottie/
-    syntax-tree.json  <==== selected
+    syntax-tree.json
+      search: {{ "something": "«static»" }}
   src/
     app/(site)/
     components/
-      ErrorBoundary.tsx"#
+      ErrorBoundary.tsx  <==== selected
+        search: «static»"#
                 )
             );
         });
@@ -6647,7 +6709,7 @@ outline: struct OutlineEntryExcerpt
                 format!(
                     r#"frontend-project/
   public/lottie/
-    syntax-tree.json  <==== selected
+    syntax-tree.json
       search: {{ "something": "«static»" }}
   src/
     app/(site)/
@@ -6658,7 +6720,7 @@ outline: struct OutlineEntryExcerpt
         page.tsx
           search: «static»
     components/
-      ErrorBoundary.tsx
+      ErrorBoundary.tsx  <==== selected
         search: «static»"#
                 )
             );
@@ -6992,35 +7054,6 @@ outline: struct OutlineEntryExcerpt
         .await;
     }
 
-    fn rust_lang() -> Language {
-        Language::new(
-            LanguageConfig {
-                name: "Rust".into(),
-                matcher: LanguageMatcher {
-                    path_suffixes: vec!["rs".to_string()],
-                    ..Default::default()
-                },
-                ..Default::default()
-            },
-            Some(tree_sitter_rust::LANGUAGE.into()),
-        )
-        .with_highlights_query(
-            r#"
-                (field_identifier) @field
-                (struct_expression) @struct
-            "#,
-        )
-        .unwrap()
-        .with_injection_query(
-            r#"
-                (macro_invocation
-                    (token_tree) @injection.content
-                    (#set! injection.language "rust"))
-            "#,
-        )
-        .unwrap()
-    }
-
     fn snapshot(outline_panel: &OutlinePanel, cx: &App) -> MultiBufferSnapshot {
         outline_panel
             .active_editor()
@@ -7086,44 +7119,7 @@ outline: struct OutlineEntryExcerpt
         .await;
 
         let project = Project::test(fs.clone(), ["/test".as_ref()], cx).await;
-        project.read_with(cx, |project, _| {
-            project.languages().add(Arc::new(
-                rust_lang()
-                    .with_outline_query(
-                        r#"
-                            (struct_item
-                                (visibility_modifier)? @context
-                                "struct" @context
-                                name: (_) @name) @item
-                            (impl_item
-                                "impl" @context
-                                trait: (_)? @context
-                                "for"? @context
-                                type: (_) @context
-                                body: (_)) @item
-                            (function_item
-                                (visibility_modifier)? @context
-                                "fn" @context
-                                name: (_) @name
-                                parameters: (_) @context) @item
-                            (mod_item
-                                (visibility_modifier)? @context
-                                "mod" @context
-                                name: (_) @name) @item
-                            (enum_item
-                                (visibility_modifier)? @context
-                                "enum" @context
-                                name: (_) @name) @item
-                            (field_declaration
-                                (visibility_modifier)? @context
-                                name: (_) @name
-                                ":" @context
-                                type: (_) @context) @item
-                            "#,
-                    )
-                    .unwrap(),
-            ))
-        });
+        project.read_with(cx, |project, _| project.languages().add(rust_lang()));
         let workspace = add_outline_panel(&project, cx).await;
         let cx = &mut VisualTestContext::from_window(*workspace, cx);
         let outline_panel = outline_panel(&workspace, cx);
@@ -7174,15 +7170,15 @@ outline: struct OutlineEntryExcerpt
                     "
 outline: mod outer  <==== selected
   outline: pub struct OuterStruct
-    outline: field: String
+    outline: field
   outline: impl OuterStruct
-    outline: pub fn new()
-    outline: pub fn method(&self)
+    outline: pub fn new
+    outline: pub fn method
   outline: mod inner
-    outline: pub fn inner_function()
+    outline: pub fn inner_function
     outline: pub struct InnerStruct
-      outline: value: i32
-outline: fn main()"
+      outline: value
+outline: fn main"
                 )
             );
         });
@@ -7232,7 +7228,7 @@ outline: fn main()"
                 indoc!(
                     "
 outline: mod outer  <==== selected
-outline: fn main()"
+outline: fn main"
                 )
             );
         });
@@ -7257,15 +7253,15 @@ outline: fn main()"
                     "
 outline: mod outer  <==== selected
   outline: pub struct OuterStruct
-    outline: field: String
+    outline: field
   outline: impl OuterStruct
-    outline: pub fn new()
-    outline: pub fn method(&self)
+    outline: pub fn new
+    outline: pub fn method
   outline: mod inner
-    outline: pub fn inner_function()
+    outline: pub fn inner_function
     outline: pub struct InnerStruct
-      outline: value: i32
-outline: fn main()"
+      outline: value
+outline: fn main"
                 )
             );
         });
@@ -7321,7 +7317,7 @@ outline: fn main()"
                 indoc!(
                     "
 outline: mod outer
-outline: fn main()"
+outline: fn main"
                 )
             );
         });
@@ -7378,44 +7374,7 @@ outline: fn main()"
         .await;
 
         let project = Project::test(fs.clone(), ["/test".as_ref()], cx).await;
-        project.read_with(cx, |project, _| {
-            project.languages().add(Arc::new(
-                rust_lang()
-                    .with_outline_query(
-                        r#"
-                            (struct_item
-                                (visibility_modifier)? @context
-                                "struct" @context
-                                name: (_) @name) @item
-                            (impl_item
-                                "impl" @context
-                                trait: (_)? @context
-                                "for"? @context
-                                type: (_) @context
-                                body: (_)) @item
-                            (function_item
-                                (visibility_modifier)? @context
-                                "fn" @context
-                                name: (_) @name
-                                parameters: (_) @context) @item
-                            (mod_item
-                                (visibility_modifier)? @context
-                                "mod" @context
-                                name: (_) @name) @item
-                            (enum_item
-                                (visibility_modifier)? @context
-                                "enum" @context
-                                name: (_) @name) @item
-                            (field_declaration
-                                (visibility_modifier)? @context
-                                name: (_) @name
-                                ":" @context
-                                type: (_) @context) @item
-                            "#,
-                    )
-                    .unwrap(),
-            ))
-        });
+        project.read_with(cx, |project, _| project.languages().add(rust_lang()));
 
         let workspace = add_outline_panel(&project, cx).await;
         let cx = &mut VisualTestContext::from_window(*workspace, cx);
@@ -7462,14 +7421,16 @@ outline: fn main()"
                 indoc!(
                     "
 outline: struct Config
-  outline: name: String
-  outline: value: i32
+  outline: name
+  outline: value
 outline: impl Config
-  outline: fn new(name: String)
-  outline: fn get_value(&self)
+  outline: fn new
+  outline: fn get_value
 outline: enum Status
-outline: fn process_config(config: Config)
-outline: fn main()"
+  outline: Active
+  outline: Inactive
+outline: fn process_config
+outline: fn main"
                 )
             );
         });
@@ -7500,14 +7461,16 @@ outline: fn main()"
                 indoc!(
                     "
 outline: struct Config  <==== selected
-  outline: name: String
-  outline: value: i32
+  outline: name
+  outline: value
 outline: impl Config
-  outline: fn new(name: String)
-  outline: fn get_value(&self)
+  outline: fn new
+  outline: fn get_value
 outline: enum Status
-outline: fn process_config(config: Config)
-outline: fn main()"
+  outline: Active
+  outline: Inactive
+outline: fn process_config
+outline: fn main"
                 )
             );
         });
@@ -7535,11 +7498,13 @@ outline: fn main()"
                     "
 outline: struct Config  <==== selected
 outline: impl Config
-  outline: fn new(name: String)
-  outline: fn get_value(&self)
+  outline: fn new
+  outline: fn get_value
 outline: enum Status
-outline: fn process_config(config: Config)
-outline: fn main()"
+  outline: Active
+  outline: Inactive
+outline: fn process_config
+outline: fn main"
                 )
             );
         });
@@ -7566,14 +7531,16 @@ outline: fn main()"
                 indoc!(
                     "
 outline: struct Config  <==== selected
-  outline: name: String
-  outline: value: i32
+  outline: name
+  outline: value
 outline: impl Config
-  outline: fn new(name: String)
-  outline: fn get_value(&self)
+  outline: fn new
+  outline: fn get_value
 outline: enum Status
-outline: fn process_config(config: Config)
-outline: fn main()"
+  outline: Active
+  outline: Inactive
+outline: fn process_config
+outline: fn main"
                 )
             );
         });
@@ -7622,44 +7589,7 @@ outline: fn main()"
         .await;
 
         let project = Project::test(fs.clone(), ["/test".as_ref()], cx).await;
-        project.read_with(cx, |project, _| {
-            project.languages().add(Arc::new(
-                rust_lang()
-                    .with_outline_query(
-                        r#"
-                            (struct_item
-                                (visibility_modifier)? @context
-                                "struct" @context
-                                name: (_) @name) @item
-                            (impl_item
-                                "impl" @context
-                                trait: (_)? @context
-                                "for"? @context
-                                type: (_) @context
-                                body: (_)) @item
-                            (function_item
-                                (visibility_modifier)? @context
-                                "fn" @context
-                                name: (_) @name
-                                parameters: (_) @context) @item
-                            (mod_item
-                                (visibility_modifier)? @context
-                                "mod" @context
-                                name: (_) @name) @item
-                            (enum_item
-                                (visibility_modifier)? @context
-                                "enum" @context
-                                name: (_) @name) @item
-                            (field_declaration
-                                (visibility_modifier)? @context
-                                name: (_) @name
-                                ":" @context
-                                type: (_) @context) @item
-                            "#,
-                    )
-                    .unwrap(),
-            ))
-        });
+        project.read_with(cx, |project, _| project.languages().add(rust_lang()));
         let workspace = add_outline_panel(&project, cx).await;
         let cx = &mut VisualTestContext::from_window(*workspace, cx);
         let outline_panel = outline_panel(&workspace, cx);
@@ -7710,15 +7640,15 @@ outline: fn main()"
                     "
 outline: mod outer  <==== selected
   outline: pub struct OuterStruct
-    outline: field: String
+    outline: field
   outline: impl OuterStruct
-    outline: pub fn new()
-    outline: pub fn method(&self)
+    outline: pub fn new
+    outline: pub fn method
   outline: mod inner
-    outline: pub fn inner_function()
+    outline: pub fn inner_function
     outline: pub struct InnerStruct
-      outline: value: i32
-outline: fn main()"
+      outline: value
+outline: fn main"
                 )
             );
         });
@@ -7759,7 +7689,7 @@ outline: fn main()"
         let expected_collapsed_output = indoc!(
             "
         outline: mod outer  <==== selected
-        outline: fn main()"
+        outline: fn main"
         );
 
         outline_panel.update(cx, |panel, cx| {
@@ -7787,15 +7717,15 @@ outline: fn main()"
             "
         outline: mod outer  <==== selected
           outline: pub struct OuterStruct
-            outline: field: String
+            outline: field
           outline: impl OuterStruct
-            outline: pub fn new()
-            outline: pub fn method(&self)
+            outline: pub fn new
+            outline: pub fn method
           outline: mod inner
-            outline: pub fn inner_function()
+            outline: pub fn inner_function
             outline: pub struct InnerStruct
-              outline: value: i32
-        outline: fn main()"
+              outline: value
+        outline: fn main"
         );
 
         outline_panel.update(cx, |panel, cx| {

crates/outline_panel/src/outline_panel_settings.rs 🔗

@@ -50,7 +50,13 @@ impl Settings for OutlinePanelSettings {
             dock: panel.dock.unwrap(),
             file_icons: panel.file_icons.unwrap(),
             folder_icons: panel.folder_icons.unwrap(),
-            git_status: panel.git_status.unwrap(),
+            git_status: panel.git_status.unwrap()
+                && content
+                    .git
+                    .unwrap()
+                    .enabled
+                    .unwrap()
+                    .is_git_status_enabled(),
             indent_size: panel.indent_size.unwrap(),
             indent_guides: IndentGuidesSettings {
                 show: panel.indent_guides.unwrap().show.unwrap(),

crates/paths/src/paths.rs 🔗

@@ -408,6 +408,12 @@ pub fn remote_servers_dir() -> &'static PathBuf {
     REMOTE_SERVERS_DIR.get_or_init(|| data_dir().join("remote_servers"))
 }
 
+/// Returns the path to the directory where the devcontainer CLI is installed.
+pub fn devcontainer_dir() -> &'static PathBuf {
+    static DEVCONTAINER_DIR: OnceLock<PathBuf> = OnceLock::new();
+    DEVCONTAINER_DIR.get_or_init(|| data_dir().join("devcontainer"))
+}
+
 /// Returns the relative path to a `.zed` folder within a project.
 pub fn local_settings_folder_name() -> &'static str {
     ".zed"

crates/picker/src/picker.rs 🔗

@@ -97,6 +97,18 @@ pub trait PickerDelegate: Sized + 'static {
         window: &mut Window,
         cx: &mut Context<Picker<Self>>,
     );
+
+    /// Called before the picker handles `SelectPrevious` or `SelectNext`. Return `Some(query)` to
+    /// set a new query and prevent the default selection behavior.
+    fn select_history(
+        &mut self,
+        _direction: Direction,
+        _query: &str,
+        _window: &mut Window,
+        _cx: &mut App,
+    ) -> Option<String> {
+        None
+    }
     fn can_select(
         &mut self,
         _ix: usize,
@@ -372,7 +384,7 @@ impl<D: PickerDelegate> Picker<D> {
     }
 
     pub fn focus(&self, window: &mut Window, cx: &mut App) {
-        self.focus_handle(cx).focus(window);
+        self.focus_handle(cx).focus(window, cx);
     }
 
     /// Handles the selecting an index, and passing the change to the delegate.
@@ -448,6 +460,14 @@ impl<D: PickerDelegate> Picker<D> {
         window: &mut Window,
         cx: &mut Context<Self>,
     ) {
+        let query = self.query(cx);
+        if let Some(query) = self
+            .delegate
+            .select_history(Direction::Down, &query, window, cx)
+        {
+            self.set_query(query, window, cx);
+            return;
+        }
         let count = self.delegate.match_count();
         if count > 0 {
             let index = self.delegate.selected_index();
@@ -467,6 +487,14 @@ impl<D: PickerDelegate> Picker<D> {
         window: &mut Window,
         cx: &mut Context<Self>,
     ) {
+        let query = self.query(cx);
+        if let Some(query) = self
+            .delegate
+            .select_history(Direction::Up, &query, window, cx)
+        {
+            self.set_query(query, window, cx);
+            return;
+        }
         let count = self.delegate.match_count();
         if count > 0 {
             let index = self.delegate.selected_index();

crates/prettier/src/prettier.rs 🔗

@@ -2,7 +2,8 @@ use anyhow::Context as _;
 use collections::{HashMap, HashSet};
 use fs::Fs;
 use gpui::{AsyncApp, Entity};
-use language::{Buffer, Diff, language_settings::language_settings};
+use language::language_settings::PrettierSettings;
+use language::{Buffer, Diff, Language, language_settings::language_settings};
 use lsp::{LanguageServer, LanguageServerId};
 use node_runtime::NodeRuntime;
 use paths::default_prettier_dir;
@@ -349,7 +350,7 @@ impl Prettier {
             Self::Real(local) => {
                 let params = buffer
                     .update(cx, |buffer, cx| {
-                        let buffer_language = buffer.language();
+                        let buffer_language = buffer.language().map(|language| language.as_ref());
                         let language_settings = language_settings(buffer_language.map(|l| l.name()), buffer.file(), cx);
                         let prettier_settings = &language_settings.prettier;
                         anyhow::ensure!(
@@ -449,15 +450,7 @@ impl Prettier {
                             })
                             .collect();
 
-                        let mut prettier_parser = prettier_settings.parser.as_deref();
-                        if buffer_path.is_none() {
-                            prettier_parser = prettier_parser.or_else(|| buffer_language.and_then(|language| language.prettier_parser_name()));
-                            if prettier_parser.is_none() {
-                                log::error!("Formatting unsaved file with prettier failed. No prettier parser configured for language {buffer_language:?}");
-                                anyhow::bail!("Cannot determine prettier parser for unsaved file");
-                            }
-
-                        }
+                        let parser = prettier_parser_name(buffer_path.as_deref(), buffer_language, prettier_settings).context("getting prettier parser")?;
 
                         let ignore_path = ignore_dir.and_then(|dir| {
                             let ignore_file = dir.join(".prettierignore");
@@ -475,15 +468,15 @@ impl Prettier {
                         anyhow::Ok(FormatParams {
                             text: buffer.text(),
                             options: FormatOptions {
-                                parser: prettier_parser.map(ToOwned::to_owned),
-                                plugins,
                                 path: buffer_path,
+                                parser,
+                                plugins,
                                 prettier_options,
                                 ignore_path,
                             },
                         })
-                    })?
-                    .context("building prettier request")?;
+                })?
+                .context("building prettier request")?;
 
                 let response = local
                     .server
@@ -503,7 +496,26 @@ impl Prettier {
                     {
                         Some("rust") => anyhow::bail!("prettier does not support Rust"),
                         Some(_other) => {
-                            let formatted_text = buffer.text() + FORMAT_SUFFIX;
+                            let mut formatted_text = buffer.text() + FORMAT_SUFFIX;
+
+                            let buffer_language =
+                                buffer.language().map(|language| language.as_ref());
+                            let language_settings = language_settings(
+                                buffer_language.map(|l| l.name()),
+                                buffer.file(),
+                                cx,
+                            );
+                            let prettier_settings = &language_settings.prettier;
+                            let parser = prettier_parser_name(
+                                buffer_path.as_deref(),
+                                buffer_language,
+                                prettier_settings,
+                            )?;
+
+                            if let Some(parser) = parser {
+                                formatted_text = format!("{formatted_text}\n{parser}");
+                            }
+
                             Ok(buffer.diff(formatted_text, cx))
                         }
                         None => panic!("Should not format buffer without a language with prettier"),
@@ -551,6 +563,40 @@ impl Prettier {
     }
 }
 
+fn prettier_parser_name(
+    buffer_path: Option<&Path>,
+    buffer_language: Option<&Language>,
+    prettier_settings: &PrettierSettings,
+) -> anyhow::Result<Option<String>> {
+    let parser = if buffer_path.is_none() {
+        let parser = prettier_settings
+            .parser
+            .as_deref()
+            .or_else(|| buffer_language.and_then(|language| language.prettier_parser_name()));
+        if parser.is_none() {
+            log::error!(
+                "Formatting unsaved file with prettier failed. No prettier parser configured for language {buffer_language:?}"
+            );
+            anyhow::bail!("Cannot determine prettier parser for unsaved file");
+        }
+        parser
+    } else if let (Some(buffer_language), Some(buffer_path)) = (buffer_language, buffer_path)
+        && buffer_path.extension().is_some_and(|extension| {
+            !buffer_language
+                .config()
+                .matcher
+                .path_suffixes
+                .contains(&extension.to_string_lossy().into_owned())
+        })
+    {
+        buffer_language.prettier_parser_name()
+    } else {
+        prettier_settings.parser.as_deref()
+    };
+
+    Ok(parser.map(ToOwned::to_owned))
+}
+
 async fn has_prettier_in_node_modules(fs: &dyn Fs, path: &Path) -> anyhow::Result<bool> {
     let possible_node_modules_location = path.join("node_modules").join(PRETTIER_PACKAGE_NAME);
     if let Some(node_modules_location_metadata) = fs

crates/project/Cargo.toml 🔗

@@ -40,6 +40,7 @@ clock.workspace = true
 collections.workspace = true
 context_server.workspace = true
 dap.workspace = true
+encoding_rs.workspace = true
 extension.workspace = true
 fancy-regex.workspace = true
 fs.workspace = true
@@ -91,9 +92,12 @@ which.workspace = true
 worktree.workspace = true
 zeroize.workspace = true
 zlog.workspace = true
+ztracing.workspace = true
+tracing.workspace = true
 
 [dev-dependencies]
 client = { workspace = true, features = ["test-support"] }
+db = { workspace = true, features = ["test-support"] }
 collections = { workspace = true, features = ["test-support"] }
 context_server = { workspace = true, features = ["test-support"] }
 buffer_diff = { workspace = true, features = ["test-support"] }
@@ -113,3 +117,6 @@ snippet_provider = { workspace = true, features = ["test-support"] }
 unindent.workspace = true
 util = { workspace = true, features = ["test-support"] }
 worktree = { workspace = true, features = ["test-support"] }
+
+[package.metadata.cargo-machete]
+ignored = ["tracing"]

crates/project/src/agent_server_store.rs 🔗

@@ -22,6 +22,7 @@ use rpc::{
     proto::{self, ExternalExtensionAgent},
 };
 use schemars::JsonSchema;
+use semver::Version;
 use serde::{Deserialize, Serialize};
 use settings::{RegisterSetting, SettingsStore};
 use task::{Shell, SpawnInTerminal};
@@ -137,6 +138,7 @@ pub struct AgentServerStore {
     state: AgentServerStoreState,
     external_agents: HashMap<ExternalAgentServerName, Box<dyn ExternalAgentServer>>,
     agent_icons: HashMap<ExternalAgentServerName, SharedString>,
+    agent_display_names: HashMap<ExternalAgentServerName, SharedString>,
 }
 
 pub struct AgentServersUpdated;
@@ -155,6 +157,7 @@ mod ext_agent_tests {
             state: AgentServerStoreState::Collab,
             external_agents: HashMap::default(),
             agent_icons: HashMap::default(),
+            agent_display_names: HashMap::default(),
         }
     }
 
@@ -258,6 +261,7 @@ impl AgentServerStore {
         self.external_agents.retain(|name, agent| {
             if agent.downcast_mut::<LocalExtensionArchiveAgent>().is_some() {
                 self.agent_icons.remove(name);
+                self.agent_display_names.remove(name);
                 false
             } else {
                 // Keep the hardcoded external agents that don't come from extensions
@@ -275,6 +279,12 @@ impl AgentServerStore {
                 for (ext_id, manifest) in manifests {
                     for (agent_name, agent_entry) in &manifest.agent_servers {
                         // Store absolute icon path if provided, resolving symlinks for dev extensions
+                        // Store display name from manifest
+                        self.agent_display_names.insert(
+                            ExternalAgentServerName(agent_name.clone().into()),
+                            SharedString::from(agent_entry.name.clone()),
+                        );
+
                         let icon_path = if let Some(icon) = &agent_entry.icon {
                             let icon_path = extensions_dir.join(ext_id).join(icon);
                             // Canonicalize to resolve symlinks (dev extensions are symlinked)
@@ -310,6 +320,12 @@ impl AgentServerStore {
                 let mut agents = vec![];
                 for (ext_id, manifest) in manifests {
                     for (agent_name, agent_entry) in &manifest.agent_servers {
+                        // Store display name from manifest
+                        self.agent_display_names.insert(
+                            ExternalAgentServerName(agent_name.clone().into()),
+                            SharedString::from(agent_entry.name.clone()),
+                        );
+
                         // Store absolute icon path if provided, resolving symlinks for dev extensions
                         let icon = if let Some(icon) = &agent_entry.icon {
                             let icon_path = extensions_dir.join(ext_id).join(icon);
@@ -369,6 +385,10 @@ impl AgentServerStore {
         self.agent_icons.get(name).cloned()
     }
 
+    pub fn agent_display_name(&self, name: &ExternalAgentServerName) -> Option<SharedString> {
+        self.agent_display_names.get(name).cloned()
+    }
+
     pub fn init_remote(session: &AnyProtoClient) {
         session.add_entity_message_handler(Self::handle_external_agents_updated);
         session.add_entity_message_handler(Self::handle_loading_status_updated);
@@ -440,7 +460,7 @@ impl AgentServerStore {
                     .gemini
                     .as_ref()
                     .and_then(|settings| settings.ignore_system_version)
-                    .unwrap_or(false),
+                    .unwrap_or(true),
             }),
         );
         self.external_agents.insert(
@@ -453,7 +473,9 @@ impl AgentServerStore {
                     .clone()
                     .and_then(|settings| settings.custom_command()),
                 http_client: http_client.clone(),
-                is_remote: downstream_client.is_some(),
+                no_browser: downstream_client
+                    .as_ref()
+                    .is_some_and(|(_, client)| !client.has_wsl_interop()),
             }),
         );
         self.external_agents.insert(
@@ -557,6 +579,7 @@ impl AgentServerStore {
             },
             external_agents: Default::default(),
             agent_icons: Default::default(),
+            agent_display_names: Default::default(),
         };
         if let Some(_events) = extension::ExtensionEvents::try_global(cx) {}
         this.agent_servers_settings_changed(cx);
@@ -607,6 +630,7 @@ impl AgentServerStore {
             },
             external_agents: external_agents.into_iter().collect(),
             agent_icons: HashMap::default(),
+            agent_display_names: HashMap::default(),
         }
     }
 
@@ -615,6 +639,7 @@ impl AgentServerStore {
             state: AgentServerStoreState::Collab,
             external_agents: Default::default(),
             agent_icons: Default::default(),
+            agent_display_names: Default::default(),
         }
     }
 
@@ -950,11 +975,10 @@ fn get_or_npm_install_builtin_agent(
         }
 
         versions.sort();
-        let newest_version = if let Some((version, file_name)) = versions.last().cloned()
+        let newest_version = if let Some((version, _)) = versions.last().cloned()
             && minimum_version.is_none_or(|minimum_version| version >= minimum_version)
         {
-            versions.pop();
-            Some(file_name)
+            versions.pop()
         } else {
             None
         };
@@ -980,9 +1004,8 @@ fn get_or_npm_install_builtin_agent(
         })
         .detach();
 
-        let version = if let Some(file_name) = newest_version {
+        let version = if let Some((version, file_name)) = newest_version {
             cx.background_spawn({
-                let file_name = file_name.clone();
                 let dir = dir.clone();
                 let fs = fs.clone();
                 async move {
@@ -991,7 +1014,7 @@ fn get_or_npm_install_builtin_agent(
                         .await
                         .ok();
                     if let Some(latest_version) = latest_version
-                        && &latest_version != &file_name.to_string_lossy()
+                        && latest_version != version
                     {
                         let download_result = download_latest_version(
                             fs,
@@ -1004,7 +1027,9 @@ fn get_or_npm_install_builtin_agent(
                         if let Some(mut new_version_available) = new_version_available
                             && download_result.is_some()
                         {
-                            new_version_available.send(Some(latest_version)).ok();
+                            new_version_available
+                                .send(Some(latest_version.to_string()))
+                                .ok();
                         }
                     }
                 }
@@ -1023,6 +1048,7 @@ fn get_or_npm_install_builtin_agent(
                 package_name.clone(),
             ))
             .await?
+            .to_string()
             .into()
         };
 
@@ -1069,7 +1095,7 @@ async fn download_latest_version(
     dir: PathBuf,
     node_runtime: NodeRuntime,
     package_name: SharedString,
-) -> Result<String> {
+) -> Result<Version> {
     log::debug!("downloading latest version of {package_name}");
 
     let tmp_dir = tempfile::tempdir_in(&dir)?;
@@ -1085,7 +1111,7 @@ async fn download_latest_version(
 
     fs.rename(
         &tmp_dir.keep(),
-        &dir.join(&version),
+        &dir.join(version.to_string()),
         RenameOptions {
             ignore_if_exists: true,
             overwrite: true,
@@ -1355,7 +1381,7 @@ struct LocalCodex {
     project_environment: Entity<ProjectEnvironment>,
     http_client: Arc<dyn HttpClient>,
     custom_command: Option<AgentServerCommand>,
-    is_remote: bool,
+    no_browser: bool,
 }
 
 impl ExternalAgentServer for LocalCodex {
@@ -1363,7 +1389,7 @@ impl ExternalAgentServer for LocalCodex {
         &mut self,
         root_dir: Option<&str>,
         extra_env: HashMap<String, String>,
-        status_tx: Option<watch::Sender<SharedString>>,
+        mut status_tx: Option<watch::Sender<SharedString>>,
         _new_version_available_tx: Option<watch::Sender<Option<String>>>,
         cx: &mut AsyncApp,
     ) -> Task<Result<(AgentServerCommand, String, Option<task::SpawnInTerminal>)>> {
@@ -1375,7 +1401,7 @@ impl ExternalAgentServer for LocalCodex {
             .map(|root_dir| Path::new(root_dir))
             .unwrap_or(paths::home_dir())
             .into();
-        let is_remote = self.is_remote;
+        let no_browser = self.no_browser;
 
         cx.spawn(async move |cx| {
             let mut env = project_environment
@@ -1388,7 +1414,7 @@ impl ExternalAgentServer for LocalCodex {
                 })?
                 .await
                 .unwrap_or_default();
-            if is_remote {
+            if no_browser {
                 env.insert("NO_BROWSER".to_owned(), "1".to_owned());
             }
 
@@ -1400,58 +1426,115 @@ impl ExternalAgentServer for LocalCodex {
                 let dir = paths::external_agents_dir().join(CODEX_NAME);
                 fs.create_dir(&dir).await?;
 
-                // Find or install the latest Codex release (no update checks for now).
-                let release = ::http_client::github::latest_github_release(
+                let bin_name = if cfg!(windows) {
+                    "codex-acp.exe"
+                } else {
+                    "codex-acp"
+                };
+
+                let find_latest_local_version = async || -> Option<PathBuf> {
+                    let mut local_versions: Vec<(semver::Version, String)> = Vec::new();
+                    let mut stream = fs.read_dir(&dir).await.ok()?;
+                    while let Some(entry) = stream.next().await {
+                        let Ok(entry) = entry else { continue };
+                        let Some(file_name) = entry.file_name() else {
+                            continue;
+                        };
+                        let version_path = dir.join(&file_name);
+                        if fs.is_file(&version_path.join(bin_name)).await {
+                            let version_str = file_name.to_string_lossy();
+                            if let Ok(version) =
+                                semver::Version::from_str(version_str.trim_start_matches('v'))
+                            {
+                                local_versions.push((version, version_str.into_owned()));
+                            }
+                        }
+                    }
+                    local_versions.sort_by(|(a, _), (b, _)| a.cmp(b));
+                    local_versions.last().map(|(_, v)| dir.join(v))
+                };
+
+                let fallback_to_latest_local_version =
+                    async |err: anyhow::Error| -> Result<PathBuf, anyhow::Error> {
+                        if let Some(local) = find_latest_local_version().await {
+                            log::info!(
+                                "Falling back to locally installed Codex version: {}",
+                                local.display()
+                            );
+                            Ok(local)
+                        } else {
+                            Err(err)
+                        }
+                    };
+
+                let version_dir = match ::http_client::github::latest_github_release(
                     CODEX_ACP_REPO,
                     true,
                     false,
                     http.clone(),
                 )
                 .await
-                .context("fetching Codex latest release")?;
-
-                let version_dir = dir.join(&release.tag_name);
-                if !fs.is_dir(&version_dir).await {
-                    if let Some(mut status_tx) = status_tx {
-                        status_tx.send("Installing…".into()).ok();
-                    }
+                {
+                    Ok(release) => {
+                        let version_dir = dir.join(&release.tag_name);
+                        if !fs.is_dir(&version_dir).await {
+                            if let Some(ref mut status_tx) = status_tx {
+                                status_tx.send("Installing…".into()).ok();
+                            }
 
-                    let tag = release.tag_name.clone();
-                    let version_number = tag.trim_start_matches('v');
-                    let asset_name = asset_name(version_number)
-                        .context("codex acp is not supported for this architecture")?;
-                    let asset = release
-                        .assets
-                        .into_iter()
-                        .find(|asset| asset.name == asset_name)
-                        .with_context(|| format!("no asset found matching `{asset_name:?}`"))?;
-                    // Strip "sha256:" prefix from digest if present (GitHub API format)
-                    let digest = asset
-                        .digest
-                        .as_deref()
-                        .and_then(|d| d.strip_prefix("sha256:").or(Some(d)));
-                    ::http_client::github_download::download_server_binary(
-                        &*http,
-                        &asset.browser_download_url,
-                        digest,
-                        &version_dir,
-                        if cfg!(target_os = "windows") && cfg!(target_arch = "x86_64") {
-                            AssetKind::Zip
+                            let tag = release.tag_name.clone();
+                            let version_number = tag.trim_start_matches('v');
+                            let asset_name = asset_name(version_number)
+                                .context("codex acp is not supported for this architecture")?;
+                            let asset = release
+                                .assets
+                                .into_iter()
+                                .find(|asset| asset.name == asset_name)
+                                .with_context(|| {
+                                    format!("no asset found matching `{asset_name:?}`")
+                                })?;
+                            // Strip "sha256:" prefix from digest if present (GitHub API format)
+                            let digest = asset
+                                .digest
+                                .as_deref()
+                                .and_then(|d| d.strip_prefix("sha256:").or(Some(d)));
+                            match ::http_client::github_download::download_server_binary(
+                                &*http,
+                                &asset.browser_download_url,
+                                digest,
+                                &version_dir,
+                                if cfg!(target_os = "windows") && cfg!(target_arch = "x86_64") {
+                                    AssetKind::Zip
+                                } else {
+                                    AssetKind::TarGz
+                                },
+                            )
+                            .await
+                            {
+                                Ok(()) => {
+                                    // remove older versions
+                                    util::fs::remove_matching(&dir, |entry| entry != version_dir)
+                                        .await;
+                                    version_dir
+                                }
+                                Err(err) => {
+                                    log::error!(
+                                        "Failed to download Codex release {}: {err:#}",
+                                        release.tag_name
+                                    );
+                                    fallback_to_latest_local_version(err).await?
+                                }
+                            }
                         } else {
-                            AssetKind::TarGz
-                        },
-                    )
-                    .await?;
-
-                    // remove older versions
-                    util::fs::remove_matching(&dir, |entry| entry != version_dir).await;
-                }
-
-                let bin_name = if cfg!(windows) {
-                    "codex-acp.exe"
-                } else {
-                    "codex-acp"
+                            version_dir
+                        }
+                    }
+                    Err(err) => {
+                        log::error!("Failed to fetch Codex latest release: {err:#}");
+                        fallback_to_latest_local_version(err).await?
+                    }
                 };
+
                 let bin_path = version_dir.join(bin_name);
                 anyhow::ensure!(
                     fs.is_file(&bin_path).await,
@@ -1499,8 +1582,8 @@ fn get_platform_info() -> Option<(&'static str, &'static str, &'static str)> {
         return None;
     };
 
-    // Only Windows x86_64 uses .zip in release assets
-    let ext = if cfg!(target_os = "windows") && cfg!(target_arch = "x86_64") {
+    // Windows uses .zip in release assets
+    let ext = if cfg!(target_os = "windows") {
         "zip"
     } else {
         "tar.gz"
@@ -1785,6 +1868,7 @@ pub struct BuiltinAgentServerSettings {
     pub ignore_system_version: Option<bool>,
     pub default_mode: Option<String>,
     pub default_model: Option<String>,
+    pub favorite_models: Vec<String>,
 }
 
 impl BuiltinAgentServerSettings {
@@ -1808,6 +1892,7 @@ impl From<settings::BuiltinAgentServerSettings> for BuiltinAgentServerSettings {
             ignore_system_version: value.ignore_system_version,
             default_mode: value.default_mode,
             default_model: value.default_model,
+            favorite_models: value.favorite_models,
         }
     }
 }
@@ -1839,6 +1924,10 @@ pub enum CustomAgentServerSettings {
         ///
         /// Default: None
         default_model: Option<String>,
+        /// The favorite models for this agent.
+        ///
+        /// Default: []
+        favorite_models: Vec<String>,
     },
     Extension {
         /// The default mode to use for this agent.
@@ -1853,6 +1942,10 @@ pub enum CustomAgentServerSettings {
         ///
         /// Default: None
         default_model: Option<String>,
+        /// The favorite models for this agent.
+        ///
+        /// Default: []
+        favorite_models: Vec<String>,
     },
 }
 
@@ -1879,6 +1972,17 @@ impl CustomAgentServerSettings {
             }
         }
     }
+
+    pub fn favorite_models(&self) -> &[String] {
+        match self {
+            CustomAgentServerSettings::Custom {
+                favorite_models, ..
+            }
+            | CustomAgentServerSettings::Extension {
+                favorite_models, ..
+            } => favorite_models,
+        }
+    }
 }
 
 impl From<settings::CustomAgentServerSettings> for CustomAgentServerSettings {
@@ -1890,6 +1994,7 @@ impl From<settings::CustomAgentServerSettings> for CustomAgentServerSettings {
                 env,
                 default_mode,
                 default_model,
+                favorite_models,
             } => CustomAgentServerSettings::Custom {
                 command: AgentServerCommand {
                     path: PathBuf::from(shellexpand::tilde(&path.to_string_lossy()).as_ref()),
@@ -1898,13 +2003,16 @@ impl From<settings::CustomAgentServerSettings> for CustomAgentServerSettings {
                 },
                 default_mode,
                 default_model,
+                favorite_models,
             },
             settings::CustomAgentServerSettings::Extension {
                 default_mode,
                 default_model,
+                favorite_models,
             } => CustomAgentServerSettings::Extension {
                 default_mode,
                 default_model,
+                favorite_models,
             },
         }
     }
@@ -1981,6 +2089,7 @@ mod extension_agent_tests {
             state: AgentServerStoreState::Collab,
             external_agents: HashMap::default(),
             agent_icons: HashMap::default(),
+            agent_display_names: HashMap::default(),
         };
 
         // Seed with extension agents (contain ": ") and custom agents (don't contain ": ")
@@ -2229,6 +2338,7 @@ mod extension_agent_tests {
             ignore_system_version: None,
             default_mode: None,
             default_model: None,
+            favorite_models: vec![],
         };
 
         let BuiltinAgentServerSettings { path, .. } = settings.into();
@@ -2245,6 +2355,7 @@ mod extension_agent_tests {
             env: None,
             default_mode: None,
             default_model: None,
+            favorite_models: vec![],
         };
 
         let converted: CustomAgentServerSettings = settings.into();

crates/project/src/buffer_store.rs 🔗

@@ -24,7 +24,7 @@ use rpc::{
 
 use std::{io, sync::Arc, time::Instant};
 use text::{BufferId, ReplicaId};
-use util::{ResultExt as _, TryFutureExt, debug_panic, maybe, paths::PathStyle, rel_path::RelPath};
+use util::{ResultExt as _, TryFutureExt, debug_panic, maybe, rel_path::RelPath};
 use worktree::{File, PathChange, ProjectEntryId, Worktree, WorktreeId};
 
 /// A set of open buffers.
@@ -376,6 +376,8 @@ impl LocalBufferStore {
 
         let text = buffer.as_rope().clone();
         let line_ending = buffer.line_ending();
+        let encoding = buffer.encoding();
+        let has_bom = buffer.has_bom();
         let version = buffer.version();
         let buffer_id = buffer.remote_id();
         let file = buffer.file().cloned();
@@ -387,7 +389,7 @@ impl LocalBufferStore {
         }
 
         let save = worktree.update(cx, |worktree, cx| {
-            worktree.write_file(path, text, line_ending, cx)
+            worktree.write_file(path, text, line_ending, encoding, has_bom, cx)
         });
 
         cx.spawn(async move |this, cx| {
@@ -620,9 +622,7 @@ impl LocalBufferStore {
         let load_file = worktree.update(cx, |worktree, cx| worktree.load_file(path.as_ref(), cx));
         cx.spawn(async move |this, cx| {
             let path = path.clone();
-            let buffer = match load_file.await.with_context(|| {
-                format!("Could not open path: {}", path.display(PathStyle::local()))
-            }) {
+            let buffer = match load_file.await {
                 Ok(loaded) => {
                     let reservation = cx.reserve_entity::<Buffer>()?;
                     let buffer_id = BufferId::from(reservation.entity_id().as_non_zero_u64());
@@ -632,7 +632,11 @@ impl LocalBufferStore {
                         })
                         .await;
                     cx.insert_entity(reservation, |_| {
-                        Buffer::build(text_buffer, Some(loaded.file), Capability::ReadWrite)
+                        let mut buffer =
+                            Buffer::build(text_buffer, Some(loaded.file), Capability::ReadWrite);
+                        buffer.set_encoding(loaded.encoding);
+                        buffer.set_has_bom(loaded.has_bom);
+                        buffer
                     })?
                 }
                 Err(error) if is_not_found_error(&error) => cx.new(|cx| {
@@ -1129,7 +1133,7 @@ impl BufferStore {
                     })
                     .log_err();
             }
-            BufferEvent::LanguageChanged => {}
+            BufferEvent::LanguageChanged(_) => {}
             _ => {}
         }
     }

crates/project/src/context_server_store.rs 🔗

@@ -411,11 +411,11 @@ impl ContextServerStore {
         ) {
             self.stop_server(&id, cx).log_err();
         }
-
         let task = cx.spawn({
             let id = server.id();
             let server = server.clone();
             let configuration = configuration.clone();
+
             async move |this, cx| {
                 match server.clone().start(cx).await {
                     Ok(_) => {

crates/project/src/debugger/breakpoint_store.rs 🔗

@@ -23,7 +23,7 @@ use super::session::ThreadId;
 
 mod breakpoints_in_file {
     use collections::HashMap;
-    use language::{BufferEvent, DiskState};
+    use language::BufferEvent;
 
     use super::*;
 
@@ -82,7 +82,7 @@ mod breakpoints_in_file {
                     BufferEvent::FileHandleChanged => {
                         let entity_id = buffer.entity_id();
 
-                        if buffer.read(cx).file().is_none_or(|f| f.disk_state() == DiskState::Deleted) {
+                        if buffer.read(cx).file().is_none_or(|f| f.disk_state().is_deleted()) {
                             breakpoint_store.breakpoints.retain(|_, breakpoints_in_file| {
                                 breakpoints_in_file.buffer.entity_id() != entity_id
                             });

crates/project/src/debugger/dap_store.rs 🔗

@@ -692,7 +692,7 @@ impl DapStore {
                     }
                     VariableLookupKind::Expression => {
                         let Ok(eval_task) = session.read_with(cx, |session, _| {
-                            session.mode.request_dap(EvaluateCommand {
+                            session.state.request_dap(EvaluateCommand {
                                 expression: inline_value_location.variable_name.clone(),
                                 frame_id: Some(stack_frame_id),
                                 source: None,

crates/project/src/debugger/locators/cargo.rs 🔗

@@ -115,18 +115,17 @@ impl DapLocator for CargoLocator {
             .clone()
             .context("Couldn't get cwd from debug config which is needed for locators")?;
         let builder = ShellBuilder::new(&build_config.shell, cfg!(windows)).non_interactive();
-        let (program, args) = builder.build(
-            Some("cargo".into()),
-            &build_config
-                .args
-                .iter()
-                .cloned()
-                .take_while(|arg| arg != "--")
-                .chain(Some("--message-format=json".to_owned()))
-                .collect::<Vec<_>>(),
-        );
-        let mut child = util::command::new_smol_command(program)
-            .args(args)
+        let mut child = builder
+            .build_command(
+                Some("cargo".into()),
+                &build_config
+                    .args
+                    .iter()
+                    .cloned()
+                    .take_while(|arg| arg != "--")
+                    .chain(Some("--message-format=json".to_owned()))
+                    .collect::<Vec<_>>(),
+            )
             .envs(build_config.env.iter().map(|(k, v)| (k.clone(), v.clone())))
             .current_dir(cwd)
             .stdout(Stdio::piped())

crates/project/src/debugger/session.rs 🔗

@@ -1,7 +1,3 @@
-use crate::debugger::breakpoint_store::BreakpointSessionState;
-use crate::debugger::dap_command::{DataBreakpointContext, ReadMemory};
-use crate::debugger::memory::{self, Memory, MemoryIterator, MemoryPageBuilder, PageAddress};
-
 use super::breakpoint_store::{
     BreakpointStore, BreakpointStoreEvent, BreakpointUpdatedReason, SourceBreakpoint,
 };
@@ -14,6 +10,9 @@ use super::dap_command::{
     TerminateCommand, TerminateThreadsCommand, ThreadsCommand, VariablesCommand,
 };
 use super::dap_store::DapStore;
+use crate::debugger::breakpoint_store::BreakpointSessionState;
+use crate::debugger::dap_command::{DataBreakpointContext, ReadMemory};
+use crate::debugger::memory::{self, Memory, MemoryIterator, MemoryPageBuilder, PageAddress};
 use anyhow::{Context as _, Result, anyhow, bail};
 use base64::Engine;
 use collections::{HashMap, HashSet, IndexMap};
@@ -42,15 +41,13 @@ use gpui::{
     Task, WeakEntity,
 };
 use http_client::HttpClient;
-
 use node_runtime::NodeRuntime;
 use remote::RemoteClient;
-use rpc::ErrorExt;
 use serde::{Deserialize, Serialize};
 use serde_json::Value;
 use smol::net::{TcpListener, TcpStream};
 use std::any::TypeId;
-use std::collections::BTreeMap;
+use std::collections::{BTreeMap, VecDeque};
 use std::net::Ipv4Addr;
 use std::ops::RangeInclusive;
 use std::path::PathBuf;
@@ -71,6 +68,9 @@ use util::command::new_smol_command;
 use util::{ResultExt, debug_panic, maybe};
 use worktree::Worktree;
 
+const MAX_TRACKED_OUTPUT_EVENTS: usize = 5000;
+const DEBUG_HISTORY_LIMIT: usize = 10;
+
 #[derive(Debug, Copy, Clone, Hash, PartialEq, PartialOrd, Ord, Eq)]
 #[repr(transparent)]
 pub struct ThreadId(pub i64);
@@ -118,11 +118,11 @@ impl ThreadStatus {
     }
 }
 
-#[derive(Debug)]
+#[derive(Debug, Clone)]
 pub struct Thread {
     dap: dap::Thread,
     stack_frames: Vec<StackFrame>,
-    stack_frames_error: Option<anyhow::Error>,
+    stack_frames_error: Option<SharedString>,
     _has_stopped: bool,
 }
 
@@ -672,7 +672,18 @@ impl ThreadStates {
                 .any(|status| *status == ThreadStatus::Stopped)
     }
 }
-const MAX_TRACKED_OUTPUT_EVENTS: usize = 5000;
+
+// TODO(debugger): Wrap dap types with reference counting so the UI doesn't have to clone them on refresh
+#[derive(Default)]
+pub struct SessionSnapshot {
+    threads: IndexMap<ThreadId, Thread>,
+    thread_states: ThreadStates,
+    variables: HashMap<VariableReference, Vec<dap::Variable>>,
+    stack_frames: IndexMap<StackFrameId, StackFrame>,
+    locations: HashMap<u64, dap::LocationsResponse>,
+    modules: Vec<dap::Module>,
+    loaded_sources: Vec<dap::Source>,
+}
 
 type IsEnabled = bool;
 
@@ -680,23 +691,19 @@ type IsEnabled = bool;
 pub struct OutputToken(pub usize);
 /// Represents a current state of a single debug adapter and provides ways to mutate it.
 pub struct Session {
-    pub mode: SessionState,
+    pub state: SessionState,
+    active_snapshot: SessionSnapshot,
+    snapshots: VecDeque<SessionSnapshot>,
+    selected_snapshot_index: Option<usize>,
     id: SessionId,
     label: Option<SharedString>,
     adapter: DebugAdapterName,
     pub(super) capabilities: Capabilities,
     child_session_ids: HashSet<SessionId>,
     parent_session: Option<Entity<Session>>,
-    modules: Vec<dap::Module>,
-    loaded_sources: Vec<dap::Source>,
     output_token: OutputToken,
     output: Box<circular_buffer::CircularBuffer<MAX_TRACKED_OUTPUT_EVENTS, dap::OutputEvent>>,
-    threads: IndexMap<ThreadId, Thread>,
-    thread_states: ThreadStates,
     watchers: HashMap<SharedString, Watcher>,
-    variables: HashMap<VariableReference, Vec<dap::Variable>>,
-    stack_frames: IndexMap<StackFrameId, StackFrame>,
-    locations: HashMap<u64, dap::LocationsResponse>,
     is_session_terminated: bool,
     requests: HashMap<TypeId, HashMap<RequestSlot, Shared<Task<Option<()>>>>>,
     pub(crate) breakpoint_store: Entity<BreakpointStore>,
@@ -801,6 +808,7 @@ pub enum SessionEvent {
     },
     DataBreakpointInfo,
     ConsoleOutput,
+    HistoricSnapshotSelected,
 }
 
 #[derive(Clone, Debug, PartialEq, Eq)]
@@ -858,24 +866,20 @@ impl Session {
             .detach();
 
             Self {
-                mode: SessionState::Booting(None),
+                state: SessionState::Booting(None),
+                snapshots: VecDeque::with_capacity(DEBUG_HISTORY_LIMIT),
+                selected_snapshot_index: None,
+                active_snapshot: Default::default(),
                 id: session_id,
                 child_session_ids: HashSet::default(),
                 parent_session,
                 capabilities: Capabilities::default(),
                 watchers: HashMap::default(),
-                variables: Default::default(),
-                stack_frames: Default::default(),
-                thread_states: ThreadStates::default(),
                 output_token: OutputToken(0),
                 output: circular_buffer::CircularBuffer::boxed(),
                 requests: HashMap::default(),
-                modules: Vec::default(),
-                loaded_sources: Vec::default(),
-                threads: IndexMap::default(),
                 background_tasks: Vec::default(),
                 restart_task: None,
-                locations: Default::default(),
                 is_session_terminated: false,
                 ignore_breakpoints: false,
                 breakpoint_store,
@@ -899,7 +903,7 @@ impl Session {
     }
 
     pub fn worktree(&self) -> Option<Entity<Worktree>> {
-        match &self.mode {
+        match &self.state {
             SessionState::Booting(_) => None,
             SessionState::Running(local_mode) => local_mode.worktree.upgrade(),
         }
@@ -960,7 +964,7 @@ impl Session {
             )
             .await?;
             this.update(cx, |this, cx| {
-                match &mut this.mode {
+                match &mut this.state {
                     SessionState::Booting(task) if task.is_some() => {
                         task.take().unwrap().detach_and_log_err(cx);
                     }
@@ -969,7 +973,7 @@ impl Session {
                         debug_panic!("Attempting to boot a session that is already running");
                     }
                 };
-                this.mode = SessionState::Running(mode);
+                this.state = SessionState::Running(mode);
                 cx.emit(SessionStateEvent::Running);
             })?;
 
@@ -1061,7 +1065,7 @@ impl Session {
     }
 
     pub fn binary(&self) -> Option<&DebugAdapterBinary> {
-        match &self.mode {
+        match &self.state {
             SessionState::Booting(_) => None,
             SessionState::Running(running_mode) => Some(&running_mode.binary),
         }
@@ -1107,25 +1111,25 @@ impl Session {
     }
 
     pub fn is_started(&self) -> bool {
-        match &self.mode {
+        match &self.state {
             SessionState::Booting(_) => false,
             SessionState::Running(running) => running.is_started,
         }
     }
 
     pub fn is_building(&self) -> bool {
-        matches!(self.mode, SessionState::Booting(_))
+        matches!(self.state, SessionState::Booting(_))
     }
 
     pub fn as_running_mut(&mut self) -> Option<&mut RunningMode> {
-        match &mut self.mode {
+        match &mut self.state {
             SessionState::Running(local_mode) => Some(local_mode),
             SessionState::Booting(_) => None,
         }
     }
 
     pub fn as_running(&self) -> Option<&RunningMode> {
-        match &self.mode {
+        match &self.state {
             SessionState::Running(local_mode) => Some(local_mode),
             SessionState::Booting(_) => None,
         }
@@ -1269,7 +1273,7 @@ impl Session {
         let adapter_id = self.adapter().to_string();
         let request = Initialize { adapter_id };
 
-        let SessionState::Running(running) = &self.mode else {
+        let SessionState::Running(running) = &self.state else {
             return Task::ready(Err(anyhow!(
                 "Cannot send initialize request, task still building"
             )));
@@ -1317,7 +1321,7 @@ impl Session {
         dap_store: WeakEntity<DapStore>,
         cx: &mut Context<Self>,
     ) -> Task<Result<()>> {
-        match &self.mode {
+        match &self.state {
             SessionState::Running(local_mode) => {
                 local_mode.initialize_sequence(&self.capabilities, initialize_rx, dap_store, cx)
             }
@@ -1333,10 +1337,12 @@ impl Session {
         active_thread_id: ThreadId,
         cx: &mut Context<Self>,
     ) {
-        match &mut self.mode {
+        match &mut self.state {
             SessionState::Running(local_mode) => {
                 if !matches!(
-                    self.thread_states.thread_state(active_thread_id),
+                    self.active_snapshot
+                        .thread_states
+                        .thread_state(active_thread_id),
                     Some(ThreadStatus::Stopped)
                 ) {
                     return;
@@ -1411,8 +1417,55 @@ impl Session {
         })
     }
 
+    fn session_state(&self) -> &SessionSnapshot {
+        self.selected_snapshot_index
+            .and_then(|ix| self.snapshots.get(ix))
+            .unwrap_or_else(|| &self.active_snapshot)
+    }
+
+    fn push_to_history(&mut self) {
+        if !self.has_ever_stopped() {
+            return;
+        }
+
+        while self.snapshots.len() >= DEBUG_HISTORY_LIMIT {
+            self.snapshots.pop_front();
+        }
+
+        self.snapshots
+            .push_back(std::mem::take(&mut self.active_snapshot));
+    }
+
+    pub fn historic_snapshots(&self) -> &VecDeque<SessionSnapshot> {
+        &self.snapshots
+    }
+
+    pub fn select_historic_snapshot(&mut self, ix: Option<usize>, cx: &mut Context<Session>) {
+        if self.selected_snapshot_index == ix {
+            return;
+        }
+
+        if self
+            .selected_snapshot_index
+            .is_some_and(|ix| self.snapshots.len() <= ix)
+        {
+            debug_panic!("Attempted to select a debug session with an out of bounds index");
+            return;
+        }
+
+        self.selected_snapshot_index = ix;
+        cx.emit(SessionEvent::HistoricSnapshotSelected);
+        cx.notify();
+    }
+
+    pub fn active_snapshot_index(&self) -> Option<usize> {
+        self.selected_snapshot_index
+    }
+
     fn handle_stopped_event(&mut self, event: StoppedEvent, cx: &mut Context<Self>) {
-        self.mode.stopped();
+        self.push_to_history();
+
+        self.state.stopped();
         // todo(debugger): Find a clean way to get around the clone
         let breakpoint_store = self.breakpoint_store.clone();
         if let Some((local, path)) = self.as_running_mut().and_then(|local| {
@@ -1431,14 +1484,16 @@ impl Session {
         };
 
         if event.all_threads_stopped.unwrap_or_default() || event.thread_id.is_none() {
-            self.thread_states.stop_all_threads();
+            self.active_snapshot.thread_states.stop_all_threads();
             self.invalidate_command_type::<StackTraceCommand>();
         }
 
         // Event if we stopped all threads we still need to insert the thread_id
         // to our own data
         if let Some(thread_id) = event.thread_id {
-            self.thread_states.stop_thread(ThreadId(thread_id));
+            self.active_snapshot
+                .thread_states
+                .stop_thread(ThreadId(thread_id));
 
             self.invalidate_state(
                 &StackTraceCommand {
@@ -1451,8 +1506,8 @@ impl Session {
         }
 
         self.invalidate_generic();
-        self.threads.clear();
-        self.variables.clear();
+        self.active_snapshot.threads.clear();
+        self.active_snapshot.variables.clear();
         cx.emit(SessionEvent::Stopped(
             event
                 .thread_id
@@ -1474,12 +1529,13 @@ impl Session {
             Events::Stopped(event) => self.handle_stopped_event(event, cx),
             Events::Continued(event) => {
                 if event.all_threads_continued.unwrap_or_default() {
-                    self.thread_states.continue_all_threads();
+                    self.active_snapshot.thread_states.continue_all_threads();
                     self.breakpoint_store.update(cx, |store, cx| {
                         store.remove_active_position(Some(self.session_id()), cx)
                     });
                 } else {
-                    self.thread_states
+                    self.active_snapshot
+                        .thread_states
                         .continue_thread(ThreadId(event.thread_id));
                 }
                 // todo(debugger): We should be able to get away with only invalidating generic if all threads were continued
@@ -1496,10 +1552,12 @@ impl Session {
 
                 match event.reason {
                     dap::ThreadEventReason::Started => {
-                        self.thread_states.continue_thread(thread_id);
+                        self.active_snapshot
+                            .thread_states
+                            .continue_thread(thread_id);
                     }
                     dap::ThreadEventReason::Exited => {
-                        self.thread_states.exit_thread(thread_id);
+                        self.active_snapshot.thread_states.exit_thread(thread_id);
                     }
                     reason => {
                         log::error!("Unhandled thread event reason {:?}", reason);
@@ -1526,10 +1584,11 @@ impl Session {
             Events::Module(event) => {
                 match event.reason {
                     dap::ModuleEventReason::New => {
-                        self.modules.push(event.module);
+                        self.active_snapshot.modules.push(event.module);
                     }
                     dap::ModuleEventReason::Changed => {
                         if let Some(module) = self
+                            .active_snapshot
                             .modules
                             .iter_mut()
                             .find(|other| event.module.id == other.id)
@@ -1538,7 +1597,9 @@ impl Session {
                         }
                     }
                     dap::ModuleEventReason::Removed => {
-                        self.modules.retain(|other| event.module.id != other.id);
+                        self.active_snapshot
+                            .modules
+                            .retain(|other| event.module.id != other.id);
                     }
                 }
 
@@ -1612,8 +1673,9 @@ impl Session {
             );
         }
 
-        if !self.thread_states.any_stopped_thread()
-            && request.type_id() != TypeId::of::<ThreadsCommand>()
+        if (!self.active_snapshot.thread_states.any_stopped_thread()
+            && request.type_id() != TypeId::of::<ThreadsCommand>())
+            || self.selected_snapshot_index.is_some()
             || self.is_session_terminated
         {
             return;
@@ -1629,7 +1691,7 @@ impl Session {
 
             let task = Self::request_inner::<Arc<T>>(
                 &self.capabilities,
-                &self.mode,
+                &self.state,
                 command,
                 |this, result, cx| {
                     process_result(this, result, cx);
@@ -1697,7 +1759,7 @@ impl Session {
         + 'static,
         cx: &mut Context<Self>,
     ) -> Task<Option<T::Response>> {
-        Self::request_inner(&self.capabilities, &self.mode, request, process_result, cx)
+        Self::request_inner(&self.capabilities, &self.state, request, process_result, cx)
     }
 
     fn invalidate_command_type<Command: LocalDapCommand>(&mut self) {
@@ -1730,11 +1792,11 @@ impl Session {
     }
 
     pub fn any_stopped_thread(&self) -> bool {
-        self.thread_states.any_stopped_thread()
+        self.active_snapshot.thread_states.any_stopped_thread()
     }
 
     pub fn thread_status(&self, thread_id: ThreadId) -> ThreadStatus {
-        self.thread_states.thread_status(thread_id)
+        self.active_snapshot.thread_states.thread_status(thread_id)
     }
 
     pub fn threads(&mut self, cx: &mut Context<Self>) -> Vec<(dap::Thread, ThreadStatus)> {
@@ -1745,7 +1807,7 @@ impl Session {
                     return;
                 };
 
-                this.threads = result
+                this.active_snapshot.threads = result
                     .into_iter()
                     .map(|thread| (ThreadId(thread.id), Thread::from(thread)))
                     .collect();
@@ -1757,12 +1819,14 @@ impl Session {
             cx,
         );
 
-        self.threads
+        let state = self.session_state();
+        state
+            .threads
             .values()
             .map(|thread| {
                 (
                     thread.dap.clone(),
-                    self.thread_states.thread_status(ThreadId(thread.dap.id)),
+                    state.thread_states.thread_status(ThreadId(thread.dap.id)),
                 )
             })
             .collect()
@@ -1776,14 +1840,14 @@ impl Session {
                     return;
                 };
 
-                this.modules = result;
+                this.active_snapshot.modules = result;
                 cx.emit(SessionEvent::Modules);
                 cx.notify();
             },
             cx,
         );
 
-        &self.modules
+        &self.session_state().modules
     }
 
     // CodeLLDB returns the size of a pointed-to-memory, which we can use to make the experience of go-to-memory better.
@@ -2034,14 +2098,13 @@ impl Session {
                 let Some(result) = result.log_err() else {
                     return;
                 };
-                this.loaded_sources = result;
+                this.active_snapshot.loaded_sources = result;
                 cx.emit(SessionEvent::LoadedSources);
                 cx.notify();
             },
             cx,
         );
-
-        &self.loaded_sources
+        &self.session_state().loaded_sources
     }
 
     fn fallback_to_manual_restart(
@@ -2073,7 +2136,7 @@ impl Session {
                 Some(response)
             }
             None => {
-                this.thread_states.stop_thread(thread_id);
+                this.active_snapshot.thread_states.stop_thread(thread_id);
                 cx.notify();
                 None
             }
@@ -2149,10 +2212,10 @@ impl Session {
         }
 
         self.is_session_terminated = true;
-        self.thread_states.exit_all_threads();
+        self.active_snapshot.thread_states.exit_all_threads();
         cx.notify();
 
-        let task = match &mut self.mode {
+        let task = match &mut self.state {
             SessionState::Running(_) => {
                 if self
                     .capabilities
@@ -2213,9 +2276,13 @@ impl Session {
     }
 
     pub fn continue_thread(&mut self, thread_id: ThreadId, cx: &mut Context<Self>) {
+        self.select_historic_snapshot(None, cx);
+
         let supports_single_thread_execution_requests =
             self.capabilities.supports_single_thread_execution_requests;
-        self.thread_states.continue_thread(thread_id);
+        self.active_snapshot
+            .thread_states
+            .continue_thread(thread_id);
         self.request(
             ContinueCommand {
                 args: ContinueArguments {
@@ -2230,21 +2297,24 @@ impl Session {
     }
 
     pub fn adapter_client(&self) -> Option<Arc<DebugAdapterClient>> {
-        match self.mode {
+        match self.state {
             SessionState::Running(ref local) => Some(local.client.clone()),
             SessionState::Booting(_) => None,
         }
     }
 
     pub fn has_ever_stopped(&self) -> bool {
-        self.mode.has_ever_stopped()
+        self.state.has_ever_stopped()
     }
+
     pub fn step_over(
         &mut self,
         thread_id: ThreadId,
         granularity: SteppingGranularity,
         cx: &mut Context<Self>,
     ) {
+        self.select_historic_snapshot(None, cx);
+
         let supports_single_thread_execution_requests =
             self.capabilities.supports_single_thread_execution_requests;
         let supports_stepping_granularity = self
@@ -2260,7 +2330,7 @@ impl Session {
             },
         };
 
-        self.thread_states.process_step(thread_id);
+        self.active_snapshot.thread_states.process_step(thread_id);
         self.request(
             command,
             Self::on_step_response::<NextCommand>(thread_id),
@@ -2275,6 +2345,8 @@ impl Session {
         granularity: SteppingGranularity,
         cx: &mut Context<Self>,
     ) {
+        self.select_historic_snapshot(None, cx);
+
         let supports_single_thread_execution_requests =
             self.capabilities.supports_single_thread_execution_requests;
         let supports_stepping_granularity = self
@@ -2290,7 +2362,7 @@ impl Session {
             },
         };
 
-        self.thread_states.process_step(thread_id);
+        self.active_snapshot.thread_states.process_step(thread_id);
         self.request(
             command,
             Self::on_step_response::<StepInCommand>(thread_id),
@@ -2305,6 +2377,8 @@ impl Session {
         granularity: SteppingGranularity,
         cx: &mut Context<Self>,
     ) {
+        self.select_historic_snapshot(None, cx);
+
         let supports_single_thread_execution_requests =
             self.capabilities.supports_single_thread_execution_requests;
         let supports_stepping_granularity = self
@@ -2320,7 +2394,7 @@ impl Session {
             },
         };
 
-        self.thread_states.process_step(thread_id);
+        self.active_snapshot.thread_states.process_step(thread_id);
         self.request(
             command,
             Self::on_step_response::<StepOutCommand>(thread_id),
@@ -2335,6 +2409,8 @@ impl Session {
         granularity: SteppingGranularity,
         cx: &mut Context<Self>,
     ) {
+        self.select_historic_snapshot(None, cx);
+
         let supports_single_thread_execution_requests =
             self.capabilities.supports_single_thread_execution_requests;
         let supports_stepping_granularity = self
@@ -2350,7 +2426,7 @@ impl Session {
             },
         };
 
-        self.thread_states.process_step(thread_id);
+        self.active_snapshot.thread_states.process_step(thread_id);
 
         self.request(
             command,
@@ -2365,9 +2441,9 @@ impl Session {
         thread_id: ThreadId,
         cx: &mut Context<Self>,
     ) -> Result<Vec<StackFrame>> {
-        if self.thread_states.thread_status(thread_id) == ThreadStatus::Stopped
+        if self.active_snapshot.thread_states.thread_status(thread_id) == ThreadStatus::Stopped
             && self.requests.contains_key(&ThreadsCommand.type_id())
-            && self.threads.contains_key(&thread_id)
+            && self.active_snapshot.threads.contains_key(&thread_id)
         // ^ todo(debugger): We need a better way to check that we're not querying stale data
         // We could still be using an old thread id and have sent a new thread's request
         // This isn't the biggest concern right now because it hasn't caused any issues outside of tests
@@ -2381,7 +2457,8 @@ impl Session {
                 },
                 move |this, stack_frames, cx| {
                     let entry =
-                        this.threads
+                        this.active_snapshot
+                            .threads
                             .entry(thread_id)
                             .and_modify(|thread| match &stack_frames {
                                 Ok(stack_frames) => {
@@ -2394,7 +2471,7 @@ impl Session {
                                 }
                                 Err(error) => {
                                     thread.stack_frames.clear();
-                                    thread.stack_frames_error = Some(error.cloned());
+                                    thread.stack_frames_error = Some(error.to_string().into());
                                 }
                             });
                     debug_assert!(
@@ -2402,7 +2479,7 @@ impl Session {
                         "Sent request for thread_id that doesn't exist"
                     );
                     if let Ok(stack_frames) = stack_frames {
-                        this.stack_frames.extend(
+                        this.active_snapshot.stack_frames.extend(
                             stack_frames
                                 .into_iter()
                                 .filter(|frame| {
@@ -2427,10 +2504,10 @@ impl Session {
             );
         }
 
-        match self.threads.get(&thread_id) {
+        match self.session_state().threads.get(&thread_id) {
             Some(thread) => {
                 if let Some(error) = &thread.stack_frames_error {
-                    Err(error.cloned())
+                    Err(anyhow!(error.to_string()))
                 } else {
                     Ok(thread.stack_frames.clone())
                 }
@@ -2457,6 +2534,7 @@ impl Session {
                     }
 
                     let entry = this
+                        .active_snapshot
                         .stack_frames
                         .entry(stack_frame_id)
                         .and_modify(|stack_frame| {
@@ -2474,7 +2552,8 @@ impl Session {
             );
         }
 
-        self.stack_frames
+        self.session_state()
+            .stack_frames
             .get(&stack_frame_id)
             .map(|frame| frame.scopes.as_slice())
             .unwrap_or_default()
@@ -2486,7 +2565,8 @@ impl Session {
         globals: bool,
         locals: bool,
     ) -> Vec<dap::Variable> {
-        let Some(stack_frame) = self.stack_frames.get(&stack_frame_id) else {
+        let state = self.session_state();
+        let Some(stack_frame) = state.stack_frames.get(&stack_frame_id) else {
             return Vec::new();
         };
 
@@ -2497,7 +2577,7 @@ impl Session {
                 (scope.name.to_lowercase().contains("local") && locals)
                     || (scope.name.to_lowercase().contains("global") && globals)
             })
-            .filter_map(|scope| self.variables.get(&scope.variables_reference))
+            .filter_map(|scope| state.variables.get(&scope.variables_reference))
             .flatten()
             .cloned()
             .collect()
@@ -2513,7 +2593,7 @@ impl Session {
         frame_id: u64,
         cx: &mut Context<Self>,
     ) -> Task<Result<()>> {
-        let request = self.mode.request_dap(EvaluateCommand {
+        let request = self.state.request_dap(EvaluateCommand {
             expression: expression.to_string(),
             context: Some(EvaluateArgumentsContext::Watch),
             frame_id: Some(frame_id),
@@ -2570,7 +2650,9 @@ impl Session {
                     return;
                 };
 
-                this.variables.insert(variables_reference, variables);
+                this.active_snapshot
+                    .variables
+                    .insert(variables_reference, variables);
 
                 cx.emit(SessionEvent::Variables);
                 cx.emit(SessionEvent::InvalidateInlineValue);
@@ -2578,7 +2660,8 @@ impl Session {
             cx,
         );
 
-        self.variables
+        self.session_state()
+            .variables
             .get(&variables_reference)
             .cloned()
             .unwrap_or_default()
@@ -2645,7 +2728,7 @@ impl Session {
             location_reference: None,
         };
         self.push_output(event);
-        let request = self.mode.request_dap(EvaluateCommand {
+        let request = self.state.request_dap(EvaluateCommand {
             expression,
             context,
             frame_id,
@@ -2656,6 +2739,8 @@ impl Session {
             this.update(cx, |this, cx| {
                 this.memory.clear(cx.background_executor());
                 this.invalidate_command_type::<ReadMemory>();
+                this.invalidate_command_type::<VariablesCommand>();
+                cx.emit(SessionEvent::Variables);
                 match response {
                     Ok(response) => {
                         let event = dap::OutputEvent {
@@ -2703,15 +2788,15 @@ impl Session {
                 let Some(response) = response.log_err() else {
                     return;
                 };
-                this.locations.insert(reference, response);
+                this.active_snapshot.locations.insert(reference, response);
             },
             cx,
         );
-        self.locations.get(&reference).cloned()
+        self.session_state().locations.get(&reference).cloned()
     }
 
     pub fn is_attached(&self) -> bool {
-        let SessionState::Running(local_mode) = &self.mode else {
+        let SessionState::Running(local_mode) = &self.state else {
             return false;
         };
         local_mode.binary.request_args.request == StartDebuggingRequestArgumentsRequest::Attach
@@ -2747,7 +2832,7 @@ impl Session {
     }
 
     pub fn thread_state(&self, thread_id: ThreadId) -> Option<ThreadStatus> {
-        self.thread_states.thread_state(thread_id)
+        self.session_state().thread_states.thread_state(thread_id)
     }
 
     pub fn quirks(&self) -> SessionQuirks {
@@ -3033,10 +3118,11 @@ async fn get_or_install_companion(node: NodeRuntime, cx: &mut AsyncApp) -> Resul
             .await
             .context("getting installed companion version")?
             .context("companion was not installed")?;
-        smol::fs::rename(temp_dir.path(), dir.join(&version))
+        let version_folder = dir.join(version.to_string());
+        smol::fs::rename(temp_dir.path(), &version_folder)
             .await
             .context("moving companion package into place")?;
-        Ok(dir.join(version))
+        Ok(version_folder)
     }
 
     let dir = paths::debug_adapters_dir().join("js-debug-companion");
@@ -3049,19 +3135,23 @@ async fn get_or_install_companion(node: NodeRuntime, cx: &mut AsyncApp) -> Resul
                     .await
                     .context("creating companion installation directory")?;
 
-                let mut children = smol::fs::read_dir(&dir)
+                let children = smol::fs::read_dir(&dir)
                     .await
                     .context("reading companion installation directory")?
                     .try_collect::<Vec<_>>()
                     .await
                     .context("reading companion installation directory entries")?;
-                children
-                    .sort_by_key(|child| semver::Version::parse(child.file_name().to_str()?).ok());
 
-                let latest_installed_version = children.last().and_then(|child| {
-                    let version = child.file_name().into_string().ok()?;
-                    Some((child.path(), version))
-                });
+                let latest_installed_version = children
+                    .iter()
+                    .filter_map(|child| {
+                        Some((
+                            child.path(),
+                            semver::Version::parse(child.file_name().to_str()?).ok()?,
+                        ))
+                    })
+                    .max_by_key(|(_, version)| version.clone());
+
                 let latest_version = node
                     .npm_package_latest_version(PACKAGE_NAME)
                     .await

crates/project/src/git_store.rs 🔗

@@ -472,6 +472,8 @@ impl GitStore {
         client.add_entity_request_handler(Self::handle_change_branch);
         client.add_entity_request_handler(Self::handle_create_branch);
         client.add_entity_request_handler(Self::handle_rename_branch);
+        client.add_entity_request_handler(Self::handle_create_remote);
+        client.add_entity_request_handler(Self::handle_remove_remote);
         client.add_entity_request_handler(Self::handle_delete_branch);
         client.add_entity_request_handler(Self::handle_git_init);
         client.add_entity_request_handler(Self::handle_push);
@@ -1028,6 +1030,7 @@ impl GitStore {
             Some(version) => buffer.rope_for_version(version),
             None => buffer.as_rope().clone(),
         };
+        let line_ending = buffer.line_ending();
         let version = version.unwrap_or(buffer.version());
         let buffer_id = buffer.remote_id();
 
@@ -1039,7 +1042,7 @@ impl GitStore {
                 .map_err(|err| anyhow::anyhow!(err))?;
             match repository_state {
                 RepositoryState::Local(LocalRepositoryState { backend, .. }) => backend
-                    .blame(repo_path.clone(), content)
+                    .blame(repo_path.clone(), content, line_ending)
                     .await
                     .with_context(|| format!("Failed to blame {:?}", repo_path.as_ref()))
                     .map(Some),
@@ -1129,6 +1132,7 @@ impl GitStore {
                     RepositoryState::Local(LocalRepositoryState { backend, .. }) => {
                         let origin_url = backend
                             .remote_url(&remote)
+                            .await
                             .with_context(|| format!("remote \"{remote}\" not found"))?;
 
                         let sha = backend.head_sha().await.context("reading HEAD SHA")?;
@@ -1447,7 +1451,7 @@ impl GitStore {
         match event {
             BufferStoreEvent::BufferAdded(buffer) => {
                 cx.subscribe(buffer, |this, buffer, event, cx| {
-                    if let BufferEvent::LanguageChanged = event {
+                    if let BufferEvent::LanguageChanged(_) = event {
                         let buffer_id = buffer.read(cx).remote_id();
                         if let Some(diff_state) = this.diffs.get(&buffer_id) {
                             diff_state.update(cx, |diff_state, cx| {
@@ -2272,6 +2276,25 @@ impl GitStore {
         Ok(proto::Ack {})
     }
 
+    async fn handle_create_remote(
+        this: Entity<Self>,
+        envelope: TypedEnvelope<proto::GitCreateRemote>,
+        mut cx: AsyncApp,
+    ) -> Result<proto::Ack> {
+        let repository_id = RepositoryId::from_proto(envelope.payload.repository_id);
+        let repository_handle = Self::repository_for_request(&this, repository_id, &mut cx)?;
+        let remote_name = envelope.payload.remote_name;
+        let remote_url = envelope.payload.remote_url;
+
+        repository_handle
+            .update(&mut cx, |repository_handle, _| {
+                repository_handle.create_remote(remote_name, remote_url)
+            })?
+            .await??;
+
+        Ok(proto::Ack {})
+    }
+
     async fn handle_delete_branch(
         this: Entity<Self>,
         envelope: TypedEnvelope<proto::GitDeleteBranch>,
@@ -2290,6 +2313,24 @@ impl GitStore {
         Ok(proto::Ack {})
     }
 
+    async fn handle_remove_remote(
+        this: Entity<Self>,
+        envelope: TypedEnvelope<proto::GitRemoveRemote>,
+        mut cx: AsyncApp,
+    ) -> Result<proto::Ack> {
+        let repository_id = RepositoryId::from_proto(envelope.payload.repository_id);
+        let repository_handle = Self::repository_for_request(&this, repository_id, &mut cx)?;
+        let remote_name = envelope.payload.remote_name;
+
+        repository_handle
+            .update(&mut cx, |repository_handle, _| {
+                repository_handle.remove_remote(remote_name)
+            })?
+            .await??;
+
+        Ok(proto::Ack {})
+    }
+
     async fn handle_show(
         this: Entity<Self>,
         envelope: TypedEnvelope<proto::GitShow>,
@@ -3253,6 +3294,8 @@ impl RepositorySnapshot {
                 .iter()
                 .map(stash_to_proto)
                 .collect(),
+            remote_upstream_url: self.remote_upstream_url.clone(),
+            remote_origin_url: self.remote_origin_url.clone(),
         }
     }
 
@@ -3322,6 +3365,8 @@ impl RepositorySnapshot {
                 .iter()
                 .map(stash_to_proto)
                 .collect(),
+            remote_upstream_url: self.remote_upstream_url.clone(),
+            remote_origin_url: self.remote_origin_url.clone(),
         }
     }
 
@@ -4157,74 +4202,29 @@ impl Repository {
         entries: Vec<RepoPath>,
         cx: &mut Context<Self>,
     ) -> Task<anyhow::Result<()>> {
-        if entries.is_empty() {
-            return Task::ready(Ok(()));
-        }
-        let id = self.id;
-        let save_tasks = self.save_buffers(&entries, cx);
-        let paths = entries
-            .iter()
-            .map(|p| p.as_unix_str())
-            .collect::<Vec<_>>()
-            .join(" ");
-        let status = format!("git add {paths}");
-        let job_key = GitJobKey::WriteIndex(entries.clone());
-
-        self.spawn_job_with_tracking(
-            entries.clone(),
-            pending_op::GitStatus::Staged,
-            cx,
-            async move |this, cx| {
-                for save_task in save_tasks {
-                    save_task.await?;
-                }
-
-                this.update(cx, |this, _| {
-                    this.send_keyed_job(
-                        Some(job_key),
-                        Some(status.into()),
-                        move |git_repo, _cx| async move {
-                            match git_repo {
-                                RepositoryState::Local(LocalRepositoryState {
-                                    backend,
-                                    environment,
-                                    ..
-                                }) => backend.stage_paths(entries, environment.clone()).await,
-                                RepositoryState::Remote(RemoteRepositoryState {
-                                    project_id,
-                                    client,
-                                }) => {
-                                    client
-                                        .request(proto::Stage {
-                                            project_id: project_id.0,
-                                            repository_id: id.to_proto(),
-                                            paths: entries
-                                                .into_iter()
-                                                .map(|repo_path| repo_path.to_proto())
-                                                .collect(),
-                                        })
-                                        .await
-                                        .context("sending stage request")?;
-
-                                    Ok(())
-                                }
-                            }
-                        },
-                    )
-                })?
-                .await?
-            },
-        )
+        self.stage_or_unstage_entries(true, entries, cx)
     }
 
     pub fn unstage_entries(
         &mut self,
         entries: Vec<RepoPath>,
         cx: &mut Context<Self>,
+    ) -> Task<anyhow::Result<()>> {
+        self.stage_or_unstage_entries(false, entries, cx)
+    }
+
+    fn stage_or_unstage_entries(
+        &mut self,
+        stage: bool,
+        entries: Vec<RepoPath>,
+        cx: &mut Context<Self>,
     ) -> Task<anyhow::Result<()>> {
         if entries.is_empty() {
             return Task::ready(Ok(()));
         }
+        let Some(git_store) = self.git_store.upgrade() else {
+            return Task::ready(Ok(()));
+        };
         let id = self.id;
         let save_tasks = self.save_buffers(&entries, cx);
         let paths = entries
@@ -4232,48 +4232,164 @@ impl Repository {
             .map(|p| p.as_unix_str())
             .collect::<Vec<_>>()
             .join(" ");
-        let status = format!("git reset {paths}");
+        let status = if stage {
+            format!("git add {paths}")
+        } else {
+            format!("git reset {paths}")
+        };
         let job_key = GitJobKey::WriteIndex(entries.clone());
 
         self.spawn_job_with_tracking(
             entries.clone(),
-            pending_op::GitStatus::Unstaged,
+            if stage {
+                pending_op::GitStatus::Staged
+            } else {
+                pending_op::GitStatus::Unstaged
+            },
             cx,
             async move |this, cx| {
                 for save_task in save_tasks {
                     save_task.await?;
                 }
 
-                this.update(cx, |this, _| {
+                this.update(cx, |this, cx| {
+                    let weak_this = cx.weak_entity();
                     this.send_keyed_job(
                         Some(job_key),
                         Some(status.into()),
-                        move |git_repo, _cx| async move {
-                            match git_repo {
+                        move |git_repo, mut cx| async move {
+                            let hunk_staging_operation_counts = weak_this
+                                .update(&mut cx, |this, cx| {
+                                    let mut hunk_staging_operation_counts = HashMap::default();
+                                    for path in &entries {
+                                        let Some(project_path) =
+                                            this.repo_path_to_project_path(path, cx)
+                                        else {
+                                            continue;
+                                        };
+                                        let Some(buffer) = git_store
+                                            .read(cx)
+                                            .buffer_store
+                                            .read(cx)
+                                            .get_by_path(&project_path)
+                                        else {
+                                            continue;
+                                        };
+                                        let Some(diff_state) = git_store
+                                            .read(cx)
+                                            .diffs
+                                            .get(&buffer.read(cx).remote_id())
+                                            .cloned()
+                                        else {
+                                            continue;
+                                        };
+                                        let Some(uncommitted_diff) =
+                                            diff_state.read(cx).uncommitted_diff.as_ref().and_then(
+                                                |uncommitted_diff| uncommitted_diff.upgrade(),
+                                            )
+                                        else {
+                                            continue;
+                                        };
+                                        let buffer_snapshot = buffer.read(cx).text_snapshot();
+                                        let file_exists = buffer
+                                            .read(cx)
+                                            .file()
+                                            .is_some_and(|file| file.disk_state().exists());
+                                        let hunk_staging_operation_count =
+                                            diff_state.update(cx, |diff_state, cx| {
+                                                uncommitted_diff.update(
+                                                    cx,
+                                                    |uncommitted_diff, cx| {
+                                                        uncommitted_diff
+                                                            .stage_or_unstage_all_hunks(
+                                                                stage,
+                                                                &buffer_snapshot,
+                                                                file_exists,
+                                                                cx,
+                                                            );
+                                                    },
+                                                );
+
+                                                diff_state.hunk_staging_operation_count += 1;
+                                                diff_state.hunk_staging_operation_count
+                                            });
+                                        hunk_staging_operation_counts.insert(
+                                            diff_state.downgrade(),
+                                            hunk_staging_operation_count,
+                                        );
+                                    }
+                                    hunk_staging_operation_counts
+                                })
+                                .unwrap_or_default();
+
+                            let result = match git_repo {
                                 RepositoryState::Local(LocalRepositoryState {
                                     backend,
                                     environment,
                                     ..
-                                }) => backend.unstage_paths(entries, environment).await,
+                                }) => {
+                                    if stage {
+                                        backend.stage_paths(entries, environment.clone()).await
+                                    } else {
+                                        backend.unstage_paths(entries, environment.clone()).await
+                                    }
+                                }
                                 RepositoryState::Remote(RemoteRepositoryState {
                                     project_id,
                                     client,
                                 }) => {
-                                    client
-                                        .request(proto::Unstage {
-                                            project_id: project_id.0,
-                                            repository_id: id.to_proto(),
-                                            paths: entries
-                                                .into_iter()
-                                                .map(|repo_path| repo_path.to_proto())
-                                                .collect(),
-                                        })
-                                        .await
-                                        .context("sending unstage request")?;
-
-                                    Ok(())
+                                    if stage {
+                                        client
+                                            .request(proto::Stage {
+                                                project_id: project_id.0,
+                                                repository_id: id.to_proto(),
+                                                paths: entries
+                                                    .into_iter()
+                                                    .map(|repo_path| repo_path.to_proto())
+                                                    .collect(),
+                                            })
+                                            .await
+                                            .context("sending stage request")
+                                            .map(|_| ())
+                                    } else {
+                                        client
+                                            .request(proto::Unstage {
+                                                project_id: project_id.0,
+                                                repository_id: id.to_proto(),
+                                                paths: entries
+                                                    .into_iter()
+                                                    .map(|repo_path| repo_path.to_proto())
+                                                    .collect(),
+                                            })
+                                            .await
+                                            .context("sending unstage request")
+                                            .map(|_| ())
+                                    }
                                 }
+                            };
+
+                            for (diff_state, hunk_staging_operation_count) in
+                                hunk_staging_operation_counts
+                            {
+                                diff_state
+                                    .update(&mut cx, |diff_state, cx| {
+                                        if result.is_ok() {
+                                            diff_state.hunk_staging_operation_count_as_of_write =
+                                                hunk_staging_operation_count;
+                                        } else if let Some(uncommitted_diff) =
+                                            &diff_state.uncommitted_diff
+                                        {
+                                            uncommitted_diff
+                                                .update(cx, |uncommitted_diff, cx| {
+                                                    uncommitted_diff.clear_pending_hunks(cx);
+                                                })
+                                                .ok();
+                                        }
+                                    })
+                                    .ok();
                             }
+
+                            result
                         },
                     )
                 })?
@@ -4299,7 +4415,7 @@ impl Repository {
                 }
             })
             .collect();
-        self.stage_entries(to_stage, cx)
+        self.stage_or_unstage_entries(true, to_stage, cx)
     }
 
     pub fn unstage_all(&mut self, cx: &mut Context<Self>) -> Task<anyhow::Result<()>> {
@@ -4319,7 +4435,7 @@ impl Repository {
                 }
             })
             .collect();
-        self.unstage_entries(to_unstage, cx)
+        self.stage_or_unstage_entries(false, to_unstage, cx)
     }
 
     pub fn stash_all(&mut self, cx: &mut Context<Self>) -> Task<anyhow::Result<()>> {
@@ -4645,11 +4761,9 @@ impl Repository {
             });
 
         let this = cx.weak_entity();
-        let rx = self.run_hook(RunHook::PrePush, cx);
         self.send_job(
             Some(format!("git push {} {} {}", args, remote, branch).into()),
             move |git_repo, mut cx| async move {
-                rx.await??;
                 match git_repo {
                     RepositoryState::Local(LocalRepositoryState {
                         backend,
@@ -4861,6 +4975,61 @@ impl Repository {
         )
     }
 
+    pub fn create_remote(
+        &mut self,
+        remote_name: String,
+        remote_url: String,
+    ) -> oneshot::Receiver<Result<()>> {
+        let id = self.id;
+        self.send_job(
+            Some(format!("git remote add {remote_name} {remote_url}").into()),
+            move |repo, _cx| async move {
+                match repo {
+                    RepositoryState::Local(LocalRepositoryState { backend, .. }) => {
+                        backend.create_remote(remote_name, remote_url).await
+                    }
+                    RepositoryState::Remote(RemoteRepositoryState { project_id, client }) => {
+                        client
+                            .request(proto::GitCreateRemote {
+                                project_id: project_id.0,
+                                repository_id: id.to_proto(),
+                                remote_name,
+                                remote_url,
+                            })
+                            .await?;
+
+                        Ok(())
+                    }
+                }
+            },
+        )
+    }
+
+    pub fn remove_remote(&mut self, remote_name: String) -> oneshot::Receiver<Result<()>> {
+        let id = self.id;
+        self.send_job(
+            Some(format!("git remove remote {remote_name}").into()),
+            move |repo, _cx| async move {
+                match repo {
+                    RepositoryState::Local(LocalRepositoryState { backend, .. }) => {
+                        backend.remove_remote(remote_name).await
+                    }
+                    RepositoryState::Remote(RemoteRepositoryState { project_id, client }) => {
+                        client
+                            .request(proto::GitRemoveRemote {
+                                project_id: project_id.0,
+                                repository_id: id.to_proto(),
+                                remote_name,
+                            })
+                            .await?;
+
+                        Ok(())
+                    }
+                }
+            },
+        )
+    }
+
     pub fn get_remotes(
         &mut self,
         branch_name: Option<String>,
@@ -4898,7 +5067,7 @@ impl Repository {
                     let remotes = response
                         .remotes
                         .into_iter()
-                        .map(|remotes| git::repository::Remote {
+                        .map(|remotes| Remote {
                             name: remotes.name.into(),
                         })
                         .collect();
@@ -5297,6 +5466,8 @@ impl Repository {
             cx.emit(RepositoryEvent::StashEntriesChanged)
         }
         self.snapshot.stash_entries = new_stash_entries;
+        self.snapshot.remote_upstream_url = update.remote_upstream_url;
+        self.snapshot.remote_origin_url = update.remote_origin_url;
 
         let edits = update
             .removed_statuses
@@ -5444,7 +5615,8 @@ impl Repository {
                 git_hosting_providers::register_additional_providers(
                     git_hosting_provider_registry,
                     state.backend.clone(),
-                );
+                )
+                .await;
             }
             let state = RepositoryState::Local(state);
             let mut jobs = VecDeque::new();
@@ -5581,6 +5753,7 @@ impl Repository {
 
         cx.spawn(|_: &mut AsyncApp| async move { rx.await? })
     }
+
     fn load_blob_content(&mut self, oid: Oid, cx: &App) -> Task<Result<String>> {
         let repository_id = self.snapshot.id;
         let rx = self.send_job(None, move |state, _| async move {
@@ -5763,6 +5936,11 @@ impl Repository {
         self.pending_ops.edit(edits, ());
         ids
     }
+    pub fn default_remote_url(&self) -> Option<String> {
+        self.remote_upstream_url
+            .clone()
+            .or(self.remote_origin_url.clone())
+    }
 }
 
 fn get_permalink_in_rust_registry_src(
@@ -5855,11 +6033,7 @@ fn serialize_blame_buffer_response(blame: Option<git::blame::Blame>) -> proto::B
         .collect::<Vec<_>>();
 
     proto::BlameBufferResponse {
-        blame_response: Some(proto::blame_buffer_response::BlameResponse {
-            entries,
-            messages,
-            remote_url: blame.remote_url,
-        }),
+        blame_response: Some(proto::blame_buffer_response::BlameResponse { entries, messages }),
     }
 }
 
@@ -5896,11 +6070,7 @@ fn deserialize_blame_buffer_response(
         .filter_map(|message| Some((git::Oid::from_bytes(&message.oid).ok()?, message.message)))
         .collect::<HashMap<_, _>>();
 
-    Some(Blame {
-        entries,
-        messages,
-        remote_url: response.remote_url,
-    })
+    Some(Blame { entries, messages })
 }
 
 fn branch_to_proto(branch: &git::repository::Branch) -> proto::Branch {
@@ -6048,9 +6218,8 @@ async fn compute_snapshot(
         events.push(RepositoryEvent::BranchChanged);
     }
 
-    // Used by edit prediction data collection
-    let remote_origin_url = backend.remote_url("origin");
-    let remote_upstream_url = backend.remote_url("upstream");
+    let remote_origin_url = backend.remote_url("origin").await;
+    let remote_upstream_url = backend.remote_url("upstream").await;
 
     let snapshot = RepositorySnapshot {
         id,

crates/project/src/git_store/branch_diff.rs 🔗

@@ -14,6 +14,7 @@ use gpui::{
 use language::Buffer;
 use text::BufferId;
 use util::ResultExt;
+use ztracing::instrument;
 
 use crate::{
     Project,
@@ -254,6 +255,7 @@ impl BranchDiff {
         self.repo.as_ref()
     }
 
+    #[instrument(skip_all)]
     pub fn load_buffers(&mut self, cx: &mut Context<Self>) -> Vec<DiffBuffer> {
         let mut output = Vec::default();
         let Some(repo) = self.repo.clone() else {
@@ -318,6 +320,7 @@ impl BranchDiff {
         output
     }
 
+    #[instrument(skip_all)]
     fn load_buffer(
         branch_diff: Option<git::status::TreeDiffStatus>,
         project_path: crate::ProjectPath,

crates/project/src/git_store/conflict_set.rs 🔗

@@ -1,4 +1,4 @@
-use gpui::{App, Context, Entity, EventEmitter};
+use gpui::{App, Context, Entity, EventEmitter, SharedString};
 use std::{cmp::Ordering, ops::Range, sync::Arc};
 use text::{Anchor, BufferId, OffsetRangeExt as _};
 
@@ -92,6 +92,8 @@ impl ConflictSetSnapshot {
 
 #[derive(Debug, Clone, PartialEq, Eq)]
 pub struct ConflictRegion {
+    pub ours_branch_name: SharedString,
+    pub theirs_branch_name: SharedString,
     pub range: Range<Anchor>,
     pub ours: Range<Anchor>,
     pub theirs: Range<Anchor>,
@@ -179,18 +181,25 @@ impl ConflictSet {
         let mut conflict_start: Option<usize> = None;
         let mut ours_start: Option<usize> = None;
         let mut ours_end: Option<usize> = None;
+        let mut ours_branch_name: Option<SharedString> = None;
         let mut base_start: Option<usize> = None;
         let mut base_end: Option<usize> = None;
         let mut theirs_start: Option<usize> = None;
+        let mut theirs_branch_name: Option<SharedString> = None;
 
         while let Some(line) = lines.next() {
             let line_end = line_pos + line.len();
 
-            if line.starts_with("<<<<<<< ") {
+            if let Some(branch_name) = line.strip_prefix("<<<<<<< ") {
                 // If we see a new conflict marker while already parsing one,
                 // abandon the previous one and start a new one
                 conflict_start = Some(line_pos);
                 ours_start = Some(line_end + 1);
+
+                let branch_name = branch_name.trim();
+                if !branch_name.is_empty() {
+                    ours_branch_name = Some(SharedString::new(branch_name));
+                }
             } else if line.starts_with("||||||| ")
                 && conflict_start.is_some()
                 && ours_start.is_some()
@@ -208,12 +217,17 @@ impl ConflictSet {
                     base_end = Some(line_pos);
                 }
                 theirs_start = Some(line_end + 1);
-            } else if line.starts_with(">>>>>>> ")
+            } else if let Some(branch_name) = line.strip_prefix(">>>>>>> ")
                 && conflict_start.is_some()
                 && ours_start.is_some()
                 && ours_end.is_some()
                 && theirs_start.is_some()
             {
+                let branch_name = branch_name.trim();
+                if !branch_name.is_empty() {
+                    theirs_branch_name = Some(SharedString::new(branch_name));
+                }
+
                 let theirs_end = line_pos;
                 let conflict_end = (line_end + 1).min(buffer_len);
 
@@ -229,6 +243,12 @@ impl ConflictSet {
                     .map(|(start, end)| buffer.anchor_after(start)..buffer.anchor_before(end));
 
                 conflicts.push(ConflictRegion {
+                    ours_branch_name: ours_branch_name
+                        .take()
+                        .unwrap_or_else(|| SharedString::new_static("HEAD")),
+                    theirs_branch_name: theirs_branch_name
+                        .take()
+                        .unwrap_or_else(|| SharedString::new_static("Origin")),
                     range,
                     ours,
                     theirs,
@@ -304,6 +324,8 @@ mod tests {
 
         let first = &conflict_snapshot.conflicts[0];
         assert!(first.base.is_none());
+        assert_eq!(first.ours_branch_name.as_ref(), "HEAD");
+        assert_eq!(first.theirs_branch_name.as_ref(), "branch-name");
         let our_text = snapshot
             .text_for_range(first.ours.clone())
             .collect::<String>();
@@ -315,6 +337,8 @@ mod tests {
 
         let second = &conflict_snapshot.conflicts[1];
         assert!(second.base.is_some());
+        assert_eq!(second.ours_branch_name.as_ref(), "HEAD");
+        assert_eq!(second.theirs_branch_name.as_ref(), "branch-name");
         let our_text = snapshot
             .text_for_range(second.ours.clone())
             .collect::<String>();
@@ -381,6 +405,8 @@ mod tests {
         // The conflict should have our version, their version, but no base
         let conflict = &conflict_snapshot.conflicts[0];
         assert!(conflict.base.is_none());
+        assert_eq!(conflict.ours_branch_name.as_ref(), "HEAD");
+        assert_eq!(conflict.theirs_branch_name.as_ref(), "branch-nested");
 
         // Check that the nested conflict was detected correctly
         let our_text = snapshot
@@ -407,6 +433,14 @@ mod tests {
 
         let conflict_snapshot = ConflictSet::parse(&snapshot);
         assert_eq!(conflict_snapshot.conflicts.len(), 1);
+        assert_eq!(
+            conflict_snapshot.conflicts[0].ours_branch_name.as_ref(),
+            "ours"
+        );
+        assert_eq!(
+            conflict_snapshot.conflicts[0].theirs_branch_name.as_ref(),
+            "Origin" // default branch name if there is none
+        );
     }
 
     #[test]
@@ -449,6 +483,38 @@ mod tests {
 
         let conflict_snapshot = ConflictSet::parse(&snapshot);
         assert_eq!(conflict_snapshot.conflicts.len(), 4);
+        assert_eq!(
+            conflict_snapshot.conflicts[0].ours_branch_name.as_ref(),
+            "HEAD1"
+        );
+        assert_eq!(
+            conflict_snapshot.conflicts[0].theirs_branch_name.as_ref(),
+            "branch1"
+        );
+        assert_eq!(
+            conflict_snapshot.conflicts[1].ours_branch_name.as_ref(),
+            "HEAD2"
+        );
+        assert_eq!(
+            conflict_snapshot.conflicts[1].theirs_branch_name.as_ref(),
+            "branch2"
+        );
+        assert_eq!(
+            conflict_snapshot.conflicts[2].ours_branch_name.as_ref(),
+            "HEAD3"
+        );
+        assert_eq!(
+            conflict_snapshot.conflicts[2].theirs_branch_name.as_ref(),
+            "branch3"
+        );
+        assert_eq!(
+            conflict_snapshot.conflicts[3].ours_branch_name.as_ref(),
+            "HEAD4"
+        );
+        assert_eq!(
+            conflict_snapshot.conflicts[3].theirs_branch_name.as_ref(),
+            "branch4"
+        );
 
         let range = test_content.find("seven").unwrap()..test_content.find("eleven").unwrap();
         let range = buffer.anchor_before(range.start)..buffer.anchor_after(range.end);

crates/project/src/invalid_item_view.rs 🔗

@@ -1,118 +0,0 @@
-use std::{path::Path, sync::Arc};
-
-use gpui::{EventEmitter, FocusHandle, Focusable};
-use ui::{
-    App, Button, ButtonCommon, ButtonStyle, Clickable, Context, FluentBuilder, InteractiveElement,
-    KeyBinding, Label, LabelCommon, LabelSize, ParentElement, Render, SharedString, Styled as _,
-    Window, h_flex, v_flex,
-};
-use zed_actions::workspace::OpenWithSystem;
-
-use crate::Item;
-
-/// A view to display when a certain buffer fails to open.
-#[derive(Debug)]
-pub struct InvalidItemView {
-    /// Which path was attempted to open.
-    pub abs_path: Arc<Path>,
-    /// An error message, happened when opening the buffer.
-    pub error: SharedString,
-    is_local: bool,
-    focus_handle: FocusHandle,
-}
-
-impl InvalidItemView {
-    pub fn new(
-        abs_path: &Path,
-        is_local: bool,
-        e: &anyhow::Error,
-        _: &mut Window,
-        cx: &mut App,
-    ) -> Self {
-        Self {
-            is_local,
-            abs_path: Arc::from(abs_path),
-            error: format!("{}", e.root_cause()).into(),
-            focus_handle: cx.focus_handle(),
-        }
-    }
-}
-
-impl Item for InvalidItemView {
-    type Event = ();
-
-    fn tab_content_text(&self, mut detail: usize, _: &App) -> SharedString {
-        // Ensure we always render at least the filename.
-        detail += 1;
-
-        let path = self.abs_path.as_ref();
-
-        let mut prefix = path;
-        while detail > 0 {
-            if let Some(parent) = prefix.parent() {
-                prefix = parent;
-                detail -= 1;
-            } else {
-                break;
-            }
-        }
-
-        let path = if detail > 0 {
-            path
-        } else {
-            path.strip_prefix(prefix).unwrap_or(path)
-        };
-
-        SharedString::new(path.to_string_lossy())
-    }
-}
-
-impl EventEmitter<()> for InvalidItemView {}
-
-impl Focusable for InvalidItemView {
-    fn focus_handle(&self, _: &App) -> FocusHandle {
-        self.focus_handle.clone()
-    }
-}
-
-impl Render for InvalidItemView {
-    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl gpui::IntoElement {
-        let abs_path = self.abs_path.clone();
-        v_flex()
-            .size_full()
-            .track_focus(&self.focus_handle(cx))
-            .flex_none()
-            .justify_center()
-            .overflow_hidden()
-            .key_context("InvalidBuffer")
-            .child(
-                h_flex().size_full().justify_center().child(
-                    v_flex()
-                        .justify_center()
-                        .gap_2()
-                        .child(h_flex().justify_center().child("Could not open file"))
-                        .child(
-                            h_flex()
-                                .justify_center()
-                                .child(Label::new(self.error.clone()).size(LabelSize::Small)),
-                        )
-                        .when(self.is_local, |contents| {
-                            contents.child(
-                                h_flex().justify_center().child(
-                                    Button::new("open-with-system", "Open in Default App")
-                                        .on_click(move |_, _, cx| {
-                                            cx.open_with_system(&abs_path);
-                                        })
-                                        .style(ButtonStyle::Outlined)
-                                        .key_binding(KeyBinding::for_action(
-                                            &OpenWithSystem,
-                                            window,
-                                            cx,
-                                        )),
-                                ),
-                            )
-                        }),
-                ),
-            )
-    }
-}

crates/project/src/lsp_command.rs 🔗

@@ -14,7 +14,7 @@ use client::proto::{self, PeerId};
 use clock::Global;
 use collections::{HashMap, HashSet};
 use futures::future;
-use gpui::{App, AsyncApp, Entity, Task};
+use gpui::{App, AsyncApp, Entity, SharedString, Task};
 use language::{
     Anchor, Bias, Buffer, BufferSnapshot, CachedLspAdapter, CharKind, CharScopeContext,
     OffsetRangeExt, PointUtf16, ToOffset, ToPointUtf16, Transaction, Unclipped,
@@ -26,8 +26,8 @@ use language::{
 use lsp::{
     AdapterServerCapabilities, CodeActionKind, CodeActionOptions, CodeDescription,
     CompletionContext, CompletionListItemDefaultsEditRange, CompletionTriggerKind,
-    DiagnosticServerCapabilities, DocumentHighlightKind, LanguageServer, LanguageServerId,
-    LinkedEditingRangeServerCapabilities, OneOf, RenameOptions, ServerCapabilities,
+    DocumentHighlightKind, LanguageServer, LanguageServerId, LinkedEditingRangeServerCapabilities,
+    OneOf, RenameOptions, ServerCapabilities,
 };
 use serde_json::Value;
 use signature_help::{lsp_to_proto_signature, proto_to_lsp_signature};
@@ -265,8 +265,9 @@ pub(crate) struct LinkedEditingRange {
 pub(crate) struct GetDocumentDiagnostics {
     /// We cannot blindly rely on server's capabilities.diagnostic_provider, as they're a singular field, whereas
     /// a server can register multiple diagnostic providers post-mortem.
-    pub dynamic_caps: DiagnosticServerCapabilities,
-    pub previous_result_id: Option<String>,
+    pub registration_id: Option<SharedString>,
+    pub identifier: Option<String>,
+    pub previous_result_id: Option<SharedString>,
 }
 
 #[async_trait(?Send)]
@@ -3755,15 +3756,16 @@ impl GetDocumentDiagnostics {
             .into_iter()
             .filter_map(|diagnostics| {
                 Some(LspPullDiagnostics::Response {
+                    registration_id: diagnostics.registration_id.map(SharedString::from),
                     server_id: LanguageServerId::from_proto(diagnostics.server_id),
                     uri: lsp::Uri::from_str(diagnostics.uri.as_str()).log_err()?,
                     diagnostics: if diagnostics.changed {
                         PulledDiagnostics::Unchanged {
-                            result_id: diagnostics.result_id?,
+                            result_id: SharedString::new(diagnostics.result_id?),
                         }
                     } else {
                         PulledDiagnostics::Changed {
-                            result_id: diagnostics.result_id,
+                            result_id: diagnostics.result_id.map(SharedString::new),
                             diagnostics: diagnostics
                                 .diagnostics
                                 .into_iter()
@@ -3927,6 +3929,7 @@ impl GetDocumentDiagnostics {
     pub fn deserialize_workspace_diagnostics_report(
         report: lsp::WorkspaceDiagnosticReportResult,
         server_id: LanguageServerId,
+        registration_id: Option<SharedString>,
     ) -> Vec<WorkspaceLspPullDiagnostics> {
         let mut pulled_diagnostics = HashMap::default();
         match report {
@@ -3938,6 +3941,7 @@ impl GetDocumentDiagnostics {
                                 &mut pulled_diagnostics,
                                 server_id,
                                 report,
+                                registration_id.clone(),
                             )
                         }
                         lsp::WorkspaceDocumentDiagnosticReport::Unchanged(report) => {
@@ -3945,6 +3949,7 @@ impl GetDocumentDiagnostics {
                                 &mut pulled_diagnostics,
                                 server_id,
                                 report,
+                                registration_id.clone(),
                             )
                         }
                     }
@@ -3960,6 +3965,7 @@ impl GetDocumentDiagnostics {
                                 &mut pulled_diagnostics,
                                 server_id,
                                 report,
+                                registration_id.clone(),
                             )
                         }
                         lsp::WorkspaceDocumentDiagnosticReport::Unchanged(report) => {
@@ -3967,6 +3973,7 @@ impl GetDocumentDiagnostics {
                                 &mut pulled_diagnostics,
                                 server_id,
                                 report,
+                                registration_id.clone(),
                             )
                         }
                     }
@@ -3987,6 +3994,7 @@ fn process_full_workspace_diagnostics_report(
     diagnostics: &mut HashMap<lsp::Uri, WorkspaceLspPullDiagnostics>,
     server_id: LanguageServerId,
     report: lsp::WorkspaceFullDocumentDiagnosticReport,
+    registration_id: Option<SharedString>,
 ) {
     let mut new_diagnostics = HashMap::default();
     process_full_diagnostics_report(
@@ -3994,6 +4002,7 @@ fn process_full_workspace_diagnostics_report(
         server_id,
         report.uri,
         report.full_document_diagnostic_report,
+        registration_id,
     );
     diagnostics.extend(new_diagnostics.into_iter().map(|(uri, diagnostics)| {
         (
@@ -4010,6 +4019,7 @@ fn process_unchanged_workspace_diagnostics_report(
     diagnostics: &mut HashMap<lsp::Uri, WorkspaceLspPullDiagnostics>,
     server_id: LanguageServerId,
     report: lsp::WorkspaceUnchangedDocumentDiagnosticReport,
+    registration_id: Option<SharedString>,
 ) {
     let mut new_diagnostics = HashMap::default();
     process_unchanged_diagnostics_report(
@@ -4017,6 +4027,7 @@ fn process_unchanged_workspace_diagnostics_report(
         server_id,
         report.uri,
         report.unchanged_document_diagnostic_report,
+        registration_id,
     );
     diagnostics.extend(new_diagnostics.into_iter().map(|(uri, diagnostics)| {
         (
@@ -4050,19 +4061,12 @@ impl LspCommand for GetDocumentDiagnostics {
         _: &Arc<LanguageServer>,
         _: &App,
     ) -> Result<lsp::DocumentDiagnosticParams> {
-        let identifier = match &self.dynamic_caps {
-            lsp::DiagnosticServerCapabilities::Options(options) => options.identifier.clone(),
-            lsp::DiagnosticServerCapabilities::RegistrationOptions(options) => {
-                options.diagnostic_options.identifier.clone()
-            }
-        };
-
         Ok(lsp::DocumentDiagnosticParams {
             text_document: lsp::TextDocumentIdentifier {
                 uri: file_path_to_lsp_url(path)?,
             },
-            identifier,
-            previous_result_id: self.previous_result_id.clone(),
+            identifier: self.identifier.clone(),
+            previous_result_id: self.previous_result_id.clone().map(|id| id.to_string()),
             partial_result_params: Default::default(),
             work_done_progress_params: Default::default(),
         })
@@ -4097,6 +4101,7 @@ impl LspCommand for GetDocumentDiagnostics {
                             &mut pulled_diagnostics,
                             server_id,
                             related_documents,
+                            self.registration_id.clone(),
                         );
                     }
                     process_full_diagnostics_report(
@@ -4104,6 +4109,7 @@ impl LspCommand for GetDocumentDiagnostics {
                         server_id,
                         url,
                         report.full_document_diagnostic_report,
+                        self.registration_id,
                     );
                 }
                 lsp::DocumentDiagnosticReport::Unchanged(report) => {
@@ -4112,6 +4118,7 @@ impl LspCommand for GetDocumentDiagnostics {
                             &mut pulled_diagnostics,
                             server_id,
                             related_documents,
+                            self.registration_id.clone(),
                         );
                     }
                     process_unchanged_diagnostics_report(
@@ -4119,6 +4126,7 @@ impl LspCommand for GetDocumentDiagnostics {
                         server_id,
                         url,
                         report.unchanged_document_diagnostic_report,
+                        self.registration_id,
                     );
                 }
             },
@@ -4128,6 +4136,7 @@ impl LspCommand for GetDocumentDiagnostics {
                         &mut pulled_diagnostics,
                         server_id,
                         related_documents,
+                        self.registration_id,
                     );
                 }
             }
@@ -4170,6 +4179,7 @@ impl LspCommand for GetDocumentDiagnostics {
                     server_id,
                     uri,
                     diagnostics,
+                    registration_id,
                 } => {
                     let mut changed = false;
                     let (diagnostics, result_id) = match diagnostics {
@@ -4184,7 +4194,7 @@ impl LspCommand for GetDocumentDiagnostics {
                     };
                     Some(proto::PulledDiagnostics {
                         changed,
-                        result_id,
+                        result_id: result_id.map(|id| id.to_string()),
                         uri: uri.to_string(),
                         server_id: server_id.to_proto(),
                         diagnostics: diagnostics
@@ -4195,6 +4205,7 @@ impl LspCommand for GetDocumentDiagnostics {
                                     .log_err()
                             })
                             .collect(),
+                        registration_id: registration_id.as_ref().map(ToString::to_string),
                     })
                 }
             })
@@ -4365,14 +4376,25 @@ fn process_related_documents(
     diagnostics: &mut HashMap<lsp::Uri, LspPullDiagnostics>,
     server_id: LanguageServerId,
     documents: impl IntoIterator<Item = (lsp::Uri, lsp::DocumentDiagnosticReportKind)>,
+    registration_id: Option<SharedString>,
 ) {
     for (url, report_kind) in documents {
         match report_kind {
-            lsp::DocumentDiagnosticReportKind::Full(report) => {
-                process_full_diagnostics_report(diagnostics, server_id, url, report)
-            }
+            lsp::DocumentDiagnosticReportKind::Full(report) => process_full_diagnostics_report(
+                diagnostics,
+                server_id,
+                url,
+                report,
+                registration_id.clone(),
+            ),
             lsp::DocumentDiagnosticReportKind::Unchanged(report) => {
-                process_unchanged_diagnostics_report(diagnostics, server_id, url, report)
+                process_unchanged_diagnostics_report(
+                    diagnostics,
+                    server_id,
+                    url,
+                    report,
+                    registration_id.clone(),
+                )
             }
         }
     }
@@ -4383,8 +4405,9 @@ fn process_unchanged_diagnostics_report(
     server_id: LanguageServerId,
     uri: lsp::Uri,
     report: lsp::UnchangedDocumentDiagnosticReport,
+    registration_id: Option<SharedString>,
 ) {
-    let result_id = report.result_id;
+    let result_id = SharedString::new(report.result_id);
     match diagnostics.entry(uri.clone()) {
         hash_map::Entry::Occupied(mut o) => match o.get_mut() {
             LspPullDiagnostics::Default => {
@@ -4392,12 +4415,14 @@ fn process_unchanged_diagnostics_report(
                     server_id,
                     uri,
                     diagnostics: PulledDiagnostics::Unchanged { result_id },
+                    registration_id,
                 });
             }
             LspPullDiagnostics::Response {
                 server_id: existing_server_id,
                 uri: existing_uri,
                 diagnostics: existing_diagnostics,
+                ..
             } => {
                 if server_id != *existing_server_id || &uri != existing_uri {
                     debug_panic!(
@@ -4417,6 +4442,7 @@ fn process_unchanged_diagnostics_report(
                 server_id,
                 uri,
                 diagnostics: PulledDiagnostics::Unchanged { result_id },
+                registration_id,
             });
         }
     }
@@ -4427,8 +4453,9 @@ fn process_full_diagnostics_report(
     server_id: LanguageServerId,
     uri: lsp::Uri,
     report: lsp::FullDocumentDiagnosticReport,
+    registration_id: Option<SharedString>,
 ) {
-    let result_id = report.result_id;
+    let result_id = report.result_id.map(SharedString::new);
     match diagnostics.entry(uri.clone()) {
         hash_map::Entry::Occupied(mut o) => match o.get_mut() {
             LspPullDiagnostics::Default => {
@@ -4439,12 +4466,14 @@ fn process_full_diagnostics_report(
                         result_id,
                         diagnostics: report.items,
                     },
+                    registration_id,
                 });
             }
             LspPullDiagnostics::Response {
                 server_id: existing_server_id,
                 uri: existing_uri,
                 diagnostics: existing_diagnostics,
+                ..
             } => {
                 if server_id != *existing_server_id || &uri != existing_uri {
                     debug_panic!(
@@ -4478,6 +4507,7 @@ fn process_full_diagnostics_report(
                     result_id,
                     diagnostics: report.items,
                 },
+                registration_id,
             });
         }
     }

crates/project/src/lsp_store.rs 🔗

@@ -38,6 +38,7 @@ use crate::{
     prettier_store::{self, PrettierStore, PrettierStoreEvent},
     project_settings::{LspSettings, ProjectSettings},
     toolchain_store::{LocalToolchainStore, ToolchainStoreEvent},
+    trusted_worktrees::{PathTrust, TrustedWorktrees, TrustedWorktreesEvent},
     worktree_store::{WorktreeStore, WorktreeStoreEvent},
     yarn::YarnPathStore,
 };
@@ -54,8 +55,8 @@ use futures::{
 };
 use globset::{Glob, GlobBuilder, GlobMatcher, GlobSet, GlobSetBuilder};
 use gpui::{
-    App, AppContext, AsyncApp, Context, Entity, EventEmitter, PromptLevel, SharedString, Task,
-    WeakEntity,
+    App, AppContext, AsyncApp, Context, Entity, EventEmitter, PromptLevel, SharedString,
+    Subscription, Task, WeakEntity,
 };
 use http_client::HttpClient;
 use itertools::Itertools as _;
@@ -92,17 +93,19 @@ use rpc::{
     AnyProtoClient, ErrorCode, ErrorExt as _,
     proto::{LspRequestId, LspRequestMessage as _},
 };
+use semver::Version;
 use serde::Serialize;
 use serde_json::Value;
 use settings::{Settings, SettingsLocation, SettingsStore};
 use sha2::{Digest, Sha256};
-use smol::channel::Sender;
+use smol::channel::{Receiver, Sender};
 use snippet::Snippet;
 use std::{
     any::TypeId,
     borrow::Cow,
     cell::RefCell,
     cmp::{Ordering, Reverse},
+    collections::hash_map,
     convert::TryInto,
     ffi::OsStr,
     future::ready,
@@ -116,6 +119,7 @@ use std::{
         atomic::{self, AtomicUsize},
     },
     time::{Duration, Instant},
+    vec,
 };
 use sum_tree::Dimensions;
 use text::{Anchor, BufferId, LineEnding, OffsetRangeExt, ToPoint as _};
@@ -124,6 +128,7 @@ use util::{
     ConnectionResult, ResultExt as _, debug_panic, defer, maybe, merge_json_value_into,
     paths::{PathStyle, SanitizedPath},
     post_inc,
+    redact::redact_command,
     rel_path::RelPath,
 };
 
@@ -200,7 +205,10 @@ pub enum LspFormatTarget {
     Ranges(BTreeMap<BufferId, Vec<Range<Anchor>>>),
 }
 
-pub type OpenLspBufferHandle = Entity<Entity<Buffer>>;
+#[derive(Clone, PartialEq, Eq, Hash)]
+pub struct OpenLspBufferHandle(Entity<OpenLspBuffer>);
+
+struct OpenLspBuffer(Entity<Buffer>);
 
 impl FormatTrigger {
     fn from_proto(value: i32) -> FormatTrigger {
@@ -218,7 +226,7 @@ struct UnifiedLanguageServer {
     project_roots: HashSet<Arc<RelPath>>,
 }
 
-#[derive(Clone, Hash, PartialEq, Eq)]
+#[derive(Clone, Debug, Hash, PartialEq, Eq)]
 struct LanguageServerSeed {
     worktree_id: WorktreeId,
     name: LanguageServerName,
@@ -229,7 +237,8 @@ struct LanguageServerSeed {
 #[derive(Debug)]
 pub struct DocumentDiagnosticsUpdate<'a, D> {
     pub diagnostics: D,
-    pub result_id: Option<String>,
+    pub result_id: Option<SharedString>,
+    pub registration_id: Option<SharedString>,
     pub server_id: LanguageServerId,
     pub disk_based_sources: Cow<'a, [String]>,
 }
@@ -248,7 +257,7 @@ struct DynamicRegistrations {
 
 pub struct LocalLspStore {
     weak: WeakEntity<LspStore>,
-    worktree_store: Entity<WorktreeStore>,
+    pub worktree_store: Entity<WorktreeStore>,
     toolchain_store: Entity<LocalToolchainStore>,
     http_client: Arc<dyn HttpClient>,
     environment: Entity<ProjectEnvironment>,
@@ -283,7 +292,15 @@ pub struct LocalLspStore {
     lsp_tree: LanguageServerTree,
     registered_buffers: HashMap<BufferId, usize>,
     buffers_opened_in_servers: HashMap<BufferId, HashSet<LanguageServerId>>,
-    buffer_pull_diagnostics_result_ids: HashMap<LanguageServerId, HashMap<PathBuf, Option<String>>>,
+    buffer_pull_diagnostics_result_ids: HashMap<
+        LanguageServerId,
+        HashMap<Option<SharedString>, HashMap<PathBuf, Option<SharedString>>>,
+    >,
+    workspace_pull_diagnostics_result_ids: HashMap<
+        LanguageServerId,
+        HashMap<Option<SharedString>, HashMap<PathBuf, Option<SharedString>>>,
+    >,
+    restricted_worktrees_tasks: HashMap<WorktreeId, (Subscription, Receiver<()>)>,
 }
 
 impl LocalLspStore {
@@ -355,7 +372,8 @@ impl LocalLspStore {
     ) -> LanguageServerId {
         let worktree = worktree_handle.read(cx);
 
-        let root_path = worktree.abs_path();
+        let worktree_id = worktree.id();
+        let worktree_abs_path = worktree.abs_path();
         let toolchain = key.toolchain.clone();
         let override_options = settings.initialization_options.clone();
 
@@ -363,19 +381,49 @@ impl LocalLspStore {
 
         let server_id = self.languages.next_language_server_id();
         log::trace!(
-            "attempting to start language server {:?}, path: {root_path:?}, id: {server_id}",
+            "attempting to start language server {:?}, path: {worktree_abs_path:?}, id: {server_id}",
             adapter.name.0
         );
 
+        let untrusted_worktree_task =
+            TrustedWorktrees::try_get_global(cx).and_then(|trusted_worktrees| {
+                let can_trust = trusted_worktrees.update(cx, |trusted_worktrees, cx| {
+                    trusted_worktrees.can_trust(worktree_id, cx)
+                });
+                if can_trust {
+                    self.restricted_worktrees_tasks.remove(&worktree_id);
+                    None
+                } else {
+                    match self.restricted_worktrees_tasks.entry(worktree_id) {
+                        hash_map::Entry::Occupied(o) => Some(o.get().1.clone()),
+                        hash_map::Entry::Vacant(v) => {
+                            let (tx, rx) = smol::channel::bounded::<()>(1);
+                            let subscription = cx.subscribe(&trusted_worktrees, move |_, e, _| {
+                                if let TrustedWorktreesEvent::Trusted(_, trusted_paths) = e {
+                                    if trusted_paths.contains(&PathTrust::Worktree(worktree_id)) {
+                                        tx.send_blocking(()).ok();
+                                    }
+                                }
+                            });
+                            v.insert((subscription, rx.clone()));
+                            Some(rx)
+                        }
+                    }
+                }
+            });
+        let update_binary_status = untrusted_worktree_task.is_none();
+
         let binary = self.get_language_server_binary(
+            worktree_abs_path.clone(),
             adapter.clone(),
             settings,
             toolchain.clone(),
             delegate.clone(),
             true,
+            untrusted_worktree_task,
             cx,
         );
-        let pending_workspace_folders: Arc<Mutex<BTreeSet<Uri>>> = Default::default();
+        let pending_workspace_folders = Arc::<Mutex<BTreeSet<Uri>>>::default();
 
         let pending_server = cx.spawn({
             let adapter = adapter.clone();
@@ -408,7 +456,7 @@ impl LocalLspStore {
                     server_id,
                     server_name,
                     binary,
-                    &root_path,
+                    &worktree_abs_path,
                     code_action_kinds,
                     Some(pending_workspace_folders),
                     cx,
@@ -530,9 +578,12 @@ impl LocalLspStore {
                                 },
                             },
                         );
-                        log::error!("Failed to start language server {server_name:?}: {err:?}");
+                        log::error!(
+                            "Failed to start language server {server_name:?}: {}",
+                            redact_command(&format!("{err:?}"))
+                        );
                         if !log.is_empty() {
-                            log::error!("server stderr: {log}");
+                            log::error!("server stderr: {}", redact_command(&log));
                         }
                         None
                     }
@@ -544,8 +595,10 @@ impl LocalLspStore {
             pending_workspace_folders,
         };
 
-        self.languages
-            .update_lsp_binary_status(adapter.name(), BinaryStatus::Starting);
+        if update_binary_status {
+            self.languages
+                .update_lsp_binary_status(adapter.name(), BinaryStatus::Starting);
+        }
 
         self.language_servers.insert(server_id, state);
         self.language_server_ids
@@ -559,19 +612,34 @@ impl LocalLspStore {
 
     fn get_language_server_binary(
         &self,
+        worktree_abs_path: Arc<Path>,
         adapter: Arc<CachedLspAdapter>,
         settings: Arc<LspSettings>,
         toolchain: Option<Toolchain>,
         delegate: Arc<dyn LspAdapterDelegate>,
         allow_binary_download: bool,
+        untrusted_worktree_task: Option<Receiver<()>>,
         cx: &mut App,
     ) -> Task<Result<LanguageServerBinary>> {
         if let Some(settings) = &settings.binary
             && let Some(path) = settings.path.as_ref().map(PathBuf::from)
         {
             let settings = settings.clone();
-
+            let languages = self.languages.clone();
             return cx.background_spawn(async move {
+                if let Some(untrusted_worktree_task) = untrusted_worktree_task {
+                    log::info!(
+                        "Waiting for worktree {worktree_abs_path:?} to be trusted, before starting language server {}",
+                        adapter.name(),
+                    );
+                    untrusted_worktree_task.recv().await.ok();
+                    log::info!(
+                        "Worktree {worktree_abs_path:?} is trusted, starting language server {}",
+                        adapter.name(),
+                    );
+                    languages
+                        .update_lsp_binary_status(adapter.name(), BinaryStatus::Starting);
+                }
                 let mut env = delegate.shell_env().await;
                 env.extend(settings.env.unwrap_or_default());
 
@@ -602,6 +670,18 @@ impl LocalLspStore {
         };
 
         cx.spawn(async move |cx| {
+            if let Some(untrusted_worktree_task) = untrusted_worktree_task {
+                log::info!(
+                    "Waiting for worktree {worktree_abs_path:?} to be trusted, before starting language server {}",
+                    adapter.name(),
+                );
+                untrusted_worktree_task.recv().await.ok();
+                log::info!(
+                    "Worktree {worktree_abs_path:?} is trusted, starting language server {}",
+                    adapter.name(),
+                );
+            }
+
             let (existing_binary, maybe_download_binary) = adapter
                 .clone()
                 .get_language_server_command(delegate.clone(), toolchain, lsp_binary_options, cx)
@@ -685,6 +765,7 @@ impl LocalLspStore {
                                     disk_based_sources: Cow::Borrowed(
                                         &adapter.disk_based_diagnostic_sources,
                                     ),
+                                    registration_id: None,
                                 }],
                                 |_, diagnostic, cx| match diagnostic.source_kind {
                                     DiagnosticSourceKind::Other | DiagnosticSourceKind::Pushed => {
@@ -979,12 +1060,15 @@ impl LocalLspStore {
             .on_request::<lsp::request::ShowMessageRequest, _, _>({
                 let this = lsp_store.clone();
                 let name = name.to_string();
+                let adapter = adapter.clone();
                 move |params, cx| {
                     let this = this.clone();
                     let name = name.to_string();
+                    let adapter = adapter.clone();
                     let mut cx = cx.clone();
                     async move {
                         let actions = params.actions.unwrap_or_default();
+                        let message = params.message.clone();
                         let (tx, rx) = smol::channel::bounded(1);
                         let request = LanguageServerPromptRequest {
                             level: match params.typ {
@@ -1005,6 +1089,14 @@ impl LocalLspStore {
                             .is_ok();
                         if did_update {
                             let response = rx.recv().await.ok();
+                            if let Some(ref selected_action) = response {
+                                let context = language::PromptResponseContext {
+                                    message,
+                                    selected_action: selected_action.clone(),
+                                };
+                                adapter.process_prompt_response(&context, &mut cx)
+                            }
+
                             Ok(response)
                         } else {
                             Ok(None)
@@ -2209,12 +2301,10 @@ impl LocalLspStore {
                     && lsp_action.data.is_some()
                     && (lsp_action.command.is_none() || lsp_action.edit.is_none())
                 {
-                    *lsp_action = Box::new(
-                        lang_server
-                            .request::<lsp::request::CodeActionResolveRequest>(*lsp_action.clone())
-                            .await
-                            .into_response()?,
-                    );
+                    **lsp_action = lang_server
+                        .request::<lsp::request::CodeActionResolveRequest>(*lsp_action.clone())
+                        .await
+                        .into_response()?;
                 }
             }
             LspAction::CodeLens(lens) => {
@@ -2256,8 +2346,9 @@ impl LocalLspStore {
                     server_id,
                     None,
                     None,
-                    diagnostics,
+                    None,
                     Vec::new(),
+                    diagnostics,
                     cx,
                 )
                 .log_err();
@@ -2335,7 +2426,8 @@ impl LocalLspStore {
         &mut self,
         buffer: &Entity<Buffer>,
         server_id: LanguageServerId,
-        result_id: Option<String>,
+        registration_id: Option<Option<SharedString>>,
+        result_id: Option<SharedString>,
         version: Option<i32>,
         new_diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
         reused_diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
@@ -2408,11 +2500,15 @@ impl LocalLspStore {
 
         let set = DiagnosticSet::new(sanitized_diagnostics, &snapshot);
         buffer.update(cx, |buffer, cx| {
-            if let Some(abs_path) = File::from_dyn(buffer.file()).map(|f| f.abs_path(cx)) {
-                self.buffer_pull_diagnostics_result_ids
-                    .entry(server_id)
-                    .or_default()
-                    .insert(abs_path, result_id);
+            if let Some(registration_id) = registration_id {
+                if let Some(abs_path) = File::from_dyn(buffer.file()).map(|f| f.abs_path(cx)) {
+                    self.buffer_pull_diagnostics_result_ids
+                        .entry(server_id)
+                        .or_default()
+                        .entry(registration_id)
+                        .or_default()
+                        .insert(abs_path, result_id);
+                }
             }
 
             buffer.update_diagnostics(server_id, set, cx)
@@ -3219,8 +3315,10 @@ impl LocalLspStore {
         )
         .await
         .log_err();
-        this.update(cx, |this, _| {
+        this.update(cx, |this, cx| {
             if let Some(transaction) = transaction {
+                cx.emit(LspStoreEvent::WorkspaceEditApplied(transaction.clone()));
+
                 this.as_local_mut()
                     .unwrap()
                     .last_workspace_edits_by_language_server
@@ -3239,6 +3337,7 @@ impl LocalLspStore {
         id_to_remove: WorktreeId,
         cx: &mut Context<LspStore>,
     ) -> Vec<LanguageServerId> {
+        self.restricted_worktrees_tasks.remove(&id_to_remove);
         self.diagnostics.remove(&id_to_remove);
         self.prettier_store.update(cx, |prettier_store, cx| {
             prettier_store.remove_worktree(id_to_remove, cx);
@@ -3266,6 +3365,8 @@ impl LocalLspStore {
             self.language_servers.remove(server_id_to_remove);
             self.buffer_pull_diagnostics_result_ids
                 .remove(server_id_to_remove);
+            self.workspace_pull_diagnostics_result_ids
+                .remove(server_id_to_remove);
             for buffer_servers in self.buffers_opened_in_servers.values_mut() {
                 buffer_servers.remove(server_id_to_remove);
             }
@@ -3757,11 +3858,13 @@ pub enum LspStoreEvent {
         edits: Vec<(lsp::Range, Snippet)>,
         most_recent_edit: clock::Lamport,
     },
+    WorkspaceEditApplied(ProjectTransaction),
 }
 
 #[derive(Clone, Debug, Serialize)]
 pub struct LanguageServerStatus {
     pub name: LanguageServerName,
+    pub server_version: Option<SharedString>,
     pub pending_work: BTreeMap<ProgressToken, LanguageServerProgress>,
     pub has_pending_diagnostic_updates: bool,
     pub progress_tokens: HashSet<ProgressToken>,
@@ -3952,6 +4055,8 @@ impl LspStore {
                 registered_buffers: HashMap::default(),
                 buffers_opened_in_servers: HashMap::default(),
                 buffer_pull_diagnostics_result_ids: HashMap::default(),
+                workspace_pull_diagnostics_result_ids: HashMap::default(),
+                restricted_worktrees_tasks: HashMap::default(),
                 watched_manifest_filenames: ManifestProvidersStore::global(cx)
                     .manifest_file_names(),
             }),
@@ -4188,7 +4293,7 @@ impl LspStore {
         cx: &mut Context<Self>,
     ) -> OpenLspBufferHandle {
         let buffer_id = buffer.read(cx).remote_id();
-        let handle = cx.new(|_| buffer.clone());
+        let handle = OpenLspBufferHandle(cx.new(|_| OpenLspBuffer(buffer.clone())));
         if let Some(local) = self.as_local_mut() {
             let refcount = local.registered_buffers.entry(buffer_id).or_insert(0);
             if !ignore_refcounts {
@@ -4210,7 +4315,7 @@ impl LspStore {
                 local.register_buffer_with_language_servers(buffer, only_register_servers, cx);
             }
             if !ignore_refcounts {
-                cx.observe_release(&handle, move |lsp_store, buffer, cx| {
+                cx.observe_release(&handle.0, move |lsp_store, buffer, cx| {
                     let refcount = {
                         let local = lsp_store.as_local_mut().unwrap();
                         let Some(refcount) = local.registered_buffers.get_mut(&buffer_id) else {
@@ -4225,9 +4330,50 @@ impl LspStore {
                         lsp_store.lsp_data.remove(&buffer_id);
                         let local = lsp_store.as_local_mut().unwrap();
                         local.registered_buffers.remove(&buffer_id);
+
                         local.buffers_opened_in_servers.remove(&buffer_id);
-                        if let Some(file) = File::from_dyn(buffer.read(cx).file()).cloned() {
-                            local.unregister_old_buffer_from_language_servers(buffer, &file, cx);
+                        if let Some(file) = File::from_dyn(buffer.0.read(cx).file()).cloned() {
+                            local.unregister_old_buffer_from_language_servers(&buffer.0, &file, cx);
+
+                            let buffer_abs_path = file.abs_path(cx);
+                            for (_, buffer_pull_diagnostics_result_ids) in
+                                &mut local.buffer_pull_diagnostics_result_ids
+                            {
+                                buffer_pull_diagnostics_result_ids.retain(
+                                    |_, buffer_result_ids| {
+                                        buffer_result_ids.remove(&buffer_abs_path);
+                                        !buffer_result_ids.is_empty()
+                                    },
+                                );
+                            }
+
+                            let diagnostic_updates = local
+                                .language_servers
+                                .keys()
+                                .cloned()
+                                .map(|server_id| DocumentDiagnosticsUpdate {
+                                    diagnostics: DocumentDiagnostics {
+                                        document_abs_path: buffer_abs_path.clone(),
+                                        version: None,
+                                        diagnostics: Vec::new(),
+                                    },
+                                    result_id: None,
+                                    registration_id: None,
+                                    server_id: server_id,
+                                    disk_based_sources: Cow::Borrowed(&[]),
+                                })
+                                .collect::<Vec<_>>();
+
+                            lsp_store
+                                .merge_diagnostic_entries(
+                                    diagnostic_updates,
+                                    |_, diagnostic, _| {
+                                        diagnostic.source_kind != DiagnosticSourceKind::Pulled
+                                    },
+                                    cx,
+                                )
+                                .context("Clearing diagnostics for the closed buffer")
+                                .log_err();
                         }
                     }
                 })
@@ -6352,7 +6498,7 @@ impl LspStore {
                 server_id == *completion_server_id,
                 "server_id mismatch, applying completion resolve for {server_id} but completion server id is {completion_server_id}"
             );
-            *lsp_completion = Box::new(resolved_completion);
+            **lsp_completion = resolved_completion;
             *resolved = true;
         }
         Ok(())
@@ -6511,7 +6657,7 @@ impl LspStore {
                 server_id == *completion_server_id,
                 "remote server_id mismatch, applying completion resolve for {server_id} but completion server id is {completion_server_id}"
             );
-            *lsp_completion = Box::new(resolved_lsp_completion);
+            **lsp_completion = resolved_lsp_completion;
             *resolved = true;
         }
 
@@ -6700,9 +6846,11 @@ impl LspStore {
             };
             assert!(any_server_has_diagnostics_provider);
 
+            let identifier = buffer_diagnostic_identifier(&dynamic_caps);
             let request = GetDocumentDiagnostics {
                 previous_result_id: None,
-                dynamic_caps,
+                identifier,
+                registration_id: None,
             };
             let request_task = client.request_lsp(
                 upstream_project_id,
@@ -6720,7 +6868,7 @@ impl LspStore {
             })
         } else {
             let servers = buffer.update(cx, |buffer, cx| {
-                self.language_servers_for_local_buffer(buffer, cx)
+                self.running_language_servers_for_local_buffer(buffer, cx)
                     .map(|(_, server)| server.clone())
                     .collect::<Vec<_>>()
             });
@@ -6735,19 +6883,27 @@ impl LspStore {
                             .language_server_dynamic_registrations
                             .get(&server_id)
                             .into_iter()
-                            .flat_map(|registrations| registrations.diagnostics.values().cloned())
+                            .flat_map(|registrations| registrations.diagnostics.clone())
                             .collect::<Vec<_>>();
                         Some(
                             providers_with_identifiers
                                 .into_iter()
-                                .map(|dynamic_caps| {
-                                    let result_id = self.result_id(server_id, buffer_id, cx);
+                                .map(|(registration_id, dynamic_caps)| {
+                                    let identifier = buffer_diagnostic_identifier(&dynamic_caps);
+                                    let registration_id = registration_id.map(SharedString::from);
+                                    let result_id = self.result_id_for_buffer_pull(
+                                        server_id,
+                                        buffer_id,
+                                        &registration_id,
+                                        cx,
+                                    );
                                     self.request_lsp(
                                         buffer.clone(),
                                         LanguageServerToQuery::Other(server_id),
                                         GetDocumentDiagnostics {
                                             previous_result_id: result_id,
-                                            dynamic_caps,
+                                            registration_id,
+                                            identifier,
                                         },
                                         cx,
                                     )
@@ -6776,9 +6932,15 @@ impl LspStore {
         ranges: &[Range<text::Anchor>],
         cx: &mut Context<Self>,
     ) -> Vec<Range<BufferRow>> {
+        let buffer_snapshot = buffer.read(cx).snapshot();
+        let ranges = ranges
+            .iter()
+            .map(|range| range.to_point(&buffer_snapshot))
+            .collect::<Vec<_>>();
+
         self.latest_lsp_data(buffer, cx)
             .inlay_hints
-            .applicable_chunks(ranges)
+            .applicable_chunks(ranges.as_slice())
             .map(|chunk| chunk.row_range())
             .collect()
     }
@@ -6825,6 +6987,12 @@ impl LspStore {
             .map(|(_, known_chunks)| known_chunks)
             .unwrap_or_default();
 
+        let buffer_snapshot = buffer.read(cx).snapshot();
+        let ranges = ranges
+            .iter()
+            .map(|range| range.to_point(&buffer_snapshot))
+            .collect::<Vec<_>>();
+
         let mut hint_fetch_tasks = Vec::new();
         let mut cached_inlay_hints = None;
         let mut ranges_to_query = None;
@@ -6849,9 +7017,7 @@ impl LspStore {
                     .cloned(),
             ) {
                 (None, None) => {
-                    let Some(chunk_range) = existing_inlay_hints.chunk_range(row_chunk) else {
-                        continue;
-                    };
+                    let chunk_range = row_chunk.anchor_range();
                     ranges_to_query
                         .get_or_insert_with(Vec::new)
                         .push((row_chunk, chunk_range));
@@ -7112,8 +7278,7 @@ impl LspStore {
                     return;
                 }
 
-                let mut unchanged_buffers = HashSet::default();
-                let mut changed_buffers = HashSet::default();
+                let mut unchanged_buffers = HashMap::default();
                 let server_diagnostics_updates = diagnostics
                     .into_iter()
                     .filter_map(|diagnostics_set| match diagnostics_set {
@@ -7121,24 +7286,25 @@ impl LspStore {
                             server_id,
                             uri,
                             diagnostics,
-                        } => Some((server_id, uri, diagnostics)),
+                            registration_id,
+                        } => Some((server_id, uri, diagnostics, registration_id)),
                         LspPullDiagnostics::Default => None,
                     })
                     .fold(
                         HashMap::default(),
-                        |mut acc, (server_id, uri, diagnostics)| {
+                        |mut acc, (server_id, uri, diagnostics, new_registration_id)| {
                             let (result_id, diagnostics) = match diagnostics {
                                 PulledDiagnostics::Unchanged { result_id } => {
-                                    unchanged_buffers.insert(uri.clone());
+                                    unchanged_buffers
+                                        .entry(new_registration_id.clone())
+                                        .or_insert_with(HashSet::default)
+                                        .insert(uri.clone());
                                     (Some(result_id), Vec::new())
                                 }
                                 PulledDiagnostics::Changed {
                                     result_id,
                                     diagnostics,
-                                } => {
-                                    changed_buffers.insert(uri.clone());
-                                    (result_id, diagnostics)
-                                }
+                                } => (result_id, diagnostics),
                             };
                             let disk_based_sources = Cow::Owned(
                                 lsp_store
@@ -7148,8 +7314,11 @@ impl LspStore {
                                     .unwrap_or(&[])
                                     .to_vec(),
                             );
-                            acc.entry(server_id).or_insert_with(Vec::new).push(
-                                DocumentDiagnosticsUpdate {
+                            acc.entry(server_id)
+                                .or_insert_with(HashMap::default)
+                                .entry(new_registration_id.clone())
+                                .or_insert_with(Vec::new)
+                                .push(DocumentDiagnosticsUpdate {
                                     server_id,
                                     diagnostics: lsp::PublishDiagnosticsParams {
                                         uri,
@@ -7158,37 +7327,35 @@ impl LspStore {
                                     },
                                     result_id,
                                     disk_based_sources,
-                                },
-                            );
+                                    registration_id: new_registration_id,
+                                });
                             acc
                         },
                     );
 
                 for diagnostic_updates in server_diagnostics_updates.into_values() {
-                    lsp_store
-                        .merge_lsp_diagnostics(
-                            DiagnosticSourceKind::Pulled,
-                            diagnostic_updates,
-                            |buffer, old_diagnostic, cx| {
-                                File::from_dyn(buffer.file())
-                                    .and_then(|file| {
-                                        let abs_path = file.as_local()?.abs_path(cx);
-                                        lsp::Uri::from_file_path(abs_path).ok()
-                                    })
-                                    .is_none_or(|buffer_uri| {
-                                        unchanged_buffers.contains(&buffer_uri)
-                                            || match old_diagnostic.source_kind {
-                                                DiagnosticSourceKind::Pulled => {
-                                                    !changed_buffers.contains(&buffer_uri)
-                                                }
-                                                DiagnosticSourceKind::Other
-                                                | DiagnosticSourceKind::Pushed => true,
-                                            }
-                                    })
-                            },
-                            cx,
-                        )
-                        .log_err();
+                    for (registration_id, diagnostic_updates) in diagnostic_updates {
+                        lsp_store
+                            .merge_lsp_diagnostics(
+                                DiagnosticSourceKind::Pulled,
+                                diagnostic_updates,
+                                |document_uri, old_diagnostic, _| match old_diagnostic.source_kind {
+                                    DiagnosticSourceKind::Pulled => {
+                                        old_diagnostic.registration_id != registration_id
+                                            || unchanged_buffers
+                                                .get(&old_diagnostic.registration_id)
+                                                .is_some_and(|unchanged_buffers| {
+                                                    unchanged_buffers.contains(&document_uri)
+                                                })
+                                    }
+                                    DiagnosticSourceKind::Other | DiagnosticSourceKind::Pushed => {
+                                        true
+                                    }
+                                },
+                                cx,
+                            )
+                            .log_err();
+                    }
                 }
             })
         })
@@ -8051,7 +8218,7 @@ impl LspStore {
         })
     }
 
-    pub fn language_servers_for_local_buffer<'a>(
+    pub fn running_language_servers_for_local_buffer<'a>(
         &'a self,
         buffer: &Buffer,
         cx: &mut App,
@@ -8073,6 +8240,17 @@ impl LspStore {
             )
     }
 
+    pub fn language_servers_for_local_buffer(
+        &self,
+        buffer: &Buffer,
+        cx: &mut App,
+    ) -> Vec<LanguageServerId> {
+        let local = self.as_local();
+        local
+            .map(|local| local.language_server_ids_for_buffer(buffer, cx))
+            .unwrap_or_default()
+    }
+
     pub fn language_server_for_local_buffer<'a>(
         &'a self,
         buffer: &'a Buffer,
@@ -8177,6 +8355,7 @@ impl LspStore {
                     server_id,
                     LanguageServerStatus {
                         name,
+                        server_version: None,
                         pending_work: Default::default(),
                         has_pending_diagnostic_updates: false,
                         progress_tokens: Default::default(),
@@ -8195,7 +8374,7 @@ impl LspStore {
         &mut self,
         server_id: LanguageServerId,
         abs_path: PathBuf,
-        result_id: Option<String>,
+        result_id: Option<SharedString>,
         version: Option<i32>,
         diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
         cx: &mut Context<Self>,
@@ -8210,6 +8389,7 @@ impl LspStore {
                 result_id,
                 server_id,
                 disk_based_sources: Cow::Borrowed(&[]),
+                registration_id: None,
             }],
             |_, _, _| false,
             cx,
@@ -8220,7 +8400,7 @@ impl LspStore {
     pub fn merge_diagnostic_entries<'a>(
         &mut self,
         diagnostic_updates: Vec<DocumentDiagnosticsUpdate<'a, DocumentDiagnostics>>,
-        merge: impl Fn(&Buffer, &Diagnostic, &App) -> bool + Clone,
+        merge: impl Fn(&lsp::Uri, &Diagnostic, &App) -> bool + Clone,
         cx: &mut Context<Self>,
     ) -> anyhow::Result<()> {
         let mut diagnostics_summary = None::<proto::UpdateDiagnosticSummary>;
@@ -8241,13 +8421,15 @@ impl LspStore {
                 path: relative_path,
             };
 
+            let document_uri = lsp::Uri::from_file_path(abs_path)
+                .map_err(|()| anyhow!("Failed to convert buffer path {abs_path:?} to lsp Uri"))?;
             if let Some(buffer_handle) = self.buffer_store.read(cx).get_by_path(&project_path) {
                 let snapshot = buffer_handle.read(cx).snapshot();
                 let buffer = buffer_handle.read(cx);
                 let reused_diagnostics = buffer
                     .buffer_diagnostics(Some(server_id))
                     .iter()
-                    .filter(|v| merge(buffer, &v.diagnostic, cx))
+                    .filter(|v| merge(&document_uri, &v.diagnostic, cx))
                     .map(|v| {
                         let start = Unclipped(v.range.start.to_point_utf16(&snapshot));
                         let end = Unclipped(v.range.end.to_point_utf16(&snapshot));
@@ -8263,6 +8445,7 @@ impl LspStore {
                     .update_buffer_diagnostics(
                         &buffer_handle,
                         server_id,
+                        Some(update.registration_id),
                         update.result_id,
                         update.diagnostics.version,
                         update.diagnostics.diagnostics.clone(),
@@ -8271,6 +8454,25 @@ impl LspStore {
                     )?;
 
                 update.diagnostics.diagnostics.extend(reused_diagnostics);
+            } else if let Some(local) = self.as_local() {
+                let reused_diagnostics = local
+                    .diagnostics
+                    .get(&worktree_id)
+                    .and_then(|diagnostics_for_tree| diagnostics_for_tree.get(&project_path.path))
+                    .and_then(|diagnostics_by_server_id| {
+                        diagnostics_by_server_id
+                            .binary_search_by_key(&server_id, |e| e.0)
+                            .ok()
+                            .map(|ix| &diagnostics_by_server_id[ix].1)
+                    })
+                    .into_iter()
+                    .flatten()
+                    .filter(|v| merge(&document_uri, &v.diagnostic, cx));
+
+                update
+                    .diagnostics
+                    .diagnostics
+                    .extend(reused_diagnostics.cloned());
             }
 
             let updated = worktree.update(cx, |worktree, cx| {
@@ -8355,7 +8557,7 @@ impl LspStore {
             .unwrap_or_default();
 
         let new_summary = DiagnosticSummary::new(&diagnostics);
-        if new_summary.is_empty() {
+        if diagnostics.is_empty() {
             if let Some(diagnostics_by_server_id) = diagnostics_for_tree.get_mut(&path_in_worktree)
             {
                 if let Ok(ix) = diagnostics_by_server_id.binary_search_by_key(&server_id, |e| e.0) {
@@ -9189,6 +9391,7 @@ impl LspStore {
                 server_id,
                 LanguageServerStatus {
                     name: server_name.clone(),
+                    server_version: None,
                     pending_work: Default::default(),
                     has_pending_diagnostic_updates: false,
                     progress_tokens: Default::default(),
@@ -9665,7 +9868,7 @@ impl LspStore {
                 );
             }
             lsp::ProgressParamsValue::WorkspaceDiagnostic(report) => {
-                let identifier = match progress_params.token {
+                let registration_id = match progress_params.token {
                     lsp::NumberOrString::Number(_) => None,
                     lsp::NumberOrString::String(token) => token
                         .split_once(WORKSPACE_DIAGNOSTICS_TOKEN_START)
@@ -9678,10 +9881,15 @@ impl LspStore {
                     .as_local_mut()
                     .and_then(|local| local.language_servers.get_mut(&language_server_id))
                     && let Some(workspace_diagnostics) =
-                        workspace_diagnostics_refresh_tasks.get_mut(&identifier)
+                        workspace_diagnostics_refresh_tasks.get_mut(&registration_id)
                 {
                     workspace_diagnostics.progress_tx.try_send(()).ok();
-                    self.apply_workspace_diagnostic_report(language_server_id, report, cx)
+                    self.apply_workspace_diagnostic_report(
+                        language_server_id,
+                        report,
+                        registration_id.map(SharedString::from),
+                        cx,
+                    )
                 }
             }
         }
@@ -10941,7 +11149,7 @@ impl LspStore {
         &mut self,
         server_id: LanguageServerId,
         diagnostics: lsp::PublishDiagnosticsParams,
-        result_id: Option<String>,
+        result_id: Option<SharedString>,
         source_kind: DiagnosticSourceKind,
         disk_based_sources: &[String],
         cx: &mut Context<Self>,
@@ -10953,6 +11161,7 @@ impl LspStore {
                 result_id,
                 server_id,
                 disk_based_sources: Cow::Borrowed(disk_based_sources),
+                registration_id: None,
             }],
             |_, _, _| false,
             cx,
@@ -10963,7 +11172,7 @@ impl LspStore {
         &mut self,
         source_kind: DiagnosticSourceKind,
         lsp_diagnostics: Vec<DocumentDiagnosticsUpdate<lsp::PublishDiagnosticsParams>>,
-        merge: impl Fn(&Buffer, &Diagnostic, &App) -> bool + Clone,
+        merge: impl Fn(&lsp::Uri, &Diagnostic, &App) -> bool + Clone,
         cx: &mut Context<Self>,
     ) -> Result<()> {
         anyhow::ensure!(self.mode.is_local(), "called update_diagnostics on remote");
@@ -10978,10 +11187,12 @@ impl LspStore {
                         update.server_id,
                         update.diagnostics,
                         &update.disk_based_sources,
+                        update.registration_id.clone(),
                     ),
                     result_id: update.result_id,
                     server_id: update.server_id,
                     disk_based_sources: update.disk_based_sources,
+                    registration_id: update.registration_id,
                 })
             })
             .collect();
@@ -10996,6 +11207,7 @@ impl LspStore {
         server_id: LanguageServerId,
         mut lsp_diagnostics: lsp::PublishDiagnosticsParams,
         disk_based_sources: &[String],
+        registration_id: Option<SharedString>,
     ) -> DocumentDiagnostics {
         let mut diagnostics = Vec::default();
         let mut primary_diagnostic_group_ids = HashMap::default();
@@ -11069,6 +11281,7 @@ impl LspStore {
                         is_unnecessary,
                         underline,
                         data: diagnostic.data.clone(),
+                        registration_id: registration_id.clone(),
                     },
                 });
                 if let Some(infos) = &diagnostic.related_information {
@@ -11096,6 +11309,7 @@ impl LspStore {
                                     is_unnecessary: false,
                                     underline,
                                     data: diagnostic.data.clone(),
+                                    registration_id: registration_id.clone(),
                                 },
                             });
                         }
@@ -11208,6 +11422,7 @@ impl LspStore {
             server_id,
             LanguageServerStatus {
                 name: language_server.name(),
+                server_version: language_server.version(),
                 pending_work: Default::default(),
                 has_pending_diagnostic_updates: false,
                 progress_tokens: Default::default(),
@@ -11845,18 +12060,22 @@ impl LspStore {
         }
         if let Some(local) = self.as_local_mut() {
             local.buffer_pull_diagnostics_result_ids.remove(&for_server);
+            local
+                .workspace_pull_diagnostics_result_ids
+                .remove(&for_server);
             for buffer_servers in local.buffers_opened_in_servers.values_mut() {
                 buffer_servers.remove(&for_server);
             }
         }
     }
 
-    pub fn result_id(
+    pub fn result_id_for_buffer_pull(
         &self,
         server_id: LanguageServerId,
         buffer_id: BufferId,
+        registration_id: &Option<SharedString>,
         cx: &App,
-    ) -> Option<String> {
+    ) -> Option<SharedString> {
         let abs_path = self
             .buffer_store
             .read(cx)
@@ -11866,20 +12085,40 @@ impl LspStore {
         self.as_local()?
             .buffer_pull_diagnostics_result_ids
             .get(&server_id)?
+            .get(registration_id)?
             .get(&abs_path)?
             .clone()
     }
 
-    pub fn all_result_ids(&self, server_id: LanguageServerId) -> HashMap<PathBuf, String> {
+    /// Gets all result_ids for a workspace diagnostics pull request.
+    /// First, it tries to find buffer's result_id retrieved via the diagnostics pull; if it fails, it falls back to the workspace disagnostics pull result_id.
+    /// The latter is supposed to be of lower priority as we keep on pulling diagnostics for open buffers eagerly.
+    pub fn result_ids_for_workspace_refresh(
+        &self,
+        server_id: LanguageServerId,
+        registration_id: &Option<SharedString>,
+    ) -> HashMap<PathBuf, SharedString> {
         let Some(local) = self.as_local() else {
             return HashMap::default();
         };
         local
-            .buffer_pull_diagnostics_result_ids
+            .workspace_pull_diagnostics_result_ids
             .get(&server_id)
             .into_iter()
+            .filter_map(|diagnostics| diagnostics.get(registration_id))
             .flatten()
-            .filter_map(|(abs_path, result_id)| Some((abs_path.clone(), result_id.clone()?)))
+            .filter_map(|(abs_path, result_id)| {
+                let result_id = local
+                    .buffer_pull_diagnostics_result_ids
+                    .get(&server_id)
+                    .and_then(|buffer_ids_result_ids| {
+                        buffer_ids_result_ids.get(registration_id)?.get(abs_path)
+                    })
+                    .cloned()
+                    .flatten()
+                    .or_else(|| result_id.clone())?;
+                Some((abs_path.clone(), result_id))
+            })
             .collect()
     }
 

crates/project/src/lsp_store/clangd_ext.rs 🔗

@@ -90,6 +90,7 @@ pub fn register_notifications(
                             disk_based_sources: Cow::Borrowed(
                                 &adapter.disk_based_diagnostic_sources,
                             ),
+                            registration_id: None,
                         }],
                         |_, diag, _| !is_inactive_region(diag),
                         cx,

crates/project/src/lsp_store/inlay_hint_cache.rs 🔗

@@ -8,7 +8,7 @@ use language::{
     row_chunk::{RowChunk, RowChunks},
 };
 use lsp::LanguageServerId;
-use text::Anchor;
+use text::Point;
 
 use crate::{InlayHint, InlayId};
 
@@ -90,10 +90,7 @@ impl BufferInlayHints {
         }
     }
 
-    pub fn applicable_chunks(
-        &self,
-        ranges: &[Range<text::Anchor>],
-    ) -> impl Iterator<Item = RowChunk> {
+    pub fn applicable_chunks(&self, ranges: &[Range<Point>]) -> impl Iterator<Item = RowChunk> {
         self.chunks.applicable_chunks(ranges)
     }
 
@@ -226,8 +223,4 @@ impl BufferInlayHints {
             }
         }
     }
-
-    pub fn chunk_range(&self, chunk: RowChunk) -> Option<Range<Anchor>> {
-        self.chunks.chunk_range(chunk)
-    }
 }

crates/project/src/lsp_store/json_language_server_ext.rs 🔗

@@ -1,5 +1,5 @@
 use anyhow::{Context, Result};
-use gpui::{App, AsyncApp, Entity, Global, WeakEntity};
+use gpui::{App, AsyncApp, Entity, Global, Task, WeakEntity};
 use lsp::LanguageServer;
 
 use crate::LspStore;
@@ -22,7 +22,7 @@ impl lsp::request::Request for SchemaContentRequest {
     const METHOD: &'static str = "vscode/content";
 }
 
-type SchemaRequestHandler = fn(Entity<LspStore>, String, &mut AsyncApp) -> Result<String>;
+type SchemaRequestHandler = fn(Entity<LspStore>, String, &mut AsyncApp) -> Task<Result<String>>;
 pub struct SchemaHandlingImpl(SchemaRequestHandler);
 
 impl Global for SchemaHandlingImpl {}
@@ -72,9 +72,7 @@ pub fn notify_schema_changed(lsp_store: Entity<LspStore>, uri: String, cx: &App)
 pub fn register_requests(lsp_store: WeakEntity<LspStore>, language_server: &LanguageServer) {
     language_server
         .on_request::<SchemaContentRequest, _, _>(move |params, cx| {
-            let handler = cx.try_read_global::<SchemaHandlingImpl, _>(|handler, _| {
-                handler.0
-            });
+            let handler = cx.try_read_global::<SchemaHandlingImpl, _>(|handler, _| handler.0);
             let mut cx = cx.clone();
             let uri = params.clone().pop();
             let lsp_store = lsp_store.clone();
@@ -82,7 +80,7 @@ pub fn register_requests(lsp_store: WeakEntity<LspStore>, language_server: &Lang
                 let lsp_store = lsp_store.upgrade().context("LSP store has been dropped")?;
                 let uri = uri.context("No URI")?;
                 let handle_schema_request = handler.context("No schema handler registered")?;
-                handle_schema_request(lsp_store, uri, &mut cx)
+                handle_schema_request(lsp_store, uri, &mut cx).await
             };
             async move {
                 zlog::trace!(LOGGER => "Handling schema request for {:?}", &params);

crates/project/src/persistence.rs 🔗

@@ -0,0 +1,60 @@
+use collections::{HashMap, HashSet};
+use gpui::{App, Entity, SharedString};
+use std::path::PathBuf;
+
+use db::{
+    query,
+    sqlez::{domain::Domain, thread_safe_connection::ThreadSafeConnection},
+    sqlez_macros::sql,
+};
+
+use crate::{
+    trusted_worktrees::{PathTrust, RemoteHostLocation, find_worktree_in_store},
+    worktree_store::WorktreeStore,
+};
+
+// https://www.sqlite.org/limits.html
+// > <..> the maximum value of a host parameter number is SQLITE_MAX_VARIABLE_NUMBER,
+// > which defaults to <..> 32766 for SQLite versions after 3.32.0.
+#[allow(unused)]
+const MAX_QUERY_PLACEHOLDERS: usize = 32000;
+
+#[allow(unused)]
+pub struct ProjectDb(ThreadSafeConnection);
+
+impl Domain for ProjectDb {
+    const NAME: &str = stringify!(ProjectDb);
+
+    const MIGRATIONS: &[&str] = &[sql!(
+        CREATE TABLE IF NOT EXISTS trusted_worktrees (
+            trust_id INTEGER PRIMARY KEY AUTOINCREMENT,
+            absolute_path TEXT,
+            user_name TEXT,
+            host_name TEXT
+        ) STRICT;
+    )];
+}
+
+db::static_connection!(PROJECT_DB, ProjectDb, []);
+
+impl ProjectDb {}
+
+#[cfg(test)]
+mod tests {
+    use std::path::PathBuf;
+
+    use collections::{HashMap, HashSet};
+    use gpui::{SharedString, TestAppContext};
+    use serde_json::json;
+    use settings::SettingsStore;
+    use smol::lock::Mutex;
+    use util::path;
+
+    use crate::{
+        FakeFs, Project,
+        persistence::PROJECT_DB,
+        trusted_worktrees::{PathTrust, RemoteHostLocation},
+    };
+
+    static TEST_WORKTREE_TRUST_LOCK: Mutex<()> = Mutex::new(());
+}

crates/project/src/prettier_store.rs 🔗

@@ -905,7 +905,7 @@ async fn install_prettier_packages(
                     .with_context(|| {
                         format!("fetching latest npm version for package {returned_package_name}")
                     })?;
-                anyhow::Ok((returned_package_name, latest_version))
+                anyhow::Ok((returned_package_name, latest_version.to_string()))
             }),
     )
     .await

crates/project/src/project.rs 🔗

@@ -19,6 +19,7 @@ pub mod task_store;
 pub mod telemetry_snapshot;
 pub mod terminals;
 pub mod toolchain_store;
+pub mod trusted_worktrees;
 pub mod worktree_store;
 
 #[cfg(test)]
@@ -39,6 +40,7 @@ use crate::{
     git_store::GitStore,
     lsp_store::{SymbolLocation, log_store::LogKind},
     project_search::SearchResultsHandle,
+    trusted_worktrees::{PathTrust, RemoteHostLocation, TrustedWorktrees},
 };
 pub use agent_server_store::{AgentServerStore, AgentServersUpdated, ExternalAgentServerName};
 pub use git_store::{
@@ -63,6 +65,7 @@ use debugger::{
     dap_store::{DapStore, DapStoreEvent},
     session::Session,
 };
+use encoding_rs;
 pub use environment::ProjectEnvironment;
 #[cfg(test)]
 use futures::future::join_all;
@@ -80,7 +83,7 @@ use gpui::{
     Task, WeakEntity, Window,
 };
 use language::{
-    Buffer, BufferEvent, Capability, CodeLabel, CursorShape, Language, LanguageName,
+    Buffer, BufferEvent, Capability, CodeLabel, CursorShape, DiskState, Language, LanguageName,
     LanguageRegistry, PointUtf16, ToOffset, ToPointUtf16, Toolchain, ToolchainMetadata,
     ToolchainScope, Transaction, Unclipped, language_settings::InlayHintKind,
     proto::split_operations,
@@ -348,6 +351,7 @@ pub enum Event {
     SnippetEdit(BufferId, Vec<(lsp::Range, Snippet)>),
     ExpandedAllForEntry(WorktreeId, ProjectEntryId),
     EntryRenamed(ProjectTransaction, ProjectPath, PathBuf),
+    WorkspaceEditApplied(ProjectTransaction),
     AgentLocationChanged,
 }
 
@@ -966,6 +970,14 @@ impl DirectoryLister {
             }
         }
     }
+
+    pub fn path_style(&self, cx: &App) -> PathStyle {
+        match self {
+            Self::Local(project, ..) | Self::Project(project, ..) => {
+                project.read(cx).path_style(cx)
+            }
+        }
+    }
 }
 
 #[cfg(any(test, feature = "test-support"))]
@@ -984,6 +996,8 @@ pub enum LspPullDiagnostics {
         server_id: LanguageServerId,
         /// URI of the resource,
         uri: lsp::Uri,
+        /// The ID provided by the dynamic registration that produced diagnostics.
+        registration_id: Option<SharedString>,
         /// The diagnostics produced by this language server.
         diagnostics: PulledDiagnostics,
     },
@@ -994,10 +1008,10 @@ pub enum PulledDiagnostics {
     Unchanged {
         /// An ID the current pulled batch for this file.
         /// If given, can be used to query workspace diagnostics partially.
-        result_id: String,
+        result_id: SharedString,
     },
     Changed {
-        result_id: Option<String>,
+        result_id: Option<SharedString>,
         diagnostics: Vec<lsp::Diagnostic>,
     },
 }
@@ -1059,6 +1073,7 @@ impl Project {
         languages: Arc<LanguageRegistry>,
         fs: Arc<dyn Fs>,
         env: Option<HashMap<String, String>>,
+        init_worktree_trust: bool,
         cx: &mut App,
     ) -> Entity<Self> {
         cx.new(|cx: &mut Context<Self>| {
@@ -1067,6 +1082,15 @@ impl Project {
                 .detach();
             let snippets = SnippetProvider::new(fs.clone(), BTreeSet::from_iter([]), cx);
             let worktree_store = cx.new(|_| WorktreeStore::local(false, fs.clone()));
+            if init_worktree_trust {
+                trusted_worktrees::track_worktree_trust(
+                    worktree_store.clone(),
+                    None,
+                    None,
+                    None,
+                    cx,
+                );
+            }
             cx.subscribe(&worktree_store, Self::on_worktree_store_event)
                 .detach();
 
@@ -1240,6 +1264,7 @@ impl Project {
         user_store: Entity<UserStore>,
         languages: Arc<LanguageRegistry>,
         fs: Arc<dyn Fs>,
+        init_worktree_trust: bool,
         cx: &mut App,
     ) -> Entity<Self> {
         cx.new(|cx: &mut Context<Self>| {
@@ -1248,8 +1273,14 @@ impl Project {
                 .detach();
             let snippets = SnippetProvider::new(fs.clone(), BTreeSet::from_iter([]), cx);
 
-            let (remote_proto, path_style) =
-                remote.read_with(cx, |remote, _| (remote.proto_client(), remote.path_style()));
+            let (remote_proto, path_style, connection_options) =
+                remote.read_with(cx, |remote, _| {
+                    (
+                        remote.proto_client(),
+                        remote.path_style(),
+                        remote.connection_options(),
+                    )
+                });
             let worktree_store = cx.new(|_| {
                 WorktreeStore::remote(
                     false,
@@ -1258,8 +1289,18 @@ impl Project {
                     path_style,
                 )
             });
+
             cx.subscribe(&worktree_store, Self::on_worktree_store_event)
                 .detach();
+            if init_worktree_trust {
+                trusted_worktrees::track_worktree_trust(
+                    worktree_store.clone(),
+                    Some(RemoteHostLocation::from(connection_options)),
+                    None,
+                    Some((remote_proto.clone(), REMOTE_SERVER_PROJECT_ID)),
+                    cx,
+                );
+            }
 
             let weak_self = cx.weak_entity();
             let context_server_store =
@@ -1284,7 +1325,12 @@ impl Project {
             cx.subscribe(&buffer_store, Self::on_buffer_store_event)
                 .detach();
             let toolchain_store = cx.new(|cx| {
-                ToolchainStore::remote(REMOTE_SERVER_PROJECT_ID, remote.read(cx).proto_client(), cx)
+                ToolchainStore::remote(
+                    REMOTE_SERVER_PROJECT_ID,
+                    worktree_store.clone(),
+                    remote.read(cx).proto_client(),
+                    cx,
+                )
             });
             let task_store = cx.new(|cx| {
                 TaskStore::remote(
@@ -1440,6 +1486,9 @@ impl Project {
             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);
+            remote_proto.add_entity_request_handler(Self::handle_trust_worktrees);
+            remote_proto.add_entity_request_handler(Self::handle_restrict_worktrees);
+
             BufferStore::init(&remote_proto);
             LspStore::init(&remote_proto);
             SettingsObserver::init(&remote_proto);
@@ -1800,6 +1849,7 @@ impl Project {
                     Arc::new(languages),
                     fs,
                     None,
+                    false,
                     cx,
                 )
             })
@@ -1824,6 +1874,25 @@ impl Project {
         fs: Arc<dyn Fs>,
         root_paths: impl IntoIterator<Item = &Path>,
         cx: &mut gpui::TestAppContext,
+    ) -> Entity<Project> {
+        Self::test_project(fs, root_paths, false, cx).await
+    }
+
+    #[cfg(any(test, feature = "test-support"))]
+    pub async fn test_with_worktree_trust(
+        fs: Arc<dyn Fs>,
+        root_paths: impl IntoIterator<Item = &Path>,
+        cx: &mut gpui::TestAppContext,
+    ) -> Entity<Project> {
+        Self::test_project(fs, root_paths, true, cx).await
+    }
+
+    #[cfg(any(test, feature = "test-support"))]
+    async fn test_project(
+        fs: Arc<dyn Fs>,
+        root_paths: impl IntoIterator<Item = &Path>,
+        init_worktree_trust: bool,
+        cx: &mut gpui::TestAppContext,
     ) -> Entity<Project> {
         use clock::FakeSystemClock;
 
@@ -1840,6 +1909,7 @@ impl Project {
                 Arc::new(languages),
                 fs,
                 None,
+                init_worktree_trust,
                 cx,
             )
         });
@@ -2415,13 +2485,11 @@ impl Project {
         cx: &mut Context<Self>,
     ) -> Result<()> {
         cx.update_global::<SettingsStore, _>(|store, cx| {
-            self.worktree_store.update(cx, |worktree_store, cx| {
-                for worktree in worktree_store.worktrees() {
-                    store
-                        .clear_local_settings(worktree.read(cx).id(), cx)
-                        .log_err();
-                }
-            });
+            for worktree_metadata in &message.worktrees {
+                store
+                    .clear_local_settings(WorktreeId::from_proto(worktree_metadata.id), cx)
+                    .log_err();
+            }
         });
 
         self.join_project_response_message_id = message_id;
@@ -2620,6 +2688,12 @@ impl Project {
         !self.is_local()
     }
 
+    pub fn disable_worktree_scanner(&mut self, cx: &mut Context<Self>) {
+        self.worktree_store.update(cx, |worktree_store, _cx| {
+            worktree_store.disable_scanner();
+        });
+    }
+
     #[inline]
     pub fn create_buffer(
         &mut self,
@@ -3177,6 +3251,9 @@ impl Project {
                     cx.emit(Event::SnippetEdit(*buffer_id, edits.clone()))
                 }
             }
+            LspStoreEvent::WorkspaceEditApplied(transaction) => {
+                cx.emit(Event::WorkspaceEditApplied(transaction.clone()))
+            }
         }
     }
 
@@ -4655,6 +4732,14 @@ impl Project {
         this.update(&mut cx, |this, cx| {
             // Don't handle messages that were sent before the response to us joining the project
             if envelope.message_id > this.join_project_response_message_id {
+                cx.update_global::<SettingsStore, _>(|store, cx| {
+                    for worktree_metadata in &envelope.payload.worktrees {
+                        store
+                            .clear_local_settings(WorktreeId::from_proto(worktree_metadata.id), cx)
+                            .log_err();
+                    }
+                });
+
                 this.set_worktrees_from_proto(envelope.payload.worktrees, cx)?;
             }
             Ok(())
@@ -4741,9 +4826,14 @@ impl Project {
         envelope: TypedEnvelope<proto::UpdateWorktree>,
         mut cx: AsyncApp,
     ) -> Result<()> {
-        this.update(&mut cx, |this, cx| {
+        this.update(&mut cx, |project, cx| {
             let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
-            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
+            if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
+                trusted_worktrees.update(cx, |trusted_worktrees, cx| {
+                    trusted_worktrees.can_trust(worktree_id, cx)
+                });
+            }
+            if let Some(worktree) = project.worktree_for_id(worktree_id, cx) {
                 worktree.update(cx, |worktree, _| {
                     let worktree = worktree.as_remote_mut().unwrap();
                     worktree.update_from_remote(envelope.payload);
@@ -4770,6 +4860,58 @@ impl Project {
         BufferStore::handle_update_buffer(buffer_store, envelope, cx).await
     }
 
+    async fn handle_trust_worktrees(
+        this: Entity<Self>,
+        envelope: TypedEnvelope<proto::TrustWorktrees>,
+        mut cx: AsyncApp,
+    ) -> Result<proto::Ack> {
+        let trusted_worktrees = cx
+            .update(|cx| TrustedWorktrees::try_get_global(cx))?
+            .context("missing trusted worktrees")?;
+        trusted_worktrees.update(&mut cx, |trusted_worktrees, cx| {
+            let remote_host = this
+                .read(cx)
+                .remote_connection_options(cx)
+                .map(RemoteHostLocation::from);
+            trusted_worktrees.trust(
+                envelope
+                    .payload
+                    .trusted_paths
+                    .into_iter()
+                    .filter_map(|proto_path| PathTrust::from_proto(proto_path))
+                    .collect(),
+                remote_host,
+                cx,
+            );
+        })?;
+        Ok(proto::Ack {})
+    }
+
+    async fn handle_restrict_worktrees(
+        this: Entity<Self>,
+        envelope: TypedEnvelope<proto::RestrictWorktrees>,
+        mut cx: AsyncApp,
+    ) -> Result<proto::Ack> {
+        let trusted_worktrees = cx
+            .update(|cx| TrustedWorktrees::try_get_global(cx))?
+            .context("missing trusted worktrees")?;
+        trusted_worktrees.update(&mut cx, |trusted_worktrees, cx| {
+            let restricted_paths = envelope
+                .payload
+                .worktree_ids
+                .into_iter()
+                .map(WorktreeId::from_proto)
+                .map(PathTrust::Worktree)
+                .collect::<HashSet<_>>();
+            let remote_host = this
+                .read(cx)
+                .remote_connection_options(cx)
+                .map(RemoteHostLocation::from);
+            trusted_worktrees.restrict(restricted_paths, remote_host, cx);
+        })?;
+        Ok(proto::Ack {})
+    }
+
     async fn handle_update_buffer(
         this: Entity<Self>,
         envelope: TypedEnvelope<proto::UpdateBuffer>,
@@ -5182,7 +5324,7 @@ impl Project {
     #[cfg(any(test, feature = "test-support"))]
     pub fn has_language_servers_for(&self, buffer: &Buffer, cx: &mut App) -> bool {
         self.lsp_store.update(cx, |this, cx| {
-            this.language_servers_for_local_buffer(buffer, cx)
+            this.running_language_servers_for_local_buffer(buffer, cx)
                 .next()
                 .is_some()
         })
@@ -5320,13 +5462,22 @@ impl Project {
                 .await
                 .context("Failed to load settings file")?;
 
+            let has_bom = file.has_bom;
+
             let new_text = cx.read_global::<SettingsStore, _>(|store, cx| {
                 store.new_text_for_update(file.text, move |settings| update(settings, cx))
             })?;
             worktree
                 .update(cx, |worktree, cx| {
                     let line_ending = text::LineEnding::detect(&new_text);
-                    worktree.write_file(rel_path.clone(), new_text.into(), line_ending, cx)
+                    worktree.write_file(
+                        rel_path.clone(),
+                        new_text.into(),
+                        line_ending,
+                        encoding_rs::UTF_8,
+                        has_bom,
+                        cx,
+                    )
                 })?
                 .await
                 .context("Failed to write settings file")?;
@@ -5515,7 +5666,9 @@ impl ProjectItem for Buffer {
     }
 
     fn project_path(&self, cx: &App) -> Option<ProjectPath> {
-        self.file().map(|file| ProjectPath {
+        let file = self.file()?;
+
+        (!matches!(file.disk_state(), DiskState::Historic { .. })).then(|| ProjectPath {
             worktree_id: file.worktree_id(cx),
             path: file.path().clone(),
         })

crates/project/src/project_search.rs 🔗

@@ -93,9 +93,6 @@ enum FindSearchCandidates {
         /// based on disk contents of a buffer. This step is not performed for buffers we already have in memory.
         confirm_contents_will_match_tx: Sender<MatchingEntry>,
         confirm_contents_will_match_rx: Receiver<MatchingEntry>,
-        /// Of those that contain at least one match (or are already in memory), look for rest of matches (and figure out their ranges).
-        /// But wait - first, we need to go back to the main thread to open a buffer (& create an entity for it).
-        get_buffer_for_full_scan_tx: Sender<ProjectPath>,
     },
     Remote,
     OpenBuffersOnly,
@@ -226,7 +223,7 @@ impl Search {
                             .boxed_local(),
                             cx.background_spawn(Self::maintain_sorted_search_results(
                                 sorted_search_results_rx,
-                                get_buffer_for_full_scan_tx.clone(),
+                                get_buffer_for_full_scan_tx,
                                 self.limit,
                             ))
                             .boxed_local(),
@@ -234,7 +231,6 @@ impl Search {
                         (
                             FindSearchCandidates::Local {
                                 fs,
-                                get_buffer_for_full_scan_tx,
                                 confirm_contents_will_match_tx,
                                 confirm_contents_will_match_rx,
                                 input_paths_rx,
@@ -593,7 +589,6 @@ impl Worker<'_> {
             input_paths_rx,
             confirm_contents_will_match_rx,
             mut confirm_contents_will_match_tx,
-            mut get_buffer_for_full_scan_tx,
             fs,
         ) = match self.candidates {
             FindSearchCandidates::Local {
@@ -601,21 +596,15 @@ impl Worker<'_> {
                 input_paths_rx,
                 confirm_contents_will_match_rx,
                 confirm_contents_will_match_tx,
-                get_buffer_for_full_scan_tx,
             } => (
                 input_paths_rx,
                 confirm_contents_will_match_rx,
                 confirm_contents_will_match_tx,
-                get_buffer_for_full_scan_tx,
                 Some(fs),
             ),
-            FindSearchCandidates::Remote | FindSearchCandidates::OpenBuffersOnly => (
-                unbounded().1,
-                unbounded().1,
-                unbounded().0,
-                unbounded().0,
-                None,
-            ),
+            FindSearchCandidates::Remote | FindSearchCandidates::OpenBuffersOnly => {
+                (unbounded().1, unbounded().1, unbounded().0, None)
+            }
         };
         // WorkerA: grabs a request for "find all matches in file/a" <- takes 5 minutes
         // right after: WorkerB: grabs a request for "find all matches in file/b" <- takes 5 seconds
@@ -629,7 +618,6 @@ impl Worker<'_> {
                 open_entries: &self.open_buffers,
                 fs: fs.as_deref(),
                 confirm_contents_will_match_tx: &confirm_contents_will_match_tx,
-                get_buffer_for_full_scan_tx: &get_buffer_for_full_scan_tx,
             };
             // Whenever we notice that some step of a pipeline is closed, we don't want to close subsequent
             // steps straight away. Another worker might be about to produce a value that will
@@ -645,10 +633,7 @@ impl Worker<'_> {
                 find_first_match = find_first_match.next() => {
                     if let Some(buffer_with_at_least_one_match) = find_first_match {
                         handler.handle_find_first_match(buffer_with_at_least_one_match).await;
-                    } else {
-                        get_buffer_for_full_scan_tx = bounded(1).0;
                     }
-
                 },
                 scan_path = scan_path.next() => {
                     if let Some(path_to_scan) = scan_path {
@@ -673,7 +658,6 @@ struct RequestHandler<'worker> {
     fs: Option<&'worker dyn Fs>,
     open_entries: &'worker HashSet<ProjectEntryId>,
     confirm_contents_will_match_tx: &'worker Sender<MatchingEntry>,
-    get_buffer_for_full_scan_tx: &'worker Sender<ProjectPath>,
 }
 
 impl RequestHandler<'_> {
@@ -729,9 +713,8 @@ impl RequestHandler<'_> {
         _ = maybe!(async move {
             let InputPath {
                 entry,
-
                 snapshot,
-                should_scan_tx,
+                mut should_scan_tx,
             } = req;
 
             if entry.is_fifo || !entry.is_file() {
@@ -754,7 +737,7 @@ impl RequestHandler<'_> {
             if self.open_entries.contains(&entry.id) {
                 // The buffer is already in memory and that's the version we want to scan;
                 // hence skip the dilly-dally and look for all matches straight away.
-                self.get_buffer_for_full_scan_tx
+                should_scan_tx
                     .send(ProjectPath {
                         worktree_id: snapshot.id(),
                         path: entry.path.clone(),

crates/project/src/project_settings.rs 🔗

@@ -23,13 +23,14 @@ use settings::{
     DapSettingsContent, InvalidSettingsError, LocalSettingsKind, RegisterSetting, Settings,
     SettingsLocation, SettingsStore, parse_json_with_comments, watch_config_file,
 };
-use std::{path::PathBuf, sync::Arc, time::Duration};
+use std::{cell::OnceCell, collections::BTreeMap, path::PathBuf, sync::Arc, time::Duration};
 use task::{DebugTaskFile, TaskTemplates, VsCodeDebugTaskFile, VsCodeTaskFile};
 use util::{ResultExt, rel_path::RelPath, serde::default_true};
 use worktree::{PathChange, UpdatedEntriesSet, Worktree, WorktreeId};
 
 use crate::{
     task_store::{TaskSettingsLocation, TaskStore},
+    trusted_worktrees::{PathTrust, TrustedWorktrees, TrustedWorktreesEvent},
     worktree_store::{WorktreeStore, WorktreeStoreEvent},
 };
 
@@ -83,6 +84,12 @@ pub struct SessionSettings {
     ///
     /// Default: true
     pub restore_unsaved_buffers: bool,
+    /// Whether or not to skip worktree trust checks.
+    /// When trusted, project settings are synchronized automatically,
+    /// language and MCP servers are downloaded and started automatically.
+    ///
+    /// Default: false
+    pub trust_all_worktrees: bool,
 }
 
 #[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
@@ -325,6 +332,10 @@ impl GoToDiagnosticSeverityFilter {
 
 #[derive(Copy, Clone, Debug)]
 pub struct GitSettings {
+    /// Whether or not git integration is enabled.
+    ///
+    /// Default: true
+    pub enabled: GitEnabledSettings,
     /// Whether or not to show the git gutter.
     ///
     /// Default: tracked_files
@@ -354,6 +365,18 @@ pub struct GitSettings {
     pub path_style: GitPathStyle,
 }
 
+#[derive(Clone, Copy, Debug)]
+pub struct GitEnabledSettings {
+    /// Whether git integration is enabled for showing git status.
+    ///
+    /// Default: true
+    pub status: bool,
+    /// Whether git integration is enabled for showing diffs.
+    ///
+    /// Default: true
+    pub diff: bool,
+}
+
 #[derive(Clone, Copy, Debug, PartialEq, Default)]
 pub enum GitPathStyle {
     #[default]
@@ -495,7 +518,14 @@ impl Settings for ProjectSettings {
         let inline_diagnostics = diagnostics.inline.as_ref().unwrap();
 
         let git = content.git.as_ref().unwrap();
+        let git_enabled = {
+            GitEnabledSettings {
+                status: git.enabled.as_ref().unwrap().is_git_status_enabled(),
+                diff: git.enabled.as_ref().unwrap().is_git_diff_enabled(),
+            }
+        };
         let git_settings = GitSettings {
+            enabled: git_enabled,
             git_gutter: git.git_gutter.unwrap(),
             gutter_debounce: git.gutter_debounce.unwrap_or_default(),
             inline_blame: {
@@ -570,6 +600,7 @@ impl Settings for ProjectSettings {
             load_direnv: project.load_direnv.clone().unwrap(),
             session: SessionSettings {
                 restore_unsaved_buffers: content.session.unwrap().restore_unsaved_buffers.unwrap(),
+                trust_all_worktrees: content.session.unwrap().trust_all_worktrees.unwrap(),
             },
         }
     }
@@ -595,6 +626,9 @@ pub struct SettingsObserver {
     worktree_store: Entity<WorktreeStore>,
     project_id: u64,
     task_store: Entity<TaskStore>,
+    pending_local_settings:
+        HashMap<PathTrust, BTreeMap<(WorktreeId, Arc<RelPath>), Option<String>>>,
+    _trusted_worktrees_watcher: Option<Subscription>,
     _user_settings_watcher: Option<Subscription>,
     _global_task_config_watcher: Task<()>,
     _global_debug_config_watcher: Task<()>,
@@ -620,11 +654,61 @@ impl SettingsObserver {
         cx.subscribe(&worktree_store, Self::on_worktree_store_event)
             .detach();
 
+        let _trusted_worktrees_watcher =
+            TrustedWorktrees::try_get_global(cx).map(|trusted_worktrees| {
+                cx.subscribe(
+                    &trusted_worktrees,
+                    move |settings_observer, _, e, cx| match e {
+                        TrustedWorktreesEvent::Trusted(_, trusted_paths) => {
+                            for trusted_path in trusted_paths {
+                                if let Some(pending_local_settings) = settings_observer
+                                    .pending_local_settings
+                                    .remove(trusted_path)
+                                {
+                                    for ((worktree_id, directory_path), settings_contents) in
+                                        pending_local_settings
+                                    {
+                                        apply_local_settings(
+                                            worktree_id,
+                                            &directory_path,
+                                            LocalSettingsKind::Settings,
+                                            &settings_contents,
+                                            cx,
+                                        );
+                                        if let Some(downstream_client) =
+                                            &settings_observer.downstream_client
+                                        {
+                                            downstream_client
+                                                .send(proto::UpdateWorktreeSettings {
+                                                    project_id: settings_observer.project_id,
+                                                    worktree_id: worktree_id.to_proto(),
+                                                    path: directory_path.to_proto(),
+                                                    content: settings_contents,
+                                                    kind: Some(
+                                                        local_settings_kind_to_proto(
+                                                            LocalSettingsKind::Settings,
+                                                        )
+                                                        .into(),
+                                                    ),
+                                                })
+                                                .log_err();
+                                        }
+                                    }
+                                }
+                            }
+                        }
+                        TrustedWorktreesEvent::Restricted(..) => {}
+                    },
+                )
+            });
+
         Self {
             worktree_store,
             task_store,
             mode: SettingsObserverMode::Local(fs.clone()),
             downstream_client: None,
+            _trusted_worktrees_watcher,
+            pending_local_settings: HashMap::default(),
             _user_settings_watcher: None,
             project_id: REMOTE_SERVER_PROJECT_ID,
             _global_task_config_watcher: Self::subscribe_to_global_task_file_changes(
@@ -677,6 +761,8 @@ impl SettingsObserver {
             mode: SettingsObserverMode::Remote,
             downstream_client: None,
             project_id: REMOTE_SERVER_PROJECT_ID,
+            _trusted_worktrees_watcher: None,
+            pending_local_settings: HashMap::default(),
             _user_settings_watcher: user_settings_watcher,
             _global_task_config_watcher: Self::subscribe_to_global_task_file_changes(
                 fs.clone(),
@@ -792,13 +878,20 @@ impl SettingsObserver {
         event: &WorktreeStoreEvent,
         cx: &mut Context<Self>,
     ) {
-        if let WorktreeStoreEvent::WorktreeAdded(worktree) = event {
-            cx.subscribe(worktree, |this, worktree, event, cx| {
-                if let worktree::Event::UpdatedEntries(changes) = event {
-                    this.update_local_worktree_settings(&worktree, changes, cx)
-                }
-            })
-            .detach()
+        match event {
+            WorktreeStoreEvent::WorktreeAdded(worktree) => cx
+                .subscribe(worktree, |this, worktree, event, cx| {
+                    if let worktree::Event::UpdatedEntries(changes) = event {
+                        this.update_local_worktree_settings(&worktree, changes, cx)
+                    }
+                })
+                .detach(),
+            WorktreeStoreEvent::WorktreeRemoved(_, worktree_id) => {
+                cx.update_global::<SettingsStore, _>(|store, cx| {
+                    store.clear_local_settings(*worktree_id, cx).log_err();
+                });
+            }
+            _ => {}
         }
     }
 
@@ -968,36 +1061,32 @@ impl SettingsObserver {
         let worktree_id = worktree.read(cx).id();
         let remote_worktree_id = worktree.read(cx).id();
         let task_store = self.task_store.clone();
-
+        let can_trust_worktree = OnceCell::new();
         for (directory, kind, file_content) in settings_contents {
+            let mut applied = true;
             match kind {
-                LocalSettingsKind::Settings | LocalSettingsKind::Editorconfig => cx
-                    .update_global::<SettingsStore, _>(|store, cx| {
-                        let result = store.set_local_settings(
-                            worktree_id,
-                            directory.clone(),
-                            kind,
-                            file_content.as_deref(),
-                            cx,
-                        );
-
-                        match result {
-                            Err(InvalidSettingsError::LocalSettings { path, message }) => {
-                                log::error!("Failed to set local settings in {path:?}: {message}");
-                                cx.emit(SettingsObserverEvent::LocalSettingsUpdated(Err(
-                                    InvalidSettingsError::LocalSettings { path, message },
-                                )));
-                            }
-                            Err(e) => {
-                                log::error!("Failed to set local settings: {e}");
-                            }
-                            Ok(()) => {
-                                cx.emit(SettingsObserverEvent::LocalSettingsUpdated(Ok(directory
-                                    .as_std_path()
-                                    .join(local_settings_file_relative_path().as_std_path()))));
-                            }
+                LocalSettingsKind::Settings => {
+                    if *can_trust_worktree.get_or_init(|| {
+                        if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
+                            trusted_worktrees.update(cx, |trusted_worktrees, cx| {
+                                trusted_worktrees.can_trust(worktree_id, cx)
+                            })
+                        } else {
+                            true
                         }
-                    }),
+                    }) {
+                        apply_local_settings(worktree_id, &directory, kind, &file_content, cx)
+                    } else {
+                        applied = false;
+                        self.pending_local_settings
+                            .entry(PathTrust::Worktree(worktree_id))
+                            .or_default()
+                            .insert((worktree_id, directory.clone()), file_content.clone());
+                    }
+                }
+                LocalSettingsKind::Editorconfig => {
+                    apply_local_settings(worktree_id, &directory, kind, &file_content, cx)
+                }
                 LocalSettingsKind::Tasks => {
                     let result = task_store.update(cx, |task_store, cx| {
                         task_store.update_user_tasks(
@@ -1060,16 +1149,18 @@ impl SettingsObserver {
                 }
             };
 
-            if let Some(downstream_client) = &self.downstream_client {
-                downstream_client
-                    .send(proto::UpdateWorktreeSettings {
-                        project_id: self.project_id,
-                        worktree_id: remote_worktree_id.to_proto(),
-                        path: directory.to_proto(),
-                        content: file_content.clone(),
-                        kind: Some(local_settings_kind_to_proto(kind).into()),
-                    })
-                    .log_err();
+            if applied {
+                if let Some(downstream_client) = &self.downstream_client {
+                    downstream_client
+                        .send(proto::UpdateWorktreeSettings {
+                            project_id: self.project_id,
+                            worktree_id: remote_worktree_id.to_proto(),
+                            path: directory.to_proto(),
+                            content: file_content.clone(),
+                            kind: Some(local_settings_kind_to_proto(kind).into()),
+                        })
+                        .log_err();
+                }
             }
         }
     }
@@ -1186,6 +1277,37 @@ impl SettingsObserver {
     }
 }
 
+fn apply_local_settings(
+    worktree_id: WorktreeId,
+    directory: &Arc<RelPath>,
+    kind: LocalSettingsKind,
+    file_content: &Option<String>,
+    cx: &mut Context<'_, SettingsObserver>,
+) {
+    cx.update_global::<SettingsStore, _>(|store, cx| {
+        let result = store.set_local_settings(
+            worktree_id,
+            directory.clone(),
+            kind,
+            file_content.as_deref(),
+            cx,
+        );
+
+        match result {
+            Err(InvalidSettingsError::LocalSettings { path, message }) => {
+                log::error!("Failed to set local settings in {path:?}: {message}");
+                cx.emit(SettingsObserverEvent::LocalSettingsUpdated(Err(
+                    InvalidSettingsError::LocalSettings { path, message },
+                )));
+            }
+            Err(e) => log::error!("Failed to set local settings: {e}"),
+            Ok(()) => cx.emit(SettingsObserverEvent::LocalSettingsUpdated(Ok(directory
+                .as_std_path()
+                .join(local_settings_file_relative_path().as_std_path())))),
+        }
+    })
+}
+
 pub fn local_settings_kind_from_proto(kind: proto::LocalSettingsKind) -> LocalSettingsKind {
     match kind {
         proto::LocalSettingsKind::Settings => LocalSettingsKind::Settings,

crates/project/src/project_tests.rs 🔗

@@ -28,7 +28,7 @@ use language::{
     ManifestName, ManifestProvider, ManifestQuery, OffsetRangeExt, Point, ToPoint, ToolchainList,
     ToolchainLister,
     language_settings::{LanguageSettingsContent, language_settings},
-    tree_sitter_rust, tree_sitter_typescript,
+    rust_lang, tree_sitter_typescript,
 };
 use lsp::{
     DiagnosticSeverity, DocumentChanges, FileOperationFilter, NumberOrString, TextDocumentEdit,
@@ -691,7 +691,7 @@ async fn test_running_multiple_instances_of_a_single_server_in_one_worktree(
     let servers = project.update(cx, |project, cx| {
         project.lsp_store.update(cx, |this, cx| {
             first_buffer.update(cx, |buffer, cx| {
-                this.language_servers_for_local_buffer(buffer, cx)
+                this.running_language_servers_for_local_buffer(buffer, cx)
                     .map(|(adapter, server)| (adapter.clone(), server.clone()))
                     .collect::<Vec<_>>()
             })
@@ -720,7 +720,7 @@ async fn test_running_multiple_instances_of_a_single_server_in_one_worktree(
     let servers = project.update(cx, |project, cx| {
         project.lsp_store.update(cx, |this, cx| {
             second_project_buffer.update(cx, |buffer, cx| {
-                this.language_servers_for_local_buffer(buffer, cx)
+                this.running_language_servers_for_local_buffer(buffer, cx)
                     .map(|(adapter, server)| (adapter.clone(), server.clone()))
                     .collect::<Vec<_>>()
             })
@@ -746,7 +746,7 @@ async fn test_running_multiple_instances_of_a_single_server_in_one_worktree(
                     worktree_id,
                     path: rel_path("project-b/source_file.py").into(),
                 },
-                LanguageName::new("Python"),
+                LanguageName::new_static("Python"),
                 cx,
             )
         })
@@ -762,7 +762,7 @@ async fn test_running_multiple_instances_of_a_single_server_in_one_worktree(
                     worktree_id,
                     path: rel_path("project-b/source_file.py").into(),
                 },
-                LanguageName::new("Python"),
+                LanguageName::new_static("Python"),
                 cx,
             )
         })
@@ -791,7 +791,7 @@ async fn test_running_multiple_instances_of_a_single_server_in_one_worktree(
     let servers = project.update(cx, |project, cx| {
         project.lsp_store.update(cx, |this, cx| {
             second_project_buffer.update(cx, |buffer, cx| {
-                this.language_servers_for_local_buffer(buffer, cx)
+                this.running_language_servers_for_local_buffer(buffer, cx)
                     .map(|(adapter, server)| (adapter.clone(), server.clone()))
                     .collect::<Vec<_>>()
             })
@@ -2750,11 +2750,13 @@ async fn test_empty_diagnostic_ranges(cx: &mut gpui::TestAppContext) {
     );
 
     let fs = FakeFs::new(cx.executor());
-    fs.insert_tree("/dir", json!({ "a.rs": text })).await;
+    fs.insert_tree(path!("/dir"), json!({ "a.rs": text })).await;
 
-    let project = Project::test(fs, ["/dir".as_ref()], cx).await;
+    let project = Project::test(fs, [Path::new(path!("/dir"))], cx).await;
     let buffer = project
-        .update(cx, |project, cx| project.open_local_buffer("/dir/a.rs", cx))
+        .update(cx, |project, cx| {
+            project.open_local_buffer(path!("/dir/a.rs"), cx)
+        })
         .await
         .unwrap();
 
@@ -2763,7 +2765,7 @@ async fn test_empty_diagnostic_ranges(cx: &mut gpui::TestAppContext) {
             lsp_store
                 .update_diagnostic_entries(
                     LanguageServerId(0),
-                    PathBuf::from("/dir/a.rs"),
+                    PathBuf::from(path!("/dir/a.rs")),
                     None,
                     None,
                     vec![
@@ -2820,17 +2822,17 @@ async fn test_diagnostics_from_multiple_language_servers(cx: &mut gpui::TestAppC
     init_test(cx);
 
     let fs = FakeFs::new(cx.executor());
-    fs.insert_tree("/dir", json!({ "a.rs": "one two three" }))
+    fs.insert_tree(path!("/dir"), json!({ "a.rs": "one two three" }))
         .await;
 
-    let project = Project::test(fs, ["/dir".as_ref()], cx).await;
+    let project = Project::test(fs, [Path::new(path!("/dir"))], cx).await;
     let lsp_store = project.read_with(cx, |project, _| project.lsp_store.clone());
 
     lsp_store.update(cx, |lsp_store, cx| {
         lsp_store
             .update_diagnostic_entries(
                 LanguageServerId(0),
-                Path::new("/dir/a.rs").to_owned(),
+                Path::new(path!("/dir/a.rs")).to_owned(),
                 None,
                 None,
                 vec![DiagnosticEntry {
@@ -2849,7 +2851,7 @@ async fn test_diagnostics_from_multiple_language_servers(cx: &mut gpui::TestAppC
         lsp_store
             .update_diagnostic_entries(
                 LanguageServerId(1),
-                Path::new("/dir/a.rs").to_owned(),
+                Path::new(path!("/dir/a.rs")).to_owned(),
                 None,
                 None,
                 vec![DiagnosticEntry {
@@ -10480,20 +10482,6 @@ fn js_lang() -> Arc<Language> {
     ))
 }
 
-fn rust_lang() -> Arc<Language> {
-    Arc::new(Language::new(
-        LanguageConfig {
-            name: "Rust".into(),
-            matcher: LanguageMatcher {
-                path_suffixes: vec!["rs".to_string()],
-                ..Default::default()
-            },
-            ..Default::default()
-        },
-        Some(tree_sitter_rust::LANGUAGE.into()),
-    ))
-}
-
 fn python_lang(fs: Arc<FakeFs>) -> Arc<Language> {
     struct PythonMootToolchainLister(Arc<FakeFs>);
     #[async_trait]
@@ -10948,3 +10936,148 @@ async fn test_git_worktree_remove(cx: &mut gpui::TestAppContext) {
     });
     assert!(active_repo_path.is_none());
 }
+
+#[gpui::test]
+async fn test_optimistic_hunks_in_staged_files(cx: &mut gpui::TestAppContext) {
+    use DiffHunkSecondaryStatus::*;
+    init_test(cx);
+
+    let committed_contents = r#"
+        one
+        two
+        three
+    "#
+    .unindent();
+    let file_contents = r#"
+        one
+        TWO
+        three
+    "#
+    .unindent();
+
+    let fs = FakeFs::new(cx.background_executor.clone());
+    fs.insert_tree(
+        path!("/dir"),
+        json!({
+            ".git": {},
+            "file.txt": file_contents.clone()
+        }),
+    )
+    .await;
+
+    fs.set_head_and_index_for_repo(
+        path!("/dir/.git").as_ref(),
+        &[("file.txt", committed_contents.clone())],
+    );
+
+    let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
+
+    let buffer = project
+        .update(cx, |project, cx| {
+            project.open_local_buffer(path!("/dir/file.txt"), cx)
+        })
+        .await
+        .unwrap();
+    let snapshot = buffer.read_with(cx, |buffer, _| buffer.snapshot());
+    let uncommitted_diff = project
+        .update(cx, |project, cx| {
+            project.open_uncommitted_diff(buffer.clone(), cx)
+        })
+        .await
+        .unwrap();
+
+    // The hunk is initially unstaged.
+    uncommitted_diff.read_with(cx, |diff, cx| {
+        assert_hunks(
+            diff.snapshot(cx).hunks(&snapshot),
+            &snapshot,
+            &diff.base_text_string(cx).unwrap(),
+            &[(
+                1..2,
+                "two\n",
+                "TWO\n",
+                DiffHunkStatus::modified(HasSecondaryHunk),
+            )],
+        );
+    });
+
+    // Get the repository handle.
+    let repo = project.read_with(cx, |project, cx| {
+        project.repositories(cx).values().next().unwrap().clone()
+    });
+
+    // Stage the file.
+    let stage_task = repo.update(cx, |repo, cx| {
+        repo.stage_entries(vec![repo_path("file.txt")], cx)
+    });
+
+    // Run a few ticks to let the job start and mark hunks as pending,
+    // but don't run_until_parked which would complete the entire operation.
+    for _ in 0..10 {
+        cx.executor().tick();
+        let [hunk]: [_; 1] = uncommitted_diff
+            .read_with(cx, |diff, cx| {
+                diff.snapshot(cx).hunks(&snapshot).collect::<Vec<_>>()
+            })
+            .try_into()
+            .unwrap();
+        match hunk.secondary_status {
+            HasSecondaryHunk => {}
+            SecondaryHunkRemovalPending => break,
+            NoSecondaryHunk => panic!("hunk was not optimistically staged"),
+            _ => panic!("unexpected hunk state"),
+        }
+    }
+    uncommitted_diff.read_with(cx, |diff, cx| {
+        assert_hunks(
+            diff.snapshot(cx).hunks(&snapshot),
+            &snapshot,
+            &diff.base_text_string(cx).unwrap(),
+            &[(
+                1..2,
+                "two\n",
+                "TWO\n",
+                DiffHunkStatus::modified(SecondaryHunkRemovalPending),
+            )],
+        );
+    });
+
+    // Let the staging complete.
+    stage_task.await.unwrap();
+    cx.run_until_parked();
+
+    // The hunk is now fully staged.
+    uncommitted_diff.read_with(cx, |diff, cx| {
+        assert_hunks(
+            diff.snapshot(cx).hunks(&snapshot),
+            &snapshot,
+            &diff.base_text_string(cx).unwrap(),
+            &[(
+                1..2,
+                "two\n",
+                "TWO\n",
+                DiffHunkStatus::modified(NoSecondaryHunk),
+            )],
+        );
+    });
+
+    // Simulate a commit by updating HEAD to match the current file contents.
+    // The FakeGitRepository's commit method is a no-op, so we need to manually
+    // update HEAD to simulate the commit completing.
+    fs.set_head_for_repo(
+        path!("/dir/.git").as_ref(),
+        &[("file.txt", file_contents.clone())],
+        "newhead",
+    );
+    cx.run_until_parked();
+
+    // After committing, there are no more hunks.
+    uncommitted_diff.read_with(cx, |diff, cx| {
+        assert_hunks(
+            diff.snapshot(cx).hunks(&snapshot),
+            &snapshot,
+            &diff.base_text_string(cx).unwrap(),
+            &[] as &[(Range<u32>, &str, &str, DiffHunkStatus)],
+        );
+    });
+}

crates/project/src/telemetry_snapshot.rs 🔗

@@ -96,7 +96,7 @@ impl TelemetryWorktreeSnapshot {
                                 };
                             };
 
-                            let remote_url = backend.remote_url("origin");
+                            let remote_url = backend.remote_url("origin").await;
                             let head_sha = backend.head_sha().await;
                             let diff = backend.diff(DiffType::HeadToWorktree).await.ok();
 

crates/project/src/terminals.rs 🔗

@@ -111,7 +111,7 @@ impl Project {
             );
         let toolchains = project_path_contexts
             .filter(|_| detect_venv)
-            .map(|p| self.active_toolchain(p, LanguageName::new("Python"), cx))
+            .map(|p| self.active_toolchain(p, LanguageName::new_static("Python"), cx))
             .collect::<Vec<_>>();
         let lang_registry = self.languages.clone();
         cx.spawn(async move |project, cx| {
@@ -311,7 +311,7 @@ impl Project {
             );
         let toolchains = project_path_contexts
             .filter(|_| detect_venv)
-            .map(|p| self.active_toolchain(p, LanguageName::new("Python"), cx))
+            .map(|p| self.active_toolchain(p, LanguageName::new_static("Python"), cx))
             .collect::<Vec<_>>();
         let remote_client = self.remote_client.clone();
         let shell = match &remote_client {

crates/project/src/toolchain_store.rs 🔗

@@ -32,6 +32,7 @@ use crate::{
 pub struct ToolchainStore {
     mode: ToolchainStoreInner,
     user_toolchains: BTreeMap<ToolchainScope, IndexSet<Toolchain>>,
+    worktree_store: Entity<WorktreeStore>,
     _sub: Subscription,
 }
 
@@ -66,7 +67,7 @@ impl ToolchainStore {
     ) -> Self {
         let entity = cx.new(|_| LocalToolchainStore {
             languages,
-            worktree_store,
+            worktree_store: worktree_store.clone(),
             project_environment,
             active_toolchains: Default::default(),
             manifest_tree,
@@ -77,12 +78,18 @@ impl ToolchainStore {
         });
         Self {
             mode: ToolchainStoreInner::Local(entity),
+            worktree_store,
             user_toolchains: Default::default(),
             _sub,
         }
     }
 
-    pub(super) fn remote(project_id: u64, client: AnyProtoClient, cx: &mut Context<Self>) -> Self {
+    pub(super) fn remote(
+        project_id: u64,
+        worktree_store: Entity<WorktreeStore>,
+        client: AnyProtoClient,
+        cx: &mut Context<Self>,
+    ) -> Self {
         let entity = cx.new(|_| RemoteToolchainStore { client, project_id });
         let _sub = cx.subscribe(&entity, |_, _, e: &ToolchainStoreEvent, cx| {
             cx.emit(e.clone())
@@ -90,6 +97,7 @@ impl ToolchainStore {
         Self {
             mode: ToolchainStoreInner::Remote(entity),
             user_toolchains: Default::default(),
+            worktree_store,
             _sub,
         }
     }
@@ -165,12 +173,22 @@ impl ToolchainStore {
         language_name: LanguageName,
         cx: &mut Context<Self>,
     ) -> Task<Option<Toolchains>> {
+        let Some(worktree) = self
+            .worktree_store
+            .read(cx)
+            .worktree_for_id(path.worktree_id, cx)
+        else {
+            return Task::ready(None);
+        };
+        let target_root_path = worktree.read_with(cx, |this, _| this.abs_path());
+
         let user_toolchains = self
             .user_toolchains
             .iter()
             .filter(|(scope, _)| {
-                if let ToolchainScope::Subproject(worktree_id, relative_path) = scope {
-                    path.worktree_id == *worktree_id && relative_path.starts_with(&path.path)
+                if let ToolchainScope::Subproject(subproject_root_path, relative_path) = scope {
+                    target_root_path == *subproject_root_path
+                        && relative_path.starts_with(&path.path)
                 } else {
                     true
                 }

crates/project/src/trusted_worktrees.rs 🔗

@@ -0,0 +1,1464 @@
+//! A module, responsible for managing the trust logic in Zed.
+//!
+//! It deals with multiple hosts, distinguished by [`RemoteHostLocation`].
+//! Each [`crate::Project`] and `HeadlessProject` should call [`init_global`], if wants to establish the trust mechanism.
+//! This will set up a [`gpui::Global`] with [`TrustedWorktrees`] entity that will persist, restore and allow querying for worktree trust.
+//! It's also possible to subscribe on [`TrustedWorktreesEvent`] events of this entity to track trust changes dynamically.
+//!
+//! The implementation can synchronize trust information with the remote hosts: currently, WSL and SSH.
+//! Docker and Collab remotes do not employ trust mechanism, as manage that themselves.
+//!
+//! Unless `trust_all_worktrees` auto trust is enabled, does not trust anything that was not persisted before.
+//! When dealing with "restricted" and other related concepts in the API, it means all explicitly restricted, after any of the [`TrustedWorktreesStore::can_trust`] and [`TrustedWorktreesStore::can_trust_global`] calls.
+//!
+//!
+//!
+//!
+//! Path rust hierarchy.
+//!
+//! Zed has multiple layers of trust, based on the requests and [`PathTrust`] enum variants.
+//! From the least to the most trusted level:
+//!
+//! * "single file worktree"
+//!
+//! After opening an empty Zed it's possible to open just a file, same as after opening a directory in Zed it's possible to open a file outside of this directory.
+//! Usual scenario for both cases is opening Zed's settings.json file via `zed: open settings file` command: that starts a language server for a new file open, which originates from a newly created, single file worktree.
+//!
+//! Spawning a language server is potentially dangerous, and Zed needs to restrict that by default.
+//! Each single file worktree requires a separate trust permission, unless a more global level is trusted.
+//!
+//! * "directory worktree"
+//!
+//! If a directory is open in Zed, it's a full worktree which may spawn multiple language servers associated with it.
+//! Each such worktree requires a separate trust permission, so each separate directory worktree has to be trusted separately, unless a more global level is trusted.
+//!
+//! When a directory worktree is trusted and language servers are allowed to be downloaded and started, hence, "single file worktree" level of trust also.
+//!
+//! * "path override"
+//!
+//! To ease trusting multiple directory worktrees at once, it's possible to trust a parent directory of a certain directory worktree opened in Zed.
+//! Trusting a directory means trusting all its subdirectories as well, including all current and potential directory worktrees.
+
+use collections::{HashMap, HashSet};
+use gpui::{App, AppContext as _, Context, Entity, EventEmitter, Global, SharedString, WeakEntity};
+use remote::RemoteConnectionOptions;
+use rpc::{AnyProtoClient, proto};
+use settings::{Settings as _, WorktreeId};
+use std::{
+    path::{Path, PathBuf},
+    sync::Arc,
+};
+use util::debug_panic;
+
+use crate::{project_settings::ProjectSettings, worktree_store::WorktreeStore};
+
+pub fn init(
+    db_trusted_paths: TrustedPaths,
+    downstream_client: Option<(AnyProtoClient, u64)>,
+    upstream_client: Option<(AnyProtoClient, u64)>,
+    cx: &mut App,
+) {
+    if TrustedWorktrees::try_get_global(cx).is_none() {
+        let trusted_worktrees = cx.new(|_| {
+            TrustedWorktreesStore::new(
+                db_trusted_paths,
+                None,
+                None,
+                downstream_client,
+                upstream_client,
+            )
+        });
+        cx.set_global(TrustedWorktrees(trusted_worktrees))
+    }
+}
+
+/// An initialization call to set up trust global for a particular project (remote or local).
+pub fn track_worktree_trust(
+    worktree_store: Entity<WorktreeStore>,
+    remote_host: Option<RemoteHostLocation>,
+    downstream_client: Option<(AnyProtoClient, u64)>,
+    upstream_client: Option<(AnyProtoClient, u64)>,
+    cx: &mut App,
+) {
+    match TrustedWorktrees::try_get_global(cx) {
+        Some(trusted_worktrees) => {
+            trusted_worktrees.update(cx, |trusted_worktrees, cx| {
+                let sync_upstream = trusted_worktrees.upstream_client.as_ref().map(|(_, id)| id)
+                    != upstream_client.as_ref().map(|(_, id)| id);
+                trusted_worktrees.downstream_client = downstream_client;
+                trusted_worktrees.upstream_client = upstream_client;
+                trusted_worktrees.add_worktree_store(worktree_store, remote_host, cx);
+
+                if sync_upstream {
+                    if let Some((upstream_client, upstream_project_id)) =
+                        &trusted_worktrees.upstream_client
+                    {
+                        let trusted_paths = trusted_worktrees
+                            .trusted_paths
+                            .iter()
+                            .flat_map(|(_, paths)| {
+                                paths.iter().map(|trusted_path| trusted_path.to_proto())
+                            })
+                            .collect::<Vec<_>>();
+                        if !trusted_paths.is_empty() {
+                            upstream_client
+                                .send(proto::TrustWorktrees {
+                                    project_id: *upstream_project_id,
+                                    trusted_paths,
+                                })
+                                .ok();
+                        }
+                    }
+                }
+            });
+        }
+        None => log::debug!("No TrustedWorktrees initialized, not tracking worktree trust"),
+    }
+}
+
+/// A collection of worktree trust metadata, can be accessed globally (if initialized) and subscribed to.
+pub struct TrustedWorktrees(Entity<TrustedWorktreesStore>);
+
+impl Global for TrustedWorktrees {}
+
+impl TrustedWorktrees {
+    pub fn try_get_global(cx: &App) -> Option<Entity<TrustedWorktreesStore>> {
+        cx.try_global::<Self>().map(|this| this.0.clone())
+    }
+}
+
+/// A collection of worktrees that are considered trusted and not trusted.
+/// This can be used when checking for this criteria before enabling certain features.
+///
+/// Emits an event each time the worktree was checked and found not trusted,
+/// or a certain worktree had been trusted.
+pub struct TrustedWorktreesStore {
+    downstream_client: Option<(AnyProtoClient, u64)>,
+    upstream_client: Option<(AnyProtoClient, u64)>,
+    worktree_stores: HashMap<WeakEntity<WorktreeStore>, Option<RemoteHostLocation>>,
+    trusted_paths: TrustedPaths,
+    restricted: HashSet<WorktreeId>,
+}
+
+/// An identifier of a host to split the trust questions by.
+/// Each trusted data change and event is done for a particular host.
+/// A host may contain more than one worktree or even project open concurrently.
+#[derive(Debug, PartialEq, Eq, Clone, Hash)]
+pub struct RemoteHostLocation {
+    pub user_name: Option<SharedString>,
+    pub host_identifier: SharedString,
+}
+
+impl From<RemoteConnectionOptions> for RemoteHostLocation {
+    fn from(options: RemoteConnectionOptions) -> Self {
+        let (user_name, host_name) = match options {
+            RemoteConnectionOptions::Ssh(ssh) => (
+                ssh.username.map(SharedString::new),
+                SharedString::new(ssh.host.to_string()),
+            ),
+            RemoteConnectionOptions::Wsl(wsl) => (
+                wsl.user.map(SharedString::new),
+                SharedString::new(wsl.distro_name),
+            ),
+            RemoteConnectionOptions::Docker(docker_connection_options) => (
+                Some(SharedString::new(docker_connection_options.name)),
+                SharedString::new(docker_connection_options.container_id),
+            ),
+        };
+        RemoteHostLocation {
+            user_name,
+            host_identifier: host_name,
+        }
+    }
+}
+
+/// A unit of trust consideration inside a particular host:
+/// either a familiar worktree, or a path that may influence other worktrees' trust.
+/// See module-level documentation on the trust model.
+#[derive(Debug, PartialEq, Eq, Clone, Hash)]
+pub enum PathTrust {
+    /// A worktree that is familiar to this workspace.
+    /// Either a single file or a directory worktree.
+    Worktree(WorktreeId),
+    /// A path that may be another worktree yet not loaded into any workspace (hence, without any `WorktreeId`),
+    /// or a parent path coming out of the security modal.
+    AbsPath(PathBuf),
+}
+
+impl PathTrust {
+    fn to_proto(&self) -> proto::PathTrust {
+        match self {
+            Self::Worktree(worktree_id) => proto::PathTrust {
+                content: Some(proto::path_trust::Content::WorktreeId(
+                    worktree_id.to_proto(),
+                )),
+            },
+            Self::AbsPath(path_buf) => proto::PathTrust {
+                content: Some(proto::path_trust::Content::AbsPath(
+                    path_buf.to_string_lossy().to_string(),
+                )),
+            },
+        }
+    }
+
+    pub fn from_proto(proto: proto::PathTrust) -> Option<Self> {
+        Some(match proto.content? {
+            proto::path_trust::Content::WorktreeId(id) => {
+                Self::Worktree(WorktreeId::from_proto(id))
+            }
+            proto::path_trust::Content::AbsPath(path) => Self::AbsPath(PathBuf::from(path)),
+        })
+    }
+}
+
+/// A change of trust on a certain host.
+#[derive(Debug)]
+pub enum TrustedWorktreesEvent {
+    Trusted(Option<RemoteHostLocation>, HashSet<PathTrust>),
+    Restricted(Option<RemoteHostLocation>, HashSet<PathTrust>),
+}
+
+impl EventEmitter<TrustedWorktreesEvent> for TrustedWorktreesStore {}
+
+pub type TrustedPaths = HashMap<Option<RemoteHostLocation>, HashSet<PathTrust>>;
+
+impl TrustedWorktreesStore {
+    fn new(
+        trusted_paths: TrustedPaths,
+        worktree_store: Option<Entity<WorktreeStore>>,
+        remote_host: Option<RemoteHostLocation>,
+        downstream_client: Option<(AnyProtoClient, u64)>,
+        upstream_client: Option<(AnyProtoClient, u64)>,
+    ) -> Self {
+        if let Some((upstream_client, upstream_project_id)) = &upstream_client {
+            let trusted_paths = trusted_paths
+                .iter()
+                .flat_map(|(_, paths)| paths.iter().map(|trusted_path| trusted_path.to_proto()))
+                .collect::<Vec<_>>();
+            if !trusted_paths.is_empty() {
+                upstream_client
+                    .send(proto::TrustWorktrees {
+                        project_id: *upstream_project_id,
+                        trusted_paths,
+                    })
+                    .ok();
+            }
+        }
+
+        let worktree_stores = match worktree_store {
+            Some(worktree_store) => HashMap::from_iter([(worktree_store.downgrade(), remote_host)]),
+            None => HashMap::default(),
+        };
+
+        Self {
+            trusted_paths,
+            downstream_client,
+            upstream_client,
+            restricted: HashSet::default(),
+            worktree_stores,
+        }
+    }
+
+    /// Whether a particular worktree store has associated worktrees that are restricted, or an associated host is restricted.
+    pub fn has_restricted_worktrees(
+        &self,
+        worktree_store: &Entity<WorktreeStore>,
+        cx: &App,
+    ) -> bool {
+        self.worktree_stores
+            .contains_key(&worktree_store.downgrade())
+            && self.restricted.iter().any(|restricted_worktree| {
+                worktree_store
+                    .read(cx)
+                    .worktree_for_id(*restricted_worktree, cx)
+                    .is_some()
+            })
+    }
+
+    /// Adds certain entities on this host to the trusted list.
+    /// This will emit [`TrustedWorktreesEvent::Trusted`] event for all passed entries
+    /// and the ones that got auto trusted based on trust hierarchy (see module-level docs).
+    pub fn trust(
+        &mut self,
+        mut trusted_paths: HashSet<PathTrust>,
+        remote_host: Option<RemoteHostLocation>,
+        cx: &mut Context<Self>,
+    ) {
+        let mut new_trusted_single_file_worktrees = HashSet::default();
+        let mut new_trusted_other_worktrees = HashSet::default();
+        let mut new_trusted_abs_paths = HashSet::default();
+        for trusted_path in trusted_paths.iter().chain(
+            self.trusted_paths
+                .remove(&remote_host)
+                .iter()
+                .flat_map(|current_trusted| current_trusted.iter()),
+        ) {
+            match trusted_path {
+                PathTrust::Worktree(worktree_id) => {
+                    self.restricted.remove(worktree_id);
+                    if let Some((abs_path, is_file, host)) =
+                        self.find_worktree_data(*worktree_id, cx)
+                    {
+                        if host == remote_host {
+                            if is_file {
+                                new_trusted_single_file_worktrees.insert(*worktree_id);
+                            } else {
+                                new_trusted_other_worktrees.insert((abs_path, *worktree_id));
+                            }
+                        }
+                    }
+                }
+                PathTrust::AbsPath(path) => {
+                    debug_assert!(
+                        path.is_absolute(),
+                        "Cannot trust non-absolute path {path:?}"
+                    );
+                    new_trusted_abs_paths.insert(path.clone());
+                }
+            }
+        }
+
+        new_trusted_other_worktrees.retain(|(worktree_abs_path, _)| {
+            new_trusted_abs_paths
+                .iter()
+                .all(|new_trusted_path| !worktree_abs_path.starts_with(new_trusted_path))
+        });
+        if !new_trusted_other_worktrees.is_empty() {
+            new_trusted_single_file_worktrees.clear();
+        }
+        self.restricted = std::mem::take(&mut self.restricted)
+            .into_iter()
+            .filter(|restricted_worktree| {
+                let Some((restricted_worktree_path, is_file, restricted_host)) =
+                    self.find_worktree_data(*restricted_worktree, cx)
+                else {
+                    return false;
+                };
+                if restricted_host != remote_host {
+                    return true;
+                }
+
+                // When trusting an abs path on the host, we transitively trust all single file worktrees on this host too.
+                if is_file && !new_trusted_abs_paths.is_empty() {
+                    trusted_paths.insert(PathTrust::Worktree(*restricted_worktree));
+                    return false;
+                }
+
+                let retain = (!is_file || new_trusted_other_worktrees.is_empty())
+                    && new_trusted_abs_paths.iter().all(|new_trusted_path| {
+                        !restricted_worktree_path.starts_with(new_trusted_path)
+                    });
+                if !retain {
+                    trusted_paths.insert(PathTrust::Worktree(*restricted_worktree));
+                }
+                retain
+            })
+            .collect();
+
+        {
+            let trusted_paths = self.trusted_paths.entry(remote_host.clone()).or_default();
+            trusted_paths.extend(new_trusted_abs_paths.into_iter().map(PathTrust::AbsPath));
+            trusted_paths.extend(
+                new_trusted_other_worktrees
+                    .into_iter()
+                    .map(|(_, worktree_id)| PathTrust::Worktree(worktree_id)),
+            );
+            trusted_paths.extend(
+                new_trusted_single_file_worktrees
+                    .into_iter()
+                    .map(PathTrust::Worktree),
+            );
+        }
+
+        cx.emit(TrustedWorktreesEvent::Trusted(
+            remote_host,
+            trusted_paths.clone(),
+        ));
+
+        if let Some((upstream_client, upstream_project_id)) = &self.upstream_client {
+            let trusted_paths = trusted_paths
+                .iter()
+                .map(|trusted_path| trusted_path.to_proto())
+                .collect::<Vec<_>>();
+            if !trusted_paths.is_empty() {
+                upstream_client
+                    .send(proto::TrustWorktrees {
+                        project_id: *upstream_project_id,
+                        trusted_paths,
+                    })
+                    .ok();
+            }
+        }
+    }
+
+    /// Restricts certain entities on this host.
+    /// This will emit [`TrustedWorktreesEvent::Restricted`] event for all passed entries.
+    pub fn restrict(
+        &mut self,
+        restricted_paths: HashSet<PathTrust>,
+        remote_host: Option<RemoteHostLocation>,
+        cx: &mut Context<Self>,
+    ) {
+        for restricted_path in restricted_paths {
+            match restricted_path {
+                PathTrust::Worktree(worktree_id) => {
+                    self.restricted.insert(worktree_id);
+                    cx.emit(TrustedWorktreesEvent::Restricted(
+                        remote_host.clone(),
+                        HashSet::from_iter([PathTrust::Worktree(worktree_id)]),
+                    ));
+                }
+                PathTrust::AbsPath(..) => debug_panic!("Unexpected: cannot restrict an abs path"),
+            }
+        }
+    }
+
+    /// Erases all trust information.
+    /// Requires Zed's restart to take proper effect.
+    pub fn clear_trusted_paths(&mut self) {
+        self.trusted_paths.clear();
+    }
+
+    /// Checks whether a certain worktree is trusted (or on a larger trust level).
+    /// If not, emits [`TrustedWorktreesEvent::Restricted`] event if for the first time and not trusted, or no corresponding worktree store was found.
+    ///
+    /// No events or data adjustment happens when `trust_all_worktrees` auto trust is enabled.
+    pub fn can_trust(&mut self, worktree_id: WorktreeId, cx: &mut Context<Self>) -> bool {
+        if ProjectSettings::get_global(cx).session.trust_all_worktrees {
+            return true;
+        }
+        if self.restricted.contains(&worktree_id) {
+            return false;
+        }
+
+        let Some((worktree_path, is_file, remote_host)) = self.find_worktree_data(worktree_id, cx)
+        else {
+            return false;
+        };
+
+        if self
+            .trusted_paths
+            .get(&remote_host)
+            .is_some_and(|trusted_paths| trusted_paths.contains(&PathTrust::Worktree(worktree_id)))
+        {
+            return true;
+        }
+
+        // See module documentation for details on trust level.
+        if is_file && self.trusted_paths.contains_key(&remote_host) {
+            return true;
+        }
+
+        let parent_path_trusted =
+            self.trusted_paths
+                .get(&remote_host)
+                .is_some_and(|trusted_paths| {
+                    trusted_paths.iter().any(|trusted_path| {
+                        let PathTrust::AbsPath(trusted_path) = trusted_path else {
+                            return false;
+                        };
+                        worktree_path.starts_with(trusted_path)
+                    })
+                });
+        if parent_path_trusted {
+            return true;
+        }
+
+        self.restricted.insert(worktree_id);
+        cx.emit(TrustedWorktreesEvent::Restricted(
+            remote_host,
+            HashSet::from_iter([PathTrust::Worktree(worktree_id)]),
+        ));
+        if let Some((downstream_client, downstream_project_id)) = &self.downstream_client {
+            downstream_client
+                .send(proto::RestrictWorktrees {
+                    project_id: *downstream_project_id,
+                    worktree_ids: vec![worktree_id.to_proto()],
+                })
+                .ok();
+        }
+        if let Some((upstream_client, upstream_project_id)) = &self.upstream_client {
+            upstream_client
+                .send(proto::RestrictWorktrees {
+                    project_id: *upstream_project_id,
+                    worktree_ids: vec![worktree_id.to_proto()],
+                })
+                .ok();
+        }
+        false
+    }
+
+    /// Lists all explicitly restricted worktrees (via [`TrustedWorktreesStore::can_trust`] method calls) for a particular worktree store on a particular host.
+    pub fn restricted_worktrees(
+        &self,
+        worktree_store: &WorktreeStore,
+        cx: &App,
+    ) -> HashSet<(WorktreeId, Arc<Path>)> {
+        let mut single_file_paths = HashSet::default();
+        let other_paths = self
+            .restricted
+            .iter()
+            .filter_map(|&restricted_worktree_id| {
+                let worktree = worktree_store.worktree_for_id(restricted_worktree_id, cx)?;
+                let worktree = worktree.read(cx);
+                let abs_path = worktree.abs_path();
+                if worktree.is_single_file() {
+                    single_file_paths.insert((restricted_worktree_id, abs_path));
+                    None
+                } else {
+                    Some((restricted_worktree_id, abs_path))
+                }
+            })
+            .collect::<HashSet<_>>();
+
+        if !other_paths.is_empty() {
+            return other_paths;
+        } else {
+            single_file_paths
+        }
+    }
+
+    /// Switches the "trust nothing" mode to "automatically trust everything".
+    /// This does not influence already persisted data, but stops adding new worktrees there.
+    pub fn auto_trust_all(&mut self, cx: &mut Context<Self>) {
+        for (remote_host, worktrees) in std::mem::take(&mut self.restricted)
+            .into_iter()
+            .flat_map(|restricted_worktree| {
+                let (_, _, host) = self.find_worktree_data(restricted_worktree, cx)?;
+                Some((restricted_worktree, host))
+            })
+            .fold(HashMap::default(), |mut acc, (worktree_id, remote_host)| {
+                acc.entry(remote_host)
+                    .or_insert_with(HashSet::default)
+                    .insert(PathTrust::Worktree(worktree_id));
+                acc
+            })
+        {
+            self.trust(worktrees, remote_host, cx);
+        }
+    }
+
+    /// Returns a normalized representation of the trusted paths to store in the DB.
+    pub fn trusted_paths_for_serialization(
+        &mut self,
+        cx: &mut Context<Self>,
+    ) -> HashMap<Option<RemoteHostLocation>, HashSet<PathBuf>> {
+        let new_trusted_worktrees = self
+            .trusted_paths
+            .clone()
+            .into_iter()
+            .map(|(host, paths)| {
+                let abs_paths = paths
+                    .into_iter()
+                    .flat_map(|path| match path {
+                        PathTrust::Worktree(worktree_id) => self
+                            .find_worktree_data(worktree_id, cx)
+                            .map(|(abs_path, ..)| abs_path.to_path_buf()),
+                        PathTrust::AbsPath(abs_path) => Some(abs_path),
+                    })
+                    .collect();
+                (host, abs_paths)
+            })
+            .collect();
+        new_trusted_worktrees
+    }
+
+    fn find_worktree_data(
+        &mut self,
+        worktree_id: WorktreeId,
+        cx: &mut Context<Self>,
+    ) -> Option<(Arc<Path>, bool, Option<RemoteHostLocation>)> {
+        let mut worktree_data = None;
+        self.worktree_stores.retain(
+            |worktree_store, remote_host| match worktree_store.upgrade() {
+                Some(worktree_store) => {
+                    if worktree_data.is_none() {
+                        if let Some(worktree) =
+                            worktree_store.read(cx).worktree_for_id(worktree_id, cx)
+                        {
+                            worktree_data = Some((
+                                worktree.read(cx).abs_path(),
+                                worktree.read(cx).is_single_file(),
+                                remote_host.clone(),
+                            ));
+                        }
+                    }
+                    true
+                }
+                None => false,
+            },
+        );
+        worktree_data
+    }
+
+    fn add_worktree_store(
+        &mut self,
+        worktree_store: Entity<WorktreeStore>,
+        remote_host: Option<RemoteHostLocation>,
+        cx: &mut Context<Self>,
+    ) {
+        self.worktree_stores
+            .insert(worktree_store.downgrade(), remote_host.clone());
+
+        if let Some(trusted_paths) = self.trusted_paths.remove(&remote_host) {
+            self.trusted_paths.insert(
+                remote_host.clone(),
+                trusted_paths
+                    .into_iter()
+                    .map(|path_trust| match path_trust {
+                        PathTrust::AbsPath(abs_path) => {
+                            find_worktree_in_store(worktree_store.read(cx), &abs_path, cx)
+                                .map(PathTrust::Worktree)
+                                .unwrap_or_else(|| PathTrust::AbsPath(abs_path))
+                        }
+                        other => other,
+                    })
+                    .collect(),
+            );
+        }
+    }
+}
+
+pub fn find_worktree_in_store(
+    worktree_store: &WorktreeStore,
+    abs_path: &Path,
+    cx: &App,
+) -> Option<WorktreeId> {
+    let (worktree, path_in_worktree) = worktree_store.find_worktree(&abs_path, cx)?;
+    if path_in_worktree.is_empty() {
+        Some(worktree.read(cx).id())
+    } else {
+        None
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use std::{cell::RefCell, path::PathBuf, rc::Rc};
+
+    use collections::HashSet;
+    use gpui::TestAppContext;
+    use serde_json::json;
+    use settings::SettingsStore;
+    use util::path;
+
+    use crate::{FakeFs, Project};
+
+    use super::*;
+
+    fn init_test(cx: &mut TestAppContext) {
+        cx.update(|cx| {
+            if cx.try_global::<SettingsStore>().is_none() {
+                let settings_store = SettingsStore::test(cx);
+                cx.set_global(settings_store);
+            }
+            if cx.try_global::<TrustedWorktrees>().is_some() {
+                cx.remove_global::<TrustedWorktrees>();
+            }
+        });
+    }
+
+    fn init_trust_global(
+        worktree_store: Entity<WorktreeStore>,
+        cx: &mut TestAppContext,
+    ) -> Entity<TrustedWorktreesStore> {
+        cx.update(|cx| {
+            init(HashMap::default(), None, None, cx);
+            track_worktree_trust(worktree_store, None, None, None, cx);
+            TrustedWorktrees::try_get_global(cx).expect("global should be set")
+        })
+    }
+
+    #[gpui::test]
+    async fn test_single_worktree_trust(cx: &mut TestAppContext) {
+        init_test(cx);
+
+        let fs = FakeFs::new(cx.executor());
+        fs.insert_tree(path!("/root"), json!({ "main.rs": "fn main() {}" }))
+            .await;
+
+        let project = Project::test(fs, [path!("/root").as_ref()], cx).await;
+        let worktree_store = project.read_with(cx, |project, _| project.worktree_store());
+        let worktree_id = worktree_store.read_with(cx, |store, cx| {
+            store.worktrees().next().unwrap().read(cx).id()
+        });
+
+        let trusted_worktrees = init_trust_global(worktree_store.clone(), cx);
+
+        let events: Rc<RefCell<Vec<TrustedWorktreesEvent>>> = Rc::default();
+        cx.update({
+            let events = events.clone();
+            |cx| {
+                cx.subscribe(&trusted_worktrees, move |_, event, _| {
+                    events.borrow_mut().push(match event {
+                        TrustedWorktreesEvent::Trusted(host, paths) => {
+                            TrustedWorktreesEvent::Trusted(host.clone(), paths.clone())
+                        }
+                        TrustedWorktreesEvent::Restricted(host, paths) => {
+                            TrustedWorktreesEvent::Restricted(host.clone(), paths.clone())
+                        }
+                    });
+                })
+            }
+        })
+        .detach();
+
+        let can_trust = trusted_worktrees.update(cx, |store, cx| store.can_trust(worktree_id, cx));
+        assert!(!can_trust, "worktree should be restricted by default");
+
+        {
+            let events = events.borrow();
+            assert_eq!(events.len(), 1);
+            match &events[0] {
+                TrustedWorktreesEvent::Restricted(host, paths) => {
+                    assert!(host.is_none());
+                    assert!(paths.contains(&PathTrust::Worktree(worktree_id)));
+                }
+                _ => panic!("expected Restricted event"),
+            }
+        }
+
+        let has_restricted = trusted_worktrees.read_with(cx, |store, cx| {
+            store.has_restricted_worktrees(&worktree_store, cx)
+        });
+        assert!(has_restricted, "should have restricted worktrees");
+
+        let restricted = worktree_store.read_with(cx, |ws, cx| {
+            trusted_worktrees.read(cx).restricted_worktrees(ws, cx)
+        });
+        assert!(restricted.iter().any(|(id, _)| *id == worktree_id));
+
+        events.borrow_mut().clear();
+
+        let can_trust_again =
+            trusted_worktrees.update(cx, |store, cx| store.can_trust(worktree_id, cx));
+        assert!(!can_trust_again, "worktree should still be restricted");
+        assert!(
+            events.borrow().is_empty(),
+            "no duplicate Restricted event on repeated can_trust"
+        );
+
+        trusted_worktrees.update(cx, |store, cx| {
+            store.trust(
+                HashSet::from_iter([PathTrust::Worktree(worktree_id)]),
+                None,
+                cx,
+            );
+        });
+
+        {
+            let events = events.borrow();
+            assert_eq!(events.len(), 1);
+            match &events[0] {
+                TrustedWorktreesEvent::Trusted(host, paths) => {
+                    assert!(host.is_none());
+                    assert!(paths.contains(&PathTrust::Worktree(worktree_id)));
+                }
+                _ => panic!("expected Trusted event"),
+            }
+        }
+
+        let can_trust_after =
+            trusted_worktrees.update(cx, |store, cx| store.can_trust(worktree_id, cx));
+        assert!(can_trust_after, "worktree should be trusted after trust()");
+
+        let has_restricted_after = trusted_worktrees.read_with(cx, |store, cx| {
+            store.has_restricted_worktrees(&worktree_store, cx)
+        });
+        assert!(
+            !has_restricted_after,
+            "should have no restricted worktrees after trust"
+        );
+
+        let restricted_after = worktree_store.read_with(cx, |ws, cx| {
+            trusted_worktrees.read(cx).restricted_worktrees(ws, cx)
+        });
+        assert!(
+            restricted_after.is_empty(),
+            "restricted set should be empty"
+        );
+    }
+
+    #[gpui::test]
+    async fn test_single_file_worktree_trust(cx: &mut TestAppContext) {
+        init_test(cx);
+
+        let fs = FakeFs::new(cx.executor());
+        fs.insert_tree(path!("/root"), json!({ "foo.rs": "fn foo() {}" }))
+            .await;
+
+        let project = Project::test(fs, [path!("/root/foo.rs").as_ref()], cx).await;
+        let worktree_store = project.read_with(cx, |project, _| project.worktree_store());
+        let worktree_id = worktree_store.read_with(cx, |store, cx| {
+            let worktree = store.worktrees().next().unwrap();
+            let worktree = worktree.read(cx);
+            assert!(worktree.is_single_file(), "expected single-file worktree");
+            worktree.id()
+        });
+
+        let trusted_worktrees = init_trust_global(worktree_store, cx);
+
+        let events: Rc<RefCell<Vec<TrustedWorktreesEvent>>> = Rc::default();
+        cx.update({
+            let events = events.clone();
+            |cx| {
+                cx.subscribe(&trusted_worktrees, move |_, event, _| {
+                    events.borrow_mut().push(match event {
+                        TrustedWorktreesEvent::Trusted(host, paths) => {
+                            TrustedWorktreesEvent::Trusted(host.clone(), paths.clone())
+                        }
+                        TrustedWorktreesEvent::Restricted(host, paths) => {
+                            TrustedWorktreesEvent::Restricted(host.clone(), paths.clone())
+                        }
+                    });
+                })
+            }
+        })
+        .detach();
+
+        let can_trust = trusted_worktrees.update(cx, |store, cx| store.can_trust(worktree_id, cx));
+        assert!(
+            !can_trust,
+            "single-file worktree should be restricted by default"
+        );
+
+        {
+            let events = events.borrow();
+            assert_eq!(events.len(), 1);
+            match &events[0] {
+                TrustedWorktreesEvent::Restricted(host, paths) => {
+                    assert!(host.is_none());
+                    assert!(paths.contains(&PathTrust::Worktree(worktree_id)));
+                }
+                _ => panic!("expected Restricted event"),
+            }
+        }
+
+        events.borrow_mut().clear();
+
+        trusted_worktrees.update(cx, |store, cx| {
+            store.trust(
+                HashSet::from_iter([PathTrust::Worktree(worktree_id)]),
+                None,
+                cx,
+            );
+        });
+
+        {
+            let events = events.borrow();
+            assert_eq!(events.len(), 1);
+            match &events[0] {
+                TrustedWorktreesEvent::Trusted(host, paths) => {
+                    assert!(host.is_none());
+                    assert!(paths.contains(&PathTrust::Worktree(worktree_id)));
+                }
+                _ => panic!("expected Trusted event"),
+            }
+        }
+
+        let can_trust_after =
+            trusted_worktrees.update(cx, |store, cx| store.can_trust(worktree_id, cx));
+        assert!(
+            can_trust_after,
+            "single-file worktree should be trusted after trust()"
+        );
+    }
+
+    #[gpui::test]
+    async fn test_multiple_single_file_worktrees_trust_one(cx: &mut TestAppContext) {
+        init_test(cx);
+
+        let fs = FakeFs::new(cx.executor());
+        fs.insert_tree(
+            path!("/root"),
+            json!({
+                "a.rs": "fn a() {}",
+                "b.rs": "fn b() {}",
+                "c.rs": "fn c() {}"
+            }),
+        )
+        .await;
+
+        let project = Project::test(
+            fs,
+            [
+                path!("/root/a.rs").as_ref(),
+                path!("/root/b.rs").as_ref(),
+                path!("/root/c.rs").as_ref(),
+            ],
+            cx,
+        )
+        .await;
+        let worktree_store = project.read_with(cx, |project, _| project.worktree_store());
+        let worktree_ids: Vec<_> = worktree_store.read_with(cx, |store, cx| {
+            store
+                .worktrees()
+                .map(|worktree| {
+                    let worktree = worktree.read(cx);
+                    assert!(worktree.is_single_file());
+                    worktree.id()
+                })
+                .collect()
+        });
+        assert_eq!(worktree_ids.len(), 3);
+
+        let trusted_worktrees = init_trust_global(worktree_store, cx);
+
+        for &worktree_id in &worktree_ids {
+            let can_trust =
+                trusted_worktrees.update(cx, |store, cx| store.can_trust(worktree_id, cx));
+            assert!(
+                !can_trust,
+                "worktree {worktree_id:?} should be restricted initially"
+            );
+        }
+
+        trusted_worktrees.update(cx, |store, cx| {
+            store.trust(
+                HashSet::from_iter([PathTrust::Worktree(worktree_ids[1])]),
+                None,
+                cx,
+            );
+        });
+
+        let can_trust_0 =
+            trusted_worktrees.update(cx, |store, cx| store.can_trust(worktree_ids[0], cx));
+        let can_trust_1 =
+            trusted_worktrees.update(cx, |store, cx| store.can_trust(worktree_ids[1], cx));
+        let can_trust_2 =
+            trusted_worktrees.update(cx, |store, cx| store.can_trust(worktree_ids[2], cx));
+
+        assert!(!can_trust_0, "worktree 0 should still be restricted");
+        assert!(can_trust_1, "worktree 1 should be trusted");
+        assert!(!can_trust_2, "worktree 2 should still be restricted");
+    }
+
+    #[gpui::test]
+    async fn test_two_directory_worktrees_separate_trust(cx: &mut TestAppContext) {
+        init_test(cx);
+
+        let fs = FakeFs::new(cx.executor());
+        fs.insert_tree(
+            path!("/projects"),
+            json!({
+                "project_a": { "main.rs": "fn main() {}" },
+                "project_b": { "lib.rs": "pub fn lib() {}" }
+            }),
+        )
+        .await;
+
+        let project = Project::test(
+            fs,
+            [
+                path!("/projects/project_a").as_ref(),
+                path!("/projects/project_b").as_ref(),
+            ],
+            cx,
+        )
+        .await;
+        let worktree_store = project.read_with(cx, |project, _| project.worktree_store());
+        let worktree_ids: Vec<_> = worktree_store.read_with(cx, |store, cx| {
+            store
+                .worktrees()
+                .map(|worktree| {
+                    let worktree = worktree.read(cx);
+                    assert!(!worktree.is_single_file());
+                    worktree.id()
+                })
+                .collect()
+        });
+        assert_eq!(worktree_ids.len(), 2);
+
+        let trusted_worktrees = init_trust_global(worktree_store, cx);
+
+        let can_trust_a =
+            trusted_worktrees.update(cx, |store, cx| store.can_trust(worktree_ids[0], cx));
+        let can_trust_b =
+            trusted_worktrees.update(cx, |store, cx| store.can_trust(worktree_ids[1], cx));
+        assert!(!can_trust_a, "project_a should be restricted initially");
+        assert!(!can_trust_b, "project_b should be restricted initially");
+
+        trusted_worktrees.update(cx, |store, cx| {
+            store.trust(
+                HashSet::from_iter([PathTrust::Worktree(worktree_ids[0])]),
+                None,
+                cx,
+            );
+        });
+
+        let can_trust_a =
+            trusted_worktrees.update(cx, |store, cx| store.can_trust(worktree_ids[0], cx));
+        let can_trust_b =
+            trusted_worktrees.update(cx, |store, cx| store.can_trust(worktree_ids[1], cx));
+        assert!(can_trust_a, "project_a should be trusted after trust()");
+        assert!(!can_trust_b, "project_b should still be restricted");
+
+        trusted_worktrees.update(cx, |store, cx| {
+            store.trust(
+                HashSet::from_iter([PathTrust::Worktree(worktree_ids[1])]),
+                None,
+                cx,
+            );
+        });
+
+        let can_trust_a =
+            trusted_worktrees.update(cx, |store, cx| store.can_trust(worktree_ids[0], cx));
+        let can_trust_b =
+            trusted_worktrees.update(cx, |store, cx| store.can_trust(worktree_ids[1], cx));
+        assert!(can_trust_a, "project_a should remain trusted");
+        assert!(can_trust_b, "project_b should now be trusted");
+    }
+
+    #[gpui::test]
+    async fn test_directory_worktree_trust_enables_single_file(cx: &mut TestAppContext) {
+        init_test(cx);
+
+        let fs = FakeFs::new(cx.executor());
+        fs.insert_tree(
+            path!("/"),
+            json!({
+                "project": { "main.rs": "fn main() {}" },
+                "standalone.rs": "fn standalone() {}"
+            }),
+        )
+        .await;
+
+        let project = Project::test(
+            fs,
+            [path!("/project").as_ref(), path!("/standalone.rs").as_ref()],
+            cx,
+        )
+        .await;
+        let worktree_store = project.read_with(cx, |project, _| project.worktree_store());
+        let (dir_worktree_id, file_worktree_id) = worktree_store.read_with(cx, |store, cx| {
+            let worktrees: Vec<_> = store.worktrees().collect();
+            assert_eq!(worktrees.len(), 2);
+            let (dir_worktree, file_worktree) = if worktrees[0].read(cx).is_single_file() {
+                (&worktrees[1], &worktrees[0])
+            } else {
+                (&worktrees[0], &worktrees[1])
+            };
+            assert!(!dir_worktree.read(cx).is_single_file());
+            assert!(file_worktree.read(cx).is_single_file());
+            (dir_worktree.read(cx).id(), file_worktree.read(cx).id())
+        });
+
+        let trusted_worktrees = init_trust_global(worktree_store, cx);
+
+        let can_trust_file =
+            trusted_worktrees.update(cx, |store, cx| store.can_trust(file_worktree_id, cx));
+        assert!(
+            !can_trust_file,
+            "single-file worktree should be restricted initially"
+        );
+
+        let can_trust_directory =
+            trusted_worktrees.update(cx, |store, cx| store.can_trust(dir_worktree_id, cx));
+        assert!(
+            !can_trust_directory,
+            "directory worktree should be restricted initially"
+        );
+
+        trusted_worktrees.update(cx, |store, cx| {
+            store.trust(
+                HashSet::from_iter([PathTrust::Worktree(dir_worktree_id)]),
+                None,
+                cx,
+            );
+        });
+
+        let can_trust_dir =
+            trusted_worktrees.update(cx, |store, cx| store.can_trust(dir_worktree_id, cx));
+        let can_trust_file_after =
+            trusted_worktrees.update(cx, |store, cx| store.can_trust(file_worktree_id, cx));
+        assert!(can_trust_dir, "directory worktree should be trusted");
+        assert!(
+            can_trust_file_after,
+            "single-file worktree should be trusted after directory worktree trust"
+        );
+    }
+
+    #[gpui::test]
+    async fn test_parent_path_trust_enables_single_file(cx: &mut TestAppContext) {
+        init_test(cx);
+
+        let fs = FakeFs::new(cx.executor());
+        fs.insert_tree(
+            path!("/"),
+            json!({
+                "project": { "main.rs": "fn main() {}" },
+                "standalone.rs": "fn standalone() {}"
+            }),
+        )
+        .await;
+
+        let project = Project::test(
+            fs,
+            [path!("/project").as_ref(), path!("/standalone.rs").as_ref()],
+            cx,
+        )
+        .await;
+        let worktree_store = project.read_with(cx, |project, _| project.worktree_store());
+        let (dir_worktree_id, file_worktree_id) = worktree_store.read_with(cx, |store, cx| {
+            let worktrees: Vec<_> = store.worktrees().collect();
+            assert_eq!(worktrees.len(), 2);
+            let (dir_worktree, file_worktree) = if worktrees[0].read(cx).is_single_file() {
+                (&worktrees[1], &worktrees[0])
+            } else {
+                (&worktrees[0], &worktrees[1])
+            };
+            assert!(!dir_worktree.read(cx).is_single_file());
+            assert!(file_worktree.read(cx).is_single_file());
+            (dir_worktree.read(cx).id(), file_worktree.read(cx).id())
+        });
+
+        let trusted_worktrees = init_trust_global(worktree_store, cx);
+
+        let can_trust_file =
+            trusted_worktrees.update(cx, |store, cx| store.can_trust(file_worktree_id, cx));
+        assert!(
+            !can_trust_file,
+            "single-file worktree should be restricted initially"
+        );
+
+        let can_trust_directory =
+            trusted_worktrees.update(cx, |store, cx| store.can_trust(dir_worktree_id, cx));
+        assert!(
+            !can_trust_directory,
+            "directory worktree should be restricted initially"
+        );
+
+        trusted_worktrees.update(cx, |store, cx| {
+            store.trust(
+                HashSet::from_iter([PathTrust::AbsPath(PathBuf::from(path!("/project")))]),
+                None,
+                cx,
+            );
+        });
+
+        let can_trust_dir =
+            trusted_worktrees.update(cx, |store, cx| store.can_trust(dir_worktree_id, cx));
+        let can_trust_file_after =
+            trusted_worktrees.update(cx, |store, cx| store.can_trust(file_worktree_id, cx));
+        assert!(
+            can_trust_dir,
+            "directory worktree should be trusted after its parent is trusted"
+        );
+        assert!(
+            can_trust_file_after,
+            "single-file worktree should be trusted after directory worktree trust via its parent directory trust"
+        );
+    }
+
+    #[gpui::test]
+    async fn test_abs_path_trust_covers_multiple_worktrees(cx: &mut TestAppContext) {
+        init_test(cx);
+
+        let fs = FakeFs::new(cx.executor());
+        fs.insert_tree(
+            path!("/root"),
+            json!({
+                "project_a": { "main.rs": "fn main() {}" },
+                "project_b": { "lib.rs": "pub fn lib() {}" }
+            }),
+        )
+        .await;
+
+        let project = Project::test(
+            fs,
+            [
+                path!("/root/project_a").as_ref(),
+                path!("/root/project_b").as_ref(),
+            ],
+            cx,
+        )
+        .await;
+        let worktree_store = project.read_with(cx, |project, _| project.worktree_store());
+        let worktree_ids: Vec<_> = worktree_store.read_with(cx, |store, cx| {
+            store
+                .worktrees()
+                .map(|worktree| worktree.read(cx).id())
+                .collect()
+        });
+        assert_eq!(worktree_ids.len(), 2);
+
+        let trusted_worktrees = init_trust_global(worktree_store, cx);
+
+        for &worktree_id in &worktree_ids {
+            let can_trust =
+                trusted_worktrees.update(cx, |store, cx| store.can_trust(worktree_id, cx));
+            assert!(!can_trust, "worktree should be restricted initially");
+        }
+
+        trusted_worktrees.update(cx, |store, cx| {
+            store.trust(
+                HashSet::from_iter([PathTrust::AbsPath(PathBuf::from(path!("/root")))]),
+                None,
+                cx,
+            );
+        });
+
+        for &worktree_id in &worktree_ids {
+            let can_trust =
+                trusted_worktrees.update(cx, |store, cx| store.can_trust(worktree_id, cx));
+            assert!(
+                can_trust,
+                "worktree should be trusted after parent path trust"
+            );
+        }
+    }
+
+    #[gpui::test]
+    async fn test_auto_trust_all(cx: &mut TestAppContext) {
+        init_test(cx);
+
+        let fs = FakeFs::new(cx.executor());
+        fs.insert_tree(
+            path!("/"),
+            json!({
+                "project_a": { "main.rs": "fn main() {}" },
+                "project_b": { "lib.rs": "pub fn lib() {}" },
+                "single.rs": "fn single() {}"
+            }),
+        )
+        .await;
+
+        let project = Project::test(
+            fs,
+            [
+                path!("/project_a").as_ref(),
+                path!("/project_b").as_ref(),
+                path!("/single.rs").as_ref(),
+            ],
+            cx,
+        )
+        .await;
+        let worktree_store = project.read_with(cx, |project, _| project.worktree_store());
+        let worktree_ids: Vec<_> = worktree_store.read_with(cx, |store, cx| {
+            store
+                .worktrees()
+                .map(|worktree| worktree.read(cx).id())
+                .collect()
+        });
+        assert_eq!(worktree_ids.len(), 3);
+
+        let trusted_worktrees = init_trust_global(worktree_store.clone(), cx);
+
+        let events: Rc<RefCell<Vec<TrustedWorktreesEvent>>> = Rc::default();
+        cx.update({
+            let events = events.clone();
+            |cx| {
+                cx.subscribe(&trusted_worktrees, move |_, event, _| {
+                    events.borrow_mut().push(match event {
+                        TrustedWorktreesEvent::Trusted(host, paths) => {
+                            TrustedWorktreesEvent::Trusted(host.clone(), paths.clone())
+                        }
+                        TrustedWorktreesEvent::Restricted(host, paths) => {
+                            TrustedWorktreesEvent::Restricted(host.clone(), paths.clone())
+                        }
+                    });
+                })
+            }
+        })
+        .detach();
+
+        for &worktree_id in &worktree_ids {
+            let can_trust =
+                trusted_worktrees.update(cx, |store, cx| store.can_trust(worktree_id, cx));
+            assert!(!can_trust, "worktree should be restricted initially");
+        }
+
+        let has_restricted = trusted_worktrees.read_with(cx, |store, cx| {
+            store.has_restricted_worktrees(&worktree_store, cx)
+        });
+        assert!(has_restricted, "should have restricted worktrees");
+
+        events.borrow_mut().clear();
+
+        trusted_worktrees.update(cx, |store, cx| {
+            store.auto_trust_all(cx);
+        });
+
+        for &worktree_id in &worktree_ids {
+            let can_trust =
+                trusted_worktrees.update(cx, |store, cx| store.can_trust(worktree_id, cx));
+            assert!(
+                can_trust,
+                "worktree {worktree_id:?} should be trusted after auto_trust_all"
+            );
+        }
+
+        let has_restricted_after = trusted_worktrees.read_with(cx, |store, cx| {
+            store.has_restricted_worktrees(&worktree_store, cx)
+        });
+        assert!(
+            !has_restricted_after,
+            "should have no restricted worktrees after auto_trust_all"
+        );
+
+        let trusted_event_count = events
+            .borrow()
+            .iter()
+            .filter(|e| matches!(e, TrustedWorktreesEvent::Trusted(..)))
+            .count();
+        assert!(
+            trusted_event_count > 0,
+            "should have emitted Trusted events"
+        );
+    }
+
+    #[gpui::test]
+    async fn test_trust_restrict_trust_cycle(cx: &mut TestAppContext) {
+        init_test(cx);
+
+        let fs = FakeFs::new(cx.executor());
+        fs.insert_tree(path!("/root"), json!({ "main.rs": "fn main() {}" }))
+            .await;
+
+        let project = Project::test(fs, [path!("/root").as_ref()], cx).await;
+        let worktree_store = project.read_with(cx, |project, _| project.worktree_store());
+        let worktree_id = worktree_store.read_with(cx, |store, cx| {
+            store.worktrees().next().unwrap().read(cx).id()
+        });
+
+        let trusted_worktrees = init_trust_global(worktree_store.clone(), cx);
+
+        let events: Rc<RefCell<Vec<TrustedWorktreesEvent>>> = Rc::default();
+        cx.update({
+            let events = events.clone();
+            |cx| {
+                cx.subscribe(&trusted_worktrees, move |_, event, _| {
+                    events.borrow_mut().push(match event {
+                        TrustedWorktreesEvent::Trusted(host, paths) => {
+                            TrustedWorktreesEvent::Trusted(host.clone(), paths.clone())
+                        }
+                        TrustedWorktreesEvent::Restricted(host, paths) => {
+                            TrustedWorktreesEvent::Restricted(host.clone(), paths.clone())
+                        }
+                    });
+                })
+            }
+        })
+        .detach();
+
+        let can_trust = trusted_worktrees.update(cx, |store, cx| store.can_trust(worktree_id, cx));
+        assert!(!can_trust, "should be restricted initially");
+        assert_eq!(events.borrow().len(), 1);
+        events.borrow_mut().clear();
+
+        trusted_worktrees.update(cx, |store, cx| {
+            store.trust(
+                HashSet::from_iter([PathTrust::Worktree(worktree_id)]),
+                None,
+                cx,
+            );
+        });
+        let can_trust = trusted_worktrees.update(cx, |store, cx| store.can_trust(worktree_id, cx));
+        assert!(can_trust, "should be trusted after trust()");
+        assert_eq!(events.borrow().len(), 1);
+        assert!(matches!(
+            &events.borrow()[0],
+            TrustedWorktreesEvent::Trusted(..)
+        ));
+        events.borrow_mut().clear();
+
+        trusted_worktrees.update(cx, |store, cx| {
+            store.restrict(
+                HashSet::from_iter([PathTrust::Worktree(worktree_id)]),
+                None,
+                cx,
+            );
+        });
+        let can_trust = trusted_worktrees.update(cx, |store, cx| store.can_trust(worktree_id, cx));
+        assert!(!can_trust, "should be restricted after restrict()");
+        assert_eq!(events.borrow().len(), 1);
+        assert!(matches!(
+            &events.borrow()[0],
+            TrustedWorktreesEvent::Restricted(..)
+        ));
+
+        let has_restricted = trusted_worktrees.read_with(cx, |store, cx| {
+            store.has_restricted_worktrees(&worktree_store, cx)
+        });
+        assert!(has_restricted);
+        events.borrow_mut().clear();
+
+        trusted_worktrees.update(cx, |store, cx| {
+            store.trust(
+                HashSet::from_iter([PathTrust::Worktree(worktree_id)]),
+                None,
+                cx,
+            );
+        });
+        let can_trust = trusted_worktrees.update(cx, |store, cx| store.can_trust(worktree_id, cx));
+        assert!(can_trust, "should be trusted again after second trust()");
+        assert_eq!(events.borrow().len(), 1);
+        assert!(matches!(
+            &events.borrow()[0],
+            TrustedWorktreesEvent::Trusted(..)
+        ));
+
+        let has_restricted = trusted_worktrees.read_with(cx, |store, cx| {
+            store.has_restricted_worktrees(&worktree_store, cx)
+        });
+        assert!(!has_restricted);
+    }
+
+    #[gpui::test]
+    async fn test_multi_host_trust_isolation(cx: &mut TestAppContext) {
+        init_test(cx);
+
+        let fs = FakeFs::new(cx.executor());
+        fs.insert_tree(
+            path!("/"),
+            json!({
+                "local_project": { "main.rs": "fn main() {}" },
+                "remote_project": { "lib.rs": "pub fn lib() {}" }
+            }),
+        )
+        .await;
+
+        let project = Project::test(
+            fs,
+            [
+                path!("/local_project").as_ref(),
+                path!("/remote_project").as_ref(),
+            ],
+            cx,
+        )
+        .await;
+        let worktree_store = project.read_with(cx, |project, _| project.worktree_store());
+        let worktree_ids: Vec<_> = worktree_store.read_with(cx, |store, cx| {
+            store
+                .worktrees()
+                .map(|worktree| worktree.read(cx).id())
+                .collect()
+        });
+        assert_eq!(worktree_ids.len(), 2);
+        let local_worktree = worktree_ids[0];
+        let _remote_worktree = worktree_ids[1];
+
+        let trusted_worktrees = init_trust_global(worktree_store, cx);
+
+        let host_a: Option<RemoteHostLocation> = None;
+
+        let can_trust_local =
+            trusted_worktrees.update(cx, |store, cx| store.can_trust(local_worktree, cx));
+        assert!(!can_trust_local, "local worktree restricted on host_a");
+
+        trusted_worktrees.update(cx, |store, cx| {
+            store.trust(
+                HashSet::from_iter([PathTrust::Worktree(local_worktree)]),
+                host_a.clone(),
+                cx,
+            );
+        });
+
+        let can_trust_local_after =
+            trusted_worktrees.update(cx, |store, cx| store.can_trust(local_worktree, cx));
+        assert!(
+            can_trust_local_after,
+            "local worktree should be trusted on host_a"
+        );
+    }
+}

crates/project/src/worktree_store.rs 🔗

@@ -57,6 +57,7 @@ pub struct WorktreeStore {
     retain_worktrees: bool,
     worktrees: Vec<WorktreeHandle>,
     worktrees_reordered: bool,
+    scanning_enabled: bool,
     #[allow(clippy::type_complexity)]
     loading_worktrees:
         HashMap<Arc<SanitizedPath>, Shared<Task<Result<Entity<Worktree>, Arc<anyhow::Error>>>>>,
@@ -93,6 +94,7 @@ impl WorktreeStore {
             downstream_client: None,
             worktrees: Vec::new(),
             worktrees_reordered: false,
+            scanning_enabled: true,
             retain_worktrees,
             state: WorktreeStoreState::Local { fs },
         }
@@ -110,6 +112,7 @@ impl WorktreeStore {
             downstream_client: None,
             worktrees: Vec::new(),
             worktrees_reordered: false,
+            scanning_enabled: true,
             retain_worktrees,
             state: WorktreeStoreState::Remote {
                 upstream_client,
@@ -119,6 +122,10 @@ impl WorktreeStore {
         }
     }
 
+    pub fn disable_scanner(&mut self) {
+        self.scanning_enabled = false;
+    }
+
     /// Iterates through all worktrees, including ones that don't appear in the project panel
     pub fn worktrees(&self) -> impl '_ + DoubleEndedIterator<Item = Entity<Worktree>> {
         self.worktrees
@@ -576,6 +583,7 @@ impl WorktreeStore {
         cx: &mut Context<Self>,
     ) -> Task<Result<Entity<Worktree>, Arc<anyhow::Error>>> {
         let next_entry_id = self.next_entry_id.clone();
+        let scanning_enabled = self.scanning_enabled;
 
         cx.spawn(async move |this, cx| {
             let worktree = Worktree::local(
@@ -583,6 +591,7 @@ impl WorktreeStore {
                 visible,
                 fs,
                 next_entry_id,
+                scanning_enabled,
                 cx,
             )
             .await;

crates/project_panel/Cargo.toml 🔗

@@ -45,6 +45,7 @@ workspace.workspace = true
 language.workspace = true
 zed_actions.workspace = true
 telemetry.workspace = true
+notifications.workspace = true
 
 [dev-dependencies]
 client = { workspace = true, features = ["test-support"] }

crates/project_panel/src/project_panel.rs 🔗

@@ -29,6 +29,7 @@ use gpui::{
 };
 use language::DiagnosticSeverity;
 use menu::{Confirm, SelectFirst, SelectLast, SelectNext, SelectPrevious};
+use notifications::status_toast::{StatusToast, ToastIcon};
 use project::{
     Entry, EntryKind, Fs, GitEntry, GitEntryRef, GitTraversal, Project, ProjectEntryId,
     ProjectPath, Worktree, WorktreeId,
@@ -880,7 +881,7 @@ impl ProjectPanel {
                                 });
                                 if !focus_opened_item {
                                     let focus_handle = project_panel.read(cx).focus_handle.clone();
-                                    window.focus(&focus_handle);
+                                    window.focus(&focus_handle, cx);
                                 }
                             }
                         }
@@ -1140,9 +1141,15 @@ impl ProjectPanel {
                                 "Copy Relative Path",
                                 Box::new(zed_actions::workspace::CopyRelativePath),
                             )
+                            .when(!is_dir && self.has_git_changes(entry_id), |menu| {
+                                menu.separator().action(
+                                    "Restore File",
+                                    Box::new(git::RestoreFile { skip_prompt: false }),
+                                )
+                            })
                             .when(has_git_repo, |menu| {
                                 menu.separator()
-                                    .action("File History", Box::new(git::FileHistory))
+                                    .action("View File History", Box::new(git::FileHistory))
                             })
                             .when(!should_hide_rename, |menu| {
                                 menu.separator().action("Rename", Box::new(Rename))
@@ -1169,7 +1176,7 @@ impl ProjectPanel {
                 })
             });
 
-            window.focus(&context_menu.focus_handle(cx));
+            window.focus(&context_menu.focus_handle(cx), cx);
             let subscription = cx.subscribe(&context_menu, |this, _, _: &DismissEvent, cx| {
                 this.context_menu.take();
                 cx.notify();
@@ -1180,6 +1187,19 @@ impl ProjectPanel {
         cx.notify();
     }
 
+    fn has_git_changes(&self, entry_id: ProjectEntryId) -> bool {
+        for visible in &self.state.visible_entries {
+            if let Some(git_entry) = visible.entries.iter().find(|e| e.id == entry_id) {
+                let total_modified =
+                    git_entry.git_summary.index.modified + git_entry.git_summary.worktree.modified;
+                let total_deleted =
+                    git_entry.git_summary.index.deleted + git_entry.git_summary.worktree.deleted;
+                return total_modified > 0 || total_deleted > 0;
+            }
+        }
+        false
+    }
+
     fn is_unfoldable(&self, entry: &Entry, worktree: &Worktree) -> bool {
         if !entry.is_dir() || self.state.unfolded_dir_ids.contains(&entry.id) {
             return false;
@@ -1376,7 +1396,7 @@ impl ProjectPanel {
                 }
             });
             self.update_visible_entries(Some((worktree_id, entry_id)), false, false, window, cx);
-            window.focus(&self.focus_handle);
+            window.focus(&self.focus_handle, cx);
             cx.notify();
         }
     }
@@ -1399,7 +1419,7 @@ impl ProjectPanel {
                 }
             }
             self.update_visible_entries(Some((worktree_id, entry_id)), false, false, window, cx);
-            window.focus(&self.focus_handle);
+            window.focus(&self.focus_handle, cx);
             cx.notify();
         }
     }
@@ -1529,7 +1549,8 @@ impl ProjectPanel {
     }
 
     fn open(&mut self, _: &Open, window: &mut Window, cx: &mut Context<Self>) {
-        let preview_tabs_enabled = PreviewTabsSettings::get_global(cx).enabled;
+        let preview_tabs_enabled =
+            PreviewTabsSettings::get_global(cx).enable_preview_from_project_panel;
         self.open_internal(true, !preview_tabs_enabled, None, window, cx);
     }
 
@@ -1662,12 +1683,20 @@ impl ProjectPanel {
         let edit_state = self.state.edit_state.as_mut()?;
         let worktree_id = edit_state.worktree_id;
         let is_new_entry = edit_state.is_new_entry();
-        let filename = self.filename_editor.read(cx).text(cx);
+        let mut filename = self.filename_editor.read(cx).text(cx);
+        let path_style = self.project.read(cx).path_style(cx);
+        if path_style.is_windows() {
+            // on windows, trailing dots are ignored in paths
+            // this can cause project panel to create a new entry with a trailing dot
+            // while the actual one without the dot gets populated by the file watcher
+            while let Some(trimmed) = filename.strip_suffix('.') {
+                filename = trimmed.to_string();
+            }
+        }
         if filename.trim().is_empty() {
             return None;
         }
 
-        let path_style = self.project.read(cx).path_style(cx);
         let filename_indicates_dir = if path_style.is_windows() {
             filename.ends_with('/') || filename.ends_with('\\')
         } else {
@@ -1710,7 +1739,7 @@ impl ProjectPanel {
             };
             if let Some(existing) = worktree.read(cx).entry_for_path(&new_path) {
                 if existing.id == entry.id && refocus {
-                    window.focus(&self.focus_handle);
+                    window.focus(&self.focus_handle, cx);
                 }
                 return None;
             }
@@ -1721,7 +1750,7 @@ impl ProjectPanel {
         };
 
         if refocus {
-            window.focus(&self.focus_handle);
+            window.focus(&self.focus_handle, cx);
         }
         edit_state.processing_filename = Some(filename);
         cx.notify();
@@ -1830,7 +1859,7 @@ impl ProjectPanel {
             self.autoscroll(cx);
         }
 
-        window.focus(&self.focus_handle);
+        window.focus(&self.focus_handle, cx);
         cx.notify();
     }
 
@@ -2032,6 +2061,100 @@ impl ProjectPanel {
         self.remove(false, action.skip_prompt, window, cx);
     }
 
+    fn restore_file(
+        &mut self,
+        action: &git::RestoreFile,
+        window: &mut Window,
+        cx: &mut Context<Self>,
+    ) {
+        maybe!({
+            let selection = self.state.selection?;
+            let project = self.project.read(cx);
+
+            let (_worktree, entry) = self.selected_sub_entry(cx)?;
+            if entry.is_dir() {
+                return None;
+            }
+
+            let project_path = project.path_for_entry(selection.entry_id, cx)?;
+
+            let git_store = project.git_store();
+            let (repository, repo_path) = git_store
+                .read(cx)
+                .repository_and_path_for_project_path(&project_path, cx)?;
+
+            let snapshot = repository.read(cx).snapshot();
+            let status = snapshot.status_for_path(&repo_path)?;
+            if !status.status.is_modified() && !status.status.is_deleted() {
+                return None;
+            }
+
+            let file_name = entry.path.file_name()?.to_string();
+
+            let answer = if !action.skip_prompt {
+                let prompt = format!("Discard changes to {}?", file_name);
+                Some(window.prompt(PromptLevel::Info, &prompt, None, &["Restore", "Cancel"], cx))
+            } else {
+                None
+            };
+
+            cx.spawn_in(window, async move |panel, cx| {
+                if let Some(answer) = answer
+                    && answer.await != Ok(0)
+                {
+                    return anyhow::Ok(());
+                }
+
+                let task = panel.update(cx, |_panel, cx| {
+                    repository.update(cx, |repo, cx| {
+                        repo.checkout_files("HEAD", vec![repo_path], cx)
+                    })
+                })?;
+
+                if let Err(e) = task.await {
+                    panel
+                        .update(cx, |panel, cx| {
+                            let message = format!("Failed to restore {}: {}", file_name, e);
+                            let toast = StatusToast::new(message, cx, |this, _| {
+                                this.icon(ToastIcon::new(IconName::XCircle).color(Color::Error))
+                                    .dismiss_button(true)
+                            });
+                            panel
+                                .workspace
+                                .update(cx, |workspace, cx| {
+                                    workspace.toggle_status_toast(toast, cx);
+                                })
+                                .ok();
+                        })
+                        .ok();
+                }
+
+                panel
+                    .update(cx, |panel, cx| {
+                        panel.project.update(cx, |project, cx| {
+                            if let Some(buffer_id) = project
+                                .buffer_store()
+                                .read(cx)
+                                .buffer_id_for_project_path(&project_path)
+                            {
+                                if let Some(buffer) = project.buffer_for_id(*buffer_id, cx) {
+                                    buffer.update(cx, |buffer, cx| {
+                                        let _ = buffer.reload(cx);
+                                    });
+                                }
+                            }
+                        })
+                    })
+                    .ok();
+
+                anyhow::Ok(())
+            })
+            .detach_and_log_err(cx);
+
+            Some(())
+        });
+    }
+
     fn remove(
         &mut self,
         trash: bool,
@@ -3607,7 +3730,7 @@ impl ProjectPanel {
                 if this.update_visible_entries_task.focus_filename_editor {
                     this.update_visible_entries_task.focus_filename_editor = false;
                     this.filename_editor.update(cx, |editor, cx| {
-                        window.focus(&editor.focus_handle(cx));
+                        window.focus(&editor.focus_handle(cx), cx);
                     });
                 }
                 if this.update_visible_entries_task.autoscroll {
@@ -4819,7 +4942,7 @@ impl ProjectPanel {
                             project_panel.toggle_expanded(entry_id, window, cx);
                         }
                     } else {
-                        let preview_tabs_enabled = PreviewTabsSettings::get_global(cx).enabled;
+                        let preview_tabs_enabled = PreviewTabsSettings::get_global(cx).enable_preview_from_project_panel;
                         let click_count = event.click_count();
                         let focus_opened_item = click_count > 1;
                         let allow_preview = preview_tabs_enabled && click_count == 1;
@@ -5622,6 +5745,7 @@ impl Render for ProjectPanel {
                         .on_action(cx.listener(Self::copy))
                         .on_action(cx.listener(Self::paste))
                         .on_action(cx.listener(Self::duplicate))
+                        .on_action(cx.listener(Self::restore_file))
                         .when(!project.is_remote(), |el| {
                             el.on_action(cx.listener(Self::trash))
                         })
@@ -5943,7 +6067,7 @@ impl Render for ProjectPanel {
                                     cx.stop_propagation();
                                     this.state.selection = None;
                                     this.marked_entries.clear();
-                                    this.focus_handle(cx).focus(window);
+                                    this.focus_handle(cx).focus(window, cx);
                                 }))
                                 .on_mouse_down(
                                     MouseButton::Right,

crates/project_panel/src/project_panel_settings.rs 🔗

@@ -92,7 +92,13 @@ impl Settings for ProjectPanelSettings {
             entry_spacing: project_panel.entry_spacing.unwrap(),
             file_icons: project_panel.file_icons.unwrap(),
             folder_icons: project_panel.folder_icons.unwrap(),
-            git_status: project_panel.git_status.unwrap(),
+            git_status: project_panel.git_status.unwrap()
+                && content
+                    .git
+                    .unwrap()
+                    .enabled
+                    .unwrap()
+                    .is_git_status_enabled(),
             indent_size: project_panel.indent_size.unwrap(),
             indent_guides: IndentGuidesSettings {
                 show: project_panel.indent_guides.unwrap().show.unwrap(),

crates/project_panel/src/project_panel_tests.rs 🔗

@@ -6612,6 +6612,74 @@ async fn test_create_entries_without_selection_hide_root(cx: &mut gpui::TestAppC
     );
 }
 
+#[cfg(windows)]
+#[gpui::test]
+async fn test_create_entry_with_trailing_dot_windows(cx: &mut gpui::TestAppContext) {
+    init_test(cx);
+
+    let fs = FakeFs::new(cx.executor());
+    fs.insert_tree(
+        path!("/root"),
+        json!({
+            "dir1": {
+                "file1.txt": "",
+            },
+        }),
+    )
+    .await;
+
+    let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
+    let workspace = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
+    let cx = &mut VisualTestContext::from_window(*workspace, cx);
+
+    let panel = workspace
+        .update(cx, |workspace, window, cx| {
+            let panel = ProjectPanel::new(workspace, window, cx);
+            workspace.add_panel(panel.clone(), window, cx);
+            panel
+        })
+        .unwrap();
+    cx.run_until_parked();
+
+    #[rustfmt::skip]
+    assert_eq!(
+        visible_entries_as_strings(&panel, 0..20, cx),
+        &[
+            "v root",
+            "    > dir1",
+        ],
+        "Initial state with nothing selected"
+    );
+
+    panel.update_in(cx, |panel, window, cx| {
+        panel.new_file(&NewFile, window, cx);
+    });
+    cx.run_until_parked();
+    panel.update_in(cx, |panel, window, cx| {
+        assert!(panel.filename_editor.read(cx).is_focused(window));
+    });
+    panel
+        .update_in(cx, |panel, window, cx| {
+            panel
+                .filename_editor
+                .update(cx, |editor, cx| editor.set_text("foo.", window, cx));
+            panel.confirm_edit(true, window, cx).unwrap()
+        })
+        .await
+        .unwrap();
+    cx.run_until_parked();
+    #[rustfmt::skip]
+    assert_eq!(
+        visible_entries_as_strings(&panel, 0..20, cx),
+        &[
+            "v root",
+            "    > dir1",
+            "      foo  <== selected  <== marked",
+        ],
+        "A new file is created under the root directory without the trailing dot"
+    );
+}
+
 #[gpui::test]
 async fn test_highlight_entry_for_external_drag(cx: &mut gpui::TestAppContext) {
     init_test(cx);

crates/project_symbols/src/project_symbols.rs 🔗

@@ -133,8 +133,9 @@ impl PickerDelegate for ProjectSymbolsDelegate {
                         workspace.active_pane().clone()
                     };
 
-                    let editor =
-                        workspace.open_project_item::<Editor>(pane, buffer, true, true, window, cx);
+                    let editor = workspace.open_project_item::<Editor>(
+                        pane, buffer, true, true, true, true, window, cx,
+                    );
 
                     editor.update(cx, |editor, cx| {
                         editor.change_selections(

crates/prompt_store/Cargo.toml 🔗

@@ -28,6 +28,11 @@ parking_lot.workspace = true
 paths.workspace = true
 rope.workspace = true
 serde.workspace = true
+strum.workspace = true
 text.workspace = true
 util.workspace = true
 uuid.workspace = true
+
+[dev-dependencies]
+gpui = { workspace = true, features = ["test-support"] }
+tempfile.workspace = true

crates/prompt_store/src/prompt_store.rs 🔗

@@ -1,6 +1,6 @@
 mod prompts;
 
-use anyhow::{Context as _, Result, anyhow};
+use anyhow::{Result, anyhow};
 use chrono::{DateTime, Utc};
 use collections::HashMap;
 use futures::FutureExt as _;
@@ -23,6 +23,7 @@ use std::{
     path::PathBuf,
     sync::{Arc, atomic::AtomicBool},
 };
+use strum::{EnumIter, IntoEnumIterator as _};
 use text::LineEnding;
 use util::ResultExt;
 use uuid::Uuid;
@@ -51,11 +52,51 @@ pub struct PromptMetadata {
     pub saved_at: DateTime<Utc>,
 }
 
+impl PromptMetadata {
+    fn builtin(builtin: BuiltInPrompt) -> Self {
+        Self {
+            id: PromptId::BuiltIn(builtin),
+            title: Some(builtin.title().into()),
+            default: false,
+            saved_at: DateTime::default(),
+        }
+    }
+}
+
+/// Built-in prompts that have default content and can be customized by users.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, EnumIter)]
+pub enum BuiltInPrompt {
+    CommitMessage,
+}
+
+impl BuiltInPrompt {
+    pub fn title(&self) -> &'static str {
+        match self {
+            Self::CommitMessage => "Commit message",
+        }
+    }
+
+    /// Returns the default content for this built-in prompt.
+    pub fn default_content(&self) -> &'static str {
+        match self {
+            Self::CommitMessage => include_str!("../../git_ui/src/commit_message_prompt.txt"),
+        }
+    }
+}
+
+impl std::fmt::Display for BuiltInPrompt {
+    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+        match self {
+            Self::CommitMessage => write!(f, "Commit message"),
+        }
+    }
+}
+
 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
 #[serde(tag = "kind")]
 pub enum PromptId {
     User { uuid: UserPromptId },
-    EditWorkflow,
+    BuiltIn(BuiltInPrompt),
 }
 
 impl PromptId {
@@ -63,8 +104,37 @@ impl PromptId {
         UserPromptId::new().into()
     }
 
+    pub fn as_user(&self) -> Option<UserPromptId> {
+        match self {
+            Self::User { uuid } => Some(*uuid),
+            Self::BuiltIn { .. } => None,
+        }
+    }
+
+    pub fn as_built_in(&self) -> Option<BuiltInPrompt> {
+        match self {
+            Self::User { .. } => None,
+            Self::BuiltIn(builtin) => Some(*builtin),
+        }
+    }
+
     pub fn is_built_in(&self) -> bool {
-        !matches!(self, PromptId::User { .. })
+        matches!(self, Self::BuiltIn { .. })
+    }
+
+    pub fn can_edit(&self) -> bool {
+        match self {
+            Self::User { .. } => true,
+            Self::BuiltIn(builtin) => match builtin {
+                BuiltInPrompt::CommitMessage => true,
+            },
+        }
+    }
+}
+
+impl From<BuiltInPrompt> for PromptId {
+    fn from(builtin: BuiltInPrompt) -> Self {
+        PromptId::BuiltIn(builtin)
     }
 }
 
@@ -94,7 +164,7 @@ impl std::fmt::Display for PromptId {
     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
         match self {
             PromptId::User { uuid } => write!(f, "{}", uuid.0),
-            PromptId::EditWorkflow => write!(f, "Edit workflow"),
+            PromptId::BuiltIn(builtin) => write!(f, "{}", builtin),
         }
     }
 }
@@ -123,10 +193,28 @@ impl MetadataCache {
     ) -> Result<Self> {
         let mut cache = MetadataCache::default();
         for result in db.iter(txn)? {
-            let (prompt_id, metadata) = result?;
+            // Fail-open: skip records that can't be decoded (e.g. from a different branch)
+            // rather than failing the entire prompt store initialization.
+            let Ok((prompt_id, metadata)) = result else {
+                log::warn!(
+                    "Skipping unreadable prompt record in database: {:?}",
+                    result.err()
+                );
+                continue;
+            };
             cache.metadata.push(metadata.clone());
             cache.metadata_by_id.insert(prompt_id, metadata);
         }
+
+        // Insert all the built-in prompts that were not customized by the user
+        for builtin in BuiltInPrompt::iter() {
+            let builtin_id = PromptId::BuiltIn(builtin);
+            if !cache.metadata_by_id.contains_key(&builtin_id) {
+                let metadata = PromptMetadata::builtin(builtin);
+                cache.metadata.push(metadata.clone());
+                cache.metadata_by_id.insert(builtin_id, metadata);
+            }
+        }
         cache.sort();
         Ok(cache)
     }
@@ -175,12 +263,6 @@ impl PromptStore {
             let mut txn = db_env.write_txn()?;
             let metadata = db_env.create_database(&mut txn, Some("metadata.v2"))?;
             let bodies = db_env.create_database(&mut txn, Some("bodies.v2"))?;
-
-            // Remove edit workflow prompt, as we decided to opt into it using
-            // a slash command instead.
-            metadata.delete(&mut txn, &PromptId::EditWorkflow).ok();
-            bodies.delete(&mut txn, &PromptId::EditWorkflow).ok();
-
             txn.commit()?;
 
             Self::upgrade_dbs(&db_env, metadata, bodies).log_err();
@@ -273,7 +355,16 @@ impl PromptStore {
         let bodies = self.bodies;
         cx.background_spawn(async move {
             let txn = env.read_txn()?;
-            let mut prompt = bodies.get(&txn, &id)?.context("prompt not found")?.into();
+            let mut prompt: String = match bodies.get(&txn, &id)? {
+                Some(body) => body.into(),
+                None => {
+                    if let Some(built_in) = id.as_built_in() {
+                        built_in.default_content().into()
+                    } else {
+                        anyhow::bail!("prompt not found")
+                    }
+                }
+            };
             LineEnding::normalize(&mut prompt);
             Ok(prompt)
         })
@@ -318,11 +409,6 @@ impl PromptStore {
         })
     }
 
-    /// Returns the number of prompts in the store.
-    pub fn prompt_count(&self) -> usize {
-        self.metadata_cache.read().metadata.len()
-    }
-
     pub fn metadata(&self, id: PromptId) -> Option<PromptMetadata> {
         self.metadata_cache.read().metadata_by_id.get(&id).cloned()
     }
@@ -387,27 +473,42 @@ impl PromptStore {
         body: Rope,
         cx: &Context<Self>,
     ) -> Task<Result<()>> {
-        if id.is_built_in() {
-            return Task::ready(Err(anyhow!("built-in prompts cannot be saved")));
+        if !id.can_edit() {
+            return Task::ready(Err(anyhow!("this prompt cannot be edited")));
         }
 
-        let prompt_metadata = PromptMetadata {
-            id,
-            title,
-            default,
-            saved_at: Utc::now(),
+        let body = body.to_string();
+        let is_default_content = id
+            .as_built_in()
+            .is_some_and(|builtin| body.trim() == builtin.default_content().trim());
+
+        let metadata = if let Some(builtin) = id.as_built_in() {
+            PromptMetadata::builtin(builtin)
+        } else {
+            PromptMetadata {
+                id,
+                title,
+                default,
+                saved_at: Utc::now(),
+            }
         };
-        self.metadata_cache.write().insert(prompt_metadata.clone());
+
+        self.metadata_cache.write().insert(metadata.clone());
 
         let db_connection = self.env.clone();
         let bodies = self.bodies;
-        let metadata = self.metadata;
+        let metadata_db = self.metadata;
 
         let task = cx.background_spawn(async move {
             let mut txn = db_connection.write_txn()?;
 
-            metadata.put(&mut txn, &id, &prompt_metadata)?;
-            bodies.put(&mut txn, &id, &body.to_string())?;
+            if is_default_content {
+                metadata_db.delete(&mut txn, &id)?;
+                bodies.delete(&mut txn, &id)?;
+            } else {
+                metadata_db.put(&mut txn, &id, &metadata)?;
+                bodies.put(&mut txn, &id, &body)?;
+            }
 
             txn.commit()?;
 
@@ -430,7 +531,7 @@ impl PromptStore {
     ) -> Task<Result<()>> {
         let mut cache = self.metadata_cache.write();
 
-        if id.is_built_in() {
+        if !id.can_edit() {
             title = cache
                 .metadata_by_id
                 .get(&id)
@@ -469,3 +570,201 @@ impl PromptStore {
 pub struct GlobalPromptStore(Shared<Task<Result<Entity<PromptStore>, Arc<anyhow::Error>>>>);
 
 impl Global for GlobalPromptStore {}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use gpui::TestAppContext;
+
+    #[gpui::test]
+    async fn test_built_in_prompt_load_save(cx: &mut TestAppContext) {
+        cx.executor().allow_parking();
+
+        let temp_dir = tempfile::tempdir().unwrap();
+        let db_path = temp_dir.path().join("prompts-db");
+
+        let store = cx.update(|cx| PromptStore::new(db_path, cx)).await.unwrap();
+        let store = cx.new(|_cx| store);
+
+        let commit_message_id = PromptId::BuiltIn(BuiltInPrompt::CommitMessage);
+
+        let loaded_content = store
+            .update(cx, |store, cx| store.load(commit_message_id, cx))
+            .await
+            .unwrap();
+
+        let mut expected_content = BuiltInPrompt::CommitMessage.default_content().to_string();
+        LineEnding::normalize(&mut expected_content);
+        assert_eq!(
+            loaded_content.trim(),
+            expected_content.trim(),
+            "Loading a built-in prompt not in DB should return default content"
+        );
+
+        let metadata = store.read_with(cx, |store, _| store.metadata(commit_message_id));
+        assert!(
+            metadata.is_some(),
+            "Built-in prompt should always have metadata"
+        );
+        assert!(
+            store.read_with(cx, |store, _| {
+                store
+                    .metadata_cache
+                    .read()
+                    .metadata_by_id
+                    .contains_key(&commit_message_id)
+            }),
+            "Built-in prompt should always be in cache"
+        );
+
+        let custom_content = "Custom commit message prompt";
+        store
+            .update(cx, |store, cx| {
+                store.save(
+                    commit_message_id,
+                    Some("Commit message".into()),
+                    false,
+                    Rope::from(custom_content),
+                    cx,
+                )
+            })
+            .await
+            .unwrap();
+
+        let loaded_custom = store
+            .update(cx, |store, cx| store.load(commit_message_id, cx))
+            .await
+            .unwrap();
+        assert_eq!(
+            loaded_custom.trim(),
+            custom_content.trim(),
+            "Custom content should be loaded after saving"
+        );
+
+        assert!(
+            store
+                .read_with(cx, |store, _| store.metadata(commit_message_id))
+                .is_some(),
+            "Built-in prompt should have metadata after customization"
+        );
+
+        store
+            .update(cx, |store, cx| {
+                store.save(
+                    commit_message_id,
+                    Some("Commit message".into()),
+                    false,
+                    Rope::from(BuiltInPrompt::CommitMessage.default_content()),
+                    cx,
+                )
+            })
+            .await
+            .unwrap();
+
+        let metadata_after_reset =
+            store.read_with(cx, |store, _| store.metadata(commit_message_id));
+        assert!(
+            metadata_after_reset.is_some(),
+            "Built-in prompt should still have metadata after reset"
+        );
+        assert_eq!(
+            metadata_after_reset
+                .as_ref()
+                .and_then(|m| m.title.as_ref().map(|t| t.as_ref())),
+            Some("Commit message"),
+            "Built-in prompt should have default title after reset"
+        );
+
+        let loaded_after_reset = store
+            .update(cx, |store, cx| store.load(commit_message_id, cx))
+            .await
+            .unwrap();
+        let mut expected_content_after_reset =
+            BuiltInPrompt::CommitMessage.default_content().to_string();
+        LineEnding::normalize(&mut expected_content_after_reset);
+        assert_eq!(
+            loaded_after_reset.trim(),
+            expected_content_after_reset.trim(),
+            "Content should be back to default after saving default content"
+        );
+    }
+
+    /// Test that the prompt store initializes successfully even when the database
+    /// contains records with incompatible/undecodable PromptId keys (e.g., from
+    /// a different branch that used a different serialization format).
+    ///
+    /// This is a regression test for the "fail-open" behavior: we should skip
+    /// bad records rather than failing the entire store initialization.
+    #[gpui::test]
+    async fn test_prompt_store_handles_incompatible_db_records(cx: &mut TestAppContext) {
+        cx.executor().allow_parking();
+
+        let temp_dir = tempfile::tempdir().unwrap();
+        let db_path = temp_dir.path().join("prompts-db-with-bad-records");
+        std::fs::create_dir_all(&db_path).unwrap();
+
+        // First, create the DB and write an incompatible record directly.
+        // We simulate a record written by a different branch that used
+        // `{"kind":"CommitMessage"}` instead of `{"kind":"BuiltIn", ...}`.
+        {
+            let db_env = unsafe {
+                heed::EnvOpenOptions::new()
+                    .map_size(1024 * 1024 * 1024)
+                    .max_dbs(4)
+                    .open(&db_path)
+                    .unwrap()
+            };
+
+            let mut txn = db_env.write_txn().unwrap();
+            // Create the metadata.v2 database with raw bytes so we can write
+            // an incompatible key format.
+            let metadata_db: Database<heed::types::Bytes, heed::types::Bytes> = db_env
+                .create_database(&mut txn, Some("metadata.v2"))
+                .unwrap();
+
+            // Write an incompatible PromptId key: `{"kind":"CommitMessage"}`
+            // This is the old/branch format that current code can't decode.
+            let bad_key = br#"{"kind":"CommitMessage"}"#;
+            let dummy_metadata = br#"{"id":{"kind":"CommitMessage"},"title":"Bad Record","default":false,"saved_at":"2024-01-01T00:00:00Z"}"#;
+            metadata_db.put(&mut txn, bad_key, dummy_metadata).unwrap();
+
+            // Also write a valid record to ensure we can still read good data.
+            let good_key = br#"{"kind":"User","uuid":"550e8400-e29b-41d4-a716-446655440000"}"#;
+            let good_metadata = br#"{"id":{"kind":"User","uuid":"550e8400-e29b-41d4-a716-446655440000"},"title":"Good Record","default":false,"saved_at":"2024-01-01T00:00:00Z"}"#;
+            metadata_db.put(&mut txn, good_key, good_metadata).unwrap();
+
+            txn.commit().unwrap();
+        }
+
+        // Now try to create a PromptStore from this DB.
+        // With fail-open behavior, this should succeed and skip the bad record.
+        // Without fail-open, this would return an error.
+        let store_result = cx.update(|cx| PromptStore::new(db_path, cx)).await;
+
+        assert!(
+            store_result.is_ok(),
+            "PromptStore should initialize successfully even with incompatible DB records. \
+             Got error: {:?}",
+            store_result.err()
+        );
+
+        let store = cx.new(|_cx| store_result.unwrap());
+
+        // Verify the good record was loaded.
+        let good_id = PromptId::User {
+            uuid: UserPromptId("550e8400-e29b-41d4-a716-446655440000".parse().unwrap()),
+        };
+        let metadata = store.read_with(cx, |store, _| store.metadata(good_id));
+        assert!(
+            metadata.is_some(),
+            "Valid records should still be loaded after skipping bad ones"
+        );
+        assert_eq!(
+            metadata
+                .as_ref()
+                .and_then(|m| m.title.as_ref().map(|t| t.as_ref())),
+            Some("Good Record"),
+            "Valid record should have correct title"
+        );
+    }
+}

crates/prompt_store/src/prompts.rs 🔗

@@ -20,6 +20,18 @@ use util::{
 
 use crate::UserPromptId;
 
+pub const RULES_FILE_NAMES: &[&str] = &[
+    ".rules",
+    ".cursorrules",
+    ".windsurfrules",
+    ".clinerules",
+    ".github/copilot-instructions.md",
+    "CLAUDE.md",
+    "AGENT.md",
+    "AGENTS.md",
+    "GEMINI.md",
+];
+
 #[derive(Default, Debug, Clone, Serialize)]
 pub struct ProjectContext {
     pub worktrees: Vec<WorktreeContext>,
@@ -94,6 +106,16 @@ pub struct ContentPromptContext {
     pub diagnostic_errors: Vec<ContentPromptDiagnosticContext>,
 }
 
+#[derive(Serialize)]
+pub struct ContentPromptContextV2 {
+    pub content_type: String,
+    pub language_name: Option<String>,
+    pub is_truncated: bool,
+    pub document_content: String,
+    pub rewrite_section: String,
+    pub diagnostic_errors: Vec<ContentPromptDiagnosticContext>,
+}
+
 #[derive(Serialize)]
 pub struct TerminalAssistantPromptContext {
     pub os: String,
@@ -276,6 +298,78 @@ impl PromptBuilder {
         Ok(())
     }
 
+    pub fn generate_inline_transformation_prompt_tools(
+        &self,
+        language_name: Option<&LanguageName>,
+        buffer: BufferSnapshot,
+        range: Range<usize>,
+    ) -> Result<String, RenderError> {
+        let content_type = match language_name.as_ref().map(|l| l.as_ref()) {
+            None | Some("Markdown" | "Plain Text") => "text",
+            Some(_) => "code",
+        };
+
+        const MAX_CTX: usize = 50000;
+        let mut is_truncated = false;
+
+        let before_range = 0..range.start;
+        let truncated_before = if before_range.len() > MAX_CTX {
+            is_truncated = true;
+            let start = buffer.clip_offset(range.start - MAX_CTX, text::Bias::Right);
+            start..range.start
+        } else {
+            before_range
+        };
+
+        let after_range = range.end..buffer.len();
+        let truncated_after = if after_range.len() > MAX_CTX {
+            is_truncated = true;
+            let end = buffer.clip_offset(range.end + MAX_CTX, text::Bias::Left);
+            range.end..end
+        } else {
+            after_range
+        };
+
+        let mut document_content = String::new();
+        for chunk in buffer.text_for_range(truncated_before) {
+            document_content.push_str(chunk);
+        }
+
+        document_content.push_str("<rewrite_this>\n");
+        for chunk in buffer.text_for_range(range.clone()) {
+            document_content.push_str(chunk);
+        }
+        document_content.push_str("\n</rewrite_this>");
+
+        for chunk in buffer.text_for_range(truncated_after) {
+            document_content.push_str(chunk);
+        }
+
+        let rewrite_section: String = buffer.text_for_range(range.clone()).collect();
+
+        let diagnostics = buffer.diagnostics_in_range::<_, Point>(range, false);
+        let diagnostic_errors: Vec<ContentPromptDiagnosticContext> = diagnostics
+            .map(|entry| {
+                let start = entry.range.start;
+                ContentPromptDiagnosticContext {
+                    line_number: (start.row + 1) as usize,
+                    error_message: entry.diagnostic.message.clone(),
+                    code_content: buffer.text_for_range(entry.range).collect(),
+                }
+            })
+            .collect();
+
+        let context = ContentPromptContextV2 {
+            content_type: content_type.to_string(),
+            language_name: language_name.map(|s| s.to_string()),
+            is_truncated,
+            document_content,
+            rewrite_section,
+            diagnostic_errors,
+        };
+        self.handlebars.lock().render("content_prompt_v2", &context)
+    }
+
     pub fn generate_inline_transformation_prompt(
         &self,
         user_prompt: String,

crates/proto/proto/buffer.proto 🔗

@@ -258,6 +258,7 @@ message Diagnostic {
     Anchor start = 1;
     Anchor end = 2;
     optional string source = 3;
+    optional string registration_id = 17;
 
     enum SourceKind {
         Pulled = 0;

crates/proto/proto/git.proto 🔗

@@ -124,6 +124,8 @@ message UpdateRepository {
     optional GitCommitDetails head_commit_details = 11;
     optional string merge_message = 12;
     repeated StashEntry stash_entries = 13;
+    optional string remote_upstream_url = 14;
+    optional string remote_origin_url = 15;
 }
 
 message RemoveRepository {
@@ -190,6 +192,19 @@ message GitRenameBranch {
     string new_name = 4;
 }
 
+message GitCreateRemote {
+    uint64 project_id = 1;
+    uint64 repository_id = 2;
+    string remote_name = 3;
+    string remote_url = 4;
+}
+
+message GitRemoveRemote {
+    uint64 project_id = 1;
+    uint64 repository_id = 2;
+    string remote_name = 3;
+}
+
 message GitDeleteBranch {
     uint64 project_id = 1;
     uint64 repository_id = 2;
@@ -487,8 +502,8 @@ message BlameBufferResponse {
     message BlameResponse {
         repeated BlameEntry entries = 1;
         repeated CommitMessage messages = 2;
-        optional string remote_url = 4;
         reserved 3;
+        reserved 4;
     }
 
     optional BlameResponse blame_response = 5;
@@ -565,7 +580,7 @@ message GitCreateWorktree {
 message RunGitHook {
     enum GitHook {
         PRE_COMMIT = 0;
-        PRE_PUSH = 1;
+        reserved 1;
     }
 
     uint64 project_id = 1;

crates/proto/proto/lsp.proto 🔗

@@ -949,6 +949,7 @@ message PulledDiagnostics {
     optional string result_id = 3;
     bool changed = 4;
     repeated LspDiagnostic diagnostics = 5;
+    optional string registration_id = 6;
 }
 
 message PullWorkspaceDiagnostics {

crates/proto/proto/worktree.proto 🔗

@@ -2,159 +2,181 @@ syntax = "proto3";
 package zed.messages;
 
 message Timestamp {
-    uint64 seconds = 1;
-    uint32 nanos = 2;
+  uint64 seconds = 1;
+  uint32 nanos = 2;
 }
 
 message File {
-    uint64 worktree_id = 1;
-    optional uint64 entry_id = 2;
-    string path = 3;
-    Timestamp mtime = 4;
-    bool is_deleted = 5;
+  uint64 worktree_id = 1;
+  optional uint64 entry_id = 2;
+  string path = 3;
+  Timestamp mtime = 4;
+  bool is_deleted = 5;
+  bool is_historic = 6;
 }
 
 message Entry {
-    uint64 id = 1;
-    bool is_dir = 2;
-    string path = 3;
-    uint64 inode = 4;
-    Timestamp mtime = 5;
-    bool is_ignored = 7;
-    bool is_external = 8;
-    reserved 6;
-    reserved 9;
-    bool is_fifo = 10;
-    optional uint64 size = 11;
-    optional string canonical_path = 12;
-    bool is_hidden = 13;
+  uint64 id = 1;
+  bool is_dir = 2;
+  string path = 3;
+  uint64 inode = 4;
+  Timestamp mtime = 5;
+  bool is_ignored = 7;
+  bool is_external = 8;
+  reserved 6;
+  reserved 9;
+  bool is_fifo = 10;
+  optional uint64 size = 11;
+  optional string canonical_path = 12;
+  bool is_hidden = 13;
 }
 
 message AddWorktree {
-    string path = 1;
-    uint64 project_id = 2;
-    bool visible = 3;
+  string path = 1;
+  uint64 project_id = 2;
+  bool visible = 3;
 }
 
 message AddWorktreeResponse {
-    uint64 worktree_id = 1;
-    string canonicalized_path = 2;
+  uint64 worktree_id = 1;
+  string canonicalized_path = 2;
 }
 
 message RemoveWorktree {
-    uint64 worktree_id = 1;
+  uint64 worktree_id = 1;
 }
 
 message GetPathMetadata {
-    uint64 project_id = 1;
-    string path = 2;
+  uint64 project_id = 1;
+  string path = 2;
 }
 
 message GetPathMetadataResponse {
-    bool exists = 1;
-    string path = 2;
-    bool is_dir = 3;
+  bool exists = 1;
+  string path = 2;
+  bool is_dir = 3;
 }
 
 message WorktreeMetadata {
-    uint64 id = 1;
-    string root_name = 2;
-    bool visible = 3;
-    string abs_path = 4;
+  uint64 id = 1;
+  string root_name = 2;
+  bool visible = 3;
+  string abs_path = 4;
 }
 
 message ProjectPath {
-    uint64 worktree_id = 1;
-    string path = 2;
+  uint64 worktree_id = 1;
+  string path = 2;
 }
 
 message ListRemoteDirectoryConfig {
-    bool is_dir = 1;
+  bool is_dir = 1;
 }
 
 message ListRemoteDirectory {
-    uint64 dev_server_id = 1;
-    string path = 2;
-    ListRemoteDirectoryConfig config = 3;
+  uint64 dev_server_id = 1;
+  string path = 2;
+  ListRemoteDirectoryConfig config = 3;
 }
 
 message EntryInfo {
-    bool is_dir = 1;
+  bool is_dir = 1;
 }
 
 message ListRemoteDirectoryResponse {
-    repeated string entries = 1;
-    repeated EntryInfo entry_info = 2;
+  repeated string entries = 1;
+  repeated EntryInfo entry_info = 2;
 }
 
 message CreateProjectEntry {
-    uint64 project_id = 1;
-    uint64 worktree_id = 2;
-    string path = 3;
-    bool is_directory = 4;
-    optional bytes content = 5;
+  uint64 project_id = 1;
+  uint64 worktree_id = 2;
+  string path = 3;
+  bool is_directory = 4;
+  optional bytes content = 5;
 }
 
 message RenameProjectEntry {
-    uint64 project_id = 1;
-    uint64 entry_id = 2;
-    string new_path = 3;
-    uint64 new_worktree_id = 4;
+  uint64 project_id = 1;
+  uint64 entry_id = 2;
+  string new_path = 3;
+  uint64 new_worktree_id = 4;
 }
 
 message CopyProjectEntry {
-    uint64 project_id = 1;
-    uint64 entry_id = 2;
-    string new_path = 3;
-    uint64 new_worktree_id = 5;
-    reserved 4;
+  uint64 project_id = 1;
+  uint64 entry_id = 2;
+  string new_path = 3;
+  uint64 new_worktree_id = 5;
+  reserved 4;
 }
 
 message DeleteProjectEntry {
-    uint64 project_id = 1;
-    uint64 entry_id = 2;
-    bool use_trash = 3;
+  uint64 project_id = 1;
+  uint64 entry_id = 2;
+  bool use_trash = 3;
 }
 
 message ExpandProjectEntry {
-    uint64 project_id = 1;
-    uint64 entry_id = 2;
+  uint64 project_id = 1;
+  uint64 entry_id = 2;
 }
 
 message ExpandProjectEntryResponse {
-    uint64 worktree_scan_id = 1;
+  uint64 worktree_scan_id = 1;
 }
 
 message ExpandAllForProjectEntry {
-    uint64 project_id = 1;
-    uint64 entry_id = 2;
+  uint64 project_id = 1;
+  uint64 entry_id = 2;
 }
 
 message ExpandAllForProjectEntryResponse {
-    uint64 worktree_scan_id = 1;
+  uint64 worktree_scan_id = 1;
 }
 
 message ProjectEntryResponse {
-    optional Entry entry = 1;
-    uint64 worktree_scan_id = 2;
+  optional Entry entry = 1;
+  uint64 worktree_scan_id = 2;
 }
 
 message UpdateWorktreeSettings {
-    uint64 project_id = 1;
-    uint64 worktree_id = 2;
-    string path = 3;
-    optional string content = 4;
-    optional LocalSettingsKind kind = 5;
+  uint64 project_id = 1;
+  uint64 worktree_id = 2;
+  string path = 3;
+  optional string content = 4;
+  optional LocalSettingsKind kind = 5;
 }
 
 enum LocalSettingsKind {
-    Settings = 0;
-    Tasks = 1;
-    Editorconfig = 2;
-    Debug = 3;
+  Settings = 0;
+  Tasks = 1;
+  Editorconfig = 2;
+  Debug = 3;
 }
 
 message UpdateUserSettings {
+  uint64 project_id = 1;
+  string contents = 2;
+}
+
+message TrustWorktrees {
+    uint64 project_id = 1;
+    repeated PathTrust trusted_paths = 2;
+}
+
+message PathTrust {
+    oneof content {
+        uint64 worktree_id = 2;
+        string abs_path = 3;
+    }
+
+    reserved 1;
+}
+
+message RestrictWorktrees {
     uint64 project_id = 1;
-    string contents = 2;
+    repeated uint64 worktree_ids = 3;
+
+    reserved 2;
 }

crates/proto/proto/zed.proto 🔗

@@ -437,13 +437,21 @@ message Envelope {
         OpenImageResponse open_image_response = 392;
         CreateImageForPeer create_image_for_peer = 393;
 
+
         GitFileHistory git_file_history = 397;
         GitFileHistoryResponse git_file_history_response = 398;
 
         RunGitHook run_git_hook = 399;
 
         GitDeleteBranch git_delete_branch = 400;
-        ExternalExtensionAgentsUpdated external_extension_agents_updated = 401; // current max
+
+        ExternalExtensionAgentsUpdated external_extension_agents_updated = 401;
+
+        GitCreateRemote git_create_remote = 402;
+        GitRemoveRemote git_remove_remote = 403;
+
+        TrustWorktrees trust_worktrees = 404;
+        RestrictWorktrees restrict_worktrees = 405; // current max
     }
 
     reserved 87 to 88, 396;

crates/proto/src/proto.rs 🔗

@@ -305,9 +305,13 @@ messages!(
     (RemoteMessageResponse, Background),
     (AskPassRequest, Background),
     (AskPassResponse, Background),
+    (GitCreateRemote, Background),
+    (GitRemoveRemote, Background),
     (GitCreateBranch, Background),
     (GitChangeBranch, Background),
     (GitRenameBranch, Background),
+    (TrustWorktrees, Background),
+    (RestrictWorktrees, Background),
     (CheckForPushedCommits, Background),
     (CheckForPushedCommitsResponse, Background),
     (GitDiff, Background),
@@ -504,6 +508,8 @@ request_messages!(
     (GetRemotes, GetRemotesResponse),
     (Pull, RemoteMessageResponse),
     (AskPassRequest, AskPassResponse),
+    (GitCreateRemote, Ack),
+    (GitRemoveRemote, Ack),
     (GitCreateBranch, Ack),
     (GitChangeBranch, Ack),
     (GitRenameBranch, Ack),
@@ -525,7 +531,9 @@ request_messages!(
     (GetAgentServerCommand, AgentServerCommand),
     (RemoteStarted, Ack),
     (GitGetWorktrees, GitWorktreesResponse),
-    (GitCreateWorktree, Ack)
+    (GitCreateWorktree, Ack),
+    (TrustWorktrees, Ack),
+    (RestrictWorktrees, Ack),
 );
 
 lsp_messages!(
@@ -676,6 +684,8 @@ entity_messages!(
     GitChangeBranch,
     GitRenameBranch,
     GitCreateBranch,
+    GitCreateRemote,
+    GitRemoveRemote,
     CheckForPushedCommits,
     GitDiff,
     GitInit,
@@ -696,7 +706,9 @@ entity_messages!(
     ExternalAgentLoadingStatusUpdated,
     NewExternalAgentVersionAvailable,
     GitGetWorktrees,
-    GitCreateWorktree
+    GitCreateWorktree,
+    TrustWorktrees,
+    RestrictWorktrees,
 );
 
 entity_messages!(

crates/recent_projects/Cargo.toml 🔗

@@ -16,6 +16,7 @@ doctest = false
 anyhow.workspace = true
 askpass.workspace = true
 auto_update.workspace = true
+db.workspace = true
 editor.workspace = true
 extension_host.workspace = true
 file_finder.workspace = true
@@ -26,6 +27,7 @@ language.workspace = true
 log.workspace = true
 markdown.workspace = true
 menu.workspace = true
+node_runtime.workspace = true
 ordered-float.workspace = true
 paths.workspace = true
 picker.workspace = true
@@ -34,6 +36,7 @@ release_channel.workspace = true
 remote.workspace = true
 semver.workspace = true
 serde.workspace = true
+serde_json.workspace = true
 settings.workspace = true
 smol.workspace = true
 task.workspace = true
@@ -42,6 +45,7 @@ theme.workspace = true
 ui.workspace = true
 util.workspace = true
 workspace.workspace = true
+worktree.workspace = true
 zed_actions.workspace = true
 indoc.workspace = true
 

crates/recent_projects/src/dev_container.rs 🔗

@@ -0,0 +1,295 @@
+use std::path::{Path, PathBuf};
+use std::sync::Arc;
+
+use gpui::AsyncWindowContext;
+use node_runtime::NodeRuntime;
+use serde::Deserialize;
+use settings::DevContainerConnection;
+use smol::fs;
+use workspace::Workspace;
+
+use crate::remote_connections::Connection;
+
+#[derive(Debug, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct DevContainerUp {
+    _outcome: String,
+    container_id: String,
+    _remote_user: String,
+    remote_workspace_folder: String,
+}
+
+#[derive(Debug, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct DevContainerConfiguration {
+    name: Option<String>,
+}
+
+#[derive(Debug, Deserialize)]
+struct DevContainerConfigurationOutput {
+    configuration: DevContainerConfiguration,
+}
+
+#[cfg(not(target_os = "windows"))]
+fn dev_container_cli() -> String {
+    "devcontainer".to_string()
+}
+
+#[cfg(target_os = "windows")]
+fn dev_container_cli() -> String {
+    "devcontainer.cmd".to_string()
+}
+
+async fn check_for_docker() -> Result<(), DevContainerError> {
+    let mut command = util::command::new_smol_command("docker");
+    command.arg("--version");
+
+    match command.output().await {
+        Ok(_) => Ok(()),
+        Err(e) => {
+            log::error!("Unable to find docker in $PATH: {:?}", e);
+            Err(DevContainerError::DockerNotAvailable)
+        }
+    }
+}
+
+async fn ensure_devcontainer_cli(node_runtime: NodeRuntime) -> Result<PathBuf, DevContainerError> {
+    let mut command = util::command::new_smol_command(&dev_container_cli());
+    command.arg("--version");
+
+    if let Err(e) = command.output().await {
+        log::error!(
+            "Unable to find devcontainer CLI in $PATH. Checking for a zed installed version. Error: {:?}",
+            e
+        );
+
+        let datadir_cli_path = paths::devcontainer_dir()
+            .join("node_modules")
+            .join(".bin")
+            .join(&dev_container_cli());
+
+        let mut command =
+            util::command::new_smol_command(&datadir_cli_path.as_os_str().display().to_string());
+        command.arg("--version");
+
+        if let Err(e) = command.output().await {
+            log::error!(
+                "Unable to find devcontainer CLI in Data dir. Will try to install. Error: {:?}",
+                e
+            );
+        } else {
+            log::info!("Found devcontainer CLI in Data dir");
+            return Ok(datadir_cli_path.clone());
+        }
+
+        if let Err(e) = fs::create_dir_all(paths::devcontainer_dir()).await {
+            log::error!("Unable to create devcontainer directory. Error: {:?}", e);
+            return Err(DevContainerError::DevContainerCliNotAvailable);
+        }
+
+        if let Err(e) = node_runtime
+            .npm_install_packages(
+                &paths::devcontainer_dir(),
+                &[("@devcontainers/cli", "latest")],
+            )
+            .await
+        {
+            log::error!(
+                "Unable to install devcontainer CLI to data directory. Error: {:?}",
+                e
+            );
+            return Err(DevContainerError::DevContainerCliNotAvailable);
+        };
+
+        let mut command = util::command::new_smol_command(&datadir_cli_path.display().to_string());
+        command.arg("--version");
+        if let Err(e) = command.output().await {
+            log::error!(
+                "Unable to find devcontainer cli after NPM install. Error: {:?}",
+                e
+            );
+            Err(DevContainerError::DevContainerCliNotAvailable)
+        } else {
+            Ok(datadir_cli_path)
+        }
+    } else {
+        log::info!("Found devcontainer cli on $PATH, using it");
+        Ok(PathBuf::from(&dev_container_cli()))
+    }
+}
+
+async fn devcontainer_up(
+    path_to_cli: &PathBuf,
+    path: Arc<Path>,
+) -> Result<DevContainerUp, DevContainerError> {
+    let mut command = util::command::new_smol_command(path_to_cli.display().to_string());
+    command.arg("up");
+    command.arg("--workspace-folder");
+    command.arg(path.display().to_string());
+
+    match command.output().await {
+        Ok(output) => {
+            if output.status.success() {
+                let raw = String::from_utf8_lossy(&output.stdout);
+                serde_json::from_str::<DevContainerUp>(&raw).map_err(|e| {
+                    log::error!(
+                        "Unable to parse response from 'devcontainer up' command, error: {:?}",
+                        e
+                    );
+                    DevContainerError::DevContainerParseFailed
+                })
+            } else {
+                log::error!(
+                    "Non-success status running devcontainer up for workspace: out: {:?}, err: {:?}",
+                    String::from_utf8_lossy(&output.stdout),
+                    String::from_utf8_lossy(&output.stderr)
+                );
+                Err(DevContainerError::DevContainerUpFailed)
+            }
+        }
+        Err(e) => {
+            log::error!("Error running devcontainer up: {:?}", e);
+            Err(DevContainerError::DevContainerUpFailed)
+        }
+    }
+}
+
+async fn devcontainer_read_configuration(
+    path_to_cli: &PathBuf,
+    path: Arc<Path>,
+) -> Result<DevContainerConfigurationOutput, DevContainerError> {
+    let mut command = util::command::new_smol_command(path_to_cli.display().to_string());
+    command.arg("read-configuration");
+    command.arg("--workspace-folder");
+    command.arg(path.display().to_string());
+    match command.output().await {
+        Ok(output) => {
+            if output.status.success() {
+                let raw = String::from_utf8_lossy(&output.stdout);
+                serde_json::from_str::<DevContainerConfigurationOutput>(&raw).map_err(|e| {
+                    log::error!(
+                        "Unable to parse response from 'devcontainer read-configuration' command, error: {:?}",
+                        e
+                    );
+                    DevContainerError::DevContainerParseFailed
+                })
+            } else {
+                log::error!(
+                    "Non-success status running devcontainer read-configuration for workspace: out: {:?}, err: {:?}",
+                    String::from_utf8_lossy(&output.stdout),
+                    String::from_utf8_lossy(&output.stderr)
+                );
+                Err(DevContainerError::DevContainerUpFailed)
+            }
+        }
+        Err(e) => {
+            log::error!("Error running devcontainer read-configuration: {:?}", e);
+            Err(DevContainerError::DevContainerUpFailed)
+        }
+    }
+}
+
+// Name the project with two fallbacks
+async fn get_project_name(
+    path_to_cli: &PathBuf,
+    path: Arc<Path>,
+    remote_workspace_folder: String,
+    container_id: String,
+) -> Result<String, DevContainerError> {
+    if let Ok(dev_container_configuration) =
+        devcontainer_read_configuration(path_to_cli, path).await
+        && let Some(name) = dev_container_configuration.configuration.name
+    {
+        // Ideally, name the project after the name defined in devcontainer.json
+        Ok(name)
+    } else {
+        // Otherwise, name the project after the remote workspace folder name
+        Ok(Path::new(&remote_workspace_folder)
+            .file_name()
+            .and_then(|name| name.to_str())
+            .map(|string| string.into())
+            // Finally, name the project after the container ID as a last resort
+            .unwrap_or_else(|| container_id.clone()))
+    }
+}
+
+fn project_directory(cx: &mut AsyncWindowContext) -> Option<Arc<Path>> {
+    let Some(workspace) = cx.window_handle().downcast::<Workspace>() else {
+        return None;
+    };
+
+    match workspace.update(cx, |workspace, _, cx| {
+        workspace.project().read(cx).active_project_directory(cx)
+    }) {
+        Ok(dir) => dir,
+        Err(e) => {
+            log::error!("Error getting project directory from workspace: {:?}", e);
+            None
+        }
+    }
+}
+
+pub(crate) async fn start_dev_container(
+    cx: &mut AsyncWindowContext,
+    node_runtime: NodeRuntime,
+) -> Result<(Connection, String), DevContainerError> {
+    check_for_docker().await?;
+
+    let path_to_devcontainer_cli = ensure_devcontainer_cli(node_runtime).await?;
+
+    let Some(directory) = project_directory(cx) else {
+        return Err(DevContainerError::DevContainerNotFound);
+    };
+
+    if let Ok(DevContainerUp {
+        container_id,
+        remote_workspace_folder,
+        ..
+    }) = devcontainer_up(&path_to_devcontainer_cli, directory.clone()).await
+    {
+        let project_name = get_project_name(
+            &path_to_devcontainer_cli,
+            directory,
+            remote_workspace_folder.clone(),
+            container_id.clone(),
+        )
+        .await?;
+
+        let connection = Connection::DevContainer(DevContainerConnection {
+            name: project_name.into(),
+            container_id: container_id.into(),
+        });
+
+        Ok((connection, remote_workspace_folder))
+    } else {
+        Err(DevContainerError::DevContainerUpFailed)
+    }
+}
+
+#[derive(Debug)]
+pub(crate) enum DevContainerError {
+    DockerNotAvailable,
+    DevContainerCliNotAvailable,
+    DevContainerUpFailed,
+    DevContainerNotFound,
+    DevContainerParseFailed,
+}
+
+#[cfg(test)]
+mod test {
+
+    use crate::dev_container::DevContainerUp;
+
+    #[test]
+    fn should_parse_from_devcontainer_json() {
+        let json = r#"{"outcome":"success","containerId":"826abcac45afd412abff083ab30793daff2f3c8ce2c831df728baf39933cb37a","remoteUser":"vscode","remoteWorkspaceFolder":"/workspaces/zed"}"#;
+        let up: DevContainerUp = serde_json::from_str(json).unwrap();
+        assert_eq!(up._outcome, "success");
+        assert_eq!(
+            up.container_id,
+            "826abcac45afd412abff083ab30793daff2f3c8ce2c831df728baf39933cb37a"
+        );
+        assert_eq!(up._remote_user, "vscode");
+        assert_eq!(up.remote_workspace_folder, "/workspaces/zed");
+    }
+}

crates/recent_projects/src/dev_container_suggest.rs 🔗

@@ -0,0 +1,106 @@
+use db::kvp::KEY_VALUE_STORE;
+use gpui::{SharedString, Window};
+use project::{Project, WorktreeId};
+use std::sync::LazyLock;
+use ui::prelude::*;
+use util::rel_path::RelPath;
+use workspace::Workspace;
+use workspace::notifications::NotificationId;
+use workspace::notifications::simple_message_notification::MessageNotification;
+use worktree::UpdatedEntriesSet;
+
+const DEV_CONTAINER_SUGGEST_KEY: &str = "dev_container_suggest_dismissed";
+
+fn devcontainer_path() -> &'static RelPath {
+    static PATH: LazyLock<&'static RelPath> =
+        LazyLock::new(|| RelPath::unix(".devcontainer").expect("valid path"));
+    *PATH
+}
+
+fn project_devcontainer_key(project_path: &str) -> String {
+    format!("{}_{}", DEV_CONTAINER_SUGGEST_KEY, project_path)
+}
+
+pub fn suggest_on_worktree_updated(
+    worktree_id: WorktreeId,
+    updated_entries: &UpdatedEntriesSet,
+    project: &gpui::Entity<Project>,
+    window: &mut Window,
+    cx: &mut Context<Workspace>,
+) {
+    let devcontainer_updated = updated_entries
+        .iter()
+        .any(|(path, _, _)| path.as_ref() == devcontainer_path());
+
+    if !devcontainer_updated {
+        return;
+    }
+
+    let Some(worktree) = project.read(cx).worktree_for_id(worktree_id, cx) else {
+        return;
+    };
+
+    let worktree = worktree.read(cx);
+
+    if !worktree.is_local() {
+        return;
+    }
+
+    let has_devcontainer = worktree
+        .entry_for_path(devcontainer_path())
+        .is_some_and(|entry| entry.is_dir());
+
+    if !has_devcontainer {
+        return;
+    }
+
+    let abs_path = worktree.abs_path();
+    let project_path = abs_path.to_string_lossy().to_string();
+    let key_for_dismiss = project_devcontainer_key(&project_path);
+
+    let already_dismissed = KEY_VALUE_STORE
+        .read_kvp(&key_for_dismiss)
+        .ok()
+        .flatten()
+        .is_some();
+
+    if already_dismissed {
+        return;
+    }
+
+    cx.on_next_frame(window, move |workspace, _window, cx| {
+        struct DevContainerSuggestionNotification;
+
+        let notification_id = NotificationId::composite::<DevContainerSuggestionNotification>(
+            SharedString::from(project_path.clone()),
+        );
+
+        workspace.show_notification(notification_id, cx, |cx| {
+            cx.new(move |cx| {
+                MessageNotification::new(
+                    "This project contains a Dev Container configuration file. Would you like to re-open it in a container?",
+                    cx,
+                )
+                .primary_message("Yes, Open in Container")
+                .primary_icon(IconName::Check)
+                .primary_icon_color(Color::Success)
+                .primary_on_click({
+                    move |window, cx| {
+                        window.dispatch_action(Box::new(zed_actions::OpenDevContainer), cx);
+                    }
+                })
+                .secondary_message("Don't Show Again")
+                .secondary_icon(IconName::Close)
+                .secondary_icon_color(Color::Error)
+                .secondary_on_click({
+                    move |_window, cx| {
+                        let key = key_for_dismiss.clone();
+                        db::write_and_log(cx, move || {
+                            KEY_VALUE_STORE.write_kvp(key, "dismissed".to_string())
+                        });
+                    }
+                })
+            })
+        });
+    });
+}

crates/recent_projects/src/recent_projects.rs 🔗

@@ -1,8 +1,12 @@
+mod dev_container;
+mod dev_container_suggest;
 pub mod disconnected_overlay;
 mod remote_connections;
 mod remote_servers;
 mod ssh_config;
 
+use std::path::PathBuf;
+
 #[cfg(target_os = "windows")]
 mod wsl_picker;
 
@@ -31,7 +35,7 @@ use workspace::{
     WORKSPACE_DB, Workspace, WorkspaceId, notifications::DetachAndPromptErr,
     with_active_or_new_workspace,
 };
-use zed_actions::{OpenRecent, OpenRemote};
+use zed_actions::{OpenDevContainer, OpenRecent, OpenRemote};
 
 pub fn init(cx: &mut App) {
     #[cfg(target_os = "windows")]
@@ -132,7 +136,8 @@ pub fn init(cx: &mut App) {
         let create_new_window = open_recent.create_new_window;
         with_active_or_new_workspace(cx, move |workspace, window, cx| {
             let Some(recent_projects) = workspace.active_modal::<RecentProjects>(cx) else {
-                RecentProjects::open(workspace, create_new_window, window, cx);
+                let focus_handle = workspace.focus_handle(cx);
+                RecentProjects::open(workspace, create_new_window, window, focus_handle, cx);
                 return;
             };
 
@@ -160,6 +165,95 @@ pub fn init(cx: &mut App) {
     });
 
     cx.observe_new(DisconnectedOverlay::register).detach();
+
+    cx.on_action(|_: &OpenDevContainer, cx| {
+        with_active_or_new_workspace(cx, move |workspace, window, cx| {
+            let app_state = workspace.app_state().clone();
+            let replace_window = window.window_handle().downcast::<Workspace>();
+
+            cx.spawn_in(window, async move |_, mut cx| {
+                let (connection, starting_dir) = match dev_container::start_dev_container(
+                    &mut cx,
+                    app_state.node_runtime.clone(),
+                )
+                .await
+                {
+                    Ok((c, s)) => (c, s),
+                    Err(e) => {
+                        log::error!("Failed to start Dev Container: {:?}", e);
+                        cx.prompt(
+                            gpui::PromptLevel::Critical,
+                            "Failed to start Dev Container",
+                            Some(&format!("{:?}", e)),
+                            &["Ok"],
+                        )
+                        .await
+                        .ok();
+                        return;
+                    }
+                };
+
+                let result = open_remote_project(
+                    connection.into(),
+                    vec![starting_dir].into_iter().map(PathBuf::from).collect(),
+                    app_state,
+                    OpenOptions {
+                        replace_window,
+                        ..OpenOptions::default()
+                    },
+                    &mut cx,
+                )
+                .await;
+
+                if let Err(e) = result {
+                    log::error!("Failed to connect: {e:#}");
+                    cx.prompt(
+                        gpui::PromptLevel::Critical,
+                        "Failed to connect",
+                        Some(&e.to_string()),
+                        &["Ok"],
+                    )
+                    .await
+                    .ok();
+                }
+            })
+            .detach();
+
+            let fs = workspace.project().read(cx).fs().clone();
+            let handle = cx.entity().downgrade();
+            workspace.toggle_modal(window, cx, |window, cx| {
+                RemoteServerProjects::new_dev_container(fs, window, handle, cx)
+            });
+        });
+    });
+
+    // Subscribe to worktree additions to suggest opening the project in a dev container
+    cx.observe_new(
+        |workspace: &mut Workspace, window: Option<&mut Window>, cx: &mut Context<Workspace>| {
+            let Some(window) = window else {
+                return;
+            };
+            cx.subscribe_in(
+                workspace.project(),
+                window,
+                move |_, project, event, window, cx| {
+                    if let project::Event::WorktreeUpdatedEntries(worktree_id, updated_entries) =
+                        event
+                    {
+                        dev_container_suggest::suggest_on_worktree_updated(
+                            *worktree_id,
+                            updated_entries,
+                            project,
+                            window,
+                            cx,
+                        );
+                    }
+                },
+            )
+            .detach();
+        },
+    )
+    .detach();
 }
 
 #[cfg(target_os = "windows")]
@@ -246,11 +340,12 @@ impl RecentProjects {
         workspace: &mut Workspace,
         create_new_window: bool,
         window: &mut Window,
+        focus_handle: FocusHandle,
         cx: &mut Context<Workspace>,
     ) {
         let weak = cx.entity().downgrade();
         workspace.toggle_modal(window, cx, |window, cx| {
-            let delegate = RecentProjectsDelegate::new(weak, create_new_window, true);
+            let delegate = RecentProjectsDelegate::new(weak, create_new_window, true, focus_handle);
 
             Self::new(delegate, 34., window, cx)
         })
@@ -289,10 +384,16 @@ pub struct RecentProjectsDelegate {
     // Flag to reset index when there is a new query vs not reset index when user delete an item
     reset_selected_match_index: bool,
     has_any_non_local_projects: bool,
+    focus_handle: FocusHandle,
 }
 
 impl RecentProjectsDelegate {
-    fn new(workspace: WeakEntity<Workspace>, create_new_window: bool, render_paths: bool) -> Self {
+    fn new(
+        workspace: WeakEntity<Workspace>,
+        create_new_window: bool,
+        render_paths: bool,
+        focus_handle: FocusHandle,
+    ) -> Self {
         Self {
             workspace,
             workspaces: Vec::new(),
@@ -302,6 +403,7 @@ impl RecentProjectsDelegate {
             render_paths,
             reset_selected_match_index: true,
             has_any_non_local_projects: false,
+            focus_handle,
         }
     }
 
@@ -532,8 +634,8 @@ impl PickerDelegate for RecentProjectsDelegate {
             .unzip();
 
         let prefix = match &location {
-            SerializedWorkspaceLocation::Remote(RemoteConnectionOptions::Wsl(wsl)) => {
-                Some(SharedString::from(&wsl.distro_name))
+            SerializedWorkspaceLocation::Remote(options) => {
+                Some(SharedString::from(options.display_name()))
             }
             _ => None,
         };
@@ -544,12 +646,23 @@ impl PickerDelegate for RecentProjectsDelegate {
             paths,
         };
 
+        let focus_handle = self.focus_handle.clone();
+
         let secondary_actions = h_flex()
             .gap_px()
             .child(
                 IconButton::new("open_new_window", IconName::ArrowUpRight)
                     .icon_size(IconSize::XSmall)
-                    .tooltip(Tooltip::text("Open Project in New Window"))
+                    .tooltip({
+                        move |_, cx| {
+                            Tooltip::for_action_in(
+                                "Open Project in New Window",
+                                &menu::SecondaryConfirm,
+                                &focus_handle,
+                                cx,
+                            )
+                        }
+                    })
                     .on_click(cx.listener(move |this, _event, window, cx| {
                         cx.stop_propagation();
                         window.prevent_default();
@@ -577,8 +690,9 @@ impl PickerDelegate for RecentProjectsDelegate {
                 .spacing(ListItemSpacing::Sparse)
                 .child(
                     h_flex()
-                        .flex_grow()
+                        .id("projecy_info_container")
                         .gap_3()
+                        .flex_grow()
                         .when(self.has_any_non_local_projects, |this| {
                             this.child(match location {
                                 SerializedWorkspaceLocation::Local => Icon::new(IconName::Screen)
@@ -588,6 +702,7 @@ impl PickerDelegate for RecentProjectsDelegate {
                                     Icon::new(match options {
                                         RemoteConnectionOptions::Ssh { .. } => IconName::Server,
                                         RemoteConnectionOptions::Wsl { .. } => IconName::Linux,
+                                        RemoteConnectionOptions::Docker(_) => IconName::Box,
                                     })
                                     .color(Color::Muted)
                                     .into_any_element()
@@ -600,6 +715,13 @@ impl PickerDelegate for RecentProjectsDelegate {
                                 highlighted.paths.clear();
                             }
                             highlighted.render(window, cx)
+                        })
+                        .tooltip(move |_, cx| {
+                            let tooltip_highlighted_location = highlighted_match.clone();
+                            cx.new(|_| MatchTooltip {
+                                highlighted_location: tooltip_highlighted_location,
+                            })
+                            .into()
                         }),
                 )
                 .map(|el| {
@@ -608,13 +730,6 @@ impl PickerDelegate for RecentProjectsDelegate {
                     } else {
                         el.end_hover_slot(secondary_actions)
                     }
-                })
-                .tooltip(move |_, cx| {
-                    let tooltip_highlighted_location = highlighted_match.clone();
-                    cx.new(|_| MatchTooltip {
-                        highlighted_location: tooltip_highlighted_location,
-                    })
-                    .into()
                 }),
         )
     }

crates/recent_projects/src/remote_connections.rs 🔗

@@ -16,18 +16,19 @@ use gpui::{
 
 use language::{CursorShape, Point};
 use markdown::{Markdown, MarkdownElement, MarkdownStyle};
+use project::trusted_worktrees;
 use release_channel::ReleaseChannel;
 use remote::{
-    ConnectionIdentifier, RemoteClient, RemoteConnection, RemoteConnectionOptions, RemotePlatform,
-    SshConnectionOptions,
+    ConnectionIdentifier, DockerConnectionOptions, RemoteClient, RemoteConnection,
+    RemoteConnectionOptions, RemotePlatform, SshConnectionOptions,
 };
 use semver::Version;
 pub use settings::SshConnection;
-use settings::{ExtendingVec, RegisterSetting, Settings, WslConnection};
+use settings::{DevContainerConnection, ExtendingVec, RegisterSetting, Settings, WslConnection};
 use theme::ThemeSettings;
 use ui::{
-    ActiveTheme, Color, CommonAnimationExt, Context, Icon, IconName, IconSize, InteractiveElement,
-    IntoElement, Label, LabelCommon, Styled, Window, prelude::*,
+    ActiveTheme, Color, CommonAnimationExt, Context, InteractiveElement, IntoElement, KeyBinding,
+    LabelCommon, ListItem, Styled, Window, prelude::*,
 };
 use util::paths::PathWithPosition;
 use workspace::{AppState, ModalView, Workspace};
@@ -51,7 +52,7 @@ impl SshSettings {
 
     pub fn fill_connection_options_from_settings(&self, options: &mut SshConnectionOptions) {
         for conn in self.ssh_connections() {
-            if conn.host == options.host
+            if conn.host == options.host.to_string()
                 && conn.username == options.username
                 && conn.port == options.port
             {
@@ -71,7 +72,7 @@ impl SshSettings {
         username: Option<String>,
     ) -> SshConnectionOptions {
         let mut options = SshConnectionOptions {
-            host,
+            host: host.into(),
             port,
             username,
             ..Default::default()
@@ -85,6 +86,7 @@ impl SshSettings {
 pub enum Connection {
     Ssh(SshConnection),
     Wsl(WslConnection),
+    DevContainer(DevContainerConnection),
 }
 
 impl From<Connection> for RemoteConnectionOptions {
@@ -92,6 +94,13 @@ impl From<Connection> for RemoteConnectionOptions {
         match val {
             Connection::Ssh(conn) => RemoteConnectionOptions::Ssh(conn.into()),
             Connection::Wsl(conn) => RemoteConnectionOptions::Wsl(conn.into()),
+            Connection::DevContainer(conn) => {
+                RemoteConnectionOptions::Docker(DockerConnectionOptions {
+                    name: conn.name.to_string(),
+                    container_id: conn.container_id.to_string(),
+                    upload_binary_over_docker_exec: false,
+                })
+            }
         }
     }
 }
@@ -123,6 +132,7 @@ pub struct RemoteConnectionPrompt {
     connection_string: SharedString,
     nickname: Option<SharedString>,
     is_wsl: bool,
+    is_devcontainer: bool,
     status_message: Option<SharedString>,
     prompt: Option<(Entity<Markdown>, oneshot::Sender<EncryptedPassword>)>,
     cancellation: Option<oneshot::Sender<()>>,
@@ -148,6 +158,7 @@ impl RemoteConnectionPrompt {
         connection_string: String,
         nickname: Option<String>,
         is_wsl: bool,
+        is_devcontainer: bool,
         window: &mut Window,
         cx: &mut Context<Self>,
     ) -> Self {
@@ -155,6 +166,7 @@ impl RemoteConnectionPrompt {
             connection_string: connection_string.into(),
             nickname: nickname.map(|nickname| nickname.into()),
             is_wsl,
+            is_devcontainer,
             editor: cx.new(|cx| Editor::single_line(window, cx)),
             status_message: None,
             cancellation: None,
@@ -197,7 +209,7 @@ impl RemoteConnectionPrompt {
         let markdown = cx.new(|cx| Markdown::new_text(prompt.into(), cx));
         self.prompt = Some((markdown, tx));
         self.status_message.take();
-        window.focus(&self.editor.focus_handle(cx));
+        window.focus(&self.editor.focus_handle(cx), cx);
         cx.notify();
     }
 
@@ -244,17 +256,16 @@ impl Render for RemoteConnectionPrompt {
 
         v_flex()
             .key_context("PasswordPrompt")
-            .py_2()
-            .px_3()
+            .p_2()
             .size_full()
             .text_buffer(cx)
             .when_some(self.status_message.clone(), |el, status_message| {
                 el.child(
                     h_flex()
-                        .gap_1()
+                        .gap_2()
                         .child(
                             Icon::new(IconName::ArrowCircle)
-                                .size(IconSize::Medium)
+                                .color(Color::Muted)
                                 .with_rotate_animation(2),
                         )
                         .child(
@@ -287,15 +298,28 @@ impl RemoteConnectionModal {
         window: &mut Window,
         cx: &mut Context<Self>,
     ) -> Self {
-        let (connection_string, nickname, is_wsl) = match connection_options {
-            RemoteConnectionOptions::Ssh(options) => {
-                (options.connection_string(), options.nickname.clone(), false)
+        let (connection_string, nickname, is_wsl, is_devcontainer) = match connection_options {
+            RemoteConnectionOptions::Ssh(options) => (
+                options.connection_string(),
+                options.nickname.clone(),
+                false,
+                false,
+            ),
+            RemoteConnectionOptions::Wsl(options) => {
+                (options.distro_name.clone(), None, true, false)
             }
-            RemoteConnectionOptions::Wsl(options) => (options.distro_name.clone(), None, true),
+            RemoteConnectionOptions::Docker(options) => (options.name.clone(), None, false, true),
         };
         Self {
             prompt: cx.new(|cx| {
-                RemoteConnectionPrompt::new(connection_string, nickname, is_wsl, window, cx)
+                RemoteConnectionPrompt::new(
+                    connection_string,
+                    nickname,
+                    is_wsl,
+                    is_devcontainer,
+                    window,
+                    cx,
+                )
             }),
             finished: false,
             paths,
@@ -328,6 +352,7 @@ pub(crate) struct SshConnectionHeader {
     pub(crate) paths: Vec<PathBuf>,
     pub(crate) nickname: Option<SharedString>,
     pub(crate) is_wsl: bool,
+    pub(crate) is_devcontainer: bool,
 }
 
 impl RenderOnce for SshConnectionHeader {
@@ -343,9 +368,12 @@ impl RenderOnce for SshConnectionHeader {
             (self.connection_string, None)
         };
 
-        let icon = match self.is_wsl {
-            true => IconName::Linux,
-            false => IconName::Server,
+        let icon = if self.is_wsl {
+            IconName::Linux
+        } else if self.is_devcontainer {
+            IconName::Box
+        } else {
+            IconName::Server
         };
 
         h_flex()
@@ -388,6 +416,7 @@ impl Render for RemoteConnectionModal {
         let nickname = self.prompt.read(cx).nickname.clone();
         let connection_string = self.prompt.read(cx).connection_string.clone();
         let is_wsl = self.prompt.read(cx).is_wsl;
+        let is_devcontainer = self.prompt.read(cx).is_devcontainer;
 
         let theme = cx.theme().clone();
         let body_color = theme.colors().editor_background;
@@ -407,18 +436,34 @@ impl Render for RemoteConnectionModal {
                     connection_string,
                     nickname,
                     is_wsl,
+                    is_devcontainer,
                 }
                 .render(window, cx),
             )
             .child(
                 div()
                     .w_full()
-                    .rounded_b_lg()
                     .bg(body_color)
-                    .border_t_1()
+                    .border_y_1()
                     .border_color(theme.colors().border_variant)
                     .child(self.prompt.clone()),
             )
+            .child(
+                div().w_full().py_1().child(
+                    ListItem::new("li-devcontainer-go-back")
+                        .inset(true)
+                        .spacing(ui::ListItemSpacing::Sparse)
+                        .start_slot(Icon::new(IconName::Close).color(Color::Muted))
+                        .child(Label::new("Cancel"))
+                        .end_slot(
+                            KeyBinding::for_action_in(&menu::Cancel, &self.focus_handle(cx), cx)
+                                .size(rems_from_px(12.)),
+                        )
+                        .on_click(cx.listener(|this, _, window, cx| {
+                            this.dismiss(&menu::Cancel, window, cx);
+                        })),
+                ),
+            )
     }
 }
 
@@ -488,8 +533,8 @@ impl remote::RemoteClientDelegate for RemoteClientDelegate {
             AutoUpdater::download_remote_server_release(
                 release_channel,
                 version.clone(),
-                platform.os,
-                platform.arch,
+                platform.os.as_str(),
+                platform.arch.as_str(),
                 move |status, cx| this.set_status(Some(status), cx),
                 cx,
             )
@@ -519,8 +564,8 @@ impl remote::RemoteClientDelegate for RemoteClientDelegate {
             AutoUpdater::get_remote_server_release_url(
                 release_channel,
                 version,
-                platform.os,
-                platform.arch,
+                platform.os.as_str(),
+                platform.arch.as_str(),
                 cx,
             )
             .await
@@ -602,6 +647,7 @@ pub async fn open_remote_project(
                 app_state.languages.clone(),
                 app_state.fs.clone(),
                 None,
+                false,
                 cx,
             );
             cx.new(|cx| {
@@ -671,6 +717,9 @@ pub async fn open_remote_project(
                                 match connection_options {
                                     RemoteConnectionOptions::Ssh(_) => "Failed to connect over SSH",
                                     RemoteConnectionOptions::Wsl(_) => "Failed to connect to WSL",
+                                    RemoteConnectionOptions::Docker(_) => {
+                                        "Failed to connect to Dev Container"
+                                    }
                                 },
                                 Some(&format!("{e:#}")),
                                 &["Retry", "Cancel"],
@@ -727,6 +776,9 @@ pub async fn open_remote_project(
                             match connection_options {
                                 RemoteConnectionOptions::Ssh(_) => "Failed to connect over SSH",
                                 RemoteConnectionOptions::Wsl(_) => "Failed to connect to WSL",
+                                RemoteConnectionOptions::Docker(_) => {
+                                    "Failed to connect to Dev Container"
+                                }
                             },
                             Some(&format!("{e:#}")),
                             &["Retry", "Cancel"],
@@ -738,11 +790,20 @@ pub async fn open_remote_project(
                     continue;
                 }
 
-                if created_new_window {
-                    window
-                        .update(cx, |_, window, _| window.remove_window())
-                        .ok();
-                }
+                window
+                    .update(cx, |workspace, window, cx| {
+                        if created_new_window {
+                            window.remove_window();
+                        }
+                        trusted_worktrees::track_worktree_trust(
+                            workspace.project().read(cx).worktree_store(),
+                            None,
+                            None,
+                            None,
+                            cx,
+                        );
+                    })
+                    .ok();
             }
 
             Ok(items) => {

crates/recent_projects/src/remote_servers.rs 🔗

@@ -1,4 +1,5 @@
 use crate::{
+    dev_container::start_dev_container,
     remote_connections::{
         Connection, RemoteConnectionModal, RemoteConnectionPrompt, SshConnection,
         SshConnectionHeader, SshSettings, connect, determine_paths_with_positions,
@@ -24,7 +25,7 @@ use remote::{
     remote_client::ConnectionIdentifier,
 };
 use settings::{
-    RemoteSettingsContent, Settings as _, SettingsStore, SshProject, update_settings_file,
+    RemoteProject, RemoteSettingsContent, Settings as _, SettingsStore, update_settings_file,
     watch_config_file,
 };
 use smol::stream::StreamExt as _;
@@ -39,12 +40,13 @@ use std::{
     },
 };
 use ui::{
-    IconButtonShape, List, ListItem, ListSeparator, Modal, ModalHeader, Navigable, NavigableEntry,
-    Section, Tooltip, WithScrollbar, prelude::*,
+    CommonAnimationExt, IconButtonShape, KeyBinding, List, ListItem, ListSeparator, Modal,
+    ModalHeader, Navigable, NavigableEntry, Section, Tooltip, WithScrollbar, prelude::*,
 };
 use util::{
     ResultExt,
     paths::{PathStyle, RemotePathBuf},
+    rel_path::RelPath,
 };
 use workspace::{
     ModalView, OpenOptions, Toast, Workspace,
@@ -74,7 +76,7 @@ impl CreateRemoteServer {
     fn new(window: &mut Window, cx: &mut App) -> Self {
         let address_editor = cx.new(|cx| Editor::single_line(window, cx));
         address_editor.update(cx, |this, cx| {
-            this.focus_handle(cx).focus(window);
+            this.focus_handle(cx).focus(window, cx);
         });
         Self {
             address_editor,
@@ -85,6 +87,39 @@ impl CreateRemoteServer {
     }
 }
 
+#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
+enum DevContainerCreationProgress {
+    Initial,
+    Creating,
+    Error(String),
+}
+
+#[derive(Clone)]
+struct CreateRemoteDevContainer {
+    // 3 Navigable Options
+    // - Create from devcontainer.json
+    // - Edit devcontainer.json
+    // - Go back
+    entries: [NavigableEntry; 3],
+    progress: DevContainerCreationProgress,
+}
+
+impl CreateRemoteDevContainer {
+    fn new(window: &mut Window, cx: &mut Context<RemoteServerProjects>) -> Self {
+        let entries = std::array::from_fn(|_| NavigableEntry::focusable(cx));
+        entries[0].focus_handle.focus(window, cx);
+        Self {
+            entries,
+            progress: DevContainerCreationProgress::Initial,
+        }
+    }
+
+    fn progress(&mut self, progress: DevContainerCreationProgress) -> Self {
+        self.progress = progress;
+        self.clone()
+    }
+}
+
 #[cfg(target_os = "windows")]
 struct AddWslDistro {
     picker: Entity<Picker<crate::wsl_picker::WslPickerDelegate>>,
@@ -164,7 +199,7 @@ impl EditNicknameState {
                 this.set_text(starting_text, window, cx);
             }
         });
-        this.editor.focus_handle(cx).focus(window);
+        this.editor.focus_handle(cx).focus(window, cx);
         this
     }
 }
@@ -182,14 +217,13 @@ impl ProjectPicker {
         connection: RemoteConnectionOptions,
         project: Entity<Project>,
         home_dir: RemotePathBuf,
-        path_style: PathStyle,
         workspace: WeakEntity<Workspace>,
         window: &mut Window,
         cx: &mut Context<RemoteServerProjects>,
     ) -> Entity<Self> {
         let (tx, rx) = oneshot::channel();
         let lister = project::DirectoryLister::Project(project.clone());
-        let delegate = file_finder::OpenPathDelegate::new(tx, lister, false, path_style);
+        let delegate = file_finder::OpenPathDelegate::new(tx, lister, false, cx);
 
         let picker = cx.new(|cx| {
             let picker = Picker::uniform_list(delegate, window, cx)
@@ -207,6 +241,11 @@ impl ProjectPicker {
             RemoteConnectionOptions::Wsl(connection) => ProjectPickerData::Wsl {
                 distro_name: connection.distro_name.clone().into(),
             },
+            RemoteConnectionOptions::Docker(_) => ProjectPickerData::Ssh {
+                // Not implemented as a project picker at this time
+                connection_string: "".into(),
+                nickname: None,
+            },
         };
         let _path_task = cx
             .spawn_in(window, {
@@ -259,7 +298,7 @@ impl ProjectPicker {
                                         .as_mut()
                                         .and_then(|connections| connections.get_mut(index.0))
                                     {
-                                        server.projects.insert(SshProject { paths });
+                                        server.projects.insert(RemoteProject { paths });
                                     };
                                 }
                                 ServerIndex::Wsl(index) => {
@@ -269,7 +308,7 @@ impl ProjectPicker {
                                         .as_mut()
                                         .and_then(|connections| connections.get_mut(index.0))
                                     {
-                                        server.projects.insert(SshProject { paths });
+                                        server.projects.insert(RemoteProject { paths });
                                     };
                                 }
                             }
@@ -349,6 +388,7 @@ impl gpui::Render for ProjectPicker {
                     paths: Default::default(),
                     nickname: nickname.clone(),
                     is_wsl: false,
+                    is_devcontainer: false,
                 }
                 .render(window, cx),
                 ProjectPickerData::Wsl { distro_name } => SshConnectionHeader {
@@ -356,6 +396,7 @@ impl gpui::Render for ProjectPicker {
                     paths: Default::default(),
                     nickname: None,
                     is_wsl: true,
+                    is_devcontainer: false,
                 }
                 .render(window, cx),
             })
@@ -406,7 +447,7 @@ impl From<WslServerIndex> for ServerIndex {
 enum RemoteEntry {
     Project {
         open_folder: NavigableEntry,
-        projects: Vec<(NavigableEntry, SshProject)>,
+        projects: Vec<(NavigableEntry, RemoteProject)>,
         configure: NavigableEntry,
         connection: Connection,
         index: ServerIndex,
@@ -440,6 +481,7 @@ impl RemoteEntry {
 struct DefaultState {
     scroll_handle: ScrollHandle,
     add_new_server: NavigableEntry,
+    add_new_devcontainer: NavigableEntry,
     add_new_wsl: NavigableEntry,
     servers: Vec<RemoteEntry>,
 }
@@ -448,6 +490,7 @@ impl DefaultState {
     fn new(ssh_config_servers: &BTreeSet<SharedString>, cx: &mut App) -> Self {
         let handle = ScrollHandle::new();
         let add_new_server = NavigableEntry::new(&handle, cx);
+        let add_new_devcontainer = NavigableEntry::new(&handle, cx);
         let add_new_wsl = NavigableEntry::new(&handle, cx);
 
         let ssh_settings = SshSettings::get_global(cx);
@@ -517,6 +560,7 @@ impl DefaultState {
         Self {
             scroll_handle: handle,
             add_new_server,
+            add_new_devcontainer,
             add_new_wsl,
             servers,
         }
@@ -552,6 +596,7 @@ enum Mode {
     EditNickname(EditNicknameState),
     ProjectPicker(Entity<ProjectPicker>),
     CreateRemoteServer(CreateRemoteServer),
+    CreateRemoteDevContainer(CreateRemoteDevContainer),
     #[cfg(target_os = "windows")]
     AddWslDistro(AddWslDistro),
 }
@@ -598,6 +643,27 @@ impl RemoteServerProjects {
         )
     }
 
+    /// Creates a new RemoteServerProjects modal that opens directly in dev container creation mode.
+    /// Used when suggesting dev container connection from toast notification.
+    pub fn new_dev_container(
+        fs: Arc<dyn Fs>,
+        window: &mut Window,
+        workspace: WeakEntity<Workspace>,
+        cx: &mut Context<Self>,
+    ) -> Self {
+        Self::new_inner(
+            Mode::CreateRemoteDevContainer(
+                CreateRemoteDevContainer::new(window, cx)
+                    .progress(DevContainerCreationProgress::Creating),
+            ),
+            false,
+            fs,
+            window,
+            workspace,
+            cx,
+        )
+    }
+
     fn new_inner(
         mode: Mode,
         create_new_window: bool,
@@ -652,7 +718,6 @@ impl RemoteServerProjects {
         connection_options: remote::RemoteConnectionOptions,
         project: Entity<Project>,
         home_dir: RemotePathBuf,
-        path_style: PathStyle,
         window: &mut Window,
         cx: &mut Context<Self>,
         workspace: WeakEntity<Workspace>,
@@ -665,7 +730,6 @@ impl RemoteServerProjects {
             connection_options,
             project,
             home_dir,
-            path_style,
             workspace,
             window,
             cx,
@@ -703,6 +767,7 @@ impl RemoteServerProjects {
                 connection_options.connection_string(),
                 connection_options.nickname.clone(),
                 false,
+                false,
                 window,
                 cx,
             )
@@ -727,7 +792,7 @@ impl RemoteServerProjects {
                         this.retained_connections.push(client);
                         this.add_ssh_server(connection_options, cx);
                         this.mode = Mode::default_mode(&this.ssh_config_servers, cx);
-                        this.focus_handle(cx).focus(window);
+                        this.focus_handle(cx).focus(window, cx);
                         cx.notify()
                     })
                     .log_err(),
@@ -778,6 +843,7 @@ impl RemoteServerProjects {
                 connection_options.distro_name.clone(),
                 None,
                 true,
+                false,
                 window,
                 cx,
             )
@@ -809,7 +875,7 @@ impl RemoteServerProjects {
 
                     crate::add_wsl_distro(fs, &connection_options, cx);
                     this.mode = Mode::default_mode(&BTreeSet::new(), cx);
-                    this.focus_handle(cx).focus(window);
+                    this.focus_handle(cx).focus(window, cx);
                     cx.notify();
                 }),
                 _ => this.update(cx, |this, cx| {
@@ -858,7 +924,16 @@ impl RemoteServerProjects {
                 return;
             }
         });
-        self.focus_handle(cx).focus(window);
+        self.focus_handle(cx).focus(window, cx);
+        cx.notify();
+    }
+
+    fn view_in_progress_dev_container(&mut self, window: &mut Window, cx: &mut Context<Self>) {
+        self.mode = Mode::CreateRemoteDevContainer(
+            CreateRemoteDevContainer::new(window, cx)
+                .progress(DevContainerCreationProgress::Creating),
+        );
+        self.focus_handle(cx).focus(window, cx);
         cx.notify();
     }
 
@@ -925,6 +1000,7 @@ impl RemoteServerProjects {
                                 app_state.user_store.clone(),
                                 app_state.languages.clone(),
                                 app_state.fs.clone(),
+                                true,
                                 cx,
                             ),
                         )
@@ -952,7 +1028,6 @@ impl RemoteServerProjects {
                                     connection_options,
                                     project,
                                     home_dir,
-                                    path_style,
                                     window,
                                     cx,
                                     weak,
@@ -981,6 +1056,7 @@ impl RemoteServerProjects {
 
                 self.create_ssh_server(state.address_editor.clone(), window, cx);
             }
+            Mode::CreateRemoteDevContainer(_) => {}
             Mode::EditNickname(state) => {
                 let text = Some(state.editor.read(cx).text(cx)).filter(|text| !text.is_empty());
                 let index = state.index;
@@ -992,7 +1068,7 @@ impl RemoteServerProjects {
                     }
                 });
                 self.mode = Mode::default_mode(&self.ssh_config_servers, cx);
-                self.focus_handle.focus(window);
+                self.focus_handle.focus(window, cx);
             }
             #[cfg(target_os = "windows")]
             Mode::AddWslDistro(state) => {
@@ -1018,20 +1094,20 @@ impl RemoteServerProjects {
             }
             _ => {
                 self.mode = Mode::default_mode(&self.ssh_config_servers, cx);
-                self.focus_handle(cx).focus(window);
+                self.focus_handle(cx).focus(window, cx);
                 cx.notify();
             }
         }
     }
 
-    fn render_ssh_connection(
+    fn render_remote_connection(
         &mut self,
         ix: usize,
-        ssh_server: RemoteEntry,
+        remote_server: RemoteEntry,
         window: &mut Window,
         cx: &mut Context<Self>,
     ) -> impl IntoElement {
-        let connection = ssh_server.connection().into_owned();
+        let connection = remote_server.connection().into_owned();
 
         let (main_label, aux_label, is_wsl) = match &connection {
             Connection::Ssh(connection) => {
@@ -1045,6 +1121,9 @@ impl RemoteServerProjects {
             Connection::Wsl(wsl_connection_options) => {
                 (wsl_connection_options.distro_name.clone(), None, true)
             }
+            Connection::DevContainer(dev_container_options) => {
+                (dev_container_options.name.clone(), None, false)
+            }
         };
         v_flex()
             .w_full()
@@ -1082,7 +1161,7 @@ impl RemoteServerProjects {
                         }),
                     ),
             )
-            .child(match &ssh_server {
+            .child(match &remote_server {
                 RemoteEntry::Project {
                     open_folder,
                     projects,
@@ -1094,9 +1173,9 @@ impl RemoteServerProjects {
                     List::new()
                         .empty_message("No projects.")
                         .children(projects.iter().enumerate().map(|(pix, p)| {
-                            v_flex().gap_0p5().child(self.render_ssh_project(
+                            v_flex().gap_0p5().child(self.render_remote_project(
                                 index,
-                                ssh_server.clone(),
+                                remote_server.clone(),
                                 pix,
                                 p,
                                 window,
@@ -1222,12 +1301,12 @@ impl RemoteServerProjects {
             })
     }
 
-    fn render_ssh_project(
+    fn render_remote_project(
         &mut self,
         server_ix: ServerIndex,
         server: RemoteEntry,
         ix: usize,
-        (navigation, project): &(NavigableEntry, SshProject),
+        (navigation, project): &(NavigableEntry, RemoteProject),
         window: &mut Window,
         cx: &mut Context<Self>,
     ) -> impl IntoElement {
@@ -1372,7 +1451,7 @@ impl RemoteServerProjects {
     fn delete_remote_project(
         &mut self,
         server: ServerIndex,
-        project: &SshProject,
+        project: &RemoteProject,
         cx: &mut Context<Self>,
     ) {
         match server {
@@ -1388,7 +1467,7 @@ impl RemoteServerProjects {
     fn delete_ssh_project(
         &mut self,
         server: SshServerIndex,
-        project: &SshProject,
+        project: &RemoteProject,
         cx: &mut Context<Self>,
     ) {
         let project = project.clone();
@@ -1406,7 +1485,7 @@ impl RemoteServerProjects {
     fn delete_wsl_project(
         &mut self,
         server: WslServerIndex,
-        project: &SshProject,
+        project: &RemoteProject,
         cx: &mut Context<Self>,
     ) {
         let project = project.clone();
@@ -1439,7 +1518,7 @@ impl RemoteServerProjects {
                 .ssh_connections
                 .get_or_insert(Default::default())
                 .push(SshConnection {
-                    host: SharedString::from(connection_options.host),
+                    host: SharedString::from(connection_options.host.to_string()),
                     username: connection_options.username,
                     port: connection_options.port,
                     projects: BTreeSet::new(),
@@ -1447,8 +1526,345 @@ impl RemoteServerProjects {
                     args: connection_options.args.unwrap_or_default(),
                     upload_binary_over_ssh: None,
                     port_forwards: connection_options.port_forwards,
+                    connection_timeout: connection_options.connection_timeout,
+                })
+        });
+    }
+
+    fn edit_in_dev_container_json(&mut self, window: &mut Window, cx: &mut Context<Self>) {
+        let Some(workspace) = self.workspace.upgrade() else {
+            cx.emit(DismissEvent);
+            cx.notify();
+            return;
+        };
+
+        workspace.update(cx, |workspace, cx| {
+            let project = workspace.project().clone();
+
+            let worktree = project
+                .read(cx)
+                .visible_worktrees(cx)
+                .find_map(|tree| tree.read(cx).root_entry()?.is_dir().then_some(tree));
+
+            if let Some(worktree) = worktree {
+                let tree_id = worktree.read(cx).id();
+                let devcontainer_path = RelPath::unix(".devcontainer/devcontainer.json").unwrap();
+                cx.spawn_in(window, async move |workspace, cx| {
+                    workspace
+                        .update_in(cx, |workspace, window, cx| {
+                            workspace.open_path(
+                                (tree_id, devcontainer_path),
+                                None,
+                                true,
+                                window,
+                                cx,
+                            )
+                        })?
+                        .await
                 })
+                .detach();
+            } else {
+                return;
+            }
         });
+        cx.emit(DismissEvent);
+        cx.notify();
+    }
+
+    fn open_dev_container(&self, window: &mut Window, cx: &mut Context<Self>) {
+        let Some(app_state) = self
+            .workspace
+            .read_with(cx, |workspace, _| workspace.app_state().clone())
+            .log_err()
+        else {
+            return;
+        };
+
+        let replace_window = window.window_handle().downcast::<Workspace>();
+
+        cx.spawn_in(window, async move |entity, cx| {
+            let (connection, starting_dir) =
+                match start_dev_container(cx, app_state.node_runtime.clone()).await {
+                    Ok((c, s)) => (c, s),
+                    Err(e) => {
+                        log::error!("Failed to start dev container: {:?}", e);
+                        entity
+                            .update_in(cx, |remote_server_projects, window, cx| {
+                                remote_server_projects.mode = Mode::CreateRemoteDevContainer(
+                                    CreateRemoteDevContainer::new(window, cx).progress(
+                                        DevContainerCreationProgress::Error(format!("{:?}", e)),
+                                    ),
+                                );
+                            })
+                            .log_err();
+                        return;
+                    }
+                };
+            entity
+                .update(cx, |_, cx| {
+                    cx.emit(DismissEvent);
+                })
+                .log_err();
+
+            let result = open_remote_project(
+                connection.into(),
+                vec![starting_dir].into_iter().map(PathBuf::from).collect(),
+                app_state,
+                OpenOptions {
+                    replace_window,
+                    ..OpenOptions::default()
+                },
+                cx,
+            )
+            .await;
+            if let Err(e) = result {
+                log::error!("Failed to connect: {e:#}");
+                cx.prompt(
+                    gpui::PromptLevel::Critical,
+                    "Failed to connect",
+                    Some(&e.to_string()),
+                    &["Ok"],
+                )
+                .await
+                .ok();
+            }
+        })
+        .detach();
+    }
+
+    fn render_create_dev_container(
+        &self,
+        state: &CreateRemoteDevContainer,
+        window: &mut Window,
+        cx: &mut Context<Self>,
+    ) -> impl IntoElement {
+        match &state.progress {
+            DevContainerCreationProgress::Error(message) => {
+                self.focus_handle(cx).focus(window, cx);
+                return div()
+                    .track_focus(&self.focus_handle(cx))
+                    .size_full()
+                    .child(
+                        v_flex()
+                            .py_1()
+                            .child(
+                                ListItem::new("Error")
+                                    .inset(true)
+                                    .selectable(false)
+                                    .spacing(ui::ListItemSpacing::Sparse)
+                                    .start_slot(Icon::new(IconName::XCircle).color(Color::Error))
+                                    .child(Label::new("Error Creating Dev Container:"))
+                                    .child(Label::new(message).buffer_font(cx)),
+                            )
+                            .child(ListSeparator)
+                            .child(
+                                div()
+                                    .id("devcontainer-go-back")
+                                    .track_focus(&state.entries[0].focus_handle)
+                                    .on_action(cx.listener(
+                                        |this, _: &menu::Confirm, window, cx| {
+                                            this.mode =
+                                                Mode::default_mode(&this.ssh_config_servers, cx);
+                                            cx.focus_self(window);
+                                            cx.notify();
+                                        },
+                                    ))
+                                    .child(
+                                        ListItem::new("li-devcontainer-go-back")
+                                            .toggle_state(
+                                                state.entries[0]
+                                                    .focus_handle
+                                                    .contains_focused(window, cx),
+                                            )
+                                            .inset(true)
+                                            .spacing(ui::ListItemSpacing::Sparse)
+                                            .start_slot(
+                                                Icon::new(IconName::ArrowLeft).color(Color::Muted),
+                                            )
+                                            .child(Label::new("Go Back"))
+                                            .end_slot(
+                                                KeyBinding::for_action_in(
+                                                    &menu::Cancel,
+                                                    &self.focus_handle,
+                                                    cx,
+                                                )
+                                                .size(rems_from_px(12.)),
+                                            )
+                                            .on_click(cx.listener(|this, _, window, cx| {
+                                                let state =
+                                                    CreateRemoteDevContainer::new(window, cx);
+                                                this.mode = Mode::CreateRemoteDevContainer(state);
+
+                                                cx.notify();
+                                            })),
+                                    ),
+                            ),
+                    )
+                    .into_any_element();
+            }
+            _ => {}
+        };
+
+        let mut view = Navigable::new(
+            div()
+                .track_focus(&self.focus_handle(cx))
+                .size_full()
+                .child(
+                    v_flex()
+                        .pb_1()
+                        .child(
+                            ModalHeader::new()
+                                .child(Headline::new("Dev Containers").size(HeadlineSize::XSmall)),
+                        )
+                        .child(ListSeparator)
+                        .child(
+                            div()
+                                .id("confirm-create-from-devcontainer-json")
+                                .track_focus(&state.entries[0].focus_handle)
+                                .on_action(cx.listener({
+                                    move |this, _: &menu::Confirm, window, cx| {
+                                        this.open_dev_container(window, cx);
+                                        this.view_in_progress_dev_container(window, cx);
+                                    }
+                                }))
+                                .map(|this| {
+                                    if state.progress == DevContainerCreationProgress::Creating {
+                                        this.child(
+                                            ListItem::new("creating")
+                                                .inset(true)
+                                                .spacing(ui::ListItemSpacing::Sparse)
+                                                .disabled(true)
+                                                .start_slot(
+                                                    Icon::new(IconName::ArrowCircle)
+                                                        .color(Color::Muted)
+                                                        .with_rotate_animation(2),
+                                                )
+                                                .child(
+                                                    h_flex()
+                                                        .opacity(0.6)
+                                                        .gap_1()
+                                                        .child(Label::new("Creating From"))
+                                                        .child(
+                                                            Label::new("devcontainer.json")
+                                                                .buffer_font(cx),
+                                                        )
+                                                        .child(LoadingLabel::new("")),
+                                                ),
+                                        )
+                                    } else {
+                                        this.child(
+                                            ListItem::new(
+                                                "li-confirm-create-from-devcontainer-json",
+                                            )
+                                            .toggle_state(
+                                                state.entries[0]
+                                                    .focus_handle
+                                                    .contains_focused(window, cx),
+                                            )
+                                            .inset(true)
+                                            .spacing(ui::ListItemSpacing::Sparse)
+                                            .start_slot(
+                                                Icon::new(IconName::Plus).color(Color::Muted),
+                                            )
+                                            .child(
+                                                h_flex()
+                                                    .gap_1()
+                                                    .child(Label::new("Open or Create New From"))
+                                                    .child(
+                                                        Label::new("devcontainer.json")
+                                                            .buffer_font(cx),
+                                                    ),
+                                            )
+                                            .on_click(
+                                                cx.listener({
+                                                    move |this, _, window, cx| {
+                                                        this.open_dev_container(window, cx);
+                                                        this.view_in_progress_dev_container(
+                                                            window, cx,
+                                                        );
+                                                        cx.notify();
+                                                    }
+                                                }),
+                                            ),
+                                        )
+                                    }
+                                }),
+                        )
+                        .child(
+                            div()
+                                .id("edit-devcontainer-json")
+                                .track_focus(&state.entries[1].focus_handle)
+                                .on_action(cx.listener(|this, _: &menu::Confirm, window, cx| {
+                                    this.edit_in_dev_container_json(window, cx);
+                                }))
+                                .child(
+                                    ListItem::new("li-edit-devcontainer-json")
+                                        .toggle_state(
+                                            state.entries[1]
+                                                .focus_handle
+                                                .contains_focused(window, cx),
+                                        )
+                                        .inset(true)
+                                        .spacing(ui::ListItemSpacing::Sparse)
+                                        .start_slot(Icon::new(IconName::Pencil).color(Color::Muted))
+                                        .child(
+                                            h_flex().gap_1().child(Label::new("Edit")).child(
+                                                Label::new("devcontainer.json").buffer_font(cx),
+                                            ),
+                                        )
+                                        .on_click(cx.listener(move |this, _, window, cx| {
+                                            this.edit_in_dev_container_json(window, cx);
+                                        })),
+                                ),
+                        )
+                        .child(ListSeparator)
+                        .child(
+                            div()
+                                .id("devcontainer-go-back")
+                                .track_focus(&state.entries[2].focus_handle)
+                                .on_action(cx.listener(|this, _: &menu::Confirm, window, cx| {
+                                    this.mode = Mode::default_mode(&this.ssh_config_servers, cx);
+                                    cx.focus_self(window);
+                                    cx.notify();
+                                }))
+                                .child(
+                                    ListItem::new("li-devcontainer-go-back")
+                                        .toggle_state(
+                                            state.entries[2]
+                                                .focus_handle
+                                                .contains_focused(window, cx),
+                                        )
+                                        .inset(true)
+                                        .spacing(ui::ListItemSpacing::Sparse)
+                                        .start_slot(
+                                            Icon::new(IconName::ArrowLeft).color(Color::Muted),
+                                        )
+                                        .child(Label::new("Go Back"))
+                                        .end_slot(
+                                            KeyBinding::for_action_in(
+                                                &menu::Cancel,
+                                                &self.focus_handle,
+                                                cx,
+                                            )
+                                            .size(rems_from_px(12.)),
+                                        )
+                                        .on_click(cx.listener(|this, _, window, cx| {
+                                            this.mode =
+                                                Mode::default_mode(&this.ssh_config_servers, cx);
+                                            cx.focus_self(window);
+                                            cx.notify()
+                                        })),
+                                ),
+                        ),
+                )
+                .into_any_element(),
+        );
+
+        view = view.entry(state.entries[0].clone());
+        view = view.entry(state.entries[1].clone());
+        view = view.entry(state.entries[2].clone());
+
+        view.render(window, cx).into_any_element()
     }
 
     fn render_create_remote_server(
@@ -1536,7 +1952,7 @@ impl RemoteServerProjects {
         let connection_prompt = state.connection_prompt.clone();
 
         state.picker.update(cx, |picker, cx| {
-            picker.focus_handle(cx).focus(window);
+            picker.focus_handle(cx).focus(window, cx);
         });
 
         v_flex()
@@ -1567,10 +1983,11 @@ impl RemoteServerProjects {
                 .size_full()
                 .child(match &options {
                     ViewServerOptionsState::Ssh { connection, .. } => SshConnectionHeader {
-                        connection_string: connection.host.clone().into(),
+                        connection_string: connection.host.to_string().into(),
                         paths: Default::default(),
                         nickname: connection.nickname.clone().map(|s| s.into()),
                         is_wsl: false,
+                        is_devcontainer: false,
                     }
                     .render(window, cx)
                     .into_any_element(),
@@ -1579,6 +1996,7 @@ impl RemoteServerProjects {
                         paths: Default::default(),
                         nickname: None,
                         is_wsl: true,
+                        is_devcontainer: false,
                     }
                     .render(window, cx)
                     .into_any_element(),
@@ -1730,7 +2148,7 @@ impl RemoteServerProjects {
         window: &mut Window,
         cx: &mut Context<Self>,
     ) -> impl IntoElement {
-        let connection_string = SharedString::new(connection.host.clone());
+        let connection_string = SharedString::new(connection.host.to_string());
 
         v_flex()
             .child({
@@ -1917,6 +2335,7 @@ impl RemoteServerProjects {
                     paths: Default::default(),
                     nickname,
                     is_wsl: false,
+                    is_devcontainer: false,
                 }
                 .render(window, cx),
             )
@@ -1998,7 +2417,7 @@ impl RemoteServerProjects {
             .track_focus(&state.add_new_server.focus_handle)
             .anchor_scroll(state.add_new_server.scroll_anchor.clone())
             .child(
-                ListItem::new("register-remove-server-button")
+                ListItem::new("register-remote-server-button")
                     .toggle_state(
                         state
                             .add_new_server
@@ -2008,7 +2427,7 @@ impl RemoteServerProjects {
                     .inset(true)
                     .spacing(ui::ListItemSpacing::Sparse)
                     .start_slot(Icon::new(IconName::Plus).color(Color::Muted))
-                    .child(Label::new("Connect New Server"))
+                    .child(Label::new("Connect SSH Server"))
                     .on_click(cx.listener(|this, _, window, cx| {
                         let state = CreateRemoteServer::new(window, cx);
                         this.mode = Mode::CreateRemoteServer(state);
@@ -2023,6 +2442,36 @@ impl RemoteServerProjects {
                 cx.notify();
             }));
 
+        let connect_dev_container_button = div()
+            .id("connect-new-dev-container")
+            .track_focus(&state.add_new_devcontainer.focus_handle)
+            .anchor_scroll(state.add_new_devcontainer.scroll_anchor.clone())
+            .child(
+                ListItem::new("register-dev-container-button")
+                    .toggle_state(
+                        state
+                            .add_new_devcontainer
+                            .focus_handle
+                            .contains_focused(window, cx),
+                    )
+                    .inset(true)
+                    .spacing(ui::ListItemSpacing::Sparse)
+                    .start_slot(Icon::new(IconName::Plus).color(Color::Muted))
+                    .child(Label::new("Connect Dev Container"))
+                    .on_click(cx.listener(|this, _, window, cx| {
+                        let state = CreateRemoteDevContainer::new(window, cx);
+                        this.mode = Mode::CreateRemoteDevContainer(state);
+
+                        cx.notify();
+                    })),
+            )
+            .on_action(cx.listener(|this, _: &menu::Confirm, window, cx| {
+                let state = CreateRemoteDevContainer::new(window, cx);
+                this.mode = Mode::CreateRemoteDevContainer(state);
+
+                cx.notify();
+            }));
+
         #[cfg(target_os = "windows")]
         let wsl_connect_button = div()
             .id("wsl-connect-new-server")
@@ -2049,13 +2498,30 @@ impl RemoteServerProjects {
                 cx.notify();
             }));
 
+        let has_open_project = self
+            .workspace
+            .upgrade()
+            .map(|workspace| {
+                workspace
+                    .read(cx)
+                    .project()
+                    .read(cx)
+                    .visible_worktrees(cx)
+                    .next()
+                    .is_some()
+            })
+            .unwrap_or(false);
+
         let modal_section = v_flex()
             .track_focus(&self.focus_handle(cx))
             .id("ssh-server-list")
             .overflow_y_scroll()
             .track_scroll(&state.scroll_handle)
             .size_full()
-            .child(connect_button);
+            .child(connect_button)
+            .when(has_open_project, |this| {
+                this.child(connect_dev_container_button)
+            });
 
         #[cfg(target_os = "windows")]
         let modal_section = modal_section.child(wsl_connect_button);
@@ -2067,17 +2533,20 @@ impl RemoteServerProjects {
                 .child(
                     List::new()
                         .empty_message(
-                            v_flex()
+                            h_flex()
+                                .size_full()
+                                .p_2()
+                                .justify_center()
+                                .border_t_1()
+                                .border_color(cx.theme().colors().border_variant)
                                 .child(
-                                    div().px_3().child(
-                                        Label::new("No remote servers registered yet.")
-                                            .color(Color::Muted),
-                                    ),
+                                    Label::new("No remote servers registered yet.")
+                                        .color(Color::Muted),
                                 )
                                 .into_any_element(),
                         )
                         .children(state.servers.iter().enumerate().map(|(ix, connection)| {
-                            self.render_ssh_connection(ix, connection.clone(), window, cx)
+                            self.render_remote_connection(ix, connection.clone(), window, cx)
                                 .into_any_element()
                         })),
                 )
@@ -2085,6 +2554,10 @@ impl RemoteServerProjects {
         )
         .entry(state.add_new_server.clone());
 
+        if has_open_project {
+            modal_section = modal_section.entry(state.add_new_devcontainer.clone());
+        }
+
         if cfg!(target_os = "windows") {
             modal_section = modal_section.entry(state.add_new_wsl.clone());
         }
@@ -2186,7 +2659,7 @@ impl RemoteServerProjects {
 
         self.add_ssh_server(
             SshConnectionOptions {
-                host: ssh_config_host.to_string(),
+                host: ssh_config_host.to_string().into(),
                 ..SshConnectionOptions::default()
             },
             cx,
@@ -2279,7 +2752,7 @@ impl Render for RemoteServerProjects {
             .on_action(cx.listener(Self::cancel))
             .on_action(cx.listener(Self::confirm))
             .capture_any_mouse_down(cx.listener(|this, _, window, cx| {
-                this.focus_handle(cx).focus(window);
+                this.focus_handle(cx).focus(window, cx);
             }))
             .on_mouse_down_out(cx.listener(|this, _, _, cx| {
                 if matches!(this.mode, Mode::Default(_)) {
@@ -2297,6 +2770,9 @@ impl Render for RemoteServerProjects {
                 Mode::CreateRemoteServer(state) => self
                     .render_create_remote_server(state, window, cx)
                     .into_any_element(),
+                Mode::CreateRemoteDevContainer(state) => self
+                    .render_create_dev_container(state, window, cx)
+                    .into_any_element(),
                 Mode::EditNickname(state) => self
                     .render_edit_nickname(state, window, cx)
                     .into_any_element(),

crates/refineable/derive_refineable/src/derive_refineable.rs 🔗

@@ -528,7 +528,12 @@ fn get_wrapper_type(field: &Field, ty: &Type) -> syn::Type {
         } else {
             panic!("Expected struct type for a refineable field");
         };
-        let refinement_struct_name = format_ident!("{}Refinement", struct_name);
+
+        let refinement_struct_name = if struct_name.to_string().ends_with("Refinement") {
+            format_ident!("{}", struct_name)
+        } else {
+            format_ident!("{}Refinement", struct_name)
+        };
         let generics = if let Type::Path(tp) = ty {
             &tp.path.segments.last().unwrap().arguments
         } else {

crates/refineable/src/refineable.rs 🔗

@@ -13,7 +13,7 @@ pub use derive_refineable::Refineable;
 /// wrapped appropriately:
 ///
 /// - **Refineable fields** (marked with `#[refineable]`): Become the corresponding refinement type
-///   (e.g., `Bar` becomes `BarRefinement`)
+///   (e.g., `Bar` becomes `BarRefinement`, or `BarRefinement` remains `BarRefinement`)
 /// - **Optional fields** (`Option<T>`): Remain as `Option<T>`
 /// - **Regular fields**: Become `Option<T>`
 ///

crates/remote/Cargo.toml 🔗

@@ -43,7 +43,6 @@ urlencoding.workspace = true
 util.workspace = true
 which.workspace = true
 
-
 [dev-dependencies]
 gpui = { workspace = true, features = ["test-support"] }
 fs = { workspace = true, features = ["test-support"] }

crates/remote/src/remote.rs 🔗

@@ -7,8 +7,10 @@ mod transport;
 #[cfg(target_os = "windows")]
 pub use remote_client::OpenWslPath;
 pub use remote_client::{
-    ConnectionIdentifier, ConnectionState, RemoteClient, RemoteClientDelegate, RemoteClientEvent,
-    RemoteConnection, RemoteConnectionOptions, RemotePlatform, connect,
+    ConnectionIdentifier, ConnectionState, RemoteArch, RemoteClient, RemoteClientDelegate,
+    RemoteClientEvent, RemoteConnection, RemoteConnectionOptions, RemoteOs, RemotePlatform,
+    connect,
 };
+pub use transport::docker::DockerConnectionOptions;
 pub use transport::ssh::{SshConnectionOptions, SshPortForwardOption};
 pub use transport::wsl::WslConnectionOptions;

crates/remote/src/remote_client.rs 🔗

@@ -3,6 +3,7 @@ use crate::{
     protocol::MessageId,
     proxy::ProxyLaunchError,
     transport::{
+        docker::{DockerConnectionOptions, DockerExecConnection},
         ssh::SshRemoteConnection,
         wsl::{WslConnectionOptions, WslRemoteConnection},
     },
@@ -48,10 +49,58 @@ use util::{
     paths::{PathStyle, RemotePathBuf},
 };
 
+#[derive(Copy, Clone, Debug, PartialEq, Eq)]
+pub enum RemoteOs {
+    Linux,
+    MacOs,
+    Windows,
+}
+
+impl RemoteOs {
+    pub fn as_str(&self) -> &'static str {
+        match self {
+            RemoteOs::Linux => "linux",
+            RemoteOs::MacOs => "macos",
+            RemoteOs::Windows => "windows",
+        }
+    }
+
+    pub fn is_windows(&self) -> bool {
+        matches!(self, RemoteOs::Windows)
+    }
+}
+
+impl std::fmt::Display for RemoteOs {
+    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+        f.write_str(self.as_str())
+    }
+}
+
+#[derive(Copy, Clone, Debug, PartialEq, Eq)]
+pub enum RemoteArch {
+    X86_64,
+    Aarch64,
+}
+
+impl RemoteArch {
+    pub fn as_str(&self) -> &'static str {
+        match self {
+            RemoteArch::X86_64 => "x86_64",
+            RemoteArch::Aarch64 => "aarch64",
+        }
+    }
+}
+
+impl std::fmt::Display for RemoteArch {
+    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+        f.write_str(self.as_str())
+    }
+}
+
 #[derive(Copy, Clone, Debug)]
 pub struct RemotePlatform {
-    pub os: &'static str,
-    pub arch: &'static str,
+    pub os: RemoteOs,
+    pub arch: RemoteArch,
 }
 
 #[derive(Clone, Debug)]
@@ -88,7 +137,8 @@ pub trait RemoteClientDelegate: Send + Sync {
 const MAX_MISSED_HEARTBEATS: usize = 5;
 const HEARTBEAT_INTERVAL: Duration = Duration::from_secs(5);
 const HEARTBEAT_TIMEOUT: Duration = Duration::from_secs(5);
-const INITIAL_CONNECTION_TIMEOUT: Duration = Duration::from_secs(60);
+const INITIAL_CONNECTION_TIMEOUT: Duration =
+    Duration::from_secs(if cfg!(debug_assertions) { 5 } else { 60 });
 
 const MAX_RECONNECT_ATTEMPTS: usize = 3;
 
@@ -328,8 +378,15 @@ impl RemoteClient {
                 let (incoming_tx, incoming_rx) = mpsc::unbounded::<Envelope>();
                 let (connection_activity_tx, connection_activity_rx) = mpsc::channel::<()>(1);
 
-                let client =
-                    cx.update(|cx| ChannelClient::new(incoming_rx, outgoing_tx, cx, "client"))?;
+                let client = cx.update(|cx| {
+                    ChannelClient::new(
+                        incoming_rx,
+                        outgoing_tx,
+                        cx,
+                        "client",
+                        remote_connection.has_wsl_interop(),
+                    )
+                })?;
 
                 let path_style = remote_connection.path_style();
                 let this = cx.new(|_| Self {
@@ -420,8 +477,9 @@ impl RemoteClient {
         outgoing_tx: mpsc::UnboundedSender<Envelope>,
         cx: &App,
         name: &'static str,
+        has_wsl_interop: bool,
     ) -> AnyProtoClient {
-        ChannelClient::new(incoming_rx, outgoing_tx, cx, name).into()
+        ChannelClient::new(incoming_rx, outgoing_tx, cx, name, has_wsl_interop).into()
     }
 
     pub fn shutdown_processes<T: RequestMessage>(
@@ -912,17 +970,19 @@ impl RemoteClient {
         client_cx: &mut gpui::TestAppContext,
         server_cx: &mut gpui::TestAppContext,
     ) -> (RemoteConnectionOptions, AnyProtoClient) {
+        use crate::transport::ssh::SshConnectionHost;
+
         let port = client_cx
             .update(|cx| cx.default_global::<ConnectionPool>().connections.len() as u16 + 1);
         let opts = RemoteConnectionOptions::Ssh(SshConnectionOptions {
-            host: "<fake>".to_string(),
+            host: SshConnectionHost::from("<fake>".to_string()),
             port: Some(port),
             ..Default::default()
         });
         let (outgoing_tx, _) = mpsc::unbounded::<Envelope>();
         let (_, incoming_rx) = mpsc::unbounded::<Envelope>();
-        let server_client =
-            server_cx.update(|cx| ChannelClient::new(incoming_rx, outgoing_tx, cx, "fake-server"));
+        let server_client = server_cx
+            .update(|cx| ChannelClient::new(incoming_rx, outgoing_tx, cx, "fake-server", false));
         let connection: Arc<dyn RemoteConnection> = Arc::new(fake::FakeRemoteConnection {
             connection_options: opts.clone(),
             server_cx: fake::SendableCx::new(server_cx),
@@ -1034,6 +1094,11 @@ impl ConnectionPool {
                                 .await
                                 .map(|connection| Arc::new(connection) as Arc<dyn RemoteConnection>)
                         }
+                        RemoteConnectionOptions::Docker(opts) => {
+                            DockerExecConnection::new(opts, delegate, cx)
+                                .await
+                                .map(|connection| Arc::new(connection) as Arc<dyn RemoteConnection>)
+                        }
                     };
 
                     cx.update_global(|pool: &mut Self, _| {
@@ -1069,13 +1134,15 @@ impl ConnectionPool {
 pub enum RemoteConnectionOptions {
     Ssh(SshConnectionOptions),
     Wsl(WslConnectionOptions),
+    Docker(DockerConnectionOptions),
 }
 
 impl RemoteConnectionOptions {
     pub fn display_name(&self) -> String {
         match self {
-            RemoteConnectionOptions::Ssh(opts) => opts.host.clone(),
+            RemoteConnectionOptions::Ssh(opts) => opts.host.to_string(),
             RemoteConnectionOptions::Wsl(opts) => opts.distro_name.clone(),
+            RemoteConnectionOptions::Docker(opts) => opts.name.clone(),
         }
     }
 }
@@ -1140,6 +1207,7 @@ pub trait RemoteConnection: Send + Sync {
     fn path_style(&self) -> PathStyle;
     fn shell(&self) -> String;
     fn default_system_shell(&self) -> String;
+    fn has_wsl_interop(&self) -> bool;
 
     #[cfg(any(test, feature = "test-support"))]
     fn simulate_disconnect(&self, _: &AsyncApp) {}
@@ -1188,6 +1256,7 @@ struct ChannelClient {
     name: &'static str,
     task: Mutex<Task<Result<()>>>,
     remote_started: Signal<()>,
+    has_wsl_interop: bool,
 }
 
 impl ChannelClient {
@@ -1196,6 +1265,7 @@ impl ChannelClient {
         outgoing_tx: mpsc::UnboundedSender<Envelope>,
         cx: &App,
         name: &'static str,
+        has_wsl_interop: bool,
     ) -> Arc<Self> {
         Arc::new_cyclic(|this| Self {
             outgoing_tx: Mutex::new(outgoing_tx),
@@ -1211,6 +1281,7 @@ impl ChannelClient {
                 &cx.to_async(),
             )),
             remote_started: Signal::new(cx),
+            has_wsl_interop,
         })
     }
 
@@ -1489,6 +1560,10 @@ impl ProtoClient for ChannelClient {
     fn is_via_collab(&self) -> bool {
         false
     }
+
+    fn has_wsl_interop(&self) -> bool {
+        self.has_wsl_interop
+    }
 }
 
 #[cfg(any(test, feature = "test-support"))]
@@ -1652,6 +1727,10 @@ mod fake {
         fn default_system_shell(&self) -> String {
             "sh".to_owned()
         }
+
+        fn has_wsl_interop(&self) -> bool {
+            false
+        }
     }
 
     pub(super) struct Delegate;

crates/remote/src/transport.rs 🔗

@@ -1,4 +1,5 @@
 use crate::{
+    RemoteArch, RemoteOs, RemotePlatform,
     json_log::LogRecord,
     protocol::{MESSAGE_LEN_SIZE, message_len_from_buffer, read_message_with_len, write_message},
 };
@@ -11,19 +12,68 @@ use gpui::{AppContext as _, AsyncApp, Task};
 use rpc::proto::Envelope;
 use smol::process::Child;
 
+pub mod docker;
 pub mod ssh;
 pub mod wsl;
 
+/// Parses the output of `uname -sm` to determine the remote platform.
+/// Takes the last line to skip possible shell initialization output.
+fn parse_platform(output: &str) -> Result<RemotePlatform> {
+    let output = output.trim();
+    let uname = output.rsplit_once('\n').map_or(output, |(_, last)| last);
+    let Some((os, arch)) = uname.split_once(" ") else {
+        anyhow::bail!("unknown uname: {uname:?}")
+    };
+
+    let os = match os {
+        "Darwin" => RemoteOs::MacOs,
+        "Linux" => RemoteOs::Linux,
+        _ => anyhow::bail!(
+            "Prebuilt remote servers are not yet available for {os:?}. See https://zed.dev/docs/remote-development"
+        ),
+    };
+
+    // exclude armv5,6,7 as they are 32-bit.
+    let arch = if arch.starts_with("armv8")
+        || arch.starts_with("armv9")
+        || arch.starts_with("arm64")
+        || arch.starts_with("aarch64")
+    {
+        RemoteArch::Aarch64
+    } else if arch.starts_with("x86") {
+        RemoteArch::X86_64
+    } else {
+        anyhow::bail!(
+            "Prebuilt remote servers are not yet available for {arch:?}. See https://zed.dev/docs/remote-development"
+        )
+    };
+
+    Ok(RemotePlatform { os, arch })
+}
+
+/// 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 {
+    let output = output.trim();
+    let shell = output.rsplit_once('\n').map_or(output, |(_, last)| last);
+    if shell.is_empty() {
+        log::error!("$SHELL is not set, falling back to {fallback_shell}");
+        fallback_shell.to_owned()
+    } else {
+        shell.to_owned()
+    }
+}
+
 fn handle_rpc_messages_over_child_process_stdio(
-    mut ssh_proxy_process: Child,
+    mut remote_proxy_process: Child,
     incoming_tx: UnboundedSender<Envelope>,
     mut outgoing_rx: UnboundedReceiver<Envelope>,
     mut connection_activity_tx: Sender<()>,
     cx: &AsyncApp,
 ) -> Task<Result<i32>> {
-    let mut child_stderr = ssh_proxy_process.stderr.take().unwrap();
-    let mut child_stdout = ssh_proxy_process.stdout.take().unwrap();
-    let mut child_stdin = ssh_proxy_process.stdin.take().unwrap();
+    let mut child_stderr = remote_proxy_process.stderr.take().unwrap();
+    let mut child_stdout = remote_proxy_process.stdout.take().unwrap();
+    let mut child_stdin = remote_proxy_process.stdin.take().unwrap();
 
     let mut stdin_buffer = Vec::new();
     let mut stdout_buffer = Vec::new();
@@ -107,7 +157,10 @@ fn handle_rpc_messages_over_child_process_stdio(
                 result.context("stderr")
             }
         };
-        let status = ssh_proxy_process.status().await?.code().unwrap_or(1);
+        let status = remote_proxy_process.status().await?.code().unwrap_or(1);
+        if status != 0 {
+            anyhow::bail!("Remote server exited with status {status}");
+        }
         match result {
             Ok(_) => Ok(status),
             Err(error) => Err(error),
@@ -131,11 +184,7 @@ async fn build_remote_server_from_source(
     let build_remote_server =
         std::env::var("ZED_BUILD_REMOTE_SERVER").unwrap_or("nocompress".into());
 
-    if build_remote_server == "false"
-        || build_remote_server == "no"
-        || build_remote_server == "off"
-        || build_remote_server == "0"
-    {
+    if let "false" | "no" | "off" | "0" = &*build_remote_server {
         return Ok(None);
     }
 
@@ -147,7 +196,8 @@ async fn build_remote_server_from_source(
             .await?;
         anyhow::ensure!(
             output.status.success(),
-            "Failed to run command: {command:?}"
+            "Failed to run command: {command:?}: output: {}",
+            String::from_utf8_lossy(&output.stderr)
         );
         Ok(())
     }
@@ -157,14 +207,15 @@ async fn build_remote_server_from_source(
         "{}-{}",
         platform.arch,
         match platform.os {
-            "linux" =>
+            RemoteOs::Linux =>
                 if use_musl {
                     "unknown-linux-musl"
                 } else {
                     "unknown-linux-gnu"
                 },
-            "macos" => "apple-darwin",
-            _ => anyhow::bail!("can't cross compile for: {:?}", platform),
+            RemoteOs::MacOs => "apple-darwin",
+            RemoteOs::Windows if cfg!(windows) => "pc-windows-msvc",
+            RemoteOs::Windows => "pc-windows-gnu",
         }
     );
     let mut rust_flags = match std::env::var("RUSTFLAGS") {
@@ -175,7 +226,7 @@ async fn build_remote_server_from_source(
             String::new()
         }
     };
-    if platform.os == "linux" && use_musl {
+    if platform.os == RemoteOs::Linux && use_musl {
         rust_flags.push_str(" -C target-feature=+crt-static");
 
         if let Ok(path) = std::env::var("ZED_ZSTD_MUSL_LIB") {
@@ -186,7 +237,9 @@ async fn build_remote_server_from_source(
         rust_flags.push_str(" -C link-arg=-fuse-ld=mold");
     }
 
-    if platform.arch == std::env::consts::ARCH && platform.os == std::env::consts::OS {
+    if platform.arch.as_str() == std::env::consts::ARCH
+        && platform.os.as_str() == std::env::consts::OS
+    {
         delegate.set_status(Some("Building remote server binary from source"), cx);
         log::info!("building remote server binary from source");
         run_cmd(
@@ -262,7 +315,8 @@ async fn build_remote_server_from_source(
         .join("remote_server")
         .join(&triple)
         .join("debug")
-        .join("remote_server");
+        .join("remote_server")
+        .with_extension(if platform.os.is_windows() { "exe" } else { "" });
 
     let path = if !build_remote_server.contains("nocompress") {
         delegate.set_status(Some("Compressing binary"), cx);
@@ -320,3 +374,72 @@ async fn which(
         )),
     }
 }
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    #[test]
+    fn test_parse_platform() {
+        let result = parse_platform("Linux x86_64\n").unwrap();
+        assert_eq!(result.os, RemoteOs::Linux);
+        assert_eq!(result.arch, RemoteArch::X86_64);
+
+        let result = parse_platform("Darwin arm64\n").unwrap();
+        assert_eq!(result.os, RemoteOs::MacOs);
+        assert_eq!(result.arch, RemoteArch::Aarch64);
+
+        let result = parse_platform("Linux x86_64").unwrap();
+        assert_eq!(result.os, RemoteOs::Linux);
+        assert_eq!(result.arch, RemoteArch::X86_64);
+
+        let result = parse_platform("some shell init output\nLinux aarch64\n").unwrap();
+        assert_eq!(result.os, RemoteOs::Linux);
+        assert_eq!(result.arch, RemoteArch::Aarch64);
+
+        let result = parse_platform("some shell init output\nLinux aarch64").unwrap();
+        assert_eq!(result.os, RemoteOs::Linux);
+        assert_eq!(result.arch, RemoteArch::Aarch64);
+
+        assert_eq!(
+            parse_platform("Linux armv8l\n").unwrap().arch,
+            RemoteArch::Aarch64
+        );
+        assert_eq!(
+            parse_platform("Linux aarch64\n").unwrap().arch,
+            RemoteArch::Aarch64
+        );
+        assert_eq!(
+            parse_platform("Linux x86_64\n").unwrap().arch,
+            RemoteArch::X86_64
+        );
+
+        let result = parse_platform(
+            r#"Linux x86_64 - What you're referring to as Linux, is in fact, GNU/Linux...\n"#,
+        )
+        .unwrap();
+        assert_eq!(result.os, RemoteOs::Linux);
+        assert_eq!(result.arch, RemoteArch::X86_64);
+
+        assert!(parse_platform("Windows x86_64\n").is_err());
+        assert!(parse_platform("Linux armv7l\n").is_err());
+    }
+
+    #[test]
+    fn test_parse_shell() {
+        assert_eq!(parse_shell("/bin/bash\n", "sh"), "/bin/bash");
+        assert_eq!(parse_shell("/bin/zsh\n", "sh"), "/bin/zsh");
+
+        assert_eq!(parse_shell("/bin/bash", "sh"), "/bin/bash");
+        assert_eq!(
+            parse_shell("some shell init output\n/bin/bash\n", "sh"),
+            "/bin/bash"
+        );
+        assert_eq!(
+            parse_shell("some shell init output\n/bin/bash", "sh"),
+            "/bin/bash"
+        );
+        assert_eq!(parse_shell("", "sh"), "sh");
+        assert_eq!(parse_shell("\n", "sh"), "sh");
+    }
+}

crates/remote/src/transport/docker.rs 🔗

@@ -0,0 +1,759 @@
+use anyhow::Context;
+use anyhow::Result;
+use anyhow::anyhow;
+use async_trait::async_trait;
+use collections::HashMap;
+use parking_lot::Mutex;
+use release_channel::{AppCommitSha, AppVersion, ReleaseChannel};
+use semver::Version as SemanticVersion;
+use std::time::Instant;
+use std::{
+    path::{Path, PathBuf},
+    process::Stdio,
+    sync::Arc,
+};
+use util::ResultExt;
+use util::shell::ShellKind;
+use util::{
+    paths::{PathStyle, RemotePathBuf},
+    rel_path::RelPath,
+};
+
+use futures::channel::mpsc::{Sender, UnboundedReceiver, UnboundedSender};
+use gpui::{App, AppContext, AsyncApp, Task};
+use rpc::proto::Envelope;
+
+use crate::{
+    RemoteArch, RemoteClientDelegate, RemoteConnection, RemoteConnectionOptions, RemoteOs,
+    RemotePlatform, remote_client::CommandTemplate,
+};
+
+#[derive(Debug, Default, Clone, PartialEq, Eq, Hash)]
+pub struct DockerConnectionOptions {
+    pub name: String,
+    pub container_id: String,
+    pub upload_binary_over_docker_exec: bool,
+}
+
+pub(crate) struct DockerExecConnection {
+    proxy_process: Mutex<Option<u32>>,
+    remote_dir_for_server: String,
+    remote_binary_relpath: Option<Arc<RelPath>>,
+    connection_options: DockerConnectionOptions,
+    remote_platform: Option<RemotePlatform>,
+    path_style: Option<PathStyle>,
+    shell: Option<String>,
+}
+
+impl DockerExecConnection {
+    pub async fn new(
+        connection_options: DockerConnectionOptions,
+        delegate: Arc<dyn RemoteClientDelegate>,
+        cx: &mut AsyncApp,
+    ) -> Result<Self> {
+        let mut this = Self {
+            proxy_process: Mutex::new(None),
+            remote_dir_for_server: "/".to_string(),
+            remote_binary_relpath: None,
+            connection_options,
+            remote_platform: None,
+            path_style: None,
+            shell: None,
+        };
+        let (release_channel, version, commit) = cx.update(|cx| {
+            (
+                ReleaseChannel::global(cx),
+                AppVersion::global(cx),
+                AppCommitSha::try_global(cx),
+            )
+        })?;
+        let remote_platform = this.check_remote_platform().await?;
+
+        this.path_style = match remote_platform.os {
+            RemoteOs::Windows => Some(PathStyle::Windows),
+            _ => Some(PathStyle::Posix),
+        };
+
+        this.remote_platform = Some(remote_platform);
+
+        this.shell = Some(this.discover_shell().await);
+
+        this.remote_dir_for_server = this.docker_user_home_dir().await?.trim().to_string();
+
+        this.remote_binary_relpath = Some(
+            this.ensure_server_binary(
+                &delegate,
+                release_channel,
+                version,
+                &this.remote_dir_for_server,
+                commit,
+                cx,
+            )
+            .await?,
+        );
+
+        Ok(this)
+    }
+
+    async fn discover_shell(&self) -> String {
+        let default_shell = "sh";
+        match self
+            .run_docker_exec("sh", None, &Default::default(), &["-c", "echo $SHELL"])
+            .await
+        {
+            Ok(shell) => match shell.trim() {
+                "" => {
+                    log::error!("$SHELL is not set, falling back to {default_shell}");
+                    default_shell.to_owned()
+                }
+                shell => shell.to_owned(),
+            },
+            Err(e) => {
+                log::error!("Failed to get shell: {e}");
+                default_shell.to_owned()
+            }
+        }
+    }
+
+    async fn check_remote_platform(&self) -> Result<RemotePlatform> {
+        let uname = self
+            .run_docker_exec("uname", None, &Default::default(), &["-sm"])
+            .await?;
+        let Some((os, arch)) = uname.split_once(" ") else {
+            anyhow::bail!("unknown uname: {uname:?}")
+        };
+
+        let os = match os.trim() {
+            "Darwin" => RemoteOs::MacOs,
+            "Linux" => RemoteOs::Linux,
+            _ => anyhow::bail!(
+                "Prebuilt remote servers are not yet available for {os:?}. See https://zed.dev/docs/remote-development"
+            ),
+        };
+        // exclude armv5,6,7 as they are 32-bit.
+        let arch = if arch.starts_with("armv8")
+            || arch.starts_with("armv9")
+            || arch.starts_with("arm64")
+            || arch.starts_with("aarch64")
+        {
+            RemoteArch::Aarch64
+        } else if arch.starts_with("x86") {
+            RemoteArch::X86_64
+        } else {
+            anyhow::bail!(
+                "Prebuilt remote servers are not yet available for {arch:?}. See https://zed.dev/docs/remote-development"
+            )
+        };
+
+        Ok(RemotePlatform { os, arch })
+    }
+
+    async fn ensure_server_binary(
+        &self,
+        delegate: &Arc<dyn RemoteClientDelegate>,
+        release_channel: ReleaseChannel,
+        version: SemanticVersion,
+        remote_dir_for_server: &str,
+        commit: Option<AppCommitSha>,
+        cx: &mut AsyncApp,
+    ) -> Result<Arc<RelPath>> {
+        let remote_platform = if self.remote_platform.is_some() {
+            self.remote_platform.unwrap()
+        } else {
+            anyhow::bail!("No remote platform defined; cannot proceed.")
+        };
+
+        let version_str = match release_channel {
+            ReleaseChannel::Nightly => {
+                let commit = commit.map(|s| s.full()).unwrap_or_default();
+                format!("{}-{}", version, commit)
+            }
+            ReleaseChannel::Dev => "build".to_string(),
+            _ => version.to_string(),
+        };
+        let binary_name = format!(
+            "zed-remote-server-{}-{}",
+            release_channel.dev_name(),
+            version_str
+        );
+        let dst_path =
+            paths::remote_server_dir_relative().join(RelPath::unix(&binary_name).unwrap());
+
+        #[cfg(debug_assertions)]
+        if let Some(remote_server_path) =
+            super::build_remote_server_from_source(&remote_platform, delegate.as_ref(), cx).await?
+        {
+            let tmp_path = paths::remote_server_dir_relative().join(
+                RelPath::unix(&format!(
+                    "download-{}-{}",
+                    std::process::id(),
+                    remote_server_path.file_name().unwrap().to_string_lossy()
+                ))
+                .unwrap(),
+            );
+            self.upload_local_server_binary(
+                &remote_server_path,
+                &tmp_path,
+                &remote_dir_for_server,
+                delegate,
+                cx,
+            )
+            .await?;
+            self.extract_server_binary(&dst_path, &tmp_path, &remote_dir_for_server, delegate, cx)
+                .await?;
+            return Ok(dst_path);
+        }
+
+        if self
+            .run_docker_exec(
+                &dst_path.display(self.path_style()),
+                Some(&remote_dir_for_server),
+                &Default::default(),
+                &["version"],
+            )
+            .await
+            .is_ok()
+        {
+            return Ok(dst_path);
+        }
+
+        let wanted_version = cx.update(|cx| match release_channel {
+            ReleaseChannel::Nightly => Ok(None),
+            ReleaseChannel::Dev => {
+                anyhow::bail!(
+                    "ZED_BUILD_REMOTE_SERVER is not set and no remote server exists at ({:?})",
+                    dst_path
+                )
+            }
+            _ => Ok(Some(AppVersion::global(cx))),
+        })??;
+
+        let tmp_path_gz = paths::remote_server_dir_relative().join(
+            RelPath::unix(&format!(
+                "{}-download-{}.gz",
+                binary_name,
+                std::process::id()
+            ))
+            .unwrap(),
+        );
+        if !self.connection_options.upload_binary_over_docker_exec
+            && let Some(url) = delegate
+                .get_download_url(remote_platform, release_channel, wanted_version.clone(), cx)
+                .await?
+        {
+            match self
+                .download_binary_on_server(&url, &tmp_path_gz, &remote_dir_for_server, delegate, cx)
+                .await
+            {
+                Ok(_) => {
+                    self.extract_server_binary(
+                        &dst_path,
+                        &tmp_path_gz,
+                        &remote_dir_for_server,
+                        delegate,
+                        cx,
+                    )
+                    .await
+                    .context("extracting server binary")?;
+                    return Ok(dst_path);
+                }
+                Err(e) => {
+                    log::error!(
+                        "Failed to download binary on server, attempting to download locally and then upload it the server: {e:#}",
+                    )
+                }
+            }
+        }
+
+        let src_path = delegate
+            .download_server_binary_locally(remote_platform, release_channel, wanted_version, cx)
+            .await
+            .context("downloading server binary locally")?;
+        self.upload_local_server_binary(
+            &src_path,
+            &tmp_path_gz,
+            &remote_dir_for_server,
+            delegate,
+            cx,
+        )
+        .await
+        .context("uploading server binary")?;
+        self.extract_server_binary(
+            &dst_path,
+            &tmp_path_gz,
+            &remote_dir_for_server,
+            delegate,
+            cx,
+        )
+        .await
+        .context("extracting server binary")?;
+        Ok(dst_path)
+    }
+
+    async fn docker_user_home_dir(&self) -> Result<String> {
+        let inner_program = self.shell();
+        self.run_docker_exec(
+            &inner_program,
+            None,
+            &Default::default(),
+            &["-c", "echo $HOME"],
+        )
+        .await
+    }
+
+    async fn extract_server_binary(
+        &self,
+        dst_path: &RelPath,
+        tmp_path: &RelPath,
+        remote_dir_for_server: &str,
+        delegate: &Arc<dyn RemoteClientDelegate>,
+        cx: &mut AsyncApp,
+    ) -> Result<()> {
+        delegate.set_status(Some("Extracting remote development server"), cx);
+        let server_mode = 0o755;
+
+        let shell_kind = ShellKind::Posix;
+        let orig_tmp_path = tmp_path.display(self.path_style());
+        let server_mode = format!("{:o}", server_mode);
+        let server_mode = shell_kind
+            .try_quote(&server_mode)
+            .context("shell quoting")?;
+        let dst_path = dst_path.display(self.path_style());
+        let dst_path = shell_kind.try_quote(&dst_path).context("shell quoting")?;
+        let script = if let Some(tmp_path) = orig_tmp_path.strip_suffix(".gz") {
+            let orig_tmp_path = shell_kind
+                .try_quote(&orig_tmp_path)
+                .context("shell quoting")?;
+            let tmp_path = shell_kind.try_quote(&tmp_path).context("shell quoting")?;
+            format!(
+                "gunzip -f {orig_tmp_path} && chmod {server_mode} {tmp_path} && mv {tmp_path} {dst_path}",
+            )
+        } else {
+            let orig_tmp_path = shell_kind
+                .try_quote(&orig_tmp_path)
+                .context("shell quoting")?;
+            format!("chmod {server_mode} {orig_tmp_path} && mv {orig_tmp_path} {dst_path}",)
+        };
+        let args = shell_kind.args_for_shell(false, script.to_string());
+        self.run_docker_exec(
+            "sh",
+            Some(&remote_dir_for_server),
+            &Default::default(),
+            &args,
+        )
+        .await
+        .log_err();
+        Ok(())
+    }
+
+    async fn upload_local_server_binary(
+        &self,
+        src_path: &Path,
+        tmp_path_gz: &RelPath,
+        remote_dir_for_server: &str,
+        delegate: &Arc<dyn RemoteClientDelegate>,
+        cx: &mut AsyncApp,
+    ) -> Result<()> {
+        if let Some(parent) = tmp_path_gz.parent() {
+            self.run_docker_exec(
+                "mkdir",
+                Some(remote_dir_for_server),
+                &Default::default(),
+                &["-p", parent.display(self.path_style()).as_ref()],
+            )
+            .await?;
+        }
+
+        let src_stat = smol::fs::metadata(&src_path).await?;
+        let size = src_stat.len();
+
+        let t0 = Instant::now();
+        delegate.set_status(Some("Uploading remote development server"), cx);
+        log::info!(
+            "uploading remote development server to {:?} ({}kb)",
+            tmp_path_gz,
+            size / 1024
+        );
+        self.upload_file(src_path, tmp_path_gz, remote_dir_for_server)
+            .await
+            .context("failed to upload server binary")?;
+        log::info!("uploaded remote development server in {:?}", t0.elapsed());
+        Ok(())
+    }
+
+    async fn upload_file(
+        &self,
+        src_path: &Path,
+        dest_path: &RelPath,
+        remote_dir_for_server: &str,
+    ) -> Result<()> {
+        log::debug!("uploading file {:?} to {:?}", src_path, dest_path);
+
+        let src_path_display = src_path.display().to_string();
+        let dest_path_str = dest_path.display(self.path_style());
+
+        let mut command = util::command::new_smol_command("docker");
+        command.arg("cp");
+        command.arg("-a");
+        command.arg(&src_path_display);
+        command.arg(format!(
+            "{}:{}/{}",
+            &self.connection_options.container_id, remote_dir_for_server, dest_path_str
+        ));
+
+        let output = command.output().await?;
+
+        if output.status.success() {
+            return Ok(());
+        }
+
+        let stderr = String::from_utf8_lossy(&output.stderr);
+        log::debug!(
+            "failed to upload file via docker cp {src_path_display} -> {dest_path_str}: {stderr}",
+        );
+        anyhow::bail!(
+            "failed to upload file via docker cp {} -> {}: {}",
+            src_path_display,
+            dest_path_str,
+            stderr,
+        );
+    }
+
+    async fn run_docker_command(
+        &self,
+        subcommand: &str,
+        args: &[impl AsRef<str>],
+    ) -> Result<String> {
+        let mut command = util::command::new_smol_command("docker");
+        command.arg(subcommand);
+        for arg in args {
+            command.arg(arg.as_ref());
+        }
+        let output = command.output().await?;
+        anyhow::ensure!(
+            output.status.success(),
+            "failed to run command {command:?}: {}",
+            String::from_utf8_lossy(&output.stderr)
+        );
+        Ok(String::from_utf8_lossy(&output.stdout).to_string())
+    }
+
+    async fn run_docker_exec(
+        &self,
+        inner_program: &str,
+        working_directory: Option<&str>,
+        env: &HashMap<String, String>,
+        program_args: &[impl AsRef<str>],
+    ) -> Result<String> {
+        let mut args = match working_directory {
+            Some(dir) => vec!["-w".to_string(), dir.to_string()],
+            None => vec![],
+        };
+
+        for (k, v) in env.iter() {
+            args.push("-e".to_string());
+            let env_declaration = format!("{}={}", k, v);
+            args.push(env_declaration);
+        }
+
+        args.push(self.connection_options.container_id.clone());
+        args.push(inner_program.to_string());
+
+        for arg in program_args {
+            args.push(arg.as_ref().to_owned());
+        }
+        self.run_docker_command("exec", args.as_ref()).await
+    }
+
+    async fn download_binary_on_server(
+        &self,
+        url: &str,
+        tmp_path_gz: &RelPath,
+        remote_dir_for_server: &str,
+        delegate: &Arc<dyn RemoteClientDelegate>,
+        cx: &mut AsyncApp,
+    ) -> Result<()> {
+        if let Some(parent) = tmp_path_gz.parent() {
+            self.run_docker_exec(
+                "mkdir",
+                Some(remote_dir_for_server),
+                &Default::default(),
+                &["-p", parent.display(self.path_style()).as_ref()],
+            )
+            .await?;
+        }
+
+        delegate.set_status(Some("Downloading remote development server on host"), cx);
+
+        match self
+            .run_docker_exec(
+                "curl",
+                Some(remote_dir_for_server),
+                &Default::default(),
+                &[
+                    "-f",
+                    "-L",
+                    url,
+                    "-o",
+                    &tmp_path_gz.display(self.path_style()),
+                ],
+            )
+            .await
+        {
+            Ok(_) => {}
+            Err(e) => {
+                if self
+                    .run_docker_exec("which", None, &Default::default(), &["curl"])
+                    .await
+                    .is_ok()
+                {
+                    return Err(e);
+                }
+
+                log::info!("curl is not available, trying wget");
+                match self
+                    .run_docker_exec(
+                        "wget",
+                        Some(remote_dir_for_server),
+                        &Default::default(),
+                        &[url, "-O", &tmp_path_gz.display(self.path_style())],
+                    )
+                    .await
+                {
+                    Ok(_) => {}
+                    Err(e) => {
+                        if self
+                            .run_docker_exec("which", None, &Default::default(), &["wget"])
+                            .await
+                            .is_ok()
+                        {
+                            return Err(e);
+                        } else {
+                            anyhow::bail!("Neither curl nor wget is available");
+                        }
+                    }
+                }
+            }
+        }
+        Ok(())
+    }
+
+    fn kill_inner(&self) -> Result<()> {
+        if let Some(pid) = self.proxy_process.lock().take() {
+            if let Ok(_) = util::command::new_smol_command("kill")
+                .arg(pid.to_string())
+                .spawn()
+            {
+                Ok(())
+            } else {
+                Err(anyhow::anyhow!("Failed to kill process"))
+            }
+        } else {
+            Ok(())
+        }
+    }
+}
+
+#[async_trait(?Send)]
+impl RemoteConnection for DockerExecConnection {
+    fn has_wsl_interop(&self) -> bool {
+        false
+    }
+    fn start_proxy(
+        &self,
+        unique_identifier: String,
+        reconnect: bool,
+        incoming_tx: UnboundedSender<Envelope>,
+        outgoing_rx: UnboundedReceiver<Envelope>,
+        connection_activity_tx: Sender<()>,
+        delegate: Arc<dyn RemoteClientDelegate>,
+        cx: &mut AsyncApp,
+    ) -> Task<Result<i32>> {
+        // We'll try connecting anew every time we open a devcontainer, so proactively try to kill any old connections.
+        if !self.has_been_killed() {
+            if let Err(e) = self.kill_inner() {
+                return Task::ready(Err(e));
+            };
+        }
+
+        delegate.set_status(Some("Starting proxy"), cx);
+
+        let Some(remote_binary_relpath) = self.remote_binary_relpath.clone() else {
+            return Task::ready(Err(anyhow!("Remote binary path not set")));
+        };
+
+        let mut docker_args = vec!["exec".to_string()];
+        for env_var in ["RUST_LOG", "RUST_BACKTRACE", "ZED_GENERATE_MINIDUMPS"] {
+            if let Some(value) = std::env::var(env_var).ok() {
+                docker_args.push("-e".to_string());
+                docker_args.push(format!("{}='{}'", env_var, value));
+            }
+        }
+
+        docker_args.extend([
+            "-w".to_string(),
+            self.remote_dir_for_server.clone(),
+            "-i".to_string(),
+            self.connection_options.container_id.to_string(),
+        ]);
+
+        let val = remote_binary_relpath
+            .display(self.path_style())
+            .into_owned();
+        docker_args.push(val);
+        docker_args.push("proxy".to_string());
+        docker_args.push("--identifier".to_string());
+        docker_args.push(unique_identifier);
+        if reconnect {
+            docker_args.push("--reconnect".to_string());
+        }
+        let mut command = util::command::new_smol_command("docker");
+        command
+            .kill_on_drop(true)
+            .stdin(Stdio::piped())
+            .stdout(Stdio::piped())
+            .stderr(Stdio::piped())
+            .args(docker_args);
+
+        let Ok(child) = command.spawn() else {
+            return Task::ready(Err(anyhow::anyhow!(
+                "Failed to start remote server process"
+            )));
+        };
+
+        let mut proxy_process = self.proxy_process.lock();
+        *proxy_process = Some(child.id());
+
+        super::handle_rpc_messages_over_child_process_stdio(
+            child,
+            incoming_tx,
+            outgoing_rx,
+            connection_activity_tx,
+            cx,
+        )
+    }
+
+    fn upload_directory(
+        &self,
+        src_path: PathBuf,
+        dest_path: RemotePathBuf,
+        cx: &App,
+    ) -> Task<Result<()>> {
+        let dest_path_str = dest_path.to_string();
+        let src_path_display = src_path.display().to_string();
+
+        let mut command = util::command::new_smol_command("docker");
+        command.arg("cp");
+        command.arg("-a"); // Archive mode is required to assign the file ownership to the default docker exec user
+        command.arg(src_path_display);
+        command.arg(format!(
+            "{}:{}",
+            self.connection_options.container_id, dest_path_str
+        ));
+
+        cx.background_spawn(async move {
+            let output = command.output().await?;
+
+            if output.status.success() {
+                Ok(())
+            } else {
+                Err(anyhow::anyhow!("Failed to upload directory"))
+            }
+        })
+    }
+
+    async fn kill(&self) -> Result<()> {
+        self.kill_inner()
+    }
+
+    fn has_been_killed(&self) -> bool {
+        self.proxy_process.lock().is_none()
+    }
+
+    fn build_command(
+        &self,
+        program: Option<String>,
+        args: &[String],
+        env: &HashMap<String, String>,
+        working_dir: Option<String>,
+        _port_forward: Option<(u16, String, u16)>,
+    ) -> Result<CommandTemplate> {
+        let mut parsed_working_dir = None;
+
+        let path_style = self.path_style();
+
+        if let Some(working_dir) = working_dir {
+            let working_dir = RemotePathBuf::new(working_dir, path_style).to_string();
+
+            const TILDE_PREFIX: &'static str = "~/";
+            if working_dir.starts_with(TILDE_PREFIX) {
+                let working_dir = working_dir.trim_start_matches("~").trim_start_matches("/");
+                parsed_working_dir = Some(format!("$HOME/{working_dir}"));
+            } else {
+                parsed_working_dir = Some(working_dir);
+            }
+        }
+
+        let mut inner_program = Vec::new();
+
+        if let Some(program) = program {
+            inner_program.push(program);
+            for arg in args {
+                inner_program.push(arg.clone());
+            }
+        } else {
+            inner_program.push(self.shell());
+            inner_program.push("-l".to_string());
+        };
+
+        let mut docker_args = vec!["exec".to_string()];
+
+        if let Some(parsed_working_dir) = parsed_working_dir {
+            docker_args.push("-w".to_string());
+            docker_args.push(parsed_working_dir);
+        }
+
+        for (k, v) in env.iter() {
+            docker_args.push("-e".to_string());
+            docker_args.push(format!("{}={}", k, v));
+        }
+
+        docker_args.push("-it".to_string());
+        docker_args.push(self.connection_options.container_id.to_string());
+
+        docker_args.append(&mut inner_program);
+
+        Ok(CommandTemplate {
+            program: "docker".to_string(),
+            args: docker_args,
+            // Docker-exec pipes in environment via the "-e" argument
+            env: Default::default(),
+        })
+    }
+
+    fn build_forward_ports_command(
+        &self,
+        _forwards: Vec<(u16, String, u16)>,
+    ) -> Result<CommandTemplate> {
+        Err(anyhow::anyhow!("Not currently supported for docker_exec"))
+    }
+
+    fn connection_options(&self) -> RemoteConnectionOptions {
+        RemoteConnectionOptions::Docker(self.connection_options.clone())
+    }
+
+    fn path_style(&self) -> PathStyle {
+        self.path_style.unwrap_or(PathStyle::Posix)
+    }
+
+    fn shell(&self) -> String {
+        match &self.shell {
+            Some(shell) => shell.clone(),
+            None => self.default_system_shell(),
+        }
+    }
+
+    fn default_system_shell(&self) -> String {
+        String::from("/bin/sh")
+    }
+}

crates/remote/src/transport/ssh.rs 🔗

@@ -1,6 +1,7 @@
 use crate::{
-    RemoteClientDelegate, RemotePlatform,
+    RemoteArch, RemoteClientDelegate, RemoteOs, RemotePlatform,
     remote_client::{CommandTemplate, RemoteConnection, RemoteConnectionOptions},
+    transport::{parse_platform, parse_shell},
 };
 use anyhow::{Context as _, Result, anyhow};
 use async_trait::async_trait;
@@ -22,6 +23,7 @@ use smol::{
     process::{self, Child, Stdio},
 };
 use std::{
+    net::IpAddr,
     path::{Path, PathBuf},
     sync::Arc,
     time::Instant,
@@ -45,14 +47,64 @@ pub(crate) struct SshRemoteConnection {
     _temp_dir: TempDir,
 }
 
+#[derive(Debug, Clone, PartialEq, Eq, Hash)]
+pub enum SshConnectionHost {
+    IpAddr(IpAddr),
+    Hostname(String),
+}
+
+impl SshConnectionHost {
+    pub fn to_bracketed_string(&self) -> String {
+        match self {
+            Self::IpAddr(IpAddr::V4(ip)) => ip.to_string(),
+            Self::IpAddr(IpAddr::V6(ip)) => format!("[{}]", ip),
+            Self::Hostname(hostname) => hostname.clone(),
+        }
+    }
+
+    pub fn to_string(&self) -> String {
+        match self {
+            Self::IpAddr(ip) => ip.to_string(),
+            Self::Hostname(hostname) => hostname.clone(),
+        }
+    }
+}
+
+impl From<&str> for SshConnectionHost {
+    fn from(value: &str) -> Self {
+        if let Ok(address) = value.parse() {
+            Self::IpAddr(address)
+        } else {
+            Self::Hostname(value.to_string())
+        }
+    }
+}
+
+impl From<String> for SshConnectionHost {
+    fn from(value: String) -> Self {
+        if let Ok(address) = value.parse() {
+            Self::IpAddr(address)
+        } else {
+            Self::Hostname(value)
+        }
+    }
+}
+
+impl Default for SshConnectionHost {
+    fn default() -> Self {
+        Self::Hostname(Default::default())
+    }
+}
+
 #[derive(Debug, Default, Clone, PartialEq, Eq, Hash)]
 pub struct SshConnectionOptions {
-    pub host: String,
+    pub host: SshConnectionHost,
     pub username: Option<String>,
     pub port: Option<u16>,
     pub password: Option<String>,
     pub args: Option<Vec<String>>,
     pub port_forwards: Option<Vec<SshPortForwardOption>>,
+    pub connection_timeout: Option<u16>,
 
     pub nickname: Option<String>,
     pub upload_binary_over_ssh: bool,
@@ -61,7 +113,7 @@ pub struct SshConnectionOptions {
 impl From<settings::SshConnection> for SshConnectionOptions {
     fn from(val: settings::SshConnection) -> Self {
         SshConnectionOptions {
-            host: val.host.into(),
+            host: val.host.to_string().into(),
             username: val.username,
             port: val.port,
             password: None,
@@ -69,6 +121,7 @@ impl From<settings::SshConnection> for SshConnectionOptions {
             nickname: val.nickname,
             upload_binary_over_ssh: val.upload_binary_over_ssh.unwrap_or_default(),
             port_forwards: val.port_forwards,
+            connection_timeout: val.connection_timeout,
         }
     }
 }
@@ -92,7 +145,7 @@ impl MasterProcess {
         askpass_script_path: &std::ffi::OsStr,
         additional_args: Vec<String>,
         socket_path: &std::path::Path,
-        url: &str,
+        destination: &str,
     ) -> Result<Self> {
         let args = [
             "-N",
@@ -114,9 +167,9 @@ impl MasterProcess {
             .args(additional_args)
             .args(args);
 
-        master_process.arg(format!("ControlPath='{}'", socket_path.display()));
+        master_process.arg(format!("ControlPath={}", socket_path.display()));
 
-        let process = master_process.arg(&url).spawn()?;
+        let process = master_process.arg(&destination).spawn()?;
 
         Ok(MasterProcess { process })
     }
@@ -139,7 +192,7 @@ impl MasterProcess {
     pub fn new(
         askpass_script_path: &std::ffi::OsStr,
         additional_args: Vec<String>,
-        url: &str,
+        destination: &str,
     ) -> Result<Self> {
         // On Windows, `ControlMaster` and `ControlPath` are not supported:
         // https://github.com/PowerShell/Win32-OpenSSH/issues/405
@@ -161,7 +214,7 @@ impl MasterProcess {
             .env("SSH_ASKPASS_REQUIRE", "force")
             .env("SSH_ASKPASS", askpass_script_path)
             .args(additional_args)
-            .arg(url)
+            .arg(destination)
             .args(args);
 
         let process = master_process.spawn()?;
@@ -348,30 +401,50 @@ impl RemoteConnection for SshRemoteConnection {
         delegate: Arc<dyn RemoteClientDelegate>,
         cx: &mut AsyncApp,
     ) -> Task<Result<i32>> {
+        const VARS: [&str; 3] = ["RUST_LOG", "RUST_BACKTRACE", "ZED_GENERATE_MINIDUMPS"];
         delegate.set_status(Some("Starting proxy"), cx);
 
         let Some(remote_binary_path) = self.remote_binary_path.clone() else {
             return Task::ready(Err(anyhow!("Remote binary path not set")));
         };
 
-        let mut proxy_args = vec![];
-        for env_var in ["RUST_LOG", "RUST_BACKTRACE", "ZED_GENERATE_MINIDUMPS"] {
-            if let Some(value) = std::env::var(env_var).ok() {
-                proxy_args.push(format!("{}='{}'", env_var, value));
+        let mut ssh_command = if self.ssh_platform.os.is_windows() {
+            // TODO: Set the `VARS` environment variables, we do not have `env` on windows
+            // so this needs a different approach
+            let mut proxy_args = vec![];
+            proxy_args.push("proxy".to_owned());
+            proxy_args.push("--identifier".to_owned());
+            proxy_args.push(unique_identifier);
+
+            if reconnect {
+                proxy_args.push("--reconnect".to_owned());
             }
-        }
-        proxy_args.push(remote_binary_path.display(self.path_style()).into_owned());
-        proxy_args.push("proxy".to_owned());
-        proxy_args.push("--identifier".to_owned());
-        proxy_args.push(unique_identifier);
+            self.socket.ssh_command(
+                self.ssh_shell_kind,
+                &remote_binary_path.display(self.path_style()),
+                &proxy_args,
+                false,
+            )
+        } else {
+            let mut proxy_args = vec![];
+            for env_var in VARS {
+                if let Some(value) = std::env::var(env_var).ok() {
+                    proxy_args.push(format!("{}='{}'", env_var, value));
+                }
+            }
+            proxy_args.push(remote_binary_path.display(self.path_style()).into_owned());
+            proxy_args.push("proxy".to_owned());
+            proxy_args.push("--identifier".to_owned());
+            proxy_args.push(unique_identifier);
 
-        if reconnect {
-            proxy_args.push("--reconnect".to_owned());
-        }
+            if reconnect {
+                proxy_args.push("--reconnect".to_owned());
+            }
+            self.socket
+                .ssh_command(self.ssh_shell_kind, "env", &proxy_args, false)
+        };
 
-        let ssh_proxy_process = match self
-            .socket
-            .ssh_command(self.ssh_shell_kind, "env", &proxy_args, false)
+        let ssh_proxy_process = match ssh_command
             // IMPORTANT: we kill this process when we drop the task that uses it.
             .kill_on_drop(true)
             .spawn()
@@ -394,6 +467,10 @@ impl RemoteConnection for SshRemoteConnection {
     fn path_style(&self) -> PathStyle {
         self.ssh_path_style
     }
+
+    fn has_wsl_interop(&self) -> bool {
+        false
+    }
 }
 
 impl SshRemoteConnection {
@@ -404,7 +481,7 @@ impl SshRemoteConnection {
     ) -> Result<Self> {
         use askpass::AskPassResult;
 
-        let url = connection_options.ssh_url();
+        let destination = connection_options.ssh_destination();
 
         let temp_dir = tempfile::Builder::new()
             .prefix("zed-ssh-session")
@@ -429,14 +506,14 @@ impl SshRemoteConnection {
         let mut master_process = MasterProcess::new(
             askpass.script_path().as_ref(),
             connection_options.additional_args(),
-            &url,
+            &destination,
         )?;
         #[cfg(not(target_os = "windows"))]
         let mut master_process = MasterProcess::new(
             askpass.script_path().as_ref(),
             connection_options.additional_args(),
             &socket_path,
-            &url,
+            &destination,
         )?;
 
         let result = select_biased! {
@@ -487,22 +564,20 @@ impl SshRemoteConnection {
         .await?;
         drop(askpass);
 
-        let ssh_shell = socket.shell().await;
+        let is_windows = socket.probe_is_windows().await;
+        log::info!("Remote is windows: {}", is_windows);
+
+        let ssh_shell = socket.shell(is_windows).await;
         log::info!("Remote shell discovered: {}", ssh_shell);
-        let ssh_platform = socket.platform(ShellKind::new(&ssh_shell, false)).await?;
+
+        let ssh_shell_kind = ShellKind::new(&ssh_shell, is_windows);
+        let ssh_platform = socket.platform(ssh_shell_kind, is_windows).await?;
         log::info!("Remote platform discovered: {:?}", ssh_platform);
-        let ssh_path_style = match ssh_platform.os {
-            "windows" => PathStyle::Windows,
-            _ => PathStyle::Posix,
+
+        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")),
         };
-        let ssh_default_system_shell = String::from("/bin/sh");
-        let ssh_shell_kind = ShellKind::new(
-            &ssh_shell,
-            match ssh_platform.os {
-                "windows" => true,
-                _ => false,
-            },
-        );
 
         let mut this = Self {
             socket,
@@ -538,9 +613,14 @@ impl SshRemoteConnection {
             _ => version.to_string(),
         };
         let binary_name = format!(
-            "zed-remote-server-{}-{}",
+            "zed-remote-server-{}-{}{}",
             release_channel.dev_name(),
-            version_str
+            version_str,
+            if self.ssh_platform.os.is_windows() {
+                ".exe"
+            } else {
+                ""
+            }
         );
         let dst_path =
             paths::remote_server_dir_relative().join(RelPath::unix(&binary_name).unwrap());
@@ -652,18 +732,30 @@ impl SshRemoteConnection {
         cx: &mut AsyncApp,
     ) -> Result<()> {
         if let Some(parent) = tmp_path_gz.parent() {
-            self.socket
+            let res = self
+                .socket
                 .run_command(
                     self.ssh_shell_kind,
                     "mkdir",
                     &["-p", parent.display(self.path_style()).as_ref()],
                     true,
                 )
-                .await?;
+                .await;
+            if !self.ssh_platform.os.is_windows() {
+                // mkdir fails on windows if the path already exists ...
+                res?;
+            }
         }
 
         delegate.set_status(Some("Downloading remote development server on host"), cx);
 
+        let connection_timeout = self
+            .socket
+            .connection_options
+            .connection_timeout
+            .unwrap_or(10)
+            .to_string();
+
         match self
             .socket
             .run_command(
@@ -672,6 +764,8 @@ impl SshRemoteConnection {
                 &[
                     "-f",
                     "-L",
+                    "--connect-timeout",
+                    &connection_timeout,
                     url,
                     "-o",
                     &tmp_path_gz.display(self.path_style()),
@@ -697,7 +791,15 @@ impl SshRemoteConnection {
                     .run_command(
                         self.ssh_shell_kind,
                         "wget",
-                        &[url, "-O", &tmp_path_gz.display(self.path_style())],
+                        &[
+                            "--connect-timeout",
+                            &connection_timeout,
+                            "--tries",
+                            "1",
+                            url,
+                            "-O",
+                            &tmp_path_gz.display(self.path_style()),
+                        ],
                         true,
                     )
                     .await
@@ -730,17 +832,24 @@ impl SshRemoteConnection {
         cx: &mut AsyncApp,
     ) -> Result<()> {
         if let Some(parent) = tmp_path_gz.parent() {
-            self.socket
+            let res = self
+                .socket
                 .run_command(
                     self.ssh_shell_kind,
                     "mkdir",
                     &["-p", parent.display(self.path_style()).as_ref()],
                     true,
                 )
-                .await?;
+                .await;
+            if !self.ssh_platform.os.is_windows() {
+                // mkdir fails on windows if the path already exists ...
+                res?;
+            }
         }
 
-        let src_stat = fs::metadata(&src_path).await?;
+        let src_stat = fs::metadata(&src_path)
+            .await
+            .with_context(|| format!("failed to get metadata for {:?}", src_path))?;
         let size = src_stat.len();
 
         let t0 = Instant::now();
@@ -791,7 +900,7 @@ impl SshRemoteConnection {
         };
         let args = shell_kind.args_for_shell(false, script.to_string());
         self.socket
-            .run_command(shell_kind, "sh", &args, true)
+            .run_command(self.ssh_shell_kind, "sh", &args, true)
             .await?;
         Ok(())
     }
@@ -815,7 +924,7 @@ impl SshRemoteConnection {
         }
         command.arg(src_path).arg(format!(
             "{}:{}",
-            self.socket.connection_options.scp_url(),
+            self.socket.connection_options.scp_destination(),
             dest_path_str
         ));
         command
@@ -831,7 +940,7 @@ impl SshRemoteConnection {
                 .unwrap_or_default(),
         );
         command.arg("-b").arg("-");
-        command.arg(self.socket.connection_options.scp_url());
+        command.arg(self.socket.connection_options.scp_destination());
         command.stdin(Stdio::piped());
         command
     }
@@ -961,7 +1070,7 @@ impl SshSocket {
         let separator = shell_kind.sequential_commands_separator();
         let to_run = format!("cd{separator} {to_run}");
         self.ssh_options(&mut command, true)
-            .arg(self.connection_options.ssh_url());
+            .arg(self.connection_options.ssh_destination());
         if !allow_pseudo_tty {
             command.arg("-T");
         }
@@ -979,6 +1088,7 @@ impl SshSocket {
     ) -> Result<String> {
         let mut command = self.ssh_command(shell_kind, program, args, allow_pseudo_tty);
         let output = command.output().await?;
+        log::debug!("{:?}: {:?}", command, output);
         anyhow::ensure!(
             output.status.success(),
             "failed to run command {command:?}: {}",
@@ -1038,7 +1148,7 @@ impl SshSocket {
             "ControlMaster=no".to_string(),
             "-o".to_string(),
             format!("ControlPath={}", self.socket_path.display()),
-            self.connection_options.ssh_url(),
+            self.connection_options.ssh_destination(),
         ]);
         arguments
     }
@@ -1046,60 +1156,94 @@ impl SshSocket {
     #[cfg(target_os = "windows")]
     fn ssh_args(&self) -> Vec<String> {
         let mut arguments = self.connection_options.additional_args();
-        arguments.push(self.connection_options.ssh_url());
+        arguments.push(self.connection_options.ssh_destination());
         arguments
     }
 
-    async fn platform(&self, shell: ShellKind) -> Result<RemotePlatform> {
-        let uname = self.run_command(shell, "uname", &["-sm"], false).await?;
-        let Some((os, arch)) = uname.split_once(" ") else {
-            anyhow::bail!("unknown uname: {uname:?}")
-        };
-
-        let os = match os.trim() {
-            "Darwin" => "macos",
-            "Linux" => "linux",
-            _ => anyhow::bail!(
-                "Prebuilt remote servers are not yet available for {os:?}. See https://zed.dev/docs/remote-development"
-            ),
-        };
-        // exclude armv5,6,7 as they are 32-bit.
-        let arch = if arch.starts_with("armv8")
-            || arch.starts_with("armv9")
-            || arch.starts_with("arm64")
-            || arch.starts_with("aarch64")
-        {
-            "aarch64"
-        } else if arch.starts_with("x86") {
-            "x86_64"
+    async fn platform(&self, shell: ShellKind, is_windows: bool) -> Result<RemotePlatform> {
+        if is_windows {
+            self.platform_windows(shell).await
         } else {
-            anyhow::bail!(
-                "Prebuilt remote servers are not yet available for {arch:?}. See https://zed.dev/docs/remote-development"
+            self.platform_posix(shell).await
+        }
+    }
+
+    async fn platform_posix(&self, shell: ShellKind) -> Result<RemotePlatform> {
+        let output = self
+            .run_command(shell, "uname", &["-sm"], false)
+            .await
+            .context("Failed to run 'uname -sm' to determine platform")?;
+        parse_platform(&output)
+    }
+
+    async fn platform_windows(&self, shell: ShellKind) -> Result<RemotePlatform> {
+        let output = self
+            .run_command(
+                shell,
+                "cmd",
+                &["/c", "echo", "%PROCESSOR_ARCHITECTURE%"],
+                false,
             )
-        };
+            .await
+            .context(
+                "Failed to run 'echo %PROCESSOR_ARCHITECTURE%' to determine Windows architecture",
+            )?;
 
-        Ok(RemotePlatform { os, arch })
+        Ok(RemotePlatform {
+            os: RemoteOs::Windows,
+            arch: match output.trim() {
+                "AMD64" => RemoteArch::X86_64,
+                "ARM64" => RemoteArch::Aarch64,
+                arch => anyhow::bail!(
+                    "Prebuilt remote servers are not yet available for windows-{arch}. See https://zed.dev/docs/remote-development"
+                ),
+            },
+        })
     }
 
-    async fn shell(&self) -> String {
-        let default_shell = "sh";
+    /// Probes whether the remote host is running Windows.
+    ///
+    /// This is done by attempting to run a simple Windows-specific command.
+    /// If it succeeds and returns Windows-like output, we assume it's Windows.
+    async fn probe_is_windows(&self) -> bool {
+        match self
+            .run_command(ShellKind::PowerShell, "cmd", &["/c", "ver"], false)
+            .await
+        {
+            // Windows 'ver' command outputs something like "Microsoft Windows [Version 10.0.19045.5011]"
+            Ok(output) => output.trim().contains("indows"),
+            Err(_) => false,
+        }
+    }
+
+    async fn shell(&self, is_windows: bool) -> String {
+        if is_windows {
+            self.shell_windows().await
+        } else {
+            self.shell_posix().await
+        }
+    }
+
+    async fn shell_posix(&self) -> String {
+        const DEFAULT_SHELL: &str = "sh";
         match self
             .run_command(ShellKind::Posix, "sh", &["-c", "echo $SHELL"], false)
             .await
         {
-            Ok(shell) => match shell.trim() {
-                "" => {
-                    log::error!("$SHELL is not set, falling back to {default_shell}");
-                    default_shell.to_owned()
-                }
-                shell => shell.to_owned(),
-            },
+            Ok(output) => parse_shell(&output, DEFAULT_SHELL),
             Err(e) => {
-                log::error!("Failed to get shell: {e}");
-                default_shell.to_owned()
+                log::error!("Failed to detect remote shell: {e}");
+                DEFAULT_SHELL.to_owned()
             }
         }
     }
+
+    async fn shell_windows(&self) -> String {
+        // powershell is always the default, and cannot really be removed from the system
+        // so we can rely on that fact and reasonably assume that we will be running in a
+        // powershell environment
+        "powershell.exe".to_owned()
+    }
 }
 
 fn parse_port_number(port_str: &str) -> Result<u16> {
@@ -1215,10 +1359,24 @@ impl SshConnectionOptions {
                 input = rest;
                 username = Some(u.to_string());
             }
-            if let Some((rest, p)) = input.split_once(':') {
+
+            // Handle port parsing, accounting for IPv6 addresses
+            // IPv6 addresses can be: 2001:db8::1 or [2001:db8::1]:22
+            if input.starts_with('[') {
+                if let Some((rest, p)) = input.rsplit_once("]:") {
+                    input = rest.strip_prefix('[').unwrap_or(rest);
+                    port = p.parse().ok();
+                } else if input.ends_with(']') {
+                    input = input.strip_prefix('[').unwrap_or(input);
+                    input = input.strip_suffix(']').unwrap_or(input);
+                }
+            } else if let Some((rest, p)) = input.rsplit_once(':')
+                && !rest.contains(":")
+            {
                 input = rest;
-                port = p.parse().ok()
+                port = p.parse().ok();
             }
+
             hostname = Some(input.to_string())
         }
 
@@ -1232,7 +1390,7 @@ impl SshConnectionOptions {
         };
 
         Ok(Self {
-            host: hostname,
+            host: hostname.into(),
             username,
             port,
             port_forwards,
@@ -1240,22 +1398,20 @@ impl SshConnectionOptions {
             password: None,
             nickname: None,
             upload_binary_over_ssh: false,
+            connection_timeout: None,
         })
     }
 
-    pub fn ssh_url(&self) -> String {
-        let mut result = String::from("ssh://");
+    pub fn ssh_destination(&self) -> String {
+        let mut result = String::default();
         if let Some(username) = &self.username {
             // Username might be: username1@username2@ip2
             let username = urlencoding::encode(username);
             result.push_str(&username);
             result.push('@');
         }
-        result.push_str(&self.host);
-        if let Some(port) = self.port {
-            result.push(':');
-            result.push_str(&port.to_string());
-        }
+
+        result.push_str(&self.host.to_string());
         result
     }
 
@@ -1266,6 +1422,15 @@ impl SshConnectionOptions {
     pub fn additional_args(&self) -> Vec<String> {
         let mut args = self.additional_args_for_scp();
 
+        if let Some(timeout) = self.connection_timeout {
+            args.extend(["-o".to_string(), format!("ConnectTimeout={}", timeout)]);
+        }
+
+        if let Some(port) = self.port {
+            args.push("-p".to_string());
+            args.push(port.to_string());
+        }
+
         if let Some(forwards) = &self.port_forwards {
             args.extend(forwards.iter().map(|pf| {
                 let local_host = match &pf.local_host {
@@ -1287,22 +1452,23 @@ impl SshConnectionOptions {
         args
     }
 
-    fn scp_url(&self) -> String {
+    fn scp_destination(&self) -> String {
         if let Some(username) = &self.username {
-            format!("{}@{}", username, self.host)
+            format!("{}@{}", username, self.host.to_bracketed_string())
         } else {
-            self.host.clone()
+            self.host.to_string()
         }
     }
 
     pub fn connection_string(&self) -> String {
-        let host = if let Some(username) = &self.username {
-            format!("{}@{}", username, self.host)
+        let host = if let Some(port) = &self.port {
+            format!("{}:{}", self.host.to_bracketed_string(), port)
         } else {
-            self.host.clone()
+            self.host.to_string()
         };
-        if let Some(port) = &self.port {
-            format!("{}:{}", host, port)
+
+        if let Some(username) = &self.username {
+            format!("{}@{}", username, host)
         } else {
             host
         }
@@ -1388,6 +1554,7 @@ fn build_command(
 
     args.push("-t".into());
     args.push(exec);
+
     Ok(CommandTemplate {
         program: "ssh".into(),
         args,
@@ -1498,12 +1665,48 @@ mod tests {
                 "-p".to_string(),
                 "2222".to_string(),
                 "-o".to_string(),
-                "StrictHostKeyChecking=no".to_string()
+                "StrictHostKeyChecking=no".to_string(),
             ]
         );
-        assert!(
-            scp_args.iter().all(|arg| !arg.starts_with("-L")),
-            "scp args should not contain port forward flags: {scp_args:?}"
-        );
+    }
+
+    #[test]
+    fn test_host_parsing() -> Result<()> {
+        let opts = SshConnectionOptions::parse_command_line("user@2001:db8::1")?;
+        assert_eq!(opts.host, "2001:db8::1".into());
+        assert_eq!(opts.username, Some("user".to_string()));
+        assert_eq!(opts.port, None);
+
+        let opts = SshConnectionOptions::parse_command_line("user@[2001:db8::1]:2222")?;
+        assert_eq!(opts.host, "2001:db8::1".into());
+        assert_eq!(opts.username, Some("user".to_string()));
+        assert_eq!(opts.port, Some(2222));
+
+        let opts = SshConnectionOptions::parse_command_line("user@[2001:db8::1]")?;
+        assert_eq!(opts.host, "2001:db8::1".into());
+        assert_eq!(opts.username, Some("user".to_string()));
+        assert_eq!(opts.port, None);
+
+        let opts = SshConnectionOptions::parse_command_line("2001:db8::1")?;
+        assert_eq!(opts.host, "2001:db8::1".into());
+        assert_eq!(opts.username, None);
+        assert_eq!(opts.port, None);
+
+        let opts = SshConnectionOptions::parse_command_line("[2001:db8::1]:2222")?;
+        assert_eq!(opts.host, "2001:db8::1".into());
+        assert_eq!(opts.username, None);
+        assert_eq!(opts.port, Some(2222));
+
+        let opts = SshConnectionOptions::parse_command_line("user@example.com:2222")?;
+        assert_eq!(opts.host, "example.com".into());
+        assert_eq!(opts.username, Some("user".to_string()));
+        assert_eq!(opts.port, Some(2222));
+
+        let opts = SshConnectionOptions::parse_command_line("user@192.168.1.1:2222")?;
+        assert_eq!(opts.host, "192.168.1.1".into());
+        assert_eq!(opts.username, Some("user".to_string()));
+        assert_eq!(opts.port, Some(2222));
+
+        Ok(())
     }
 }

crates/remote/src/transport/wsl.rs 🔗

@@ -1,6 +1,7 @@
 use crate::{
-    RemoteClientDelegate, RemotePlatform,
+    RemoteArch, RemoteClientDelegate, RemoteOs, RemotePlatform,
     remote_client::{CommandTemplate, RemoteConnection, RemoteConnectionOptions},
+    transport::{parse_platform, parse_shell},
 };
 use anyhow::{Context, Result, anyhow, bail};
 use async_trait::async_trait;
@@ -22,7 +23,8 @@ use std::{
 use util::{
     paths::{PathStyle, RemotePathBuf},
     rel_path::RelPath,
-    shell::ShellKind,
+    shell::{Shell, ShellKind},
+    shell_builder::ShellBuilder,
 };
 
 #[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Deserialize, schemars::JsonSchema)]
@@ -47,6 +49,7 @@ pub(crate) struct WslRemoteConnection {
     shell: String,
     shell_kind: ShellKind,
     default_system_shell: String,
+    has_wsl_interop: bool,
     connection_options: WslConnectionOptions,
 }
 
@@ -67,10 +70,14 @@ impl WslRemoteConnection {
         let mut this = Self {
             connection_options,
             remote_binary_path: None,
-            platform: RemotePlatform { os: "", arch: "" },
+            platform: RemotePlatform {
+                os: RemoteOs::Linux,
+                arch: RemoteArch::X86_64,
+            },
             shell: String::new(),
             shell_kind: ShellKind::Posix,
             default_system_shell: String::from("/bin/sh"),
+            has_wsl_interop: false,
         };
         delegate.set_status(Some("Detecting WSL environment"), cx);
         this.shell = this
@@ -79,6 +86,15 @@ impl WslRemoteConnection {
             .context("failed detecting shell")?;
         log::info!("Remote shell discovered: {}", this.shell);
         this.shell_kind = ShellKind::new(&this.shell, false);
+        this.has_wsl_interop = this.detect_has_wsl_interop().await.unwrap_or_default();
+        log::info!(
+            "Remote has wsl interop {}",
+            if this.has_wsl_interop {
+                "enabled"
+            } else {
+                "disabled"
+            }
+        );
         this.platform = this
             .detect_platform()
             .await
@@ -96,23 +112,30 @@ impl WslRemoteConnection {
 
     async fn detect_platform(&self) -> Result<RemotePlatform> {
         let program = self.shell_kind.prepend_command_prefix("uname");
-        let arch_str = self.run_wsl_command_with_output(&program, &["-m"]).await?;
-        let arch_str = arch_str.trim().to_string();
-        let arch = match arch_str.as_str() {
-            "x86_64" => "x86_64",
-            "aarch64" | "arm64" => "aarch64",
-            _ => "x86_64",
-        };
-        Ok(RemotePlatform { os: "linux", arch })
+        let output = self.run_wsl_command_with_output(&program, &["-sm"]).await?;
+        parse_platform(&output)
     }
 
     async fn detect_shell(&self) -> Result<String> {
-        Ok(self
+        const DEFAULT_SHELL: &str = "sh";
+        match self
             .run_wsl_command_with_output("sh", &["-c", "echo $SHELL"])
             .await
-            .inspect_err(|err| log::error!("Failed to detect remote shell: {err}"))
-            .ok()
-            .unwrap_or_else(|| "/bin/sh".to_string()))
+        {
+            Ok(output) => Ok(parse_shell(&output, DEFAULT_SHELL)),
+            Err(e) => {
+                log::error!("Failed to detect remote shell: {e}");
+                Ok(DEFAULT_SHELL.to_owned())
+            }
+        }
+    }
+
+    async fn detect_has_wsl_interop(&self) -> Result<bool> {
+        Ok(self
+            .run_wsl_command_with_output("cat", &["/proc/sys/fs/binfmt_misc/WSLInterop"])
+            .await
+            .inspect_err(|err| log::error!("Failed to detect wsl interop: {err}"))?
+            .contains("enabled"))
     }
 
     async fn windows_path_to_wsl_path(&self, source: &Path) -> Result<String> {
@@ -317,6 +340,7 @@ impl RemoteConnection for WslRemoteConnection {
                 proxy_args.push(format!("{}={}", env_var, value));
             }
         }
+
         proxy_args.push(remote_binary_path.display(PathStyle::Posix).into_owned());
         proxy_args.push("proxy".to_owned());
         proxy_args.push("--identifier".to_owned());
@@ -433,8 +457,10 @@ impl RemoteConnection for WslRemoteConnection {
         } else {
             write!(&mut exec, "{} -l", self.shell)?;
         }
+        let (command, args) =
+            ShellBuilder::new(&Shell::Program(self.shell.clone()), false).build(Some(exec), &[]);
 
-        let wsl_args = if let Some(user) = &self.connection_options.user {
+        let mut wsl_args = if let Some(user) = &self.connection_options.user {
             vec![
                 "--distribution".to_string(),
                 self.connection_options.distro_name.clone(),
@@ -443,9 +469,7 @@ impl RemoteConnection for WslRemoteConnection {
                 "--cd".to_string(),
                 working_dir,
                 "--".to_string(),
-                self.shell.clone(),
-                "-c".to_string(),
-                exec,
+                command,
             ]
         } else {
             vec![
@@ -454,11 +478,10 @@ impl RemoteConnection for WslRemoteConnection {
                 "--cd".to_string(),
                 working_dir,
                 "--".to_string(),
-                self.shell.clone(),
-                "-c".to_string(),
-                exec,
+                command,
             ]
         };
+        wsl_args.extend(args);
 
         Ok(CommandTemplate {
             program: "wsl.exe".to_string(),
@@ -489,6 +512,10 @@ impl RemoteConnection for WslRemoteConnection {
     fn default_system_shell(&self) -> String {
         self.default_system_shell.clone()
     }
+
+    fn has_wsl_interop(&self) -> bool {
+        self.has_wsl_interop
+    }
 }
 
 /// `wslpath` is a executable available in WSL, it's a linux binary.

crates/remote_server/Cargo.toml 🔗

@@ -26,6 +26,7 @@ anyhow.workspace = true
 askpass.workspace = true
 clap.workspace = true
 client.workspace = true
+collections.workspace = true
 dap_adapters.workspace = true
 debug_adapter_extension.workspace = true
 env_logger.workspace = true
@@ -81,7 +82,6 @@ action_log.workspace = true
 agent = { workspace = true, features = ["test-support"] }
 client = { workspace = true, features = ["test-support"] }
 clock = { workspace = true, features = ["test-support"] }
-collections.workspace = true
 dap = { workspace = true, features = ["test-support"] }
 editor = { workspace = true, features = ["test-support"] }
 workspace = { workspace = true, features = ["test-support"] }

crates/remote_server/src/headless_project.rs 🔗

@@ -1,4 +1,5 @@
 use anyhow::{Context as _, Result, anyhow};
+use collections::HashSet;
 use language::File;
 use lsp::LanguageServerId;
 
@@ -21,6 +22,7 @@ use project::{
     project_settings::SettingsObserver,
     search::SearchQuery,
     task_store::TaskStore,
+    trusted_worktrees::{PathTrust, RemoteHostLocation, TrustedWorktrees},
     worktree_store::WorktreeStore,
 };
 use rpc::{
@@ -86,6 +88,7 @@ impl HeadlessProject {
             languages,
             extension_host_proxy: proxy,
         }: HeadlessAppState,
+        init_worktree_trust: bool,
         cx: &mut Context<Self>,
     ) -> Self {
         debug_adapter_extension::init(proxy.clone(), cx);
@@ -97,6 +100,16 @@ impl HeadlessProject {
             store
         });
 
+        if init_worktree_trust {
+            project::trusted_worktrees::track_worktree_trust(
+                worktree_store.clone(),
+                None::<RemoteHostLocation>,
+                Some((session.clone(), REMOTE_SERVER_PROJECT_ID)),
+                None,
+                cx,
+            );
+        }
+
         let environment =
             cx.new(|cx| ProjectEnvironment::new(None, worktree_store.downgrade(), None, true, cx));
         let manifest_tree = ManifestTree::new(worktree_store.clone(), cx);
@@ -264,6 +277,8 @@ impl HeadlessProject {
         session.add_entity_request_handler(Self::handle_get_directory_environment);
         session.add_entity_message_handler(Self::handle_toggle_lsp_logs);
         session.add_entity_request_handler(Self::handle_open_image_by_path);
+        session.add_entity_request_handler(Self::handle_trust_worktrees);
+        session.add_entity_request_handler(Self::handle_restrict_worktrees);
 
         session.add_entity_request_handler(BufferStore::handle_update_buffer);
         session.add_entity_message_handler(BufferStore::handle_close_buffer);
@@ -449,6 +464,7 @@ impl HeadlessProject {
                     message.payload.visible,
                     this.fs.clone(),
                     this.next_entry_id.clone(),
+                    true,
                     &mut cx,
                 )
             })?
@@ -594,6 +610,50 @@ impl HeadlessProject {
         })
     }
 
+    pub async fn handle_trust_worktrees(
+        _: Entity<Self>,
+        envelope: TypedEnvelope<proto::TrustWorktrees>,
+        mut cx: AsyncApp,
+    ) -> Result<proto::Ack> {
+        let trusted_worktrees = cx
+            .update(|cx| TrustedWorktrees::try_get_global(cx))?
+            .context("missing trusted worktrees")?;
+        trusted_worktrees.update(&mut cx, |trusted_worktrees, cx| {
+            trusted_worktrees.trust(
+                envelope
+                    .payload
+                    .trusted_paths
+                    .into_iter()
+                    .filter_map(PathTrust::from_proto)
+                    .collect(),
+                None,
+                cx,
+            );
+        })?;
+        Ok(proto::Ack {})
+    }
+
+    pub async fn handle_restrict_worktrees(
+        _: Entity<Self>,
+        envelope: TypedEnvelope<proto::RestrictWorktrees>,
+        mut cx: AsyncApp,
+    ) -> Result<proto::Ack> {
+        let trusted_worktrees = cx
+            .update(|cx| TrustedWorktrees::try_get_global(cx))?
+            .context("missing trusted worktrees")?;
+        trusted_worktrees.update(&mut cx, |trusted_worktrees, cx| {
+            let restricted_paths = envelope
+                .payload
+                .worktree_ids
+                .into_iter()
+                .map(WorktreeId::from_proto)
+                .map(PathTrust::Worktree)
+                .collect::<HashSet<_>>();
+            trusted_worktrees.restrict(restricted_paths, None, cx);
+        })?;
+        Ok(proto::Ack {})
+    }
+
     pub async fn handle_open_new_buffer(
         this: Entity<Self>,
         _message: TypedEnvelope<proto::OpenNewBuffer>,

crates/remote_server/src/remote_editing_tests.rs 🔗

@@ -455,7 +455,7 @@ async fn test_remote_lsp(cx: &mut TestAppContext, server_cx: &mut TestAppContext
     });
 
     let mut fake_lsp = server_cx.update(|cx| {
-        headless.read(cx).languages.register_fake_language_server(
+        headless.read(cx).languages.register_fake_lsp_server(
             LanguageServerName("rust-analyzer".into()),
             lsp::ServerCapabilities {
                 completion_provider: Some(lsp::CompletionOptions::default()),
@@ -479,7 +479,7 @@ async fn test_remote_lsp(cx: &mut TestAppContext, server_cx: &mut TestAppContext
                 ..FakeLspAdapter::default()
             },
         );
-        headless.read(cx).languages.register_fake_language_server(
+        headless.read(cx).languages.register_fake_lsp_server(
             LanguageServerName("fake-analyzer".into()),
             lsp::ServerCapabilities {
                 completion_provider: Some(lsp::CompletionOptions::default()),
@@ -672,7 +672,7 @@ async fn test_remote_cancel_language_server_work(
     });
 
     let mut fake_lsp = server_cx.update(|cx| {
-        headless.read(cx).languages.register_fake_language_server(
+        headless.read(cx).languages.register_fake_lsp_server(
             LanguageServerName("rust-analyzer".into()),
             Default::default(),
             None,
@@ -1936,6 +1936,7 @@ pub async fn init_test(
                 languages,
                 extension_host_proxy: proxy,
             },
+            false,
             cx,
         )
     });
@@ -1980,5 +1981,5 @@ fn build_project(ssh: Entity<RemoteClient>, cx: &mut TestAppContext) -> Entity<P
         Project::init(&client, cx);
     });
 
-    cx.update(|cx| Project::remote(ssh, client, node, user_store, languages, fs, cx))
+    cx.update(|cx| Project::remote(ssh, client, node, user_store, languages, fs, false, cx))
 }

crates/remote_server/src/unix.rs 🔗

@@ -2,6 +2,8 @@ use crate::HeadlessProject;
 use crate::headless_project::HeadlessAppState;
 use anyhow::{Context as _, Result, anyhow};
 use client::ProxySettings;
+use collections::HashMap;
+use project::trusted_worktrees;
 use util::ResultExt;
 
 use extension::ExtensionHostProxy;
@@ -199,6 +201,7 @@ fn start_server(
     listeners: ServerListeners,
     log_rx: Receiver<Vec<u8>>,
     cx: &mut App,
+    is_wsl_interop: bool,
 ) -> AnyProtoClient {
     // This is the server idle timeout. If no connection comes in this timeout, the server will shut down.
     const IDLE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10 * 60);
@@ -318,7 +321,7 @@ fn start_server(
     })
     .detach();
 
-    RemoteClient::proto_client_from_channels(incoming_rx, outgoing_tx, cx, "server")
+    RemoteClient::proto_client_from_channels(incoming_rx, outgoing_tx, cx, "server", is_wsl_interop)
 }
 
 fn init_paths() -> anyhow::Result<()> {
@@ -407,8 +410,16 @@ pub fn execute_run(
 
         HeadlessProject::init(cx);
 
+        let is_wsl_interop = if cfg!(target_os = "linux") {
+            // See: https://learn.microsoft.com/en-us/windows/wsl/filesystems#disable-interoperability
+            matches!(std::fs::read_to_string("/proc/sys/fs/binfmt_misc/WSLInterop"), Ok(s) if s.contains("enabled"))
+        } else {
+            false
+        };
+
         log::info!("gpui app started, initializing server");
-        let session = start_server(listeners, log_rx, cx);
+        let session = start_server(listeners, log_rx, cx, is_wsl_interop);
+        trusted_worktrees::init(HashMap::default(), Some((session.clone(), REMOTE_SERVER_PROJECT_ID)), None, cx);
 
         GitHostingProviderRegistry::set_global(git_hosting_provider_registry, cx);
         git_hosting_providers::init(cx);
@@ -460,6 +471,7 @@ pub fn execute_run(
                     languages,
                     extension_host_proxy,
                 },
+                true,
                 cx,
             )
         });

crates/repl/src/kernels/mod.rs 🔗

@@ -81,7 +81,7 @@ pub fn python_env_kernel_specifications(
     worktree_id: WorktreeId,
     cx: &mut App,
 ) -> impl Future<Output = Result<Vec<KernelSpecification>>> + use<> {
-    let python_language = LanguageName::new("Python");
+    let python_language = LanguageName::new_static("Python");
     let toolchains = project.read(cx).available_toolchains(
         ProjectPath {
             worktree_id,

crates/repl/src/repl.rs 🔗

@@ -12,7 +12,7 @@ mod session;
 use std::{sync::Arc, time::Duration};
 
 use async_dispatcher::{Dispatcher, Runnable, set_dispatcher};
-use gpui::{App, PlatformDispatcher, RunnableVariant};
+use gpui::{App, PlatformDispatcher, Priority, RunnableVariant};
 use project::Fs;
 pub use runtimelib::ExecutionState;
 
@@ -46,7 +46,7 @@ fn zed_dispatcher(cx: &mut App) -> impl Dispatcher {
     impl Dispatcher for ZedDispatcher {
         fn dispatch(&self, runnable: Runnable) {
             self.dispatcher
-                .dispatch(RunnableVariant::Compat(runnable), None);
+                .dispatch(RunnableVariant::Compat(runnable), None, Priority::default());
         }
 
         fn dispatch_after(&self, duration: Duration, runnable: Runnable) {

crates/reqwest_client/src/reqwest_client.rs 🔗

@@ -270,26 +270,6 @@ impl http_client::HttpClient for ReqwestClient {
         }
         .boxed()
     }
-
-    fn send_multipart_form<'a>(
-        &'a self,
-        url: &str,
-        form: reqwest::multipart::Form,
-    ) -> futures::future::BoxFuture<'a, anyhow::Result<http_client::Response<http_client::AsyncBody>>>
-    {
-        let response = self.client.post(url).multipart(form).send();
-        self.handle
-            .spawn(async move {
-                let response = response.await?;
-                let mut builder = http::response::Builder::new().status(response.status());
-                for (k, v) in response.headers() {
-                    builder = builder.header(k, v)
-                }
-                Ok(builder.body(response.bytes().await?.into())?)
-            })
-            .map(|e| e?)
-            .boxed()
-    }
 }
 
 #[cfg(test)]

crates/rope/Cargo.toml 🔗

@@ -18,6 +18,8 @@ rayon.workspace = true
 sum_tree.workspace = true
 unicode-segmentation.workspace = true
 util.workspace = true
+ztracing.workspace = true
+tracing.workspace = true
 
 [dev-dependencies]
 ctor.workspace = true
@@ -30,3 +32,6 @@ zlog.workspace = true
 [[bench]]
 name = "rope_benchmark"
 harness = false
+
+[package.metadata.cargo-machete]
+ignored = ["tracing"]

crates/rope/src/chunk.rs 🔗

@@ -47,22 +47,59 @@ impl Chunk {
 
     #[inline(always)]
     pub fn new(text: &str) -> Self {
-        let mut this = Chunk::default();
-        this.push_str(text);
-        this
+        let text = ArrayString::from(text).unwrap();
+
+        const CHUNK_SIZE: usize = 8;
+
+        let mut chars_bytes = [0; MAX_BASE / CHUNK_SIZE];
+        let mut newlines_bytes = [0; MAX_BASE / CHUNK_SIZE];
+        let mut tabs_bytes = [0; MAX_BASE / CHUNK_SIZE];
+        let mut chars_utf16_bytes = [0; MAX_BASE / CHUNK_SIZE];
+
+        let mut chunk_ix = 0;
+
+        let mut bytes = text.as_bytes();
+        while !bytes.is_empty() {
+            let (chunk, rest) = bytes.split_at(bytes.len().min(CHUNK_SIZE));
+            bytes = rest;
+
+            let mut chars = 0;
+            let mut newlines = 0;
+            let mut tabs = 0;
+            let mut chars_utf16 = 0;
+
+            for (ix, &b) in chunk.iter().enumerate() {
+                chars |= (util::is_utf8_char_boundary(b) as u8) << ix;
+                newlines |= ((b == b'\n') as u8) << ix;
+                tabs |= ((b == b'\t') as u8) << ix;
+                // b >= 240 when we are at the first byte of the 4 byte encoded
+                // utf-8 code point (U+010000 or greater) it means that it would
+                // be encoded as two 16-bit code units in utf-16
+                chars_utf16 |= ((b >= 240) as u8) << ix;
+            }
+
+            chars_bytes[chunk_ix] = chars;
+            newlines_bytes[chunk_ix] = newlines;
+            tabs_bytes[chunk_ix] = tabs;
+            chars_utf16_bytes[chunk_ix] = chars_utf16;
+
+            chunk_ix += 1;
+        }
+
+        let chars = Bitmap::from_le_bytes(chars_bytes);
+
+        Chunk {
+            text,
+            chars,
+            chars_utf16: (Bitmap::from_le_bytes(chars_utf16_bytes) << 1) | chars,
+            newlines: Bitmap::from_le_bytes(newlines_bytes),
+            tabs: Bitmap::from_le_bytes(tabs_bytes),
+        }
     }
 
     #[inline(always)]
     pub fn push_str(&mut self, text: &str) {
-        for (char_ix, c) in text.char_indices() {
-            let ix = self.text.len() + char_ix;
-            self.chars |= 1 << ix;
-            self.chars_utf16 |= 1 << ix;
-            self.chars_utf16 |= (c.len_utf16() as Bitmap) << ix;
-            self.newlines |= ((c == '\n') as Bitmap) << ix;
-            self.tabs |= ((c == '\t') as Bitmap) << ix;
-        }
-        self.text.push_str(text);
+        self.append(Chunk::new(text).as_slice());
     }
 
     #[inline(always)]

crates/rope/src/rope.rs 🔗

@@ -12,6 +12,7 @@ use std::{
     str,
 };
 use sum_tree::{Bias, Dimension, Dimensions, SumTree};
+use ztracing::instrument;
 
 pub use chunk::{Chunk, ChunkSlice};
 pub use offset_utf16::OffsetUtf16;
@@ -226,7 +227,7 @@ impl Rope {
         #[cfg(all(test, not(rust_analyzer)))]
         const PARALLEL_THRESHOLD: usize = 4;
         #[cfg(not(all(test, not(rust_analyzer))))]
-        const PARALLEL_THRESHOLD: usize = 4 * (2 * sum_tree::TREE_BASE);
+        const PARALLEL_THRESHOLD: usize = 84 * (2 * sum_tree::TREE_BASE);
 
         if new_chunks.len() >= PARALLEL_THRESHOLD {
             self.chunks
@@ -428,6 +429,7 @@ impl Rope {
             })
     }
 
+    #[instrument(skip_all)]
     pub fn point_to_offset(&self, point: Point) -> usize {
         if point >= self.summary().lines {
             return self.summary().len;

crates/rpc/src/proto_client.rs 🔗

@@ -59,6 +59,7 @@ pub trait ProtoClient: Send + Sync {
     fn message_handler_set(&self) -> &parking_lot::Mutex<ProtoMessageHandlerSet>;
 
     fn is_via_collab(&self) -> bool;
+    fn has_wsl_interop(&self) -> bool;
 }
 
 #[derive(Default)]
@@ -510,6 +511,10 @@ impl AnyProtoClient {
             },
         );
     }
+
+    pub fn has_wsl_interop(&self) -> bool {
+        self.0.client.has_wsl_interop()
+    }
 }
 
 fn to_any_envelope<T: EnvelopedMessage>(

crates/rules_library/src/rules_library.rs 🔗

@@ -3,9 +3,9 @@ use collections::{HashMap, HashSet};
 use editor::{CompletionProvider, SelectionEffects};
 use editor::{CurrentLineHighlight, Editor, EditorElement, EditorEvent, EditorStyle, actions::Tab};
 use gpui::{
-    Action, App, Bounds, DEFAULT_ADDITIONAL_WINDOW_SIZE, Entity, EventEmitter, Focusable,
-    PromptLevel, Subscription, Task, TextStyle, TitlebarOptions, WindowBounds, WindowHandle,
-    WindowOptions, actions, point, size, transparent_black,
+    App, Bounds, DEFAULT_ADDITIONAL_WINDOW_SIZE, Entity, EventEmitter, Focusable, PromptLevel,
+    Subscription, Task, TextStyle, TitlebarOptions, WindowBounds, WindowHandle, WindowOptions,
+    actions, point, size, transparent_black,
 };
 use language::{Buffer, LanguageRegistry, language_settings::SoftWrap};
 use language_model::{
@@ -21,9 +21,7 @@ use std::sync::atomic::AtomicBool;
 use std::time::Duration;
 use theme::ThemeSettings;
 use title_bar::platform_title_bar::PlatformTitleBar;
-use ui::{
-    Divider, KeyBinding, ListItem, ListItemSpacing, ListSubHeader, Render, Tooltip, prelude::*,
-};
+use ui::{Divider, ListItem, ListItemSpacing, ListSubHeader, Tooltip, prelude::*};
 use util::{ResultExt, TryFutureExt};
 use workspace::{Workspace, WorkspaceSettings, client_side_decorations};
 use zed_actions::assistant::InlineAssist;
@@ -44,15 +42,12 @@ actions!(
         /// Duplicates the selected rule.
         DuplicateRule,
         /// Toggles whether the selected rule is a default rule.
-        ToggleDefaultRule
+        ToggleDefaultRule,
+        /// Restores a built-in rule to its default content.
+        RestoreDefaultContent
     ]
 );
 
-const BUILT_IN_TOOLTIP_TEXT: &str = concat!(
-    "This rule supports special functionality.\n",
-    "It's read-only, but you can remove it from your default rules."
-);
-
 pub trait InlineAssistDelegate {
     fn assist(
         &self,
@@ -211,13 +206,8 @@ impl PickerDelegate for RulePickerDelegate {
         self.filtered_entries.len()
     }
 
-    fn no_matches_text(&self, _window: &mut Window, cx: &mut App) -> Option<SharedString> {
-        let text = if self.store.read(cx).prompt_count() == 0 {
-            "No rules.".into()
-        } else {
-            "No rules found matching your search.".into()
-        };
-        Some(text)
+    fn no_matches_text(&self, _window: &mut Window, _cx: &mut App) -> Option<SharedString> {
+        Some("No rules found matching your search.".into())
     }
 
     fn selected_index(&self) -> usize {
@@ -270,23 +260,35 @@ impl PickerDelegate for RulePickerDelegate {
                 .background_spawn(async move {
                     let matches = search.await;
 
-                    let (default_rules, non_default_rules): (Vec<_>, Vec<_>) =
-                        matches.iter().partition(|rule| rule.default);
+                    let (built_in_rules, user_rules): (Vec<_>, Vec<_>) =
+                        matches.into_iter().partition(|rule| rule.id.is_built_in());
+                    let (default_rules, other_rules): (Vec<_>, Vec<_>) =
+                        user_rules.into_iter().partition(|rule| rule.default);
 
                     let mut filtered_entries = Vec::new();
 
+                    if !built_in_rules.is_empty() {
+                        filtered_entries.push(RulePickerEntry::Header("Built-in Rules".into()));
+
+                        for rule in built_in_rules {
+                            filtered_entries.push(RulePickerEntry::Rule(rule));
+                        }
+
+                        filtered_entries.push(RulePickerEntry::Separator);
+                    }
+
                     if !default_rules.is_empty() {
                         filtered_entries.push(RulePickerEntry::Header("Default Rules".into()));
 
                         for rule in default_rules {
-                            filtered_entries.push(RulePickerEntry::Rule(rule.clone()));
+                            filtered_entries.push(RulePickerEntry::Rule(rule));
                         }
 
                         filtered_entries.push(RulePickerEntry::Separator);
                     }
 
-                    for rule in non_default_rules {
-                        filtered_entries.push(RulePickerEntry::Rule(rule.clone()));
+                    for rule in other_rules {
+                        filtered_entries.push(RulePickerEntry::Rule(rule));
                     }
 
                     let selected_index = prev_prompt_id
@@ -341,21 +343,27 @@ impl PickerDelegate for RulePickerDelegate {
         cx: &mut Context<Picker<Self>>,
     ) -> Option<Self::ListItem> {
         match self.filtered_entries.get(ix)? {
-            RulePickerEntry::Header(title) => Some(
-                ListSubHeader::new(title.clone())
-                    .end_slot(
-                        IconButton::new("info", IconName::Info)
-                            .style(ButtonStyle::Transparent)
-                            .icon_size(IconSize::Small)
-                            .icon_color(Color::Muted)
-                            .tooltip(Tooltip::text(
-                                "Default Rules are attached by default with every new thread.",
-                            ))
-                            .into_any_element(),
-                    )
-                    .inset(true)
-                    .into_any_element(),
-            ),
+            RulePickerEntry::Header(title) => {
+                let tooltip_text = if title.as_ref() == "Built-in Rules" {
+                    "Built-in rules are those included out of the box with Zed."
+                } else {
+                    "Default Rules are attached by default with every new thread."
+                };
+
+                Some(
+                    ListSubHeader::new(title.clone())
+                        .end_slot(
+                            IconButton::new("info", IconName::Info)
+                                .style(ButtonStyle::Transparent)
+                                .icon_size(IconSize::Small)
+                                .icon_color(Color::Muted)
+                                .tooltip(Tooltip::text(tooltip_text))
+                                .into_any_element(),
+                        )
+                        .inset(true)
+                        .into_any_element(),
+                )
+            }
             RulePickerEntry::Separator => Some(
                 h_flex()
                     .py_1()
@@ -376,7 +384,7 @@ impl PickerDelegate for RulePickerDelegate {
                                 .truncate()
                                 .mr_10(),
                         )
-                        .end_slot::<IconButton>(default.then(|| {
+                        .end_slot::<IconButton>((default && !prompt_id.is_built_in()).then(|| {
                             IconButton::new("toggle-default-rule", IconName::Paperclip)
                                 .toggle_state(true)
                                 .icon_color(Color::Accent)
@@ -386,62 +394,52 @@ impl PickerDelegate for RulePickerDelegate {
                                     cx.emit(RulePickerEvent::ToggledDefault { prompt_id })
                                 }))
                         }))
-                        .end_hover_slot(
-                            h_flex()
-                                .child(if prompt_id.is_built_in() {
-                                    div()
-                                        .id("built-in-rule")
-                                        .child(Icon::new(IconName::FileLock).color(Color::Muted))
-                                        .tooltip(move |_window, cx| {
-                                            Tooltip::with_meta(
-                                                "Built-in rule",
-                                                None,
-                                                BUILT_IN_TOOLTIP_TEXT,
-                                                cx,
-                                            )
-                                        })
-                                        .into_any()
-                                } else {
-                                    IconButton::new("delete-rule", IconName::Trash)
-                                        .icon_color(Color::Muted)
-                                        .icon_size(IconSize::Small)
-                                        .tooltip(Tooltip::text("Delete Rule"))
-                                        .on_click(cx.listener(move |_, _, _, cx| {
-                                            cx.emit(RulePickerEvent::Deleted { prompt_id })
-                                        }))
-                                        .into_any_element()
-                                })
-                                .child(
-                                    IconButton::new("toggle-default-rule", IconName::Plus)
-                                        .selected_icon(IconName::Dash)
-                                        .toggle_state(default)
-                                        .icon_size(IconSize::Small)
-                                        .icon_color(if default {
-                                            Color::Accent
-                                        } else {
-                                            Color::Muted
-                                        })
-                                        .map(|this| {
-                                            if default {
-                                                this.tooltip(Tooltip::text(
-                                                    "Remove from Default Rules",
-                                                ))
+                        .when(!prompt_id.is_built_in(), |this| {
+                            this.end_hover_slot(
+                                h_flex()
+                                    .child(
+                                        IconButton::new("delete-rule", IconName::Trash)
+                                            .icon_color(Color::Muted)
+                                            .icon_size(IconSize::Small)
+                                            .tooltip(Tooltip::text("Delete Rule"))
+                                            .on_click(cx.listener(move |_, _, _, cx| {
+                                                cx.emit(RulePickerEvent::Deleted { prompt_id })
+                                            })),
+                                    )
+                                    .child(
+                                        IconButton::new("toggle-default-rule", IconName::Plus)
+                                            .selected_icon(IconName::Dash)
+                                            .toggle_state(default)
+                                            .icon_size(IconSize::Small)
+                                            .icon_color(if default {
+                                                Color::Accent
                                             } else {
-                                                this.tooltip(move |_window, cx| {
-                                                    Tooltip::with_meta(
-                                                        "Add to Default Rules",
-                                                        None,
-                                                        "Always included in every thread.",
-                                                        cx,
-                                                    )
+                                                Color::Muted
+                                            })
+                                            .map(|this| {
+                                                if default {
+                                                    this.tooltip(Tooltip::text(
+                                                        "Remove from Default Rules",
+                                                    ))
+                                                } else {
+                                                    this.tooltip(move |_window, cx| {
+                                                        Tooltip::with_meta(
+                                                            "Add to Default Rules",
+                                                            None,
+                                                            "Always included in every thread.",
+                                                            cx,
+                                                        )
+                                                    })
+                                                }
+                                            })
+                                            .on_click(cx.listener(move |_, _, _, cx| {
+                                                cx.emit(RulePickerEvent::ToggledDefault {
+                                                    prompt_id,
                                                 })
-                                            }
-                                        })
-                                        .on_click(cx.listener(move |_, _, _, cx| {
-                                            cx.emit(RulePickerEvent::ToggledDefault { prompt_id })
-                                        })),
-                                ),
-                        )
+                                            })),
+                                    ),
+                            )
+                        })
                         .into_any_element(),
                 )
             }
@@ -573,7 +571,7 @@ impl RulesLibrary {
     pub fn save_rule(&mut self, prompt_id: PromptId, window: &mut Window, cx: &mut Context<Self>) {
         const SAVE_THROTTLE: Duration = Duration::from_millis(500);
 
-        if prompt_id.is_built_in() {
+        if !prompt_id.can_edit() {
             return;
         }
 
@@ -661,6 +659,33 @@ impl RulesLibrary {
         }
     }
 
+    pub fn restore_default_content_for_active_rule(
+        &mut self,
+        window: &mut Window,
+        cx: &mut Context<Self>,
+    ) {
+        if let Some(active_rule_id) = self.active_rule_id {
+            self.restore_default_content(active_rule_id, window, cx);
+        }
+    }
+
+    pub fn restore_default_content(
+        &mut self,
+        prompt_id: PromptId,
+        window: &mut Window,
+        cx: &mut Context<Self>,
+    ) {
+        let Some(built_in) = prompt_id.as_built_in() else {
+            return;
+        };
+
+        if let Some(rule_editor) = self.rule_editors.get(&prompt_id) {
+            rule_editor.body_editor.update(cx, |editor, cx| {
+                editor.set_text(built_in.default_content(), window, cx);
+            });
+        }
+    }
+
     pub fn toggle_default_for_rule(
         &mut self,
         prompt_id: PromptId,
@@ -690,7 +715,7 @@ impl RulesLibrary {
             if focus {
                 rule_editor
                     .body_editor
-                    .update(cx, |editor, cx| window.focus(&editor.focus_handle(cx)));
+                    .update(cx, |editor, cx| window.focus(&editor.focus_handle(cx), cx));
             }
             self.set_active_rule(Some(prompt_id), window, cx);
         } else if let Some(rule_metadata) = self.store.read(cx).metadata(prompt_id) {
@@ -721,7 +746,7 @@ impl RulesLibrary {
                             });
 
                             let mut editor = Editor::for_buffer(buffer, None, window, cx);
-                            if prompt_id.is_built_in() {
+                            if !prompt_id.can_edit() {
                                 editor.set_read_only(true);
                                 editor.set_show_edit_predictions(Some(false), window, cx);
                             }
@@ -733,7 +758,7 @@ impl RulesLibrary {
                             editor.set_current_line_highlight(Some(CurrentLineHighlight::None));
                             editor.set_completion_provider(Some(make_completion_provider()));
                             if focus {
-                                window.focus(&editor.focus_handle(cx));
+                                window.focus(&editor.focus_handle(cx), cx);
                             }
                             editor
                         });
@@ -909,7 +934,7 @@ impl RulesLibrary {
         if let Some(active_rule) = self.active_rule_id {
             self.rule_editors[&active_rule]
                 .body_editor
-                .update(cx, |editor, cx| window.focus(&editor.focus_handle(cx)));
+                .update(cx, |editor, cx| window.focus(&editor.focus_handle(cx), cx));
             cx.stop_propagation();
         }
     }
@@ -968,7 +993,7 @@ impl RulesLibrary {
         if let Some(rule_id) = self.active_rule_id
             && let Some(rule_editor) = self.rule_editors.get(&rule_id)
         {
-            window.focus(&rule_editor.body_editor.focus_handle(cx));
+            window.focus(&rule_editor.body_editor.focus_handle(cx), cx);
         }
     }
 
@@ -981,7 +1006,7 @@ impl RulesLibrary {
         if let Some(rule_id) = self.active_rule_id
             && let Some(rule_editor) = self.rule_editors.get(&rule_id)
         {
-            window.focus(&rule_editor.title_editor.focus_handle(cx));
+            window.focus(&rule_editor.title_editor.focus_handle(cx), cx);
         }
     }
 
@@ -1148,30 +1173,38 @@ impl RulesLibrary {
     fn render_active_rule_editor(
         &self,
         editor: &Entity<Editor>,
+        read_only: bool,
         cx: &mut Context<Self>,
     ) -> impl IntoElement {
         let settings = ThemeSettings::get_global(cx);
+        let text_color = if read_only {
+            cx.theme().colors().text_muted
+        } else {
+            cx.theme().colors().text
+        };
 
         div()
             .w_full()
-            .on_action(cx.listener(Self::move_down_from_title))
             .pl_1()
             .border_1()
             .border_color(transparent_black())
             .rounded_sm()
-            .group_hover("active-editor-header", |this| {
-                this.border_color(cx.theme().colors().border_variant)
+            .when(!read_only, |this| {
+                this.group_hover("active-editor-header", |this| {
+                    this.border_color(cx.theme().colors().border_variant)
+                })
             })
+            .on_action(cx.listener(Self::move_down_from_title))
             .child(EditorElement::new(
                 &editor,
                 EditorStyle {
                     background: cx.theme().system().transparent,
                     local_player: cx.theme().players().local(),
                     text: TextStyle {
-                        color: cx.theme().colors().editor_foreground,
+                        color: text_color,
                         font_family: settings.ui_font.family.clone(),
                         font_features: settings.ui_font.features.clone(),
-                        font_size: HeadlineSize::Large.rems().into(),
+                        font_size: HeadlineSize::Medium.rems().into(),
                         font_weight: settings.ui_font.weight,
                         line_height: relative(settings.buffer_line_height.value()),
                         ..Default::default()
@@ -1186,6 +1219,68 @@ impl RulesLibrary {
             ))
     }
 
+    fn render_duplicate_rule_button(&self) -> impl IntoElement {
+        IconButton::new("duplicate-rule", IconName::BookCopy)
+            .tooltip(move |_window, cx| Tooltip::for_action("Duplicate Rule", &DuplicateRule, cx))
+            .on_click(|_, window, cx| {
+                window.dispatch_action(Box::new(DuplicateRule), cx);
+            })
+    }
+
+    fn render_built_in_rule_controls(&self) -> impl IntoElement {
+        h_flex()
+            .gap_1()
+            .child(self.render_duplicate_rule_button())
+            .child(
+                IconButton::new("restore-default", IconName::RotateCcw)
+                    .tooltip(move |_window, cx| {
+                        Tooltip::for_action(
+                            "Restore to Default Content",
+                            &RestoreDefaultContent,
+                            cx,
+                        )
+                    })
+                    .on_click(|_, window, cx| {
+                        window.dispatch_action(Box::new(RestoreDefaultContent), cx);
+                    }),
+            )
+    }
+
+    fn render_regular_rule_controls(&self, default: bool) -> impl IntoElement {
+        h_flex()
+            .gap_1()
+            .child(
+                IconButton::new("toggle-default-rule", IconName::Paperclip)
+                    .toggle_state(default)
+                    .when(default, |this| this.icon_color(Color::Accent))
+                    .map(|this| {
+                        if default {
+                            this.tooltip(Tooltip::text("Remove from Default Rules"))
+                        } else {
+                            this.tooltip(move |_window, cx| {
+                                Tooltip::with_meta(
+                                    "Add to Default Rules",
+                                    None,
+                                    "Always included in every thread.",
+                                    cx,
+                                )
+                            })
+                        }
+                    })
+                    .on_click(|_, window, cx| {
+                        window.dispatch_action(Box::new(ToggleDefaultRule), cx);
+                    }),
+            )
+            .child(self.render_duplicate_rule_button())
+            .child(
+                IconButton::new("delete-rule", IconName::Trash)
+                    .tooltip(move |_window, cx| Tooltip::for_action("Delete Rule", &DeleteRule, cx))
+                    .on_click(|_, window, cx| {
+                        window.dispatch_action(Box::new(DeleteRule), cx);
+                    }),
+            )
+    }
+
     fn render_active_rule(&mut self, cx: &mut Context<RulesLibrary>) -> gpui::Stateful<Div> {
         div()
             .id("rule-editor")
@@ -1198,9 +1293,9 @@ impl RulesLibrary {
                 let rule_metadata = self.store.read(cx).metadata(prompt_id)?;
                 let rule_editor = &self.rule_editors[&prompt_id];
                 let focus_handle = rule_editor.body_editor.focus_handle(cx);
-                let model = LanguageModelRegistry::read_global(cx)
-                    .default_model()
-                    .map(|default| default.model);
+                let registry = LanguageModelRegistry::read_global(cx);
+                let model = registry.default_model().map(|default| default.model);
+                let built_in = prompt_id.is_built_in();
 
                 Some(
                     v_flex()
@@ -1208,20 +1303,21 @@ impl RulesLibrary {
                         .size_full()
                         .relative()
                         .overflow_hidden()
-                        .on_click(cx.listener(move |_, _, window, _| {
-                            window.focus(&focus_handle);
+                        .on_click(cx.listener(move |_, _, window, cx| {
+                            window.focus(&focus_handle, cx);
                         }))
                         .child(
                             h_flex()
                                 .group("active-editor-header")
-                                .pt_2()
-                                .pl_1p5()
-                                .pr_2p5()
+                                .h_12()
+                                .px_2()
                                 .gap_2()
                                 .justify_between()
-                                .child(
-                                    self.render_active_rule_editor(&rule_editor.title_editor, cx),
-                                )
+                                .child(self.render_active_rule_editor(
+                                    &rule_editor.title_editor,
+                                    built_in,
+                                    cx,
+                                ))
                                 .child(
                                     h_flex()
                                         .h_full()
@@ -1258,89 +1354,15 @@ impl RulesLibrary {
                                                     .color(Color::Muted),
                                                 )
                                         }))
-                                        .child(if prompt_id.is_built_in() {
-                                            div()
-                                                .id("built-in-rule")
-                                                .child(
-                                                    Icon::new(IconName::FileLock)
-                                                        .color(Color::Muted),
-                                                )
-                                                .tooltip(move |_window, cx| {
-                                                    Tooltip::with_meta(
-                                                        "Built-in rule",
-                                                        None,
-                                                        BUILT_IN_TOOLTIP_TEXT,
-                                                        cx,
-                                                    )
-                                                })
-                                                .into_any()
-                                        } else {
-                                            IconButton::new("delete-rule", IconName::Trash)
-                                                .tooltip(move |_window, cx| {
-                                                    Tooltip::for_action(
-                                                        "Delete Rule",
-                                                        &DeleteRule,
-                                                        cx,
-                                                    )
-                                                })
-                                                .on_click(|_, window, cx| {
-                                                    window
-                                                        .dispatch_action(Box::new(DeleteRule), cx);
-                                                })
-                                                .into_any_element()
-                                        })
-                                        .child(
-                                            IconButton::new("duplicate-rule", IconName::BookCopy)
-                                                .tooltip(move |_window, cx| {
-                                                    Tooltip::for_action(
-                                                        "Duplicate Rule",
-                                                        &DuplicateRule,
-                                                        cx,
-                                                    )
-                                                })
-                                                .on_click(|_, window, cx| {
-                                                    window.dispatch_action(
-                                                        Box::new(DuplicateRule),
-                                                        cx,
-                                                    );
-                                                }),
-                                        )
-                                        .child(
-                                            IconButton::new(
-                                                "toggle-default-rule",
-                                                IconName::Paperclip,
-                                            )
-                                            .toggle_state(rule_metadata.default)
-                                            .icon_color(if rule_metadata.default {
-                                                Color::Accent
+                                        .map(|this| {
+                                            if built_in {
+                                                this.child(self.render_built_in_rule_controls())
                                             } else {
-                                                Color::Muted
-                                            })
-                                            .map(|this| {
-                                                if rule_metadata.default {
-                                                    this.tooltip(Tooltip::text(
-                                                        "Remove from Default Rules",
-                                                    ))
-                                                } else {
-                                                    this.tooltip(move |_window, cx| {
-                                                        Tooltip::with_meta(
-                                                            "Add to Default Rules",
-                                                            None,
-                                                            "Always included in every thread.",
-                                                            cx,
-                                                        )
-                                                    })
-                                                }
-                                            })
-                                            .on_click(
-                                                |_, window, cx| {
-                                                    window.dispatch_action(
-                                                        Box::new(ToggleDefaultRule),
-                                                        cx,
-                                                    );
-                                                },
-                                            ),
-                                        ),
+                                                this.child(self.render_regular_rule_controls(
+                                                    rule_metadata.default,
+                                                ))
+                                            }
+                                        }),
                                 ),
                         )
                         .child(
@@ -1385,6 +1407,9 @@ impl Render for RulesLibrary {
                 .on_action(cx.listener(|this, &ToggleDefaultRule, window, cx| {
                     this.toggle_default_for_active_rule(window, cx)
                 }))
+                .on_action(cx.listener(|this, &RestoreDefaultContent, window, cx| {
+                    this.restore_default_content_for_active_rule(window, cx)
+                }))
                 .size_full()
                 .overflow_hidden()
                 .font(ui_font)
@@ -1398,31 +1423,7 @@ impl Render for RulesLibrary {
                             this.border_t_1().border_color(cx.theme().colors().border)
                         })
                         .child(self.render_rule_list(cx))
-                        .map(|el| {
-                            if self.store.read(cx).prompt_count() == 0 {
-                                el.child(
-                                    v_flex()
-                                        .h_full()
-                                        .flex_1()
-                                        .items_center()
-                                        .justify_center()
-                                        .border_l_1()
-                                        .border_color(cx.theme().colors().border)
-                                        .bg(cx.theme().colors().editor_background)
-                                        .child(
-                                            Button::new("create-rule", "New Rule")
-                                                .style(ButtonStyle::Outlined)
-                                                .key_binding(KeyBinding::for_action(&NewRule, cx))
-                                                .on_click(|_, window, cx| {
-                                                    window
-                                                        .dispatch_action(NewRule.boxed_clone(), cx)
-                                                }),
-                                        ),
-                                )
-                            } else {
-                                el.child(self.render_active_rule(cx))
-                            }
-                        }),
+                        .child(self.render_active_rule(cx)),
                 ),
             window,
             cx,

crates/schema_generator/Cargo.toml 🔗

@@ -15,4 +15,5 @@ env_logger.workspace = true
 schemars = { workspace = true, features = ["indexmap2"] }
 serde.workspace = true
 serde_json.workspace = true
+settings.workspace = true
 theme.workspace = true

crates/schema_generator/src/main.rs 🔗

@@ -1,6 +1,7 @@
 use anyhow::Result;
 use clap::{Parser, ValueEnum};
 use schemars::schema_for;
+use settings::ProjectSettingsContent;
 use theme::{IconThemeFamilyContent, ThemeFamilyContent};
 
 #[derive(Parser, Debug)]
@@ -14,6 +15,7 @@ pub struct Args {
 pub enum SchemaType {
     Theme,
     IconTheme,
+    Project,
 }
 
 fn main() -> Result<()> {
@@ -30,6 +32,10 @@ fn main() -> Result<()> {
             let schema = schema_for!(IconThemeFamilyContent);
             println!("{}", serde_json::to_string_pretty(&schema)?);
         }
+        SchemaType::Project => {
+            let schema = schema_for!(ProjectSettingsContent);
+            println!("{}", serde_json::to_string_pretty(&schema)?);
+        }
     }
 
     Ok(())

crates/search/Cargo.toml 🔗

@@ -43,6 +43,8 @@ util_macros.workspace = true
 workspace.workspace = true
 zed_actions.workspace = true
 itertools.workspace = true
+ztracing.workspace = true
+tracing.workspace = true
 
 [dev-dependencies]
 client = { workspace = true, features = ["test-support"] }
@@ -53,3 +55,7 @@ lsp.workspace = true
 pretty_assertions.workspace = true
 unindent.workspace = true
 workspace = { workspace = true, features = ["test-support"] }
+
+[package.metadata.cargo-machete]
+ignored = ["tracing"]
+

crates/search/src/buffer_search.rs 🔗

@@ -7,7 +7,6 @@ use crate::{
     search_bar::{ActionButtonState, input_base_styles, render_action_button, render_text_input},
 };
 use any_vec::AnyVec;
-use anyhow::Context as _;
 use collections::HashMap;
 use editor::{
     DisplayPoint, Editor, EditorSettings, MultiBufferOffset,
@@ -107,7 +106,10 @@ pub struct BufferSearchBar {
     replacement_editor_focused: bool,
     active_searchable_item: Option<Box<dyn SearchableItemHandle>>,
     active_match_index: Option<usize>,
-    active_searchable_item_subscription: Option<Subscription>,
+    #[cfg(target_os = "macos")]
+    active_searchable_item_subscriptions: Option<[Subscription; 2]>,
+    #[cfg(not(target_os = "macos"))]
+    active_searchable_item_subscriptions: Option<Subscription>,
     active_search: Option<Arc<SearchQuery>>,
     searchable_items_with_matches: HashMap<Box<dyn WeakSearchableItemHandle>, AnyVec<dyn Send>>,
     pending_search: Option<Task<()>>,
@@ -473,7 +475,7 @@ impl ToolbarItemView for BufferSearchBar {
         cx: &mut Context<Self>,
     ) -> ToolbarItemLocation {
         cx.notify();
-        self.active_searchable_item_subscription.take();
+        self.active_searchable_item_subscriptions.take();
         self.active_searchable_item.take();
 
         self.pending_search.take();
@@ -483,18 +485,58 @@ impl ToolbarItemView for BufferSearchBar {
         {
             let this = cx.entity().downgrade();
 
-            self.active_searchable_item_subscription =
-                Some(searchable_item_handle.subscribe_to_search_events(
-                    window,
-                    cx,
-                    Box::new(move |search_event, window, cx| {
-                        if let Some(this) = this.upgrade() {
-                            this.update(cx, |this, cx| {
-                                this.on_active_searchable_item_event(search_event, window, cx)
-                            });
+            let search_event_subscription = searchable_item_handle.subscribe_to_search_events(
+                window,
+                cx,
+                Box::new(move |search_event, window, cx| {
+                    if let Some(this) = this.upgrade() {
+                        this.update(cx, |this, cx| {
+                            this.on_active_searchable_item_event(search_event, window, cx)
+                        });
+                    }
+                }),
+            );
+
+            #[cfg(target_os = "macos")]
+            {
+                let item_focus_handle = searchable_item_handle.item_focus_handle(cx);
+
+                self.active_searchable_item_subscriptions = Some([
+                    search_event_subscription,
+                    cx.on_focus(&item_focus_handle, window, |this, window, cx| {
+                        if this.query_editor_focused || this.replacement_editor_focused {
+                            // no need to read pasteboard since focus came from toolbar
+                            return;
                         }
+
+                        cx.defer_in(window, |this, window, cx| {
+                            if let Some(item) = cx.read_from_find_pasteboard()
+                                && let Some(text) = item.text()
+                            {
+                                if this.query(cx) != text {
+                                    let search_options = item
+                                        .metadata()
+                                        .and_then(|m| m.parse().ok())
+                                        .and_then(SearchOptions::from_bits)
+                                        .unwrap_or(this.search_options);
+
+                                    drop(this.search(
+                                        &text,
+                                        Some(search_options),
+                                        true,
+                                        window,
+                                        cx,
+                                    ));
+                                }
+                            }
+                        });
                     }),
-                ));
+                ]);
+            }
+            #[cfg(not(target_os = "macos"))]
+            {
+                self.active_searchable_item_subscriptions = Some(search_event_subscription);
+            }
 
             let is_project_search = searchable_item_handle.supported_options(cx).find_in_results;
             self.active_searchable_item = Some(searchable_item_handle);
@@ -518,7 +560,7 @@ impl BufferSearchBar {
 
     pub fn register(registrar: &mut impl SearchActionsRegistrar) {
         registrar.register_handler(ForDeployed(|this, _: &FocusSearch, window, cx| {
-            this.query_editor.focus_handle(cx).focus(window);
+            this.query_editor.focus_handle(cx).focus(window, cx);
             this.select_query(window, cx);
         }));
         registrar.register_handler(ForDeployed(
@@ -634,15 +676,19 @@ impl BufferSearchBar {
                 .read(cx)
                 .as_singleton()
                 .expect("query editor should be backed by a singleton buffer");
+
             query_buffer
                 .read(cx)
                 .set_language_registry(languages.clone());
 
             cx.spawn(async move |buffer_search_bar, cx| {
+                use anyhow::Context as _;
+
                 let regex_language = languages
                     .language_for_name("regex")
                     .await
                     .context("loading regex language")?;
+
                 buffer_search_bar
                     .update(cx, |buffer_search_bar, cx| {
                         buffer_search_bar.regex_language = Some(regex_language);
@@ -660,7 +706,7 @@ impl BufferSearchBar {
             replacement_editor,
             replacement_editor_focused: false,
             active_searchable_item: None,
-            active_searchable_item_subscription: None,
+            active_searchable_item_subscriptions: None,
             active_match_index: None,
             searchable_items_with_matches: Default::default(),
             default_options: search_options,
@@ -706,7 +752,7 @@ impl BufferSearchBar {
             active_editor.search_bar_visibility_changed(false, window, cx);
             active_editor.toggle_filtered_search_ranges(None, window, cx);
             let handle = active_editor.item_focus_handle(cx);
-            self.focus(&handle, window);
+            self.focus(&handle, window, cx);
         }
 
         cx.emit(Event::UpdateLocation);
@@ -729,12 +775,14 @@ impl BufferSearchBar {
             self.search_suggested(window, cx);
             self.smartcase(window, cx);
             self.sync_select_next_case_sensitivity(cx);
-            self.replace_enabled = deploy.replace_enabled;
-            self.selection_search_enabled = if deploy.selection_search_enabled {
-                Some(FilteredSearchRange::Default)
-            } else {
-                None
-            };
+            self.replace_enabled |= deploy.replace_enabled;
+            self.selection_search_enabled =
+                self.selection_search_enabled
+                    .or(if deploy.selection_search_enabled {
+                        Some(FilteredSearchRange::Default)
+                    } else {
+                        None
+                    });
             if deploy.focus {
                 let mut handle = self.query_editor.focus_handle(cx);
                 let mut select_query = true;
@@ -747,7 +795,7 @@ impl BufferSearchBar {
                     self.select_query(window, cx);
                 }
 
-                window.focus(&handle);
+                window.focus(&handle, cx);
             }
             return true;
         }
@@ -876,7 +924,7 @@ impl BufferSearchBar {
     }
 
     pub fn focus_replace(&mut self, window: &mut Window, cx: &mut Context<Self>) {
-        self.focus(&self.replacement_editor.focus_handle(cx), window);
+        self.focus(&self.replacement_editor.focus_handle(cx), window, cx);
         cx.notify();
     }
 
@@ -899,15 +947,25 @@ impl BufferSearchBar {
             });
             self.set_search_options(options, cx);
             self.clear_matches(window, cx);
+            #[cfg(target_os = "macos")]
+            self.update_find_pasteboard(cx);
             cx.notify();
         }
         self.update_matches(!updated, add_to_history, window, cx)
     }
 
+    #[cfg(target_os = "macos")]
+    pub fn update_find_pasteboard(&mut self, cx: &mut App) {
+        cx.write_to_find_pasteboard(gpui::ClipboardItem::new_string_with_metadata(
+            self.query(cx),
+            self.search_options.bits().to_string(),
+        ));
+    }
+
     pub fn focus_editor(&mut self, _: &FocusEditor, window: &mut Window, cx: &mut Context<Self>) {
         if let Some(active_editor) = self.active_searchable_item.as_ref() {
             let handle = active_editor.item_focus_handle(cx);
-            window.focus(&handle);
+            window.focus(&handle, cx);
         }
     }
 
@@ -1031,7 +1089,7 @@ impl BufferSearchBar {
             let new_match_index = searchable_item
                 .match_index_for_direction(matches, index, direction, count, window, cx);
 
-            searchable_item.update_matches(matches, window, cx);
+            searchable_item.update_matches(matches, Some(new_match_index), window, cx);
             searchable_item.activate_match(new_match_index, matches, window, cx);
         }
     }
@@ -1045,7 +1103,7 @@ impl BufferSearchBar {
             if matches.is_empty() {
                 return;
             }
-            searchable_item.update_matches(matches, window, cx);
+            searchable_item.update_matches(matches, Some(0), window, cx);
             searchable_item.activate_match(0, matches, window, cx);
         }
     }
@@ -1060,7 +1118,7 @@ impl BufferSearchBar {
                 return;
             }
             let new_match_index = matches.len() - 1;
-            searchable_item.update_matches(matches, window, cx);
+            searchable_item.update_matches(matches, Some(new_match_index), window, cx);
             searchable_item.activate_match(new_match_index, matches, window, cx);
         }
     }
@@ -1093,11 +1151,12 @@ impl BufferSearchBar {
                 cx.spawn_in(window, async move |this, cx| {
                     if search.await.is_ok() {
                         this.update_in(cx, |this, window, cx| {
-                            this.activate_current_match(window, cx)
-                        })
-                    } else {
-                        Ok(())
+                            this.activate_current_match(window, cx);
+                            #[cfg(target_os = "macos")]
+                            this.update_find_pasteboard(cx);
+                        })?;
                     }
+                    anyhow::Ok(())
                 })
                 .detach_and_log_err(cx);
             }
@@ -1288,6 +1347,7 @@ impl BufferSearchBar {
                                 .insert(active_searchable_item.downgrade(), matches);
 
                             this.update_match_index(window, cx);
+
                             if add_to_history {
                                 this.search_history
                                     .add(&mut this.search_history_cursor, query_text);
@@ -1300,7 +1360,12 @@ impl BufferSearchBar {
                                 if matches.is_empty() {
                                     active_searchable_item.clear_matches(window, cx);
                                 } else {
-                                    active_searchable_item.update_matches(matches, window, cx);
+                                    active_searchable_item.update_matches(
+                                        matches,
+                                        this.active_match_index,
+                                        window,
+                                        cx,
+                                    );
                                 }
                                 let _ = done_tx.send(());
                             }
@@ -1335,6 +1400,18 @@ impl BufferSearchBar {
             });
         if new_index != self.active_match_index {
             self.active_match_index = new_index;
+            if !self.dismissed {
+                if let Some(searchable_item) = self.active_searchable_item.as_ref() {
+                    if let Some(matches) = self
+                        .searchable_items_with_matches
+                        .get(&searchable_item.downgrade())
+                    {
+                        if !matches.is_empty() {
+                            searchable_item.update_matches(matches, new_index, window, cx);
+                        }
+                    }
+                }
+            }
             cx.notify();
         }
     }
@@ -1365,7 +1442,7 @@ impl BufferSearchBar {
             Direction::Prev => (current_index - 1) % handles.len(),
         };
         let next_focus_handle = &handles[new_index];
-        self.focus(next_focus_handle, window);
+        self.focus(next_focus_handle, window, cx);
         cx.stop_propagation();
     }
 
@@ -1412,9 +1489,9 @@ impl BufferSearchBar {
         }
     }
 
-    fn focus(&self, handle: &gpui::FocusHandle, window: &mut Window) {
+    fn focus(&self, handle: &gpui::FocusHandle, window: &mut Window, cx: &mut App) {
         window.invalidate_character_coordinates();
-        window.focus(handle);
+        window.focus(handle, cx);
     }
 
     fn toggle_replace(&mut self, _: &ToggleReplace, window: &mut Window, cx: &mut Context<Self>) {
@@ -1425,7 +1502,7 @@ impl BufferSearchBar {
             } else {
                 self.query_editor.focus_handle(cx)
             };
-            self.focus(&handle, window);
+            self.focus(&handle, window, cx);
             cx.notify();
         }
     }
@@ -2019,7 +2096,7 @@ mod tests {
             .update(cx, |_, window, cx| {
                 search_bar.update(cx, |search_bar, cx| {
                     let handle = search_bar.query_editor.focus_handle(cx);
-                    window.focus(&handle);
+                    window.focus(&handle, cx);
                     search_bar.activate_current_match(window, cx);
                 });
                 assert!(
@@ -2037,7 +2114,7 @@ mod tests {
                 search_bar.update(cx, |search_bar, cx| {
                     assert_eq!(search_bar.active_match_index, Some(0));
                     let handle = search_bar.query_editor.focus_handle(cx);
-                    window.focus(&handle);
+                    window.focus(&handle, cx);
                     search_bar.select_all_matches(&SelectAllMatches, window, cx);
                 });
                 assert!(
@@ -2090,7 +2167,7 @@ mod tests {
                         "Match index should be updated to the next one"
                     );
                     let handle = search_bar.query_editor.focus_handle(cx);
-                    window.focus(&handle);
+                    window.focus(&handle, cx);
                     search_bar.select_all_matches(&SelectAllMatches, window, cx);
                 });
             })
@@ -2156,7 +2233,7 @@ mod tests {
             .update(cx, |_, window, cx| {
                 search_bar.update(cx, |search_bar, cx| {
                     let handle = search_bar.query_editor.focus_handle(cx);
-                    window.focus(&handle);
+                    window.focus(&handle, cx);
                     search_bar.search("abas_nonexistent_match", None, true, window, cx)
                 })
             })

crates/search/src/project_search.rs 🔗

@@ -954,9 +954,9 @@ impl ProjectSearchView {
             cx.on_next_frame(window, |this, window, cx| {
                 if this.focus_handle.is_focused(window) {
                     if this.has_matches() {
-                        this.results_editor.focus_handle(cx).focus(window);
+                        this.results_editor.focus_handle(cx).focus(window, cx);
                     } else {
-                        this.query_editor.focus_handle(cx).focus(window);
+                        this.query_editor.focus_handle(cx).focus(window, cx);
                     }
                 }
             });
@@ -1147,7 +1147,7 @@ impl ProjectSearchView {
         };
 
         search.update(cx, |search, cx| {
-            search.replace_enabled = action.replace_enabled;
+            search.replace_enabled |= action.replace_enabled;
             if let Some(query) = query {
                 search.set_query(&query, window, cx);
             }
@@ -1444,6 +1444,7 @@ impl ProjectSearchView {
                     s.select_ranges([range_to_select])
                 });
             });
+            self.highlight_matches(&match_ranges, Some(new_index), cx);
         }
     }
 
@@ -1452,7 +1453,7 @@ impl ProjectSearchView {
             query_editor.select_all(&SelectAll, window, cx);
         });
         let editor_handle = self.query_editor.focus_handle(cx);
-        window.focus(&editor_handle);
+        window.focus(&editor_handle, cx);
     }
 
     fn set_query(&mut self, query: &str, window: &mut Window, cx: &mut Context<Self>) {
@@ -1492,7 +1493,7 @@ impl ProjectSearchView {
             });
         });
         let results_handle = self.results_editor.focus_handle(cx);
-        window.focus(&results_handle);
+        window.focus(&results_handle, cx);
     }
 
     fn entity_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
@@ -1518,11 +1519,6 @@ impl ProjectSearchView {
                     });
                     editor.scroll(Point::default(), Some(Axis::Vertical), window, cx);
                 }
-                editor.highlight_background::<Self>(
-                    &match_ranges,
-                    |theme| theme.colors().search_match_background,
-                    cx,
-                );
             });
             if is_new_search && self.query_editor.focus_handle(cx).is_focused(window) {
                 self.focus_results_editor(window, cx);
@@ -1535,18 +1531,48 @@ impl ProjectSearchView {
 
     fn update_match_index(&mut self, cx: &mut Context<Self>) {
         let results_editor = self.results_editor.read(cx);
-        let new_index = active_match_index(
-            Direction::Next,
-            &self.entity.read(cx).match_ranges,
-            &results_editor.selections.newest_anchor().head(),
-            &results_editor.buffer().read(cx).snapshot(cx),
-        );
+        let newest_anchor = results_editor.selections.newest_anchor().head();
+        let buffer_snapshot = results_editor.buffer().read(cx).snapshot(cx);
+        let new_index = self.entity.update(cx, |this, cx| {
+            let new_index = active_match_index(
+                Direction::Next,
+                &this.match_ranges,
+                &newest_anchor,
+                &buffer_snapshot,
+            );
+
+            self.highlight_matches(&this.match_ranges, new_index, cx);
+            new_index
+        });
+
         if self.active_match_index != new_index {
             self.active_match_index = new_index;
             cx.notify();
         }
     }
 
+    #[ztracing::instrument(skip_all)]
+    fn highlight_matches(
+        &self,
+        match_ranges: &[Range<Anchor>],
+        active_index: Option<usize>,
+        cx: &mut App,
+    ) {
+        self.results_editor.update(cx, |editor, cx| {
+            editor.highlight_background::<Self>(
+                match_ranges,
+                move |index, theme| {
+                    if active_index == Some(*index) {
+                        theme.colors().search_active_match_background
+                    } else {
+                        theme.colors().search_match_background
+                    }
+                },
+                cx,
+            );
+        });
+    }
+
     pub fn has_matches(&self) -> bool {
         self.active_match_index.is_some()
     }
@@ -1730,7 +1756,7 @@ impl ProjectSearchBar {
     fn focus_search(&mut self, window: &mut Window, cx: &mut Context<Self>) {
         if let Some(search_view) = self.active_project_search.as_ref() {
             search_view.update(cx, |search_view, cx| {
-                search_view.query_editor.focus_handle(cx).focus(window);
+                search_view.query_editor.focus_handle(cx).focus(window, cx);
             });
         }
     }
@@ -1763,7 +1789,7 @@ impl ProjectSearchBar {
                 Direction::Prev => (current_index - 1) % views.len(),
             };
             let next_focus_handle = &views[new_index];
-            window.focus(next_focus_handle);
+            window.focus(next_focus_handle, cx);
             cx.stop_propagation();
         });
     }
@@ -1812,7 +1838,7 @@ impl ProjectSearchBar {
                 } else {
                     this.query_editor.focus_handle(cx)
                 };
-                window.focus(&editor_to_focus);
+                window.focus(&editor_to_focus, cx);
                 cx.notify();
             });
         }
@@ -2456,7 +2482,9 @@ pub mod tests {
     use pretty_assertions::assert_eq;
     use project::FakeFs;
     use serde_json::json;
-    use settings::{InlayHintSettingsContent, SettingsStore};
+    use settings::{
+        InlayHintSettingsContent, SettingsStore, ThemeColorsContent, ThemeStyleContent,
+    };
     use util::{path, paths::PathStyle, rel_path::rel_path};
     use util_macros::perf;
     use workspace::DeploySearch;
@@ -2464,8 +2492,105 @@ pub mod tests {
     #[perf]
     #[gpui::test]
     async fn test_project_search(cx: &mut TestAppContext) {
+        fn dp(row: u32, col: u32) -> DisplayPoint {
+            DisplayPoint::new(DisplayRow(row), col)
+        }
+
+        fn assert_active_match_index(
+            search_view: &WindowHandle<ProjectSearchView>,
+            cx: &mut TestAppContext,
+            expected_index: usize,
+        ) {
+            search_view
+                .update(cx, |search_view, _window, _cx| {
+                    assert_eq!(search_view.active_match_index, Some(expected_index));
+                })
+                .unwrap();
+        }
+
+        fn assert_selection_range(
+            search_view: &WindowHandle<ProjectSearchView>,
+            cx: &mut TestAppContext,
+            expected_range: Range<DisplayPoint>,
+        ) {
+            search_view
+                .update(cx, |search_view, _window, cx| {
+                    assert_eq!(
+                        search_view.results_editor.update(cx, |editor, cx| editor
+                            .selections
+                            .display_ranges(&editor.display_snapshot(cx))),
+                        [expected_range]
+                    );
+                })
+                .unwrap();
+        }
+
+        fn assert_highlights(
+            search_view: &WindowHandle<ProjectSearchView>,
+            cx: &mut TestAppContext,
+            expected_highlights: Vec<(Range<DisplayPoint>, &str)>,
+        ) {
+            search_view
+                .update(cx, |search_view, window, cx| {
+                    let match_bg = cx.theme().colors().search_match_background;
+                    let active_match_bg = cx.theme().colors().search_active_match_background;
+                    let selection_bg = cx
+                        .theme()
+                        .colors()
+                        .editor_document_highlight_bracket_background;
+
+                    let highlights: Vec<_> = expected_highlights
+                        .into_iter()
+                        .map(|(range, color_type)| {
+                            let color = match color_type {
+                                "active" => active_match_bg,
+                                "match" => match_bg,
+                                "selection" => selection_bg,
+                                _ => panic!("Unknown color type"),
+                            };
+                            (range, color)
+                        })
+                        .collect();
+
+                    assert_eq!(
+                        search_view.results_editor.update(cx, |editor, cx| editor
+                            .all_text_background_highlights(window, cx)),
+                        highlights.as_slice()
+                    );
+                })
+                .unwrap();
+        }
+
+        fn select_match(
+            search_view: &WindowHandle<ProjectSearchView>,
+            cx: &mut TestAppContext,
+            direction: Direction,
+        ) {
+            search_view
+                .update(cx, |search_view, window, cx| {
+                    search_view.select_match(direction, window, cx);
+                })
+                .unwrap();
+        }
+
         init_test(cx);
 
+        // Override active search match color since the fallback theme uses the same color
+        // for normal search match and active one, which can make this test less robust.
+        cx.update(|cx| {
+            SettingsStore::update_global(cx, |settings, cx| {
+                settings.update_user_settings(cx, |settings| {
+                    settings.theme.experimental_theme_overrides = Some(ThemeStyleContent {
+                        colors: ThemeColorsContent {
+                            search_active_match_background: Some("#ff0000ff".to_string()),
+                            ..Default::default()
+                        },
+                        ..Default::default()
+                    });
+                });
+            });
+        });
+
         let fs = FakeFs::new(cx.background_executor.clone());
         fs.insert_tree(
             path!("/dir"),
@@ -2486,113 +2611,113 @@ pub mod tests {
         });
 
         perform_search(search_view, "TWO", cx);
-        search_view.update(cx, |search_view, window, cx| {
-            assert_eq!(
-                search_view
-                    .results_editor
-                    .update(cx, |editor, cx| editor.display_text(cx)),
-                "\n\nconst THREE: usize = one::ONE + two::TWO;\n\n\nconst TWO: usize = one::ONE + one::ONE;"
-            );
-            let match_background_color = cx.theme().colors().search_match_background;
-            let selection_background_color = cx.theme().colors().editor_document_highlight_bracket_background;
-            assert_eq!(
-                search_view
-                    .results_editor
-                    .update(cx, |editor, cx| editor.all_text_background_highlights(window, cx)),
-                &[
-                    (
-                        DisplayPoint::new(DisplayRow(2), 32)..DisplayPoint::new(DisplayRow(2), 35),
-                        match_background_color
-                    ),
-                    (
-                        DisplayPoint::new(DisplayRow(2), 37)..DisplayPoint::new(DisplayRow(2), 40),
-                        selection_background_color
-                    ),
-                    (
-                        DisplayPoint::new(DisplayRow(2), 37)..DisplayPoint::new(DisplayRow(2), 40),
-                        match_background_color
-                    ),
-                    (
-                        DisplayPoint::new(DisplayRow(5), 6)..DisplayPoint::new(DisplayRow(5), 9),
-                        match_background_color
-                    ),
-
-                ]
-            );
-            assert_eq!(search_view.active_match_index, Some(0));
-            assert_eq!(
-                search_view
-                    .results_editor
-                    .update(cx, |editor, cx| editor.selections.display_ranges(&editor.display_snapshot(cx))),
-                [DisplayPoint::new(DisplayRow(2), 32)..DisplayPoint::new(DisplayRow(2), 35)]
-            );
-
-            search_view.select_match(Direction::Next, window, cx);
-        }).unwrap();
+        cx.run_until_parked();
 
         search_view
-            .update(cx, |search_view, window, cx| {
-                assert_eq!(search_view.active_match_index, Some(1));
+            .update(cx, |search_view, _window, cx| {
                 assert_eq!(
-                    search_view.results_editor.update(cx, |editor, cx| editor
-                        .selections
-                        .display_ranges(&editor.display_snapshot(cx))),
-                    [DisplayPoint::new(DisplayRow(2), 37)..DisplayPoint::new(DisplayRow(2), 40)]
+                    search_view
+                        .results_editor
+                        .update(cx, |editor, cx| editor.display_text(cx)),
+                    "\n\nconst THREE: usize = one::ONE + two::TWO;\n\n\nconst TWO: usize = one::ONE + one::ONE;"
                 );
-                search_view.select_match(Direction::Next, window, cx);
             })
             .unwrap();
 
-        search_view
-            .update(cx, |search_view, window, cx| {
-                assert_eq!(search_view.active_match_index, Some(2));
-                assert_eq!(
-                    search_view.results_editor.update(cx, |editor, cx| editor
-                        .selections
-                        .display_ranges(&editor.display_snapshot(cx))),
-                    [DisplayPoint::new(DisplayRow(5), 6)..DisplayPoint::new(DisplayRow(5), 9)]
-                );
-                search_view.select_match(Direction::Next, window, cx);
-            })
-            .unwrap();
+        assert_active_match_index(&search_view, cx, 0);
+        assert_selection_range(&search_view, cx, dp(2, 32)..dp(2, 35));
+        assert_highlights(
+            &search_view,
+            cx,
+            vec![
+                (dp(2, 32)..dp(2, 35), "active"),
+                (dp(2, 37)..dp(2, 40), "selection"),
+                (dp(2, 37)..dp(2, 40), "match"),
+                (dp(5, 6)..dp(5, 9), "match"),
+                // TODO: we should be getting selection highlight here after project search
+                // but for some reason we are not getting it here
+            ],
+        );
+        select_match(&search_view, cx, Direction::Next);
+        cx.run_until_parked();
 
-        search_view
-            .update(cx, |search_view, window, cx| {
-                assert_eq!(search_view.active_match_index, Some(0));
-                assert_eq!(
-                    search_view.results_editor.update(cx, |editor, cx| editor
-                        .selections
-                        .display_ranges(&editor.display_snapshot(cx))),
-                    [DisplayPoint::new(DisplayRow(2), 32)..DisplayPoint::new(DisplayRow(2), 35)]
-                );
-                search_view.select_match(Direction::Prev, window, cx);
-            })
-            .unwrap();
+        assert_active_match_index(&search_view, cx, 1);
+        assert_selection_range(&search_view, cx, dp(2, 37)..dp(2, 40));
+        assert_highlights(
+            &search_view,
+            cx,
+            vec![
+                (dp(2, 32)..dp(2, 35), "selection"),
+                (dp(2, 32)..dp(2, 35), "match"),
+                (dp(2, 37)..dp(2, 40), "active"),
+                (dp(5, 6)..dp(5, 9), "selection"),
+                (dp(5, 6)..dp(5, 9), "match"),
+            ],
+        );
+        select_match(&search_view, cx, Direction::Next);
+        cx.run_until_parked();
 
-        search_view
-            .update(cx, |search_view, window, cx| {
-                assert_eq!(search_view.active_match_index, Some(2));
-                assert_eq!(
-                    search_view.results_editor.update(cx, |editor, cx| editor
-                        .selections
-                        .display_ranges(&editor.display_snapshot(cx))),
-                    [DisplayPoint::new(DisplayRow(5), 6)..DisplayPoint::new(DisplayRow(5), 9)]
-                );
-                search_view.select_match(Direction::Prev, window, cx);
-            })
-            .unwrap();
+        assert_active_match_index(&search_view, cx, 2);
+        assert_selection_range(&search_view, cx, dp(5, 6)..dp(5, 9));
+        assert_highlights(
+            &search_view,
+            cx,
+            vec![
+                (dp(2, 32)..dp(2, 35), "selection"),
+                (dp(2, 32)..dp(2, 35), "match"),
+                (dp(2, 37)..dp(2, 40), "selection"),
+                (dp(2, 37)..dp(2, 40), "match"),
+                (dp(5, 6)..dp(5, 9), "active"),
+            ],
+        );
+        select_match(&search_view, cx, Direction::Next);
+        cx.run_until_parked();
 
-        search_view
-            .update(cx, |search_view, _, cx| {
-                assert_eq!(search_view.active_match_index, Some(1));
-                assert_eq!(
-                    search_view.results_editor.update(cx, |editor, cx| editor
-                        .selections
-                        .display_ranges(&editor.display_snapshot(cx))),
-                    [DisplayPoint::new(DisplayRow(2), 37)..DisplayPoint::new(DisplayRow(2), 40)]
-                );
-            })
-            .unwrap();
+        assert_active_match_index(&search_view, cx, 0);
+        assert_selection_range(&search_view, cx, dp(2, 32)..dp(2, 35));
+        assert_highlights(
+            &search_view,
+            cx,
+            vec![
+                (dp(2, 32)..dp(2, 35), "active"),
+                (dp(2, 37)..dp(2, 40), "selection"),
+                (dp(2, 37)..dp(2, 40), "match"),
+                (dp(5, 6)..dp(5, 9), "selection"),
+                (dp(5, 6)..dp(5, 9), "match"),
+            ],
+        );
+        select_match(&search_view, cx, Direction::Prev);
+        cx.run_until_parked();
+
+        assert_active_match_index(&search_view, cx, 2);
+        assert_selection_range(&search_view, cx, dp(5, 6)..dp(5, 9));
+        assert_highlights(
+            &search_view,
+            cx,
+            vec![
+                (dp(2, 32)..dp(2, 35), "selection"),
+                (dp(2, 32)..dp(2, 35), "match"),
+                (dp(2, 37)..dp(2, 40), "selection"),
+                (dp(2, 37)..dp(2, 40), "match"),
+                (dp(5, 6)..dp(5, 9), "active"),
+            ],
+        );
+        select_match(&search_view, cx, Direction::Prev);
+        cx.run_until_parked();
+
+        assert_active_match_index(&search_view, cx, 1);
+        assert_selection_range(&search_view, cx, dp(2, 37)..dp(2, 40));
+        assert_highlights(
+            &search_view,
+            cx,
+            vec![
+                (dp(2, 32)..dp(2, 35), "selection"),
+                (dp(2, 32)..dp(2, 35), "match"),
+                (dp(2, 37)..dp(2, 40), "active"),
+                (dp(5, 6)..dp(5, 9), "selection"),
+                (dp(5, 6)..dp(5, 9), "match"),
+            ],
+        );
     }
 
     #[perf]
@@ -4233,7 +4358,7 @@ pub mod tests {
         let buffer_search_query = "search bar query";
         buffer_search_bar
             .update_in(&mut cx, |buffer_search_bar, window, cx| {
-                buffer_search_bar.focus_handle(cx).focus(window);
+                buffer_search_bar.focus_handle(cx).focus(window, cx);
                 buffer_search_bar.search(buffer_search_query, None, true, window, cx)
             })
             .await

crates/search/src/search.rs 🔗

@@ -143,7 +143,7 @@ impl SearchOption {
                 let focus_handle = focus_handle.clone();
                 button.on_click(move |_: &ClickEvent, window, cx| {
                     if !focus_handle.is_focused(window) {
-                        window.focus(&focus_handle);
+                        window.focus(&focus_handle, cx);
                     }
                     window.dispatch_action(action.boxed_clone(), cx);
                 })

crates/search/src/search_bar.rs 🔗

@@ -27,7 +27,7 @@ pub(super) fn render_action_button(
         let focus_handle = focus_handle.clone();
         move |_, window, cx| {
             if !focus_handle.is_focused(window) {
-                window.focus(&focus_handle);
+                window.focus(&focus_handle, cx);
             }
             window.dispatch_action(action.boxed_clone(), cx);
         }

crates/settings/src/keymap_file.rs 🔗

@@ -15,6 +15,7 @@ use util::ResultExt as _;
 use util::{
     asset_str,
     markdown::{MarkdownEscaped, MarkdownInlineCode, MarkdownString},
+    schemars::AllowTrailingCommas,
 };
 
 use crate::SettingsAssets;
@@ -302,19 +303,21 @@ impl KeymapFile {
         if errors.is_empty() {
             KeymapFileLoadResult::Success { key_bindings }
         } else {
-            let mut error_message = "Errors in user keymap file.\n".to_owned();
+            let mut error_message = "Errors in user keymap file.".to_owned();
+
             for (context, section_errors) in errors {
                 if context.is_empty() {
-                    let _ = write!(error_message, "\n\nIn section without context predicate:");
+                    let _ = write!(error_message, "\nIn section without context predicate:");
                 } else {
                     let _ = write!(
                         error_message,
-                        "\n\nIn section with {}:",
+                        "\nIn section with {}:",
                         MarkdownInlineCode(&format!("context = \"{}\"", context))
                     );
                 }
                 let _ = write!(error_message, "{section_errors}");
             }
+
             KeymapFileLoadResult::SomeFailedToLoad {
                 key_bindings,
                 error_message: MarkdownString(error_message),
@@ -451,7 +454,9 @@ impl KeymapFile {
     /// Creates a JSON schema generator, suitable for generating json schemas
     /// for actions
     pub fn action_schema_generator() -> schemars::SchemaGenerator {
-        schemars::generate::SchemaSettings::draft2019_09().into_generator()
+        schemars::generate::SchemaSettings::draft2019_09()
+            .with_transform(AllowTrailingCommas)
+            .into_generator()
     }
 
     pub fn generate_json_schema_for_registered_actions(cx: &mut App) -> Value {

crates/settings/src/merge_from.rs 🔗

@@ -56,6 +56,7 @@ merge_from_overwrites!(
     std::sync::Arc<str>,
     gpui::SharedString,
     std::path::PathBuf,
+    std::sync::Arc<std::path::Path>,
     gpui::Modifiers,
     gpui::FontFeatures,
     gpui::FontWeight

crates/settings/src/settings.rs 🔗

@@ -33,8 +33,9 @@ pub use serde_helper::*;
 pub use settings_file::*;
 pub use settings_json::*;
 pub use settings_store::{
-    InvalidSettingsError, LocalSettingsKind, MigrationStatus, ParseStatus, Settings, SettingsFile,
-    SettingsJsonSchemaParams, SettingsKey, SettingsLocation, SettingsParseResult, SettingsStore,
+    InvalidSettingsError, LSP_SETTINGS_SCHEMA_URL_PREFIX, LocalSettingsKind, MigrationStatus,
+    ParseStatus, Settings, SettingsFile, SettingsJsonSchemaParams, SettingsKey, SettingsLocation,
+    SettingsParseResult, SettingsStore,
 };
 
 pub use vscode_import::{VsCodeSettings, VsCodeSettingsSource};

crates/settings/src/settings_content.rs 🔗

@@ -158,6 +158,9 @@ pub struct SettingsContent {
     /// Default: false
     pub disable_ai: Option<SaturatingBool>,
 
+    /// Settings for the which-key popup.
+    pub which_key: Option<WhichKeySettingsContent>,
+
     /// Settings related to Vim mode in Zed.
     pub vim: Option<VimSettingsContent>,
 }
@@ -286,6 +289,10 @@ pub struct TitleBarSettingsContent {
     ///
     /// Default: true
     pub show_sign_in: Option<bool>,
+    /// Whether to show the user menu button in the title bar.
+    ///
+    /// Default: true
+    pub show_user_menu: Option<bool>,
     /// Whether to show the menus in the title bar.
     ///
     /// Default: false
@@ -511,6 +518,11 @@ pub struct GitPanelSettingsContent {
     ///
     /// Default: false
     pub collapse_untracked_diff: Option<bool>,
+
+    /// Whether to show entries with tree or flat view in the panel
+    ///
+    /// Default: false
+    pub tree_view: Option<bool>,
 }
 
 #[derive(
@@ -889,9 +901,19 @@ pub enum ImageFileSizeUnit {
 pub struct RemoteSettingsContent {
     pub ssh_connections: Option<Vec<SshConnection>>,
     pub wsl_connections: Option<Vec<WslConnection>>,
+    pub dev_container_connections: Option<Vec<DevContainerConnection>>,
     pub read_ssh_config: Option<bool>,
 }
 
+#[with_fallible_options]
+#[derive(
+    Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq, JsonSchema, MergeFrom, Hash,
+)]
+pub struct DevContainerConnection {
+    pub name: SharedString,
+    pub container_id: SharedString,
+}
+
 #[with_fallible_options]
 #[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, JsonSchema, MergeFrom)]
 pub struct SshConnection {
@@ -901,7 +923,7 @@ pub struct SshConnection {
     #[serde(default)]
     pub args: Vec<String>,
     #[serde(default)]
-    pub projects: collections::BTreeSet<SshProject>,
+    pub projects: collections::BTreeSet<RemoteProject>,
     /// Name to use for this server in UI.
     pub nickname: Option<String>,
     // By default Zed will download the binary to the host directly.
@@ -911,6 +933,9 @@ pub struct SshConnection {
     pub upload_binary_over_ssh: Option<bool>,
 
     pub port_forwards: Option<Vec<SshPortForwardOption>>,
+    /// Timeout in seconds for SSH connection and downloading the remote server binary.
+    /// Defaults to 10 seconds if not specified.
+    pub connection_timeout: Option<u16>,
 }
 
 #[derive(Clone, Default, Serialize, Deserialize, PartialEq, JsonSchema, MergeFrom, Debug)]
@@ -918,14 +943,14 @@ pub struct WslConnection {
     pub distro_name: SharedString,
     pub user: Option<String>,
     #[serde(default)]
-    pub projects: BTreeSet<SshProject>,
+    pub projects: BTreeSet<RemoteProject>,
 }
 
 #[with_fallible_options]
 #[derive(
     Clone, Debug, Default, Serialize, PartialEq, Eq, PartialOrd, Ord, Deserialize, JsonSchema,
 )]
-pub struct SshProject {
+pub struct RemoteProject {
     pub paths: Vec<String>,
 }
 
@@ -954,6 +979,19 @@ pub struct ReplSettingsContent {
     pub max_columns: Option<usize>,
 }
 
+/// Settings for configuring the which-key popup behaviour.
+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, JsonSchema, MergeFrom)]
+pub struct WhichKeySettingsContent {
+    /// Whether to show the which-key popup when holding down key combinations
+    ///
+    /// Default: false
+    pub enabled: Option<bool>,
+    /// Delay in milliseconds before showing the which-key popup.
+    ///
+    /// Default: 700
+    pub delay_ms: Option<u64>,
+}
+
 #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
 /// An ExtendingVec in the settings can only accumulate new values.
 ///

crates/settings/src/settings_content/agent.rs 🔗

@@ -5,7 +5,7 @@ use serde::{Deserialize, Serialize};
 use settings_macros::{MergeFrom, with_fallible_options};
 use std::{borrow::Cow, path::PathBuf, sync::Arc};
 
-use crate::DockPosition;
+use crate::{DockPosition, DockSide};
 
 #[with_fallible_options]
 #[derive(Clone, PartialEq, Serialize, Deserialize, JsonSchema, MergeFrom, Debug, Default)]
@@ -22,6 +22,10 @@ pub struct AgentSettingsContent {
     ///
     /// Default: right
     pub dock: Option<DockPosition>,
+    /// Where to dock the utility pane (the thread view pane).
+    ///
+    /// Default: left
+    pub agents_panel_dock: Option<DockSide>,
     /// Default width in pixels when the agent panel is docked to the left or right.
     ///
     /// Default: 640
@@ -34,9 +38,18 @@ pub struct AgentSettingsContent {
     pub default_height: Option<f32>,
     /// The default model to use when creating new chats and for other features when a specific model is not specified.
     pub default_model: Option<LanguageModelSelection>,
+    /// Favorite models to show at the top of the model selector.
+    #[serde(default)]
+    pub favorite_models: Vec<LanguageModelSelection>,
     /// Model to use for the inline assistant. Defaults to default_model when not specified.
     pub inline_assistant_model: Option<LanguageModelSelection>,
-    /// Model to use for generating git commit messages. Defaults to default_model when not specified.
+    /// Model to use for the inline assistant when streaming tools are enabled.
+    ///
+    /// Default: true
+    pub inline_assistant_use_streaming_tools: Option<bool>,
+    /// Model to use for generating git commit messages.
+    ///
+    /// Default: true
     pub commit_message_model: Option<LanguageModelSelection>,
     /// Model to use for generating thread summaries. Defaults to default_model when not specified.
     pub thread_summary_model: Option<LanguageModelSelection>,
@@ -129,6 +142,9 @@ impl AgentSettingsContent {
             model,
         });
     }
+    pub fn set_inline_assistant_use_streaming_tools(&mut self, use_tools: bool) {
+        self.inline_assistant_use_streaming_tools = Some(use_tools);
+    }
 
     pub fn set_commit_message_model(&mut self, provider: String, model: String) {
         self.commit_message_model = Some(LanguageModelSelection {
@@ -163,6 +179,16 @@ impl AgentSettingsContent {
     pub fn set_profile(&mut self, profile_id: Arc<str>) {
         self.default_profile = Some(profile_id);
     }
+
+    pub fn add_favorite_model(&mut self, model: LanguageModelSelection) {
+        if !self.favorite_models.contains(&model) {
+            self.favorite_models.push(model);
+        }
+    }
+
+    pub fn remove_favorite_model(&mut self, model: &LanguageModelSelection) {
+        self.favorite_models.retain(|m| m != model);
+    }
 }
 
 #[with_fallible_options]
@@ -337,6 +363,13 @@ pub struct BuiltinAgentServerSettings {
     ///
     /// Default: None
     pub default_model: Option<String>,
+    /// The favorite models for this agent.
+    ///
+    /// These are the model IDs as reported by the agent.
+    ///
+    /// Default: []
+    #[serde(default)]
+    pub favorite_models: Vec<String>,
 }
 
 #[with_fallible_options]
@@ -361,6 +394,13 @@ pub enum CustomAgentServerSettings {
         ///
         /// Default: None
         default_model: Option<String>,
+        /// The favorite models for this agent.
+        ///
+        /// These are the model IDs as reported by the agent.
+        ///
+        /// Default: []
+        #[serde(default)]
+        favorite_models: Vec<String>,
     },
     Extension {
         /// The default mode to use for this agent.
@@ -375,5 +415,12 @@ pub enum CustomAgentServerSettings {
         ///
         /// Default: None
         default_model: Option<String>,
+        /// The favorite models for this agent.
+        ///
+        /// These are the model IDs as reported by the agent.
+        ///
+        /// Default: []
+        #[serde(default)]
+        favorite_models: Vec<String>,
     },
 }

crates/settings/src/settings_content/language.rs 🔗

@@ -1,4 +1,4 @@
-use std::num::NonZeroU32;
+use std::{num::NonZeroU32, path::Path};
 
 use collections::{HashMap, HashSet};
 use gpui::{Modifiers, SharedString};
@@ -62,6 +62,8 @@ impl merge_from::MergeFrom for AllLanguageSettingsContent {
 pub struct FeaturesContent {
     /// Determines which edit prediction provider to use.
     pub edit_prediction_provider: Option<EditPredictionProvider>,
+    /// Enables the experimental edit prediction context retrieval system.
+    pub experimental_edit_prediction_context_retrieval: Option<bool>,
 }
 
 /// The provider that supplies edit predictions.
@@ -79,6 +81,7 @@ pub enum EditPredictionProvider {
 
 pub const EXPERIMENTAL_SWEEP_EDIT_PREDICTION_PROVIDER_NAME: &str = "sweep";
 pub const EXPERIMENTAL_ZETA2_EDIT_PREDICTION_PROVIDER_NAME: &str = "zeta2";
+pub const EXPERIMENTAL_MERCURY_EDIT_PREDICTION_PROVIDER_NAME: &str = "mercury";
 
 impl<'de> Deserialize<'de> for EditPredictionProvider {
     fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
@@ -109,6 +112,13 @@ impl<'de> Deserialize<'de> for EditPredictionProvider {
                     EXPERIMENTAL_SWEEP_EDIT_PREDICTION_PROVIDER_NAME,
                 )
             }
+            Content::Experimental(name)
+                if name == EXPERIMENTAL_MERCURY_EDIT_PREDICTION_PROVIDER_NAME =>
+            {
+                EditPredictionProvider::Experimental(
+                    EXPERIMENTAL_MERCURY_EDIT_PREDICTION_PROVIDER_NAME,
+                )
+            }
             Content::Experimental(name)
                 if name == EXPERIMENTAL_ZETA2_EDIT_PREDICTION_PROVIDER_NAME =>
             {
@@ -157,6 +167,8 @@ pub struct EditPredictionSettingsContent {
     /// Whether edit predictions are enabled in the assistant prompt editor.
     /// This has no effect if globally disabled.
     pub enabled_in_text_threads: Option<bool>,
+    /// The directory where manually captured edit prediction examples are stored.
+    pub examples_dir: Option<Arc<Path>>,
 }
 
 #[with_fallible_options]
@@ -176,22 +188,20 @@ pub struct CopilotSettingsContent {
     pub enterprise_uri: Option<String>,
 }
 
+#[with_fallible_options]
 #[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema, MergeFrom, PartialEq)]
 pub struct CodestralSettingsContent {
     /// Model to use for completions.
     ///
     /// Default: "codestral-latest"
-    #[serde(default)]
     pub model: Option<String>,
     /// Maximum tokens to generate.
     ///
     /// Default: 150
-    #[serde(default)]
     pub max_tokens: Option<u32>,
     /// Api URL to use for completions.
     ///
     /// Default: "https://codestral.mistral.ai"
-    #[serde(default)]
     pub api_url: Option<String>,
 }
 
@@ -355,6 +365,14 @@ pub struct LanguageSettingsContent {
     ///
     /// Default: true
     pub extend_comment_on_newline: Option<bool>,
+    /// Whether to continue markdown lists when pressing enter.
+    ///
+    /// Default: true
+    pub extend_list_on_newline: Option<bool>,
+    /// Whether to indent list items when pressing tab after a list marker.
+    ///
+    /// Default: true
+    pub indent_list_on_tab: Option<bool>,
     /// Inlay hint related settings.
     pub inlay_hints: Option<InlayHintSettingsContent>,
     /// Whether to automatically type closing characters for you. For example,

crates/settings/src/settings_content/language_model.rs 🔗

@@ -61,6 +61,7 @@ pub struct AmazonBedrockSettingsContent {
     pub region: Option<String>,
     pub profile: Option<String>,
     pub authentication_method: Option<BedrockAuthMethodContent>,
+    pub allow_global: Option<bool>,
 }
 
 #[with_fallible_options]
@@ -82,6 +83,8 @@ pub enum BedrockAuthMethodContent {
     NamedProfile,
     #[serde(rename = "sso")]
     SingleSignOn,
+    #[serde(rename = "api_key")]
+    ApiKey,
     /// IMDSv2, PodIdentity, env vars, etc.
     #[serde(rename = "default")]
     Automatic,
@@ -91,6 +94,7 @@ pub enum BedrockAuthMethodContent {
 #[derive(Default, Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema, MergeFrom)]
 pub struct OllamaSettingsContent {
     pub api_url: Option<String>,
+    pub auto_discover: Option<bool>,
     pub available_models: Option<Vec<OllamaAvailableModel>>,
 }
 

crates/settings/src/settings_content/project.rs 🔗

@@ -11,6 +11,19 @@ use crate::{
     SlashCommandSettings,
 };
 
+#[with_fallible_options]
+#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema, MergeFrom)]
+pub struct LspSettingsMap(pub HashMap<Arc<str>, LspSettings>);
+
+impl IntoIterator for LspSettingsMap {
+    type Item = (Arc<str>, LspSettings);
+    type IntoIter = std::collections::hash_map::IntoIter<Arc<str>, LspSettings>;
+
+    fn into_iter(self) -> Self::IntoIter {
+        self.0.into_iter()
+    }
+}
+
 #[with_fallible_options]
 #[derive(Debug, PartialEq, Clone, Default, Serialize, Deserialize, JsonSchema, MergeFrom)]
 pub struct ProjectSettingsContent {
@@ -29,7 +42,7 @@ pub struct ProjectSettingsContent {
     /// name to the lsp value.
     /// Default: null
     #[serde(default)]
-    pub lsp: HashMap<Arc<str>, LspSettings>,
+    pub lsp: LspSettingsMap,
 
     pub terminal: Option<ProjectTerminalSettingsContent>,
 
@@ -187,6 +200,12 @@ pub struct SessionSettingsContent {
     ///
     /// Default: true
     pub restore_unsaved_buffers: Option<bool>,
+    /// Whether or not to skip worktree trust checks.
+    /// When trusted, project settings are synchronized automatically,
+    /// language and MCP servers are downloaded and started automatically.
+    ///
+    /// Default: false
+    pub trust_all_worktrees: Option<bool>,
 }
 
 #[derive(Deserialize, Serialize, Clone, PartialEq, Eq, JsonSchema, MergeFrom, Debug)]
@@ -282,6 +301,11 @@ impl std::fmt::Debug for ContextServerCommand {
 #[with_fallible_options]
 #[derive(Copy, Clone, Debug, PartialEq, Default, Serialize, Deserialize, JsonSchema, MergeFrom)]
 pub struct GitSettings {
+    /// Whether or not to enable git integration.
+    ///
+    /// Default: true
+    #[serde(flatten)]
+    pub enabled: Option<GitEnabledSettings>,
     /// Whether or not to show the git gutter.
     ///
     /// Default: tracked_files
@@ -311,6 +335,25 @@ pub struct GitSettings {
     pub path_style: Option<GitPathStyle>,
 }
 
+#[with_fallible_options]
+#[derive(Clone, Copy, Debug, PartialEq, Default, Serialize, Deserialize, JsonSchema, MergeFrom)]
+#[serde(rename_all = "snake_case")]
+pub struct GitEnabledSettings {
+    pub disable_git: Option<bool>,
+    pub enable_status: Option<bool>,
+    pub enable_diff: Option<bool>,
+}
+
+impl GitEnabledSettings {
+    pub fn is_git_status_enabled(&self) -> bool {
+        !self.disable_git.unwrap_or(false) && self.enable_status.unwrap_or(true)
+    }
+
+    pub fn is_git_diff_enabled(&self) -> bool {
+        !self.disable_git.unwrap_or(false) && self.enable_diff.unwrap_or(true)
+    }
+}
+
 #[derive(
     Clone,
     Copy,
@@ -543,7 +586,7 @@ pub enum DiagnosticSeverityContent {
 pub struct GitHostingProviderConfig {
     /// The type of the provider.
     ///
-    /// Must be one of `github`, `gitlab`, or `bitbucket`.
+    /// Must be one of `github`, `gitlab`, `bitbucket`, `gitea`, `forgejo`, or `source_hut`.
     pub provider: GitHostingProviderKind,
 
     /// The base URL for the provider (e.g., "https://code.corp.big.com").
@@ -559,4 +602,7 @@ pub enum GitHostingProviderKind {
     Github,
     Gitlab,
     Bitbucket,
+    Gitea,
+    Forgejo,
+    SourceHut,
 }

crates/settings/src/settings_content/terminal.rs 🔗

@@ -1,7 +1,7 @@
 use std::path::PathBuf;
 
 use collections::HashMap;
-use gpui::{AbsoluteLength, FontFeatures, SharedString, px};
+use gpui::{AbsoluteLength, FontFeatures, FontWeight, SharedString, px};
 use schemars::JsonSchema;
 use serde::{Deserialize, Serialize};
 use settings_macros::{MergeFrom, with_fallible_options};
@@ -96,8 +96,7 @@ pub struct TerminalSettingsContent {
     pub line_height: Option<TerminalLineHeight>,
     pub font_features: Option<FontFeatures>,
     /// Sets the terminal's font weight in CSS weight units 0-900.
-    #[serde(serialize_with = "crate::serialize_optional_f32_with_two_decimal_places")]
-    pub font_weight: Option<f32>,
+    pub font_weight: Option<FontWeight>,
     /// Default cursor shape for the terminal.
     /// Can be "bar", "block", "underline", or "hollow".
     ///

crates/settings/src/settings_content/theme.rs 🔗

@@ -570,6 +570,9 @@ pub struct ThemeColorsContent {
     #[serde(rename = "search.match_background")]
     pub search_match_background: Option<String>,
 
+    #[serde(rename = "search.active_match_background")]
+    pub search_active_match_background: Option<String>,
+
     #[serde(rename = "panel.background")]
     pub panel_background: Option<String>,
 

crates/settings/src/settings_content/workspace.rs 🔗

@@ -42,7 +42,7 @@ pub struct WorkspaceSettingsContent {
     /// Default: off
     pub autosave: Option<AutosaveSetting>,
     /// Controls previous session restoration in freshly launched Zed instance.
-    /// Values: none, last_workspace, last_session
+    /// Values: empty_tab, last_workspace, last_session, launchpad
     /// Default: last_session
     pub restore_on_startup: Option<RestoreOnStartupBehavior>,
     /// Whether to attempt to restore previous file's state when opening it again.
@@ -152,14 +152,31 @@ pub struct PreviewTabsSettingsContent {
     ///
     /// Default: true
     pub enabled: Option<bool>,
+    /// Whether to open tabs in preview mode when opened from the project panel with a single click.
+    ///
+    /// Default: true
+    pub enable_preview_from_project_panel: Option<bool>,
     /// Whether to open tabs in preview mode when selected from the file finder.
     ///
     /// Default: false
     pub enable_preview_from_file_finder: Option<bool>,
-    /// Whether a preview tab gets replaced when code navigation is used to navigate away from the tab.
+    /// Whether to open tabs in preview mode when opened from a multibuffer.
+    ///
+    /// Default: true
+    pub enable_preview_from_multibuffer: Option<bool>,
+    /// Whether to open tabs in preview mode when code navigation is used to open a multibuffer.
+    ///
+    /// Default: false
+    pub enable_preview_multibuffer_from_code_navigation: Option<bool>,
+    /// Whether to open tabs in preview mode when code navigation is used to open a single file.
+    ///
+    /// Default: true
+    pub enable_preview_file_from_code_navigation: Option<bool>,
+    /// Whether to keep tabs in preview mode when code navigation is used to navigate away from them.
+    /// If `enable_preview_file_from_code_navigation` or `enable_preview_multibuffer_from_code_navigation` is also true, the new tab may replace the existing one.
     ///
     /// Default: false
-    pub enable_preview_from_code_navigation: Option<bool>,
+    pub enable_keep_preview_on_code_navigation: Option<bool>,
 }
 
 #[derive(
@@ -365,13 +382,16 @@ impl CloseWindowWhenNoItems {
 )]
 #[serde(rename_all = "snake_case")]
 pub enum RestoreOnStartupBehavior {
-    /// Always start with an empty editor
-    None,
+    /// Always start with an empty editor tab
+    #[serde(alias = "none")]
+    EmptyTab,
     /// Restore the workspace that was closed last.
     LastWorkspace,
     /// Restore all workspaces that were open when quitting Zed.
     #[default]
     LastSession,
+    /// Show the launchpad with recent projects (no tabs).
+    Launchpad,
 }
 
 #[with_fallible_options]

crates/settings/src/settings_store.rs 🔗

@@ -25,14 +25,15 @@ use std::{
 use util::{
     ResultExt as _,
     rel_path::RelPath,
-    schemars::{DefaultDenyUnknownFields, replace_subschema},
+    schemars::{AllowTrailingCommas, DefaultDenyUnknownFields, replace_subschema},
 };
 
 pub type EditorconfigProperties = ec4rs::Properties;
 
 use crate::{
     ActiveSettingsProfileName, FontFamilyName, IconThemeName, LanguageSettingsContent,
-    LanguageToSettingsMap, ThemeName, VsCodeSettings, WorktreeId, fallible_options,
+    LanguageToSettingsMap, LspSettings, LspSettingsMap, ThemeName, VsCodeSettings, WorktreeId,
+    fallible_options,
     merge_from::MergeFrom,
     settings_content::{
         ExtensionsSettingsContent, ProjectSettingsContent, SettingsContent, UserSettingsContent,
@@ -41,6 +42,8 @@ use crate::{
 
 use settings_json::{infer_json_indent_size, parse_json_with_comments, update_value_in_json_text};
 
+pub const LSP_SETTINGS_SCHEMA_URL_PREFIX: &str = "zed://schemas/settings/lsp/";
+
 pub trait SettingsKey: 'static + Send + Sync {
     /// The name of a key within the JSON file from which this setting should
     /// be deserialized. If this is `None`, then the setting will be deserialized
@@ -247,6 +250,7 @@ pub trait AnySettingValue: 'static + Send + Sync {
     fn all_local_values(&self) -> Vec<(WorktreeId, Arc<RelPath>, &dyn Any)>;
     fn set_global_value(&mut self, value: Box<dyn Any>);
     fn set_local_value(&mut self, root_id: WorktreeId, path: Arc<RelPath>, value: Box<dyn Any>);
+    fn clear_local_values(&mut self, root_id: WorktreeId);
 }
 
 /// Parameters that are used when generating some JSON schemas at runtime.
@@ -255,6 +259,7 @@ pub struct SettingsJsonSchemaParams<'a> {
     pub font_names: &'a [String],
     pub theme_names: &'a [SharedString],
     pub icon_theme_names: &'a [SharedString],
+    pub lsp_adapter_names: &'a [String],
 }
 
 impl SettingsStore {
@@ -971,6 +976,11 @@ impl SettingsStore {
     pub fn clear_local_settings(&mut self, root_id: WorktreeId, cx: &mut App) -> Result<()> {
         self.local_settings
             .retain(|(worktree_id, _), _| worktree_id != &root_id);
+        self.raw_editorconfig_settings
+            .retain(|(worktree_id, _), _| worktree_id != &root_id);
+        for setting_value in self.setting_values.values_mut() {
+            setting_value.clear_local_values(root_id);
+        }
         self.recompute_values(Some((root_id, RelPath::empty())), cx);
         Ok(())
     }
@@ -1010,6 +1020,7 @@ impl SettingsStore {
     pub fn json_schema(&self, params: &SettingsJsonSchemaParams) -> Value {
         let mut generator = schemars::generate::SchemaSettings::draft2019_09()
             .with_transform(DefaultDenyUnknownFields)
+            .with_transform(AllowTrailingCommas)
             .into_generator();
 
         UserSettingsContent::json_schema(&mut generator);
@@ -1018,6 +1029,14 @@ impl SettingsStore {
             .subschema_for::<LanguageSettingsContent>()
             .to_value();
 
+        generator.subschema_for::<LspSettings>();
+
+        let lsp_settings_def = generator
+            .definitions()
+            .get("LspSettings")
+            .expect("LspSettings should be defined")
+            .clone();
+
         replace_subschema::<LanguageToSettingsMap>(&mut generator, || {
             json_schema!({
                 "type": "object",
@@ -1056,6 +1075,38 @@ impl SettingsStore {
             })
         });
 
+        replace_subschema::<LspSettingsMap>(&mut generator, || {
+            let mut lsp_properties = serde_json::Map::new();
+
+            for adapter_name in params.lsp_adapter_names {
+                let mut base_lsp_settings = lsp_settings_def
+                    .as_object()
+                    .expect("LspSettings should be an object")
+                    .clone();
+
+                if let Some(properties) = base_lsp_settings.get_mut("properties") {
+                    if let Some(props_obj) = properties.as_object_mut() {
+                        props_obj.insert(
+                            "initialization_options".to_string(),
+                            serde_json::json!({
+                                "$ref": format!("{LSP_SETTINGS_SCHEMA_URL_PREFIX}{adapter_name}")
+                            }),
+                        );
+                    }
+                }
+
+                lsp_properties.insert(
+                    adapter_name.clone(),
+                    serde_json::Value::Object(base_lsp_settings),
+                );
+            }
+
+            json_schema!({
+                "type": "object",
+                "properties": lsp_properties,
+            })
+        });
+
         generator
             .root_schema_for::<UserSettingsContent>()
             .to_value()
@@ -1337,6 +1388,11 @@ impl<T: Settings> AnySettingValue for SettingValue<T> {
             Err(ix) => self.local_values.insert(ix, (root_id, path, value)),
         }
     }
+
+    fn clear_local_values(&mut self, root_id: WorktreeId) {
+        self.local_values
+            .retain(|(worktree_id, _, _)| *worktree_id != root_id);
+    }
 }
 
 #[cfg(test)]
@@ -2292,4 +2348,39 @@ mod tests {
             ]
         )
     }
+
+    #[gpui::test]
+    fn test_lsp_settings_schema_generation(cx: &mut App) {
+        let store = SettingsStore::test(cx);
+
+        let schema = store.json_schema(&SettingsJsonSchemaParams {
+            language_names: &["Rust".to_string(), "TypeScript".to_string()],
+            font_names: &["Zed Mono".to_string()],
+            theme_names: &["One Dark".into()],
+            icon_theme_names: &["Zed Icons".into()],
+            lsp_adapter_names: &[
+                "rust-analyzer".to_string(),
+                "typescript-language-server".to_string(),
+            ],
+        });
+
+        let properties = schema
+            .pointer("/$defs/LspSettingsMap/properties")
+            .expect("LspSettingsMap should have properties")
+            .as_object()
+            .unwrap();
+
+        assert!(properties.contains_key("rust-analyzer"));
+        assert!(properties.contains_key("typescript-language-server"));
+
+        let init_options_ref = properties
+            .get("rust-analyzer")
+            .unwrap()
+            .pointer("/properties/initialization_options/$ref")
+            .expect("initialization_options should have a $ref")
+            .as_str()
+            .unwrap();
+
+        assert_eq!(init_options_ref, "zed://schemas/settings/lsp/rust-analyzer");
+    }
 }

crates/settings/src/vscode_import.rs 🔗

@@ -215,6 +215,7 @@ impl VsCodeSettings {
             vim: None,
             vim_mode: None,
             workspace: self.workspace_settings_content(),
+            which_key: None,
         }
     }
 
@@ -429,6 +430,8 @@ impl VsCodeSettings {
             enable_language_server: None,
             ensure_final_newline_on_save: self.read_bool("files.insertFinalNewline"),
             extend_comment_on_newline: None,
+            extend_list_on_newline: None,
+            indent_list_on_tab: None,
             format_on_save: self.read_bool("editor.guides.formatOnSave").map(|b| {
                 if b {
                     FormatOnSave::On
@@ -619,9 +622,13 @@ impl VsCodeSettings {
     fn preview_tabs_settings_content(&self) -> Option<PreviewTabsSettingsContent> {
         skip_default(PreviewTabsSettingsContent {
             enabled: self.read_bool("workbench.editor.enablePreview"),
+            enable_preview_from_project_panel: None,
             enable_preview_from_file_finder: self
                 .read_bool("workbench.editor.enablePreviewFromQuickOpen"),
-            enable_preview_from_code_navigation: self
+            enable_preview_from_multibuffer: None,
+            enable_preview_multibuffer_from_code_navigation: None,
+            enable_preview_file_from_code_navigation: None,
+            enable_keep_preview_on_code_navigation: self
                 .read_bool("workbench.editor.enablePreviewFromCodeNavigation"),
         })
     }

crates/settings_ui/Cargo.toml 🔗

@@ -18,6 +18,9 @@ test-support = []
 [dependencies]
 anyhow.workspace = true
 bm25 = "2.3.2"
+copilot.workspace = true
+edit_prediction.workspace = true
+language_models.workspace = true
 editor.workspace = true
 feature_flags.workspace = true
 fs.workspace = true
@@ -38,8 +41,8 @@ strum.workspace = true
 telemetry.workspace = true
 theme.workspace = true
 title_bar.workspace = true
-ui.workspace = true
 ui_input.workspace = true
+ui.workspace = true
 util.workspace = true
 workspace.workspace = true
 zed_actions.workspace = true

crates/settings_ui/src/components.rs 🔗

@@ -2,10 +2,12 @@ mod dropdown;
 mod font_picker;
 mod icon_theme_picker;
 mod input_field;
+mod section_items;
 mod theme_picker;
 
 pub use dropdown::*;
 pub use font_picker::font_picker;
 pub use icon_theme_picker::icon_theme_picker;
 pub use input_field::*;
+pub use section_items::*;
 pub use theme_picker::theme_picker;

crates/settings_ui/src/components/input_field.rs 🔗

@@ -13,6 +13,7 @@ pub struct SettingsInputField {
     tab_index: Option<isize>,
 }
 
+// TODO: Update the `ui_input::InputField` to use `window.use_state` and `RenceOnce` and remove this component
 impl SettingsInputField {
     pub fn new() -> Self {
         Self {

crates/settings_ui/src/components/section_items.rs 🔗

@@ -0,0 +1,56 @@
+use gpui::{IntoElement, ParentElement, Styled};
+use ui::{Divider, DividerColor, prelude::*};
+
+#[derive(IntoElement)]
+pub struct SettingsSectionHeader {
+    icon: Option<IconName>,
+    label: SharedString,
+    no_padding: bool,
+}
+
+impl SettingsSectionHeader {
+    pub fn new(label: impl Into<SharedString>) -> Self {
+        Self {
+            label: label.into(),
+            icon: None,
+            no_padding: false,
+        }
+    }
+
+    pub fn icon(mut self, icon: IconName) -> Self {
+        self.icon = Some(icon);
+        self
+    }
+
+    pub fn no_padding(mut self, no_padding: bool) -> Self {
+        self.no_padding = no_padding;
+        self
+    }
+}
+
+impl RenderOnce for SettingsSectionHeader {
+    fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
+        let label = Label::new(self.label)
+            .size(LabelSize::Small)
+            .color(Color::Muted)
+            .buffer_font(cx);
+
+        v_flex()
+            .w_full()
+            .when(!self.no_padding, |this| this.px_8())
+            .gap_1p5()
+            .map(|this| {
+                if self.icon.is_some() {
+                    this.child(
+                        h_flex()
+                            .gap_1p5()
+                            .child(Icon::new(self.icon.unwrap()).color(Color::Muted))
+                            .child(label),
+                    )
+                } else {
+                    this.child(label)
+                }
+            })
+            .child(Divider::horizontal().color(DividerColor::BorderFaded))
+    }
+}

crates/settings_ui/src/page_data.rs 🔗

@@ -1,12 +1,12 @@
-use gpui::App;
+use gpui::{Action as _, App};
 use settings::{LanguageSettingsContent, SettingsContent};
 use std::sync::Arc;
 use strum::IntoDiscriminant as _;
 use ui::{IntoElement, SharedString};
 
 use crate::{
-    DynamicItem, PROJECT, SettingField, SettingItem, SettingsFieldMetadata, SettingsPage,
-    SettingsPageItem, SubPageLink, USER, all_language_names, sub_page_stack,
+    ActionLink, DynamicItem, PROJECT, SettingField, SettingItem, SettingsFieldMetadata,
+    SettingsPage, SettingsPageItem, SubPageLink, USER, all_language_names, sub_page_stack,
 };
 
 const DEFAULT_STRING: String = String::new();
@@ -138,6 +138,28 @@ pub(crate) fn settings_data(cx: &App) -> Vec<SettingsPage> {
                     metadata: None,
                     files: USER,
                 }),
+                SettingsPageItem::SectionHeader("Security"),
+                SettingsPageItem::SettingItem(SettingItem {
+                    title: "Trust All Projects By Default",
+                    description: "When opening Zed, avoid Restricted Mode by auto-trusting all projects, enabling use of all features without having to give permission to each new project.",
+                    field: Box::new(SettingField {
+                        json_path: Some("session.trust_all_projects"),
+                        pick: |settings_content| {
+                            settings_content
+                                .session
+                                .as_ref()
+                                .and_then(|session| session.trust_all_worktrees.as_ref())
+                        },
+                        write: |settings_content, value| {
+                            settings_content
+                                .session
+                                .get_or_insert_default()
+                                .trust_all_worktrees = value;
+                        },
+                    }),
+                    metadata: None,
+                    files: USER,
+                }),
                 SettingsPageItem::SectionHeader("Workspace Restoration"),
                 SettingsPageItem::SettingItem(SettingItem {
                     title: "Restore Unsaved Buffers",
@@ -1054,6 +1076,25 @@ pub(crate) fn settings_data(cx: &App) -> Vec<SettingsPage> {
         SettingsPage {
             title: "Keymap",
             items: vec![
+                SettingsPageItem::SectionHeader("Keybindings"),
+                SettingsPageItem::ActionLink(ActionLink {
+                    title: "Edit Keybindings".into(),
+                    description: Some("Customize keybindings in the keymap editor.".into()),
+                    button_text: "Open Keymap".into(),
+                    on_click: Arc::new(|settings_window, window, cx| {
+                        let Some(original_window) = settings_window.original_window else {
+                            return;
+                        };
+                        original_window
+                            .update(cx, |_workspace, original_window, cx| {
+                                original_window
+                                    .dispatch_action(zed_actions::OpenKeymap.boxed_clone(), cx);
+                                original_window.activate_window();
+                            })
+                            .ok();
+                        window.remove_window();
+                    }),
+                }),
                 SettingsPageItem::SectionHeader("Base Keymap"),
                 SettingsPageItem::SettingItem(SettingItem {
                     title: "Base Keymap",
@@ -1192,6 +1233,49 @@ pub(crate) fn settings_data(cx: &App) -> Vec<SettingsPage> {
                             }
                         }).collect(),
                     }),
+                    SettingsPageItem::SectionHeader("Which-key Menu"),
+                    SettingsPageItem::SettingItem(SettingItem {
+                        title: "Show Which-key Menu",
+                        description: "Display the which-key menu with matching bindings while a multi-stroke binding is pending.",
+                        field: Box::new(SettingField {
+                            json_path: Some("which_key.enabled"),
+                            pick: |settings_content| {
+                                settings_content
+                                    .which_key
+                                    .as_ref()
+                                    .and_then(|settings| settings.enabled.as_ref())
+                            },
+                            write: |settings_content, value| {
+                                settings_content
+                                    .which_key
+                                    .get_or_insert_default()
+                                    .enabled = value;
+                            },
+                        }),
+                        metadata: None,
+                        files: USER,
+                    }),
+                    SettingsPageItem::SettingItem(SettingItem {
+                        title: "Menu Delay",
+                        description: "Delay in milliseconds before the which-key menu appears.",
+                        field: Box::new(SettingField {
+                            json_path: Some("which_key.delay_ms"),
+                            pick: |settings_content| {
+                                settings_content
+                                    .which_key
+                                    .as_ref()
+                                    .and_then(|settings| settings.delay_ms.as_ref())
+                            },
+                            write: |settings_content, value| {
+                                settings_content
+                                    .which_key
+                                    .get_or_insert_default()
+                                    .delay_ms = value;
+                            },
+                        }),
+                        metadata: None,
+                        files: USER,
+                    }),
                     SettingsPageItem::SectionHeader("Multibuffer"),
                     SettingsPageItem::SettingItem(SettingItem {
                         title: "Double Click In Multibuffer",
@@ -2330,8 +2414,12 @@ pub(crate) fn settings_data(cx: &App) -> Vec<SettingsPage> {
                 // Note that `crates/json_schema_store` solves the same problem, there is probably a way to unify the two
                 items.push(SettingsPageItem::SectionHeader(LANGUAGES_SECTION_HEADER));
                 items.extend(all_language_names(cx).into_iter().map(|language_name| {
+                    let link = format!("languages.{language_name}");
                     SettingsPageItem::SubPageLink(SubPageLink {
                         title: language_name,
+                        description: None,
+                        json_path: Some(link.leak()),
+                        in_json: true,
                         files: USER | PROJECT,
                         render: Arc::new(|this, window, cx| {
                             this.render_sub_page_items(
@@ -2909,40 +2997,58 @@ pub(crate) fn settings_data(cx: &App) -> Vec<SettingsPage> {
                     files: USER,
                 }),
                 SettingsPageItem::SettingItem(SettingItem {
-                    title: "Show User Picture",
-                    description: "Show user picture in the titlebar.",
+                    title: "Show Sign In",
+                    description: "Show the sign in button in the titlebar.",
                     field: Box::new(SettingField {
-                        json_path: Some("title_bar.show_user_picture"),
+                        json_path: Some("title_bar.show_sign_in"),
                         pick: |settings_content| {
+                            settings_content.title_bar.as_ref()?.show_sign_in.as_ref()
+                        },
+                        write: |settings_content, value| {
                             settings_content
                                 .title_bar
-                                .as_ref()?
-                                .show_user_picture
-                                .as_ref()
+                                .get_or_insert_default()
+                                .show_sign_in = value;
+                        },
+                    }),
+                    metadata: None,
+                    files: USER,
+                }),
+                SettingsPageItem::SettingItem(SettingItem {
+                    title: "Show User Menu",
+                    description: "Show the user menu button in the titlebar.",
+                    field: Box::new(SettingField {
+                        json_path: Some("title_bar.show_user_menu"),
+                        pick: |settings_content| {
+                            settings_content.title_bar.as_ref()?.show_user_menu.as_ref()
                         },
                         write: |settings_content, value| {
                             settings_content
                                 .title_bar
                                 .get_or_insert_default()
-                                .show_user_picture = value;
+                                .show_user_menu = value;
                         },
                     }),
                     metadata: None,
                     files: USER,
                 }),
                 SettingsPageItem::SettingItem(SettingItem {
-                    title: "Show Sign In",
-                    description: "Show the sign in button in the titlebar.",
+                    title: "Show User Picture",
+                    description: "Show user picture in the titlebar.",
                     field: Box::new(SettingField {
-                        json_path: Some("title_bar.show_sign_in"),
+                        json_path: Some("title_bar.show_user_picture"),
                         pick: |settings_content| {
-                            settings_content.title_bar.as_ref()?.show_sign_in.as_ref()
+                            settings_content
+                                .title_bar
+                                .as_ref()?
+                                .show_user_picture
+                                .as_ref()
                         },
                         write: |settings_content, value| {
                             settings_content
                                 .title_bar
                                 .get_or_insert_default()
-                                .show_sign_in = value;
+                                .show_user_picture = value;
                         },
                     }),
                     metadata: None,
@@ -3145,7 +3251,7 @@ pub(crate) fn settings_data(cx: &App) -> Vec<SettingsPage> {
                 SettingsPageItem::SectionHeader("Preview Tabs"),
                 SettingsPageItem::SettingItem(SettingItem {
                     title: "Preview Tabs Enabled",
-                    description: "Show opened editors as Preview tabs.",
+                    description: "Show opened editors as preview tabs.",
                     field: Box::new(SettingField {
                         json_path: Some("preview_tabs.enabled"),
                         pick: |settings_content| {
@@ -3161,9 +3267,31 @@ pub(crate) fn settings_data(cx: &App) -> Vec<SettingsPage> {
                     metadata: None,
                     files: USER,
                 }),
+                SettingsPageItem::SettingItem(SettingItem {
+                    title: "Enable Preview From Project Panel",
+                    description: "Whether to open tabs in preview mode when opened from the project panel with a single click.",
+                    field: Box::new(SettingField {
+                        json_path: Some("preview_tabs.enable_preview_from_project_panel"),
+                        pick: |settings_content| {
+                            settings_content
+                                .preview_tabs
+                                .as_ref()?
+                                .enable_preview_from_project_panel
+                                .as_ref()
+                        },
+                        write: |settings_content, value| {
+                            settings_content
+                                .preview_tabs
+                                .get_or_insert_default()
+                                .enable_preview_from_project_panel = value;
+                        },
+                    }),
+                    metadata: None,
+                    files: USER,
+                }),
                 SettingsPageItem::SettingItem(SettingItem {
                     title: "Enable Preview From File Finder",
-                    description: "Whether to open tabs in Preview mode when selected from the file finder.",
+                    description: "Whether to open tabs in preview mode when selected from the file finder.",
                     field: Box::new(SettingField {
                         json_path: Some("preview_tabs.enable_preview_from_file_finder"),
                         pick: |settings_content| {
@@ -3184,22 +3312,88 @@ pub(crate) fn settings_data(cx: &App) -> Vec<SettingsPage> {
                     files: USER,
                 }),
                 SettingsPageItem::SettingItem(SettingItem {
-                    title: "Enable Preview From Code Navigation",
-                    description: "Whether a preview tab gets replaced when code navigation is used to navigate away from the tab.",
+                    title: "Enable Preview From Multibuffer",
+                    description: "Whether to open tabs in preview mode when opened from a multibuffer.",
+                    field: Box::new(SettingField {
+                        json_path: Some("preview_tabs.enable_preview_from_multibuffer"),
+                        pick: |settings_content| {
+                            settings_content
+                                .preview_tabs
+                                .as_ref()?
+                                .enable_preview_from_multibuffer
+                                .as_ref()
+                        },
+                        write: |settings_content, value| {
+                            settings_content
+                                .preview_tabs
+                                .get_or_insert_default()
+                                .enable_preview_from_multibuffer = value;
+                        },
+                    }),
+                    metadata: None,
+                    files: USER,
+                }),
+                SettingsPageItem::SettingItem(SettingItem {
+                    title: "Enable Preview Multibuffer From Code Navigation",
+                    description: "Whether to open tabs in preview mode when code navigation is used to open a multibuffer.",
+                    field: Box::new(SettingField {
+                        json_path: Some("preview_tabs.enable_preview_multibuffer_from_code_navigation"),
+                        pick: |settings_content| {
+                            settings_content
+                                .preview_tabs
+                                .as_ref()?
+                                .enable_preview_multibuffer_from_code_navigation
+                                .as_ref()
+                        },
+                        write: |settings_content, value| {
+                            settings_content
+                                .preview_tabs
+                                .get_or_insert_default()
+                                .enable_preview_multibuffer_from_code_navigation = value;
+                        },
+                    }),
+                    metadata: None,
+                    files: USER,
+                }),
+                SettingsPageItem::SettingItem(SettingItem {
+                    title: "Enable Preview File From Code Navigation",
+                    description: "Whether to open tabs in preview mode when code navigation is used to open a single file.",
+                    field: Box::new(SettingField {
+                        json_path: Some("preview_tabs.enable_preview_file_from_code_navigation"),
+                        pick: |settings_content| {
+                            settings_content
+                                .preview_tabs
+                                .as_ref()?
+                                .enable_preview_file_from_code_navigation
+                                .as_ref()
+                        },
+                        write: |settings_content, value| {
+                            settings_content
+                                .preview_tabs
+                                .get_or_insert_default()
+                                .enable_preview_file_from_code_navigation = value;
+                        },
+                    }),
+                    metadata: None,
+                    files: USER,
+                }),
+                SettingsPageItem::SettingItem(SettingItem {
+                    title: "Enable Keep Preview On Code Navigation",
+                    description: "Whether to keep tabs in preview mode when code navigation is used to navigate away from them. If `enable_preview_file_from_code_navigation` or `enable_preview_multibuffer_from_code_navigation` is also true, the new tab may replace the existing one.",
                     field: Box::new(SettingField {
-                        json_path: Some("preview_tabs.enable_preview_from_code_navigation"),
+                        json_path: Some("preview_tabs.enable_keep_preview_on_code_navigation"),
                         pick: |settings_content| {
                             settings_content
                                 .preview_tabs
                                 .as_ref()?
-                                .enable_preview_from_code_navigation
+                                .enable_keep_preview_on_code_navigation
                                 .as_ref()
                         },
                         write: |settings_content, value| {
                             settings_content
                                 .preview_tabs
                                 .get_or_insert_default()
-                                .enable_preview_from_code_navigation = value;
+                                .enable_keep_preview_on_code_navigation = value;
                         },
                     }),
                     metadata: None,
@@ -4226,6 +4420,24 @@ pub(crate) fn settings_data(cx: &App) -> Vec<SettingsPage> {
                     metadata: None,
                     files: USER,
                 }),
+                SettingsPageItem::SettingItem(SettingItem {
+                    title: "Tree View",
+                    description: "Enable to show entries in tree view list, disable to show in flat view list.",
+                    field: Box::new(SettingField {
+                        json_path: Some("git_panel.tree_view"),
+                        pick: |settings_content| {
+                            settings_content.git_panel.as_ref()?.tree_view.as_ref()
+                        },
+                        write: |settings_content, value| {
+                            settings_content
+                                .git_panel
+                                .get_or_insert_default()
+                                .tree_view = value;
+                        },
+                    }),
+                    metadata: None,
+                    files: USER,
+                }),
                 SettingsPageItem::SettingItem(SettingItem {
                     title: "Scroll Bar",
                     description: "How and when the scrollbar should be displayed.",
@@ -5307,6 +5519,102 @@ pub(crate) fn settings_data(cx: &App) -> Vec<SettingsPage> {
         SettingsPage {
             title: "Version Control",
             items: vec![
+                SettingsPageItem::SectionHeader("Git Integration"),
+                SettingsPageItem::DynamicItem(DynamicItem {
+                    discriminant: SettingItem {
+                        files: USER,
+                        title: "Disable Git Integration",
+                        description: "Disable all Git integration features in Zed.",
+                        field: Box::new(SettingField::<bool> {
+                            json_path: Some("git.disable_git"),
+                            pick: |settings_content| {
+                                settings_content
+                                    .git
+                                    .as_ref()?
+                                    .enabled
+                                    .as_ref()?
+                                    .disable_git
+                                    .as_ref()
+                            },
+                            write: |settings_content, value| {
+                                settings_content
+                                    .git
+                                    .get_or_insert_default()
+                                    .enabled
+                                    .get_or_insert_default()
+                                    .disable_git = value;
+                            },
+                        }),
+                        metadata: None,
+                    },
+                    pick_discriminant: |settings_content| {
+                        let disabled = settings_content
+                            .git
+                            .as_ref()?
+                            .enabled
+                            .as_ref()?
+                            .disable_git
+                            .unwrap_or(false);
+                        Some(if disabled { 0 } else { 1 })
+                    },
+                    fields: vec![
+                        vec![],
+                        vec![
+                            SettingItem {
+                                files: USER,
+                                title: "Enable Git Status",
+                                description: "Show Git status information in the editor.",
+                                field: Box::new(SettingField::<bool> {
+                                    json_path: Some("git.enable_status"),
+                                    pick: |settings_content| {
+                                        settings_content
+                                            .git
+                                            .as_ref()?
+                                            .enabled
+                                            .as_ref()?
+                                            .enable_status
+                                            .as_ref()
+                                    },
+                                    write: |settings_content, value| {
+                                        settings_content
+                                            .git
+                                            .get_or_insert_default()
+                                            .enabled
+                                            .get_or_insert_default()
+                                            .enable_status = value;
+                                    },
+                                }),
+                                metadata: None,
+                            },
+                            SettingItem {
+                                files: USER,
+                                title: "Enable Git Diff",
+                                description: "Show Git diff information in the editor.",
+                                field: Box::new(SettingField::<bool> {
+                                    json_path: Some("git.enable_diff"),
+                                    pick: |settings_content| {
+                                        settings_content
+                                            .git
+                                            .as_ref()?
+                                            .enabled
+                                            .as_ref()?
+                                            .enable_diff
+                                            .as_ref()
+                                    },
+                                    write: |settings_content, value| {
+                                        settings_content
+                                            .git
+                                            .get_or_insert_default()
+                                            .enabled
+                                            .get_or_insert_default()
+                                            .enable_diff = value;
+                                    },
+                                }),
+                                metadata: None,
+                            },
+                        ],
+                    ],
+                }),
                 SettingsPageItem::SectionHeader("Git Gutter"),
                 SettingsPageItem::SettingItem(SettingItem {
                     title: "Visibility",
@@ -5907,7 +6215,7 @@ pub(crate) fn settings_data(cx: &App) -> Vec<SettingsPage> {
                             files: USER,
                         }),
                         SettingsPageItem::SettingItem(SettingItem {
-                            title: "In Text Threads",
+                            title: "Display In Text Threads",
                             description: "Whether edit predictions are enabled when editing text threads in the agent panel.",
                             field: Box::new(SettingField {
                                 json_path: Some("edit_prediction.in_text_threads"),
@@ -5921,42 +6229,6 @@ pub(crate) fn settings_data(cx: &App) -> Vec<SettingsPage> {
                             metadata: None,
                             files: USER,
                         }),
-                        SettingsPageItem::SettingItem(SettingItem {
-                            title: "Copilot Provider",
-                            description: "Use GitHub Copilot as your edit prediction provider.",
-                            field: Box::new(
-                                SettingField {
-                                    json_path: Some("edit_prediction.copilot_provider"),
-                                    pick: |settings_content| {
-                                        settings_content.project.all_languages.edit_predictions.as_ref()?.copilot.as_ref()
-                                    },
-                                    write: |settings_content, value| {
-                                        settings_content.project.all_languages.edit_predictions.get_or_insert_default().copilot = value;
-                                    },
-                                }
-                                .unimplemented(),
-                            ),
-                            metadata: None,
-                            files: USER | PROJECT,
-                        }),
-                        SettingsPageItem::SettingItem(SettingItem {
-                            title: "Codestral Provider",
-                            description: "Use Mistral's Codestral as your edit prediction provider.",
-                            field: Box::new(
-                                SettingField {
-                                    json_path: Some("edit_prediction.codestral_provider"),
-                                    pick: |settings_content| {
-                                        settings_content.project.all_languages.edit_predictions.as_ref()?.codestral.as_ref()
-                                    },
-                                    write: |settings_content, value| {
-                                        settings_content.project.all_languages.edit_predictions.get_or_insert_default().codestral = value;
-                                    },
-                                }
-                                .unimplemented(),
-                            ),
-                            metadata: None,
-                            files: USER | PROJECT,
-                        }),
                     ]
                 );
                 items
@@ -6526,7 +6798,7 @@ fn language_settings_data() -> Vec<SettingsPageItem> {
             files: USER | PROJECT,
         }),
         SettingsPageItem::SettingItem(SettingItem {
-            title: "Jsx Tag Auto Close",
+            title: "JSX Tag Auto Close",
             description: "Whether to automatically close JSX tags.",
             field: Box::new(SettingField {
                 json_path: Some("languages.$(language).jsx_tag_auto_close"),
@@ -7053,7 +7325,7 @@ fn language_settings_data() -> Vec<SettingsPageItem> {
             files: USER | PROJECT,
         }),
         SettingsPageItem::SettingItem(SettingItem {
-            title: "Colorize brackets",
+            title: "Colorize Brackets",
             description: "Whether to colorize brackets in the editor.",
             field: Box::new(SettingField {
                 json_path: Some("languages.$(language).colorize_brackets"),
@@ -7379,9 +7651,23 @@ fn non_editor_language_settings_data() -> Vec<SettingsPageItem> {
 fn edit_prediction_language_settings_section() -> Vec<SettingsPageItem> {
     vec![
         SettingsPageItem::SectionHeader("Edit Predictions"),
+        SettingsPageItem::SubPageLink(SubPageLink {
+            title: "Configure Providers".into(),
+            json_path: Some("edit_predictions.providers"),
+            description: Some("Set up different edit prediction providers in complement to Zed's built-in Zeta model.".into()),
+            in_json: false,
+            files: USER,
+            render: Arc::new(|_, window, cx| {
+                let settings_window = cx.entity();
+                let page = window.use_state(cx, |_, _| {
+                    crate::pages::EditPredictionSetupPage::new(settings_window)
+                });
+                page.into_any_element()
+            }),
+        }),
         SettingsPageItem::SettingItem(SettingItem {
             title: "Show Edit Predictions",
-            description: "Controls whether edit predictions are shown immediately or manually by triggering `editor::showeditprediction` (false).",
+            description: "Controls whether edit predictions are shown immediately or manually.",
             field: Box::new(SettingField {
                 json_path: Some("languages.$(language).show_edit_predictions"),
                 pick: |settings_content| {
@@ -7399,7 +7685,7 @@ fn edit_prediction_language_settings_section() -> Vec<SettingsPageItem> {
             files: USER | PROJECT,
         }),
         SettingsPageItem::SettingItem(SettingItem {
-            title: "Edit Predictions Disabled In",
+            title: "Disable in Language Scopes",
             description: "Controls whether edit predictions are shown in the given language scopes.",
             field: Box::new(
                 SettingField {

crates/settings_ui/src/pages/edit_prediction_provider_setup.rs 🔗

@@ -0,0 +1,365 @@
+use edit_prediction::{
+    ApiKeyState, Zeta2FeatureFlag,
+    mercury::{MERCURY_CREDENTIALS_URL, mercury_api_token},
+    sweep_ai::{SWEEP_CREDENTIALS_URL, sweep_api_token},
+};
+use feature_flags::FeatureFlagAppExt as _;
+use gpui::{Entity, ScrollHandle, prelude::*};
+use language_models::provider::mistral::{CODESTRAL_API_URL, codestral_api_key};
+use ui::{ButtonLink, ConfiguredApiCard, WithScrollbar, prelude::*};
+
+use crate::{
+    SettingField, SettingItem, SettingsFieldMetadata, SettingsPageItem, SettingsWindow, USER,
+    components::{SettingsInputField, SettingsSectionHeader},
+};
+
+pub struct EditPredictionSetupPage {
+    settings_window: Entity<SettingsWindow>,
+    scroll_handle: ScrollHandle,
+}
+
+impl EditPredictionSetupPage {
+    pub fn new(settings_window: Entity<SettingsWindow>) -> Self {
+        Self {
+            settings_window,
+            scroll_handle: ScrollHandle::new(),
+        }
+    }
+}
+
+impl Render for EditPredictionSetupPage {
+    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
+        let settings_window = self.settings_window.clone();
+
+        let providers = [
+            Some(render_github_copilot_provider(window, cx).into_any_element()),
+            cx.has_flag::<Zeta2FeatureFlag>().then(|| {
+                render_api_key_provider(
+                    IconName::Inception,
+                    "Mercury",
+                    "https://platform.inceptionlabs.ai/dashboard/api-keys".into(),
+                    mercury_api_token(cx),
+                    |_cx| MERCURY_CREDENTIALS_URL,
+                    None,
+                    window,
+                    cx,
+                )
+                .into_any_element()
+            }),
+            cx.has_flag::<Zeta2FeatureFlag>().then(|| {
+                render_api_key_provider(
+                    IconName::SweepAi,
+                    "Sweep",
+                    "https://app.sweep.dev/".into(),
+                    sweep_api_token(cx),
+                    |_cx| SWEEP_CREDENTIALS_URL,
+                    None,
+                    window,
+                    cx,
+                )
+                .into_any_element()
+            }),
+            Some(
+                render_api_key_provider(
+                    IconName::AiMistral,
+                    "Codestral",
+                    "https://console.mistral.ai/codestral".into(),
+                    codestral_api_key(cx),
+                    |cx| language_models::MistralLanguageModelProvider::api_url(cx),
+                    Some(settings_window.update(cx, |settings_window, cx| {
+                        let codestral_settings = codestral_settings();
+                        settings_window
+                            .render_sub_page_items_section(
+                                codestral_settings.iter().enumerate(),
+                                None,
+                                window,
+                                cx,
+                            )
+                            .into_any_element()
+                    })),
+                    window,
+                    cx,
+                )
+                .into_any_element(),
+            ),
+        ];
+
+        div()
+            .size_full()
+            .vertical_scrollbar_for(&self.scroll_handle, window, cx)
+            .child(
+                v_flex()
+                    .id("ep-setup-page")
+                    .min_w_0()
+                    .size_full()
+                    .px_8()
+                    .pb_16()
+                    .overflow_y_scroll()
+                    .track_scroll(&self.scroll_handle)
+                    .children(providers.into_iter().flatten()),
+            )
+    }
+}
+
+fn render_api_key_provider(
+    icon: IconName,
+    title: &'static str,
+    link: SharedString,
+    api_key_state: Entity<ApiKeyState>,
+    current_url: fn(&mut App) -> SharedString,
+    additional_fields: Option<AnyElement>,
+    window: &mut Window,
+    cx: &mut Context<EditPredictionSetupPage>,
+) -> impl IntoElement {
+    let weak_page = cx.weak_entity();
+    _ = window.use_keyed_state(title, cx, |_, cx| {
+        let task = api_key_state.update(cx, |key_state, cx| {
+            key_state.load_if_needed(current_url(cx), |state| state, cx)
+        });
+        cx.spawn(async move |_, cx| {
+            task.await.ok();
+            weak_page
+                .update(cx, |_, cx| {
+                    cx.notify();
+                })
+                .ok();
+        })
+    });
+
+    let (has_key, env_var_name, is_from_env_var) = api_key_state.read_with(cx, |state, _| {
+        (
+            state.has_key(),
+            Some(state.env_var_name().clone()),
+            state.is_from_env_var(),
+        )
+    });
+
+    let write_key = move |api_key: Option<String>, cx: &mut App| {
+        api_key_state
+            .update(cx, |key_state, cx| {
+                let url = current_url(cx);
+                key_state.store(url, api_key, |key_state| key_state, cx)
+            })
+            .detach_and_log_err(cx);
+    };
+
+    let base_container = v_flex().id(title).min_w_0().pt_8().gap_1p5();
+    let header = SettingsSectionHeader::new(title)
+        .icon(icon)
+        .no_padding(true);
+    let button_link_label = format!("{} dashboard", title);
+    let description = h_flex()
+        .min_w_0()
+        .gap_0p5()
+        .child(
+            Label::new("Visit the")
+                .size(LabelSize::Small)
+                .color(Color::Muted),
+        )
+        .child(
+            ButtonLink::new(button_link_label, link)
+                .no_icon(true)
+                .label_size(LabelSize::Small)
+                .label_color(Color::Muted),
+        )
+        .child(
+            Label::new("to generate an API key.")
+                .size(LabelSize::Small)
+                .color(Color::Muted),
+        );
+    let configured_card_label = if is_from_env_var {
+        "API Key Set in Environment Variable"
+    } else {
+        "API Key Configured"
+    };
+
+    let container = if has_key {
+        base_container.child(header).child(
+            ConfiguredApiCard::new(configured_card_label)
+                .button_label("Reset Key")
+                .button_tab_index(0)
+                .disabled(is_from_env_var)
+                .when_some(env_var_name, |this, env_var_name| {
+                    this.when(is_from_env_var, |this| {
+                        this.tooltip_label(format!(
+                            "To reset your API key, unset the {} environment variable.",
+                            env_var_name
+                        ))
+                    })
+                })
+                .on_click(move |_, _, cx| {
+                    write_key(None, cx);
+                }),
+        )
+    } else {
+        base_container.child(header).child(
+            h_flex()
+                .pt_2p5()
+                .w_full()
+                .justify_between()
+                .child(
+                    v_flex()
+                        .w_full()
+                        .max_w_1_2()
+                        .child(Label::new("API Key"))
+                        .child(description)
+                        .when_some(env_var_name, |this, env_var_name| {
+                            this.child({
+                                let label = format!(
+                                    "Or set the {} env var and restart Zed.",
+                                    env_var_name.as_ref()
+                                );
+                                Label::new(label).size(LabelSize::Small).color(Color::Muted)
+                            })
+                        }),
+                )
+                .child(
+                    SettingsInputField::new()
+                        .tab_index(0)
+                        .with_placeholder("xxxxxxxxxxxxxxxxxxxx")
+                        .on_confirm(move |api_key, cx| {
+                            write_key(api_key.filter(|key| !key.is_empty()), cx);
+                        }),
+                ),
+        )
+    };
+
+    container.when_some(additional_fields, |this, additional_fields| {
+        this.child(
+            div()
+                .map(|this| if has_key { this.mt_1() } else { this.mt_4() })
+                .px_neg_8()
+                .border_t_1()
+                .border_color(cx.theme().colors().border_variant)
+                .child(additional_fields),
+        )
+    })
+}
+
+fn codestral_settings() -> Box<[SettingsPageItem]> {
+    Box::new([
+        SettingsPageItem::SettingItem(SettingItem {
+            title: "API URL",
+            description: "The API URL to use for Codestral.",
+            field: Box::new(SettingField {
+                pick: |settings| {
+                    settings
+                        .project
+                        .all_languages
+                        .edit_predictions
+                        .as_ref()?
+                        .codestral
+                        .as_ref()?
+                        .api_url
+                        .as_ref()
+                },
+                write: |settings, value| {
+                    settings
+                        .project
+                        .all_languages
+                        .edit_predictions
+                        .get_or_insert_default()
+                        .codestral
+                        .get_or_insert_default()
+                        .api_url = value;
+                },
+                json_path: Some("edit_predictions.codestral.api_url"),
+            }),
+            metadata: Some(Box::new(SettingsFieldMetadata {
+                placeholder: Some(CODESTRAL_API_URL),
+                ..Default::default()
+            })),
+            files: USER,
+        }),
+        SettingsPageItem::SettingItem(SettingItem {
+            title: "Max Tokens",
+            description: "The maximum number of tokens to generate.",
+            field: Box::new(SettingField {
+                pick: |settings| {
+                    settings
+                        .project
+                        .all_languages
+                        .edit_predictions
+                        .as_ref()?
+                        .codestral
+                        .as_ref()?
+                        .max_tokens
+                        .as_ref()
+                },
+                write: |settings, value| {
+                    settings
+                        .project
+                        .all_languages
+                        .edit_predictions
+                        .get_or_insert_default()
+                        .codestral
+                        .get_or_insert_default()
+                        .max_tokens = value;
+                },
+                json_path: Some("edit_predictions.codestral.max_tokens"),
+            }),
+            metadata: None,
+            files: USER,
+        }),
+        SettingsPageItem::SettingItem(SettingItem {
+            title: "Model",
+            description: "The Codestral model id to use.",
+            field: Box::new(SettingField {
+                pick: |settings| {
+                    settings
+                        .project
+                        .all_languages
+                        .edit_predictions
+                        .as_ref()?
+                        .codestral
+                        .as_ref()?
+                        .model
+                        .as_ref()
+                },
+                write: |settings, value| {
+                    settings
+                        .project
+                        .all_languages
+                        .edit_predictions
+                        .get_or_insert_default()
+                        .codestral
+                        .get_or_insert_default()
+                        .model = value;
+                },
+                json_path: Some("edit_predictions.codestral.model"),
+            }),
+            metadata: Some(Box::new(SettingsFieldMetadata {
+                placeholder: Some("codestral-latest"),
+                ..Default::default()
+            })),
+            files: USER,
+        }),
+    ])
+}
+
+pub(crate) fn render_github_copilot_provider(
+    window: &mut Window,
+    cx: &mut App,
+) -> impl IntoElement {
+    let configuration_view = window.use_state(cx, |_, cx| {
+        copilot::ConfigurationView::new(
+            |cx| {
+                copilot::Copilot::global(cx)
+                    .is_some_and(|copilot| copilot.read(cx).is_authenticated())
+            },
+            copilot::ConfigurationMode::EditPrediction,
+            cx,
+        )
+    });
+
+    v_flex()
+        .id("github-copilot")
+        .min_w_0()
+        .gap_1p5()
+        .child(
+            SettingsSectionHeader::new("GitHub Copilot")
+                .icon(IconName::Copilot)
+                .no_padding(true),
+        )
+        .child(configuration_view)
+}

crates/settings_ui/src/settings_ui.rs 🔗

@@ -1,9 +1,9 @@
 mod components;
 mod page_data;
+mod pages;
 
 use anyhow::Result;
 use editor::{Editor, EditorEvent};
-use feature_flags::FeatureFlag;
 use fuzzy::StringMatchCandidate;
 use gpui::{
     Action, App, ClipboardItem, DEFAULT_ADDITIONAL_WINDOW_SIZE, Div, Entity, FocusHandle,
@@ -28,9 +28,8 @@ use std::{
 };
 use title_bar::platform_title_bar::PlatformTitleBar;
 use ui::{
-    Banner, ContextMenu, Divider, DividerColor, DropdownMenu, DropdownStyle, IconButtonShape,
-    KeyBinding, KeybindingHint, PopoverMenu, Switch, SwitchColor, Tooltip, TreeViewItem,
-    WithScrollbar, prelude::*,
+    Banner, ContextMenu, Divider, DropdownMenu, DropdownStyle, IconButtonShape, KeyBinding,
+    KeybindingHint, PopoverMenu, Switch, Tooltip, TreeViewItem, WithScrollbar, prelude::*,
 };
 use ui_input::{NumberField, NumberFieldType};
 use util::{ResultExt as _, paths::PathStyle, rel_path::RelPath};
@@ -38,7 +37,8 @@ use workspace::{AppState, OpenOptions, OpenVisible, Workspace, client_side_decor
 use zed_actions::{OpenProjectSettings, OpenSettings, OpenSettingsAt};
 
 use crate::components::{
-    EnumVariantDropdown, SettingsInputField, font_picker, icon_theme_picker, theme_picker,
+    EnumVariantDropdown, SettingsInputField, SettingsSectionHeader, font_picker, icon_theme_picker,
+    theme_picker,
 };
 
 const NAVBAR_CONTAINER_TAB_INDEX: isize = 0;
@@ -345,8 +345,8 @@ impl NonFocusableHandle {
     fn from_handle(handle: FocusHandle, window: &mut Window, cx: &mut App) -> Entity<Self> {
         cx.new(|cx| {
             let _subscription = cx.on_focus(&handle, window, {
-                move |_, window, _| {
-                    window.focus_next();
+                move |_, window, cx| {
+                    window.focus_next(cx);
                 }
             });
             Self {
@@ -369,12 +369,6 @@ struct SettingsFieldMetadata {
     should_do_titlecase: Option<bool>,
 }
 
-pub struct SettingsUiFeatureFlag;
-
-impl FeatureFlag for SettingsUiFeatureFlag {
-    const NAME: &'static str = "settings-ui";
-}
-
 pub fn init(cx: &mut App) {
     init_renderers(cx);
 
@@ -608,12 +602,15 @@ pub fn open_settings_editor(
                 focus: true,
                 show: true,
                 is_movable: true,
-                kind: gpui::WindowKind::Floating,
+                kind: gpui::WindowKind::Normal,
                 window_background: cx.theme().window_background_appearance(),
                 app_id: Some(app_id.to_owned()),
                 window_decorations: Some(window_decorations),
                 window_min_size: Some(gpui::Size {
-                    width: px(360.0),
+                    // Don't make the settings window thinner than this,
+                    // otherwise, it gets unusable. Users with smaller res monitors
+                    // can customize the height, but not the width.
+                    width: px(900.0),
                     height: px(240.0),
                 }),
                 window_bounds: Some(WindowBounds::centered(scaled_bounds, cx)),
@@ -734,6 +731,7 @@ enum SettingsPageItem {
     SettingItem(SettingItem),
     SubPageLink(SubPageLink),
     DynamicItem(DynamicItem),
+    ActionLink(ActionLink),
 }
 
 impl std::fmt::Debug for SettingsPageItem {
@@ -749,6 +747,9 @@ impl std::fmt::Debug for SettingsPageItem {
             SettingsPageItem::DynamicItem(dynamic_item) => {
                 write!(f, "DynamicItem({})", dynamic_item.discriminant.title)
             }
+            SettingsPageItem::ActionLink(action_link) => {
+                write!(f, "ActionLink({})", action_link.title)
+            }
         }
     }
 }
@@ -834,18 +835,9 @@ impl SettingsPageItem {
             };
 
         match self {
-            SettingsPageItem::SectionHeader(header) => v_flex()
-                .w_full()
-                .px_8()
-                .gap_1p5()
-                .child(
-                    Label::new(SharedString::new_static(header))
-                        .size(LabelSize::Small)
-                        .color(Color::Muted)
-                        .buffer_font(cx),
-                )
-                .child(Divider::horizontal().color(DividerColor::BorderFaded))
-                .into_any_element(),
+            SettingsPageItem::SectionHeader(header) => {
+                SettingsSectionHeader::new(SharedString::new_static(header)).into_any_element()
+            }
             SettingsPageItem::SettingItem(setting_item) => {
                 let (field_with_padding, _) =
                     render_setting_item_inner(setting_item, true, false, cx);
@@ -869,9 +861,20 @@ impl SettingsPageItem {
                         .map(apply_padding)
                         .child(
                             v_flex()
+                                .relative()
                                 .w_full()
                                 .max_w_1_2()
-                                .child(Label::new(sub_page_link.title.clone())),
+                                .child(Label::new(sub_page_link.title.clone()))
+                                .when_some(
+                                    sub_page_link.description.as_ref(),
+                                    |this, description| {
+                                        this.child(
+                                            Label::new(description.clone())
+                                                .size(LabelSize::Small)
+                                                .color(Color::Muted),
+                                        )
+                                    },
+                                ),
                         )
                         .child(
                             Button::new(
@@ -887,7 +890,7 @@ impl SettingsPageItem {
                             .size(ButtonSize::Medium)
                             .on_click({
                                 let sub_page_link = sub_page_link.clone();
-                                cx.listener(move |this, _, _, cx| {
+                                cx.listener(move |this, _, window, cx| {
                                     let mut section_index = item_index;
                                     let current_page = this.current_page();
 
@@ -906,10 +909,16 @@ impl SettingsPageItem {
                                         )
                                     };
 
-                                    this.push_sub_page(sub_page_link.clone(), header, cx)
+                                    this.push_sub_page(sub_page_link.clone(), header, window, cx)
                                 })
                             }),
-                        ),
+                        )
+                        .child(render_settings_item_link(
+                            sub_page_link.title.clone(),
+                            sub_page_link.json_path,
+                            false,
+                            cx,
+                        )),
                 )
                 .when(!is_last, |this| this.child(Divider::horizontal()))
                 .into_any_element(),
@@ -968,6 +977,55 @@ impl SettingsPageItem {
 
                 return content.into_any_element();
             }
+            SettingsPageItem::ActionLink(action_link) => v_flex()
+                .group("setting-item")
+                .px_8()
+                .child(
+                    h_flex()
+                        .id(action_link.title.clone())
+                        .w_full()
+                        .min_w_0()
+                        .justify_between()
+                        .map(apply_padding)
+                        .child(
+                            v_flex()
+                                .relative()
+                                .w_full()
+                                .max_w_1_2()
+                                .child(Label::new(action_link.title.clone()))
+                                .when_some(
+                                    action_link.description.as_ref(),
+                                    |this, description| {
+                                        this.child(
+                                            Label::new(description.clone())
+                                                .size(LabelSize::Small)
+                                                .color(Color::Muted),
+                                        )
+                                    },
+                                ),
+                        )
+                        .child(
+                            Button::new(
+                                ("action-link".into(), action_link.title.clone()),
+                                action_link.button_text.clone(),
+                            )
+                            .icon(IconName::ArrowUpRight)
+                            .tab_index(0_isize)
+                            .icon_position(IconPosition::End)
+                            .icon_color(Color::Muted)
+                            .icon_size(IconSize::Small)
+                            .style(ButtonStyle::OutlinedGhost)
+                            .size(ButtonSize::Medium)
+                            .on_click({
+                                let on_click = action_link.on_click.clone();
+                                cx.listener(move |this, _, window, cx| {
+                                    on_click(this, window, cx);
+                                })
+                            }),
+                        ),
+                )
+                .when(!is_last, |this| this.child(Divider::horizontal()))
+                .into_any_element(),
         }
     }
 }
@@ -983,20 +1041,6 @@ fn render_settings_item(
     let (found_in_file, _) = setting_item.field.file_set_in(file.clone(), cx);
     let file_set_in = SettingsUiFile::from_settings(found_in_file.clone());
 
-    let clipboard_has_link = cx
-        .read_from_clipboard()
-        .and_then(|entry| entry.text())
-        .map_or(false, |maybe_url| {
-            setting_item.field.json_path().is_some()
-                && maybe_url.strip_prefix("zed://settings/") == setting_item.field.json_path()
-        });
-
-    let (link_icon, link_icon_color) = if clipboard_has_link {
-        (IconName::Check, Color::Success)
-    } else {
-        (IconName::Link, Color::Muted)
-    };
-
     h_flex()
         .id(setting_item.title)
         .min_w_0()
@@ -1056,40 +1100,60 @@ fn render_settings_item(
         )
         .child(control)
         .when(sub_page_stack().is_empty(), |this| {
-            // Intentionally using the description to make the icon button
-            // unique because some items share the same title (e.g., "Font Size")
-            let icon_button_id =
-                SharedString::new(format!("copy-link-btn-{}", setting_item.description));
+            this.child(render_settings_item_link(
+                setting_item.description,
+                setting_item.field.json_path(),
+                sub_field,
+                cx,
+            ))
+        })
+}
 
-            this.child(
-                div()
-                    .absolute()
-                    .top(rems_from_px(18.))
-                    .map(|this| {
-                        if sub_field {
-                            this.visible_on_hover("setting-sub-item")
-                                .left(rems_from_px(-8.5))
-                        } else {
-                            this.visible_on_hover("setting-item")
-                                .left(rems_from_px(-22.))
-                        }
-                    })
-                    .child({
-                        IconButton::new(icon_button_id, link_icon)
-                            .icon_color(link_icon_color)
-                            .icon_size(IconSize::Small)
-                            .shape(IconButtonShape::Square)
-                            .tooltip(Tooltip::text("Copy Link"))
-                            .when_some(setting_item.field.json_path(), |this, path| {
-                                this.on_click(cx.listener(move |_, _, _, cx| {
-                                    let link = format!("zed://settings/{}", path);
-                                    cx.write_to_clipboard(ClipboardItem::new_string(link));
-                                    cx.notify();
-                                }))
-                            })
-                    }),
-            )
+fn render_settings_item_link(
+    id: impl Into<ElementId>,
+    json_path: Option<&'static str>,
+    sub_field: bool,
+    cx: &mut Context<'_, SettingsWindow>,
+) -> impl IntoElement {
+    let clipboard_has_link = cx
+        .read_from_clipboard()
+        .and_then(|entry| entry.text())
+        .map_or(false, |maybe_url| {
+            json_path.is_some() && maybe_url.strip_prefix("zed://settings/") == json_path
+        });
+
+    let (link_icon, link_icon_color) = if clipboard_has_link {
+        (IconName::Check, Color::Success)
+    } else {
+        (IconName::Link, Color::Muted)
+    };
+
+    div()
+        .absolute()
+        .top(rems_from_px(18.))
+        .map(|this| {
+            if sub_field {
+                this.visible_on_hover("setting-sub-item")
+                    .left(rems_from_px(-8.5))
+            } else {
+                this.visible_on_hover("setting-item")
+                    .left(rems_from_px(-22.))
+            }
         })
+        .child(
+            IconButton::new((id.into(), "copy-link-btn"), link_icon)
+                .icon_color(link_icon_color)
+                .icon_size(IconSize::Small)
+                .shape(IconButtonShape::Square)
+                .tooltip(Tooltip::text("Copy Link"))
+                .when_some(json_path, |this, path| {
+                    this.on_click(cx.listener(move |_, _, _, cx| {
+                        let link = format!("zed://settings/{}", path);
+                        cx.write_to_clipboard(ClipboardItem::new_string(link));
+                        cx.notify();
+                    }))
+                }),
+        )
 }
 
 struct SettingItem {
@@ -1175,6 +1239,12 @@ impl PartialEq for SettingItem {
 #[derive(Clone)]
 struct SubPageLink {
     title: SharedString,
+    description: Option<SharedString>,
+    /// See [`SettingField.json_path`]
+    json_path: Option<&'static str>,
+    /// Whether or not the settings in this sub page are configurable in settings.json
+    /// Removes the "Edit in settings.json" button from the page.
+    in_json: bool,
     files: FileMask,
     render: Arc<
         dyn Fn(&mut SettingsWindow, &mut Window, &mut Context<SettingsWindow>) -> AnyElement
@@ -1190,6 +1260,20 @@ impl PartialEq for SubPageLink {
     }
 }
 
+#[derive(Clone)]
+struct ActionLink {
+    title: SharedString,
+    description: Option<SharedString>,
+    button_text: SharedString,
+    on_click: Arc<dyn Fn(&mut SettingsWindow, &mut Window, &mut App) + Send + Sync>,
+}
+
+impl PartialEq for ActionLink {
+    fn eq(&self, other: &Self) -> bool {
+        self.title == other.title
+    }
+}
+
 fn all_language_names(cx: &App) -> Vec<SharedString> {
     workspace::AppState::global(cx)
         .upgrade()
@@ -1453,7 +1537,7 @@ impl SettingsWindow {
         this.build_search_index();
 
         this.search_bar.update(cx, |editor, cx| {
-            editor.focus_handle(cx).focus(window);
+            editor.focus_handle(cx).focus(window, cx);
         });
 
         this
@@ -1609,6 +1693,9 @@ impl SettingsWindow {
                             any_found_since_last_header = true;
                         }
                     }
+                    SettingsPageItem::ActionLink(_) => {
+                        any_found_since_last_header = true;
+                    }
                 }
             }
             if let Some(last_header) = page_filter.get_mut(header_index)
@@ -1835,6 +1922,7 @@ impl SettingsWindow {
                         header_str = *header;
                     }
                     SettingsPageItem::SubPageLink(sub_page_link) => {
+                        json_path = sub_page_link.json_path;
                         documents.push(bm25::Document {
                             id: key_index,
                             contents: [page.title, header_str, sub_page_link.title.as_ref()]
@@ -1846,6 +1934,18 @@ impl SettingsWindow {
                             sub_page_link.title.as_ref(),
                         );
                     }
+                    SettingsPageItem::ActionLink(action_link) => {
+                        documents.push(bm25::Document {
+                            id: key_index,
+                            contents: [page.title, header_str, action_link.title.as_ref()]
+                                .join("\n"),
+                        });
+                        push_candidates(
+                            &mut fuzzy_match_candidates,
+                            key_index,
+                            action_link.title.as_ref(),
+                        );
+                    }
                 }
                 push_candidates(&mut fuzzy_match_candidates, key_index, page.title);
                 push_candidates(&mut fuzzy_match_candidates, key_index, header_str);
@@ -2074,7 +2174,7 @@ impl SettingsWindow {
                     let focus_handle = focus_handle.clone();
                     move |this, _: &gpui::ClickEvent, window, cx| {
                         this.change_file(ix, window, cx);
-                        focus_handle.focus(window);
+                        focus_handle.focus(window, cx);
                     }
                 }))
             };
@@ -2151,7 +2251,7 @@ impl SettingsWindow {
                                                             this.update(cx, |this, cx| {
                                                                 this.change_file(ix, window, cx);
                                                             });
-                                                            focus_handle.focus(window);
+                                                            focus_handle.focus(window, cx);
                                                         }
                                                     },
                                                 );
@@ -2285,7 +2385,7 @@ impl SettingsWindow {
                 let focused_entry_parent = this.root_entry_containing(focused_entry);
                 if this.navbar_entries[focused_entry_parent].expanded {
                     this.toggle_navbar_entry(focused_entry_parent);
-                    window.focus(&this.navbar_entries[focused_entry_parent].focus_handle);
+                    window.focus(&this.navbar_entries[focused_entry_parent].focus_handle, cx);
                 }
                 cx.notify();
             }))
@@ -2434,6 +2534,7 @@ impl SettingsWindow {
                                                         window.focus(
                                                             &this.navbar_entries[entry_index]
                                                                 .focus_handle,
+                                                            cx,
                                                         );
                                                         cx.notify();
                                                     },
@@ -2558,7 +2659,7 @@ impl SettingsWindow {
         // back to back.
         cx.on_next_frame(window, move |_, window, cx| {
             if let Some(handle) = handle_to_focus.as_ref() {
-                window.focus(handle);
+                window.focus(handle, cx);
             }
 
             cx.on_next_frame(window, |_, _, cx| {
@@ -2625,7 +2726,7 @@ impl SettingsWindow {
         };
         self.navbar_scroll_handle
             .scroll_to_item(position, gpui::ScrollStrategy::Top);
-        window.focus(&self.navbar_entries[nav_entry_index].focus_handle);
+        window.focus(&self.navbar_entries[nav_entry_index].focus_handle, cx);
         cx.notify();
     }
 
@@ -2758,19 +2859,49 @@ impl SettingsWindow {
         page_content
     }
 
-    fn render_sub_page_items<'a, Items: Iterator<Item = (usize, &'a SettingsPageItem)>>(
+    fn render_sub_page_items<'a, Items>(
         &self,
         items: Items,
         page_index: Option<usize>,
         window: &mut Window,
         cx: &mut Context<SettingsWindow>,
-    ) -> impl IntoElement {
-        let mut page_content = v_flex()
+    ) -> impl IntoElement
+    where
+        Items: Iterator<Item = (usize, &'a SettingsPageItem)>,
+    {
+        let page_content = v_flex()
             .id("settings-ui-page")
             .size_full()
             .overflow_y_scroll()
             .track_scroll(&self.sub_page_scroll_handle);
+        self.render_sub_page_items_in(page_content, items, page_index, window, cx)
+    }
+
+    fn render_sub_page_items_section<'a, Items>(
+        &self,
+        items: Items,
+        page_index: Option<usize>,
+        window: &mut Window,
+        cx: &mut Context<SettingsWindow>,
+    ) -> impl IntoElement
+    where
+        Items: Iterator<Item = (usize, &'a SettingsPageItem)>,
+    {
+        let page_content = v_flex().id("settings-ui-sub-page-section").size_full();
+        self.render_sub_page_items_in(page_content, items, page_index, window, cx)
+    }
 
+    fn render_sub_page_items_in<'a, Items>(
+        &self,
+        mut page_content: Stateful<Div>,
+        items: Items,
+        page_index: Option<usize>,
+        window: &mut Window,
+        cx: &mut Context<SettingsWindow>,
+    ) -> impl IntoElement
+    where
+        Items: Iterator<Item = (usize, &'a SettingsPageItem)>,
+    {
         let items: Vec<_> = items.collect();
         let items_len = items.len();
         let mut section_header = None;
@@ -2865,24 +2996,31 @@ impl SettingsWindow {
                             IconButton::new("back-btn", IconName::ArrowLeft)
                                 .icon_size(IconSize::Small)
                                 .shape(IconButtonShape::Square)
-                                .on_click(cx.listener(|this, _, _, cx| {
-                                    this.pop_sub_page(cx);
+                                .on_click(cx.listener(|this, _, window, cx| {
+                                    this.pop_sub_page(window, cx);
                                 })),
                         )
                         .child(self.render_sub_page_breadcrumbs()),
                 )
-                .child(
-                    Button::new("open-in-settings-file", "Edit in settings.json")
-                        .tab_index(0_isize)
-                        .style(ButtonStyle::OutlinedGhost)
-                        .tooltip(Tooltip::for_action_title_in(
-                            "Edit in settings.json",
-                            &OpenCurrentFile,
-                            &self.focus_handle,
-                        ))
-                        .on_click(cx.listener(|this, _, window, cx| {
-                            this.open_current_settings_file(window, cx);
-                        })),
+                .when(
+                    sub_page_stack()
+                        .last()
+                        .is_none_or(|sub_page| sub_page.link.in_json),
+                    |this| {
+                        this.child(
+                            Button::new("open-in-settings-file", "Edit in settings.json")
+                                .tab_index(0_isize)
+                                .style(ButtonStyle::OutlinedGhost)
+                                .tooltip(Tooltip::for_action_title_in(
+                                    "Edit in settings.json",
+                                    &OpenCurrentFile,
+                                    &self.focus_handle,
+                                ))
+                                .on_click(cx.listener(|this, _, window, cx| {
+                                    this.open_current_settings_file(window, cx);
+                                })),
+                        )
+                    },
                 )
                 .into_any_element();
 
@@ -2963,7 +3101,7 @@ impl SettingsWindow {
             .id("settings-ui-page")
             .on_action(cx.listener(|this, _: &menu::SelectNext, window, cx| {
                 if !sub_page_stack().is_empty() {
-                    window.focus_next();
+                    window.focus_next(cx);
                     return;
                 }
                 for (logical_index, (actual_index, _)) in this.visible_page_items().enumerate() {
@@ -2983,7 +3121,7 @@ impl SettingsWindow {
                         cx.on_next_frame(window, |_, window, cx| {
                             cx.notify();
                             cx.on_next_frame(window, |_, window, cx| {
-                                window.focus_next();
+                                window.focus_next(cx);
                                 cx.notify();
                             });
                         });
@@ -2991,11 +3129,11 @@ impl SettingsWindow {
                         return;
                     }
                 }
-                window.focus_next();
+                window.focus_next(cx);
             }))
             .on_action(cx.listener(|this, _: &menu::SelectPrevious, window, cx| {
                 if !sub_page_stack().is_empty() {
-                    window.focus_prev();
+                    window.focus_prev(cx);
                     return;
                 }
                 let mut prev_was_header = false;
@@ -3015,7 +3153,7 @@ impl SettingsWindow {
                         cx.on_next_frame(window, |_, window, cx| {
                             cx.notify();
                             cx.on_next_frame(window, |_, window, cx| {
-                                window.focus_prev();
+                                window.focus_prev(cx);
                                 cx.notify();
                             });
                         });
@@ -3024,7 +3162,7 @@ impl SettingsWindow {
                     }
                     prev_was_header = is_header;
                 }
-                window.focus_prev();
+                window.focus_prev(cx);
             }))
             .when(sub_page_stack().is_empty(), |this| {
                 this.vertical_scrollbar_for(&self.list_state, window, cx)
@@ -3218,23 +3356,28 @@ impl SettingsWindow {
         &mut self,
         sub_page_link: SubPageLink,
         section_header: &'static str,
+        window: &mut Window,
         cx: &mut Context<SettingsWindow>,
     ) {
         sub_page_stack_mut().push(SubPage {
             link: sub_page_link,
             section_header,
         });
+        self.sub_page_scroll_handle
+            .set_offset(point(px(0.), px(0.)));
+        self.content_focus_handle.focus_handle(cx).focus(window, cx);
         cx.notify();
     }
 
-    fn pop_sub_page(&mut self, cx: &mut Context<SettingsWindow>) {
+    fn pop_sub_page(&mut self, window: &mut Window, cx: &mut Context<SettingsWindow>) {
         sub_page_stack_mut().pop();
+        self.content_focus_handle.focus_handle(cx).focus(window, cx);
         cx.notify();
     }
 
-    fn focus_file_at_index(&mut self, index: usize, window: &mut Window) {
+    fn focus_file_at_index(&mut self, index: usize, window: &mut Window, cx: &mut App) {
         if let Some((_, handle)) = self.files.get(index) {
-            handle.focus(window);
+            handle.focus(window, cx);
         }
     }
 
@@ -3314,7 +3457,7 @@ impl Render for SettingsWindow {
                             window.minimize_window();
                         })
                         .on_action(cx.listener(|this, _: &search::FocusSearch, window, cx| {
-                            this.search_bar.focus_handle(cx).focus(window);
+                            this.search_bar.focus_handle(cx).focus(window, cx);
                         }))
                         .on_action(cx.listener(|this, _: &ToggleFocusNav, window, cx| {
                             if this
@@ -3334,8 +3477,8 @@ impl Render for SettingsWindow {
                             }
                         }))
                         .on_action(cx.listener(
-                            |this, FocusFile(file_index): &FocusFile, window, _| {
-                                this.focus_file_at_index(*file_index as usize, window);
+                            |this, FocusFile(file_index): &FocusFile, window, cx| {
+                                this.focus_file_at_index(*file_index as usize, window, cx);
                             },
                         ))
                         .on_action(cx.listener(|this, _: &FocusNextFile, window, cx| {
@@ -3343,11 +3486,11 @@ impl Render for SettingsWindow {
                                 this.focused_file_index(window, cx) + 1,
                                 this.files.len().saturating_sub(1),
                             );
-                            this.focus_file_at_index(next_index, window);
+                            this.focus_file_at_index(next_index, window, cx);
                         }))
                         .on_action(cx.listener(|this, _: &FocusPreviousFile, window, cx| {
                             let prev_index = this.focused_file_index(window, cx).saturating_sub(1);
-                            this.focus_file_at_index(prev_index, window);
+                            this.focus_file_at_index(prev_index, window, cx);
                         }))
                         .on_action(cx.listener(|this, _: &menu::SelectNext, window, cx| {
                             if this
@@ -3357,11 +3500,11 @@ impl Render for SettingsWindow {
                             {
                                 this.focus_and_scroll_to_first_visible_nav_entry(window, cx);
                             } else {
-                                window.focus_next();
+                                window.focus_next(cx);
                             }
                         }))
-                        .on_action(|_: &menu::SelectPrevious, window, _| {
-                            window.focus_prev();
+                        .on_action(|_: &menu::SelectPrevious, window, cx| {
+                            window.focus_prev(cx);
                         })
                         .flex()
                         .flex_row()
@@ -3501,7 +3644,6 @@ fn render_toggle_button<B: Into<bool> + From<bool> + Copy>(
 
     Switch::new("toggle_button", toggle_state)
         .tab_index(0_isize)
-        .color(SwitchColor::Accent)
         .on_click({
             move |state, _window, cx| {
                 telemetry::event!("Settings Change", setting = field.json_path, type = file.setting_type());

crates/snippet_provider/src/format.rs 🔗

@@ -2,7 +2,7 @@ use collections::HashMap;
 use schemars::{JsonSchema, json_schema};
 use serde::Deserialize;
 use std::borrow::Cow;
-use util::schemars::DefaultDenyUnknownFields;
+use util::schemars::{AllowTrailingCommas, DefaultDenyUnknownFields};
 
 #[derive(Deserialize)]
 pub struct VsSnippetsFile {
@@ -14,6 +14,7 @@ impl VsSnippetsFile {
     pub fn generate_json_schema() -> serde_json::Value {
         let schema = schemars::generate::SchemaSettings::draft2019_09()
             .with_transform(DefaultDenyUnknownFields)
+            .with_transform(AllowTrailingCommas)
             .into_generator()
             .root_schema_for::<Self>();
 

crates/snippet_provider/src/lib.rs 🔗

@@ -22,7 +22,7 @@ pub fn init(cx: &mut App) {
     extension_snippet::init(cx);
 }
 
-// Is `None` if the snippet file is global.
+/// Language name, or `None` if the snippet file is global.
 type SnippetKind = Option<String>;
 fn file_stem_to_key(stem: &str) -> SnippetKind {
     if stem == "snippets" {

crates/sum_tree/Cargo.toml 🔗

@@ -17,8 +17,13 @@ doctest = false
 arrayvec = "0.7.1"
 rayon.workspace = true
 log.workspace = true
+ztracing.workspace = true
+tracing.workspace = true
 
 [dev-dependencies]
 ctor.workspace = true
 rand.workspace = true
 zlog.workspace = true
+
+[package.metadata.cargo-machete]
+ignored = ["tracing"]

crates/sum_tree/src/cursor.rs 🔗

@@ -1,6 +1,7 @@
 use super::*;
 use arrayvec::ArrayVec;
 use std::{cmp::Ordering, mem, sync::Arc};
+use ztracing::instrument;
 
 #[derive(Clone)]
 struct StackEntry<'a, T: Item, D> {
@@ -211,6 +212,7 @@ where
     }
 
     #[track_caller]
+    #[instrument(skip_all)]
     pub fn prev(&mut self) {
         self.search_backward(|_| true)
     }
@@ -394,6 +396,7 @@ where
 {
     /// Returns whether we found the item you were seeking for.
     #[track_caller]
+    #[instrument(skip_all)]
     pub fn seek<Target>(&mut self, pos: &Target, bias: Bias) -> bool
     where
         Target: SeekTarget<'a, T::Summary, D>,
@@ -408,6 +411,7 @@ where
     ///
     /// If we did not seek before, use seek instead in that case.
     #[track_caller]
+    #[instrument(skip_all)]
     pub fn seek_forward<Target>(&mut self, pos: &Target, bias: Bias) -> bool
     where
         Target: SeekTarget<'a, T::Summary, D>,
@@ -449,6 +453,7 @@ where
 
     /// Returns whether we found the item you were seeking for.
     #[track_caller]
+    #[instrument(skip_all)]
     fn seek_internal(
         &mut self,
         target: &dyn SeekTarget<'a, T::Summary, D>,

crates/sum_tree/src/sum_tree.rs 🔗

@@ -8,6 +8,7 @@ use std::marker::PhantomData;
 use std::mem;
 use std::{cmp::Ordering, fmt, iter::FromIterator, sync::Arc};
 pub use tree_map::{MapSeekTarget, TreeMap, TreeSet};
+use ztracing::instrument;
 
 #[cfg(test)]
 pub const TREE_BASE: usize = 2;
@@ -249,11 +250,11 @@ impl<T: Item> SumTree<T> {
                 <T::Summary as Summary>::add_summary(&mut summary, item_summary, cx);
             }
 
-            nodes.push(Node::Leaf {
+            nodes.push(SumTree(Arc::new(Node::Leaf {
                 summary,
                 items,
                 item_summaries,
-            });
+            })));
         }
 
         let mut parent_nodes = Vec::new();
@@ -262,25 +263,27 @@ impl<T: Item> SumTree<T> {
             height += 1;
             let mut current_parent_node = None;
             for child_node in nodes.drain(..) {
-                let parent_node = current_parent_node.get_or_insert_with(|| Node::Internal {
-                    summary: <T::Summary as Summary>::zero(cx),
-                    height,
-                    child_summaries: ArrayVec::new(),
-                    child_trees: ArrayVec::new(),
+                let parent_node = current_parent_node.get_or_insert_with(|| {
+                    SumTree(Arc::new(Node::Internal {
+                        summary: <T::Summary as Summary>::zero(cx),
+                        height,
+                        child_summaries: ArrayVec::new(),
+                        child_trees: ArrayVec::new(),
+                    }))
                 });
                 let Node::Internal {
                     summary,
                     child_summaries,
                     child_trees,
                     ..
-                } = parent_node
+                } = Arc::get_mut(&mut parent_node.0).unwrap()
                 else {
                     unreachable!()
                 };
                 let child_summary = child_node.summary();
                 <T::Summary as Summary>::add_summary(summary, child_summary, cx);
                 child_summaries.push(child_summary.clone());
-                child_trees.push(Self(Arc::new(child_node)));
+                child_trees.push(child_node);
 
                 if child_trees.len() == 2 * TREE_BASE {
                     parent_nodes.extend(current_parent_node.take());
@@ -294,7 +297,7 @@ impl<T: Item> SumTree<T> {
             Self::new(cx)
         } else {
             debug_assert_eq!(nodes.len(), 1);
-            Self(Arc::new(nodes.pop().unwrap()))
+            nodes.pop().unwrap()
         }
     }
 
@@ -379,6 +382,7 @@ impl<T: Item> SumTree<T> {
     /// A more efficient version of `Cursor::new()` + `Cursor::seek()` + `Cursor::item()`.
     ///
     /// Only returns the item that exactly has the target match.
+    #[instrument(skip_all)]
     pub fn find_exact<'a, 'slf, D, Target>(
         &'slf self,
         cx: <T::Summary as Summary>::Context<'a>,
@@ -404,6 +408,7 @@ impl<T: Item> SumTree<T> {
     }
 
     /// A more efficient version of `Cursor::new()` + `Cursor::seek()` + `Cursor::item()`
+    #[instrument(skip_all)]
     pub fn find<'a, 'slf, D, Target>(
         &'slf self,
         cx: <T::Summary as Summary>::Context<'a>,

crates/supermaven/Cargo.toml 🔗

@@ -16,7 +16,7 @@ doctest = false
 anyhow.workspace = true
 client.workspace = true
 collections.workspace = true
-edit_prediction.workspace = true
+edit_prediction_types.workspace = true
 futures.workspace = true
 gpui.workspace = true
 language.workspace = true

crates/supermaven/src/supermaven.rs 🔗

@@ -1,7 +1,7 @@
 mod messages;
-mod supermaven_completion_provider;
+mod supermaven_edit_prediction_delegate;
 
-pub use supermaven_completion_provider::*;
+pub use supermaven_edit_prediction_delegate::*;
 
 use anyhow::{Context as _, Result};
 #[allow(unused_imports)]

crates/supermaven/src/supermaven_completion_provider.rs → crates/supermaven/src/supermaven_edit_prediction_delegate.rs 🔗

@@ -1,6 +1,6 @@
 use crate::{Supermaven, SupermavenCompletionStateId};
 use anyhow::Result;
-use edit_prediction::{Direction, EditPrediction, EditPredictionProvider};
+use edit_prediction_types::{EditPrediction, EditPredictionDelegate};
 use futures::StreamExt as _;
 use gpui::{App, Context, Entity, EntityId, Task};
 use language::{Anchor, Buffer, BufferSnapshot};
@@ -15,7 +15,7 @@ use unicode_segmentation::UnicodeSegmentation;
 
 pub const DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
 
-pub struct SupermavenCompletionProvider {
+pub struct SupermavenEditPredictionDelegate {
     supermaven: Entity<Supermaven>,
     buffer_id: Option<EntityId>,
     completion_id: Option<SupermavenCompletionStateId>,
@@ -25,7 +25,7 @@ pub struct SupermavenCompletionProvider {
     completion_position: Option<language::Anchor>,
 }
 
-impl SupermavenCompletionProvider {
+impl SupermavenEditPredictionDelegate {
     pub fn new(supermaven: Entity<Supermaven>) -> Self {
         Self {
             supermaven,
@@ -104,7 +104,7 @@ fn completion_from_diff(
     }
 }
 
-impl EditPredictionProvider for SupermavenCompletionProvider {
+impl EditPredictionDelegate for SupermavenEditPredictionDelegate {
     fn name() -> &'static str {
         "supermaven"
     }
@@ -113,7 +113,7 @@ impl EditPredictionProvider for SupermavenCompletionProvider {
         "Supermaven"
     }
 
-    fn show_completions_in_menu() -> bool {
+    fn show_predictions_in_menu() -> bool {
         true
     }
 
@@ -189,15 +189,6 @@ impl EditPredictionProvider for SupermavenCompletionProvider {
         }));
     }
 
-    fn cycle(
-        &mut self,
-        _buffer: Entity<Buffer>,
-        _cursor_position: Anchor,
-        _direction: Direction,
-        _cx: &mut Context<Self>,
-    ) {
-    }
-
     fn accept(&mut self, _cx: &mut Context<Self>) {
         reset_completion_cache(self, _cx);
     }
@@ -269,8 +260,8 @@ impl EditPredictionProvider for SupermavenCompletionProvider {
 }
 
 fn reset_completion_cache(
-    provider: &mut SupermavenCompletionProvider,
-    _cx: &mut Context<SupermavenCompletionProvider>,
+    provider: &mut SupermavenEditPredictionDelegate,
+    _cx: &mut Context<SupermavenEditPredictionDelegate>,
 ) {
     provider.pending_refresh = None;
     provider.completion_id = None;

crates/tab_switcher/src/tab_switcher.rs 🔗

@@ -23,9 +23,9 @@ use ui::{
 };
 use util::ResultExt;
 use workspace::{
-    ModalView, Pane, SaveIntent, Workspace,
+    Event as WorkspaceEvent, ModalView, Pane, SaveIntent, Workspace,
     item::{ItemHandle, ItemSettings, ShowDiagnostics, TabContentParams},
-    pane::{Event as PaneEvent, render_item_indicator, tab_details},
+    pane::{render_item_indicator, tab_details},
 };
 
 const PANEL_WIDTH_REMS: f32 = 28.;
@@ -322,7 +322,7 @@ impl TabSwitcherDelegate {
         cx: &mut Context<TabSwitcher>,
         original_items: Vec<(Entity<Pane>, usize)>,
     ) -> Self {
-        Self::subscribe_to_updates(&pane, window, cx);
+        Self::subscribe_to_updates(&workspace, window, cx);
         Self {
             select_last,
             tab_switcher,
@@ -338,22 +338,36 @@ impl TabSwitcherDelegate {
     }
 
     fn subscribe_to_updates(
-        pane: &WeakEntity<Pane>,
+        workspace: &WeakEntity<Workspace>,
         window: &mut Window,
         cx: &mut Context<TabSwitcher>,
     ) {
-        let Some(pane) = pane.upgrade() else {
+        let Some(workspace) = workspace.upgrade() else {
             return;
         };
-        cx.subscribe_in(&pane, window, |tab_switcher, _, event, window, cx| {
+        cx.subscribe_in(&workspace, window, |tab_switcher, _, event, window, cx| {
             match event {
-                PaneEvent::AddItem { .. }
-                | PaneEvent::RemovedItem { .. }
-                | PaneEvent::Remove { .. } => tab_switcher.picker.update(cx, |picker, cx| {
-                    let query = picker.query(cx);
-                    picker.delegate.update_matches(query, window, cx);
-                    cx.notify();
-                }),
+                WorkspaceEvent::ItemAdded { .. } | WorkspaceEvent::PaneRemoved => {
+                    tab_switcher.picker.update(cx, |picker, cx| {
+                        let query = picker.query(cx);
+                        picker.delegate.update_matches(query, window, cx);
+                        cx.notify();
+                    })
+                }
+                WorkspaceEvent::ItemRemoved { .. } => {
+                    tab_switcher.picker.update(cx, |picker, cx| {
+                        let query = picker.query(cx);
+                        picker.delegate.update_matches(query, window, cx);
+
+                        // When the Tab Switcher is being used and an item is
+                        // removed, there's a chance that the new selected index
+                        // will not match the actual tab that is now being displayed
+                        // by the pane, as such, the selected index needs to be
+                        // updated to match the pane's state.
+                        picker.delegate.sync_selected_index(cx);
+                        cx.notify();
+                    })
+                }
                 _ => {}
             };
         })
@@ -515,7 +529,9 @@ impl TabSwitcherDelegate {
         }
 
         if self.select_last {
-            return self.matches.len() - 1;
+            let item_index = self.matches.len() - 1;
+            self.set_selected_index(item_index, window, cx);
+            return item_index;
         }
 
         // This only runs when initially opening the picker
@@ -540,11 +556,40 @@ impl TabSwitcherDelegate {
         let Some(pane) = tab_match.pane.upgrade() else {
             return;
         };
+
         pane.update(cx, |pane, cx| {
             pane.close_item_by_id(tab_match.item.item_id(), SaveIntent::Close, window, cx)
                 .detach_and_log_err(cx);
         });
     }
+
+    /// Updates the selected index to ensure it matches the pane's active item,
+    /// as the pane's active item can be indirectly updated and this method
+    /// ensures that the picker can react to those changes.
+    fn sync_selected_index(&mut self, cx: &mut Context<Picker<TabSwitcherDelegate>>) {
+        let item = if self.is_all_panes {
+            self.workspace
+                .read_with(cx, |workspace, cx| workspace.active_item(cx))
+        } else {
+            self.pane.read_with(cx, |pane, _cx| pane.active_item())
+        };
+
+        let Ok(Some(item)) = item else {
+            return;
+        };
+
+        let item_id = item.item_id();
+        let Some((index, _tab_match)) = self
+            .matches
+            .iter()
+            .enumerate()
+            .find(|(_index, tab_match)| tab_match.item.item_id() == item_id)
+        else {
+            return;
+        };
+
+        self.selected_index = index;
+    }
 }
 
 impl PickerDelegate for TabSwitcherDelegate {

crates/tab_switcher/src/tab_switcher_tests.rs 🔗

@@ -5,7 +5,7 @@ use menu::SelectPrevious;
 use project::{Project, ProjectPath};
 use serde_json::json;
 use util::{path, rel_path::rel_path};
-use workspace::{AppState, Workspace};
+use workspace::{ActivatePreviousItem, AppState, Workspace};
 
 #[ctor::ctor]
 fn init_logger() {
@@ -197,6 +197,8 @@ async fn test_close_selected_item(cx: &mut gpui::TestAppContext) {
             json!({
                 "1.txt": "First file",
                 "2.txt": "Second file",
+                "3.txt": "Third file",
+                "4.txt": "Fourth file",
             }),
         )
         .await;
@@ -206,80 +208,47 @@ async fn test_close_selected_item(cx: &mut gpui::TestAppContext) {
         cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
 
     let tab_1 = open_buffer("1.txt", &workspace, cx).await;
+    let tab_3 = open_buffer("3.txt", &workspace, cx).await;
     let tab_2 = open_buffer("2.txt", &workspace, cx).await;
+    let tab_4 = open_buffer("4.txt", &workspace, cx).await;
+
+    // After opening all buffers, let's navigate to the previous item two times, finishing with:
+    //
+    // 1.txt | [3.txt] | 2.txt | 4.txt
+    //
+    // With 3.txt being the active item in the pane.
+    cx.dispatch_action(ActivatePreviousItem);
+    cx.dispatch_action(ActivatePreviousItem);
+    cx.run_until_parked();
 
     cx.simulate_modifiers_change(Modifiers::control());
     let tab_switcher = open_tab_switcher(false, &workspace, cx);
     tab_switcher.update(cx, |tab_switcher, _| {
-        assert_eq!(tab_switcher.delegate.matches.len(), 2);
-        assert_match_at_position(tab_switcher, 0, tab_2.boxed_clone());
-        assert_match_selection(tab_switcher, 1, tab_1.boxed_clone());
+        assert_eq!(tab_switcher.delegate.matches.len(), 4);
+        assert_match_at_position(tab_switcher, 0, tab_3.boxed_clone());
+        assert_match_selection(tab_switcher, 1, tab_2.boxed_clone());
+        assert_match_at_position(tab_switcher, 2, tab_4.boxed_clone());
+        assert_match_at_position(tab_switcher, 3, tab_1.boxed_clone());
     });
 
     cx.simulate_modifiers_change(Modifiers::control());
     cx.dispatch_action(CloseSelectedItem);
     tab_switcher.update(cx, |tab_switcher, _| {
-        assert_eq!(tab_switcher.delegate.matches.len(), 1);
-        assert_match_selection(tab_switcher, 0, tab_2);
+        assert_eq!(tab_switcher.delegate.matches.len(), 3);
+        assert_match_selection(tab_switcher, 0, tab_3);
+        assert_match_at_position(tab_switcher, 1, tab_4);
+        assert_match_at_position(tab_switcher, 2, tab_1);
     });
 
     // Still switches tab on modifiers release
     cx.simulate_modifiers_change(Modifiers::none());
     cx.read(|cx| {
         let active_editor = workspace.read(cx).active_item_as::<Editor>(cx).unwrap();
-        assert_eq!(active_editor.read(cx).title(cx), "2.txt");
+        assert_eq!(active_editor.read(cx).title(cx), "3.txt");
     });
     assert_tab_switcher_is_closed(workspace, cx);
 }
 
-#[gpui::test]
-async fn test_close_preserves_selected_position(cx: &mut gpui::TestAppContext) {
-    let app_state = init_test(cx);
-    app_state
-        .fs
-        .as_fake()
-        .insert_tree(
-            path!("/root"),
-            json!({
-                "1.txt": "First file",
-                "2.txt": "Second file",
-                "3.txt": "Third file",
-            }),
-        )
-        .await;
-
-    let project = Project::test(app_state.fs.clone(), [path!("/root").as_ref()], cx).await;
-    let (workspace, cx) =
-        cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
-
-    let tab_1 = open_buffer("1.txt", &workspace, cx).await;
-    let tab_2 = open_buffer("2.txt", &workspace, cx).await;
-    let tab_3 = open_buffer("3.txt", &workspace, cx).await;
-
-    let tab_switcher = open_tab_switcher(false, &workspace, cx);
-    tab_switcher.update(cx, |tab_switcher, _| {
-        assert_eq!(tab_switcher.delegate.matches.len(), 3);
-        assert_match_at_position(tab_switcher, 0, tab_3.boxed_clone());
-        assert_match_selection(tab_switcher, 1, tab_2.boxed_clone());
-        assert_match_at_position(tab_switcher, 2, tab_1.boxed_clone());
-    });
-
-    // Verify that if the selected tab was closed, tab at the same position is selected.
-    cx.dispatch_action(CloseSelectedItem);
-    tab_switcher.update(cx, |tab_switcher, _| {
-        assert_eq!(tab_switcher.delegate.matches.len(), 2);
-        assert_match_at_position(tab_switcher, 0, tab_3.boxed_clone());
-        assert_match_selection(tab_switcher, 1, tab_1.boxed_clone());
-    });
-
-    // But if the position is no longer valid, fall back to the position above.
-    cx.dispatch_action(CloseSelectedItem);
-    tab_switcher.update(cx, |tab_switcher, _| {
-        assert_eq!(tab_switcher.delegate.matches.len(), 1);
-        assert_match_selection(tab_switcher, 0, tab_3.boxed_clone());
-    });
-}
-
 fn init_test(cx: &mut TestAppContext) -> Arc<AppState> {
     cx.update(|cx| {
         let state = AppState::test(cx);

crates/task/src/debug_format.rs 🔗

@@ -357,6 +357,7 @@ impl DebugTaskFile {
             "$schema": meta_schema,
             "title": "Debug Configurations",
             "description": "Configuration for debug scenarios",
+            "allowTrailingCommas": true,
             "type": "array",
             "items": {
                 "type": "object",

crates/task/src/task_template.rs 🔗

@@ -4,7 +4,7 @@ use schemars::JsonSchema;
 use serde::{Deserialize, Serialize};
 use sha2::{Digest, Sha256};
 use std::path::PathBuf;
-use util::schemars::DefaultDenyUnknownFields;
+use util::schemars::{AllowTrailingCommas, DefaultDenyUnknownFields};
 use util::serde::default_true;
 use util::{ResultExt, truncate_and_remove_front};
 
@@ -118,6 +118,7 @@ impl TaskTemplates {
     pub fn generate_json_schema() -> serde_json::Value {
         let schema = schemars::generate::SchemaSettings::draft2019_09()
             .with_transform(DefaultDenyUnknownFields)
+            .with_transform(AllowTrailingCommas)
             .into_generator()
             .root_schema_for::<Self>();
 

crates/tasks_ui/src/modal.rs 🔗

@@ -5,8 +5,8 @@ use editor::Editor;
 use fuzzy::{StringMatch, StringMatchCandidate};
 use gpui::{
     Action, AnyElement, App, AppContext as _, Context, DismissEvent, Entity, EventEmitter,
-    Focusable, InteractiveElement, ParentElement, Render, SharedString, Styled, Subscription, Task,
-    WeakEntity, Window, rems,
+    Focusable, InteractiveElement, ParentElement, Render, Styled, Subscription, Task, WeakEntity,
+    Window, rems,
 };
 use itertools::Itertools;
 use picker::{Picker, PickerDelegate, highlighted_match_with_paths::HighlightedMatch};
@@ -526,7 +526,7 @@ impl PickerDelegate for TasksModalDelegate {
         };
 
         Some(
-            ListItem::new(SharedString::from(format!("tasks-modal-{ix}")))
+            ListItem::new(format!("tasks-modal-{ix}"))
                 .inset(true)
                 .start_slot::<IconWithIndicator>(icon)
                 .end_slot::<AnyElement>(

crates/terminal/Cargo.toml 🔗

@@ -28,6 +28,7 @@ gpui.workspace = true
 itertools.workspace = true
 libc.workspace = true
 log.workspace = true
+regex.workspace = true
 release_channel.workspace = true
 schemars.workspace = true
 serde.workspace = true
@@ -37,8 +38,8 @@ smol.workspace = true
 task.workspace = true
 theme.workspace = true
 thiserror.workspace = true
+url.workspace = true
 util.workspace = true
-fancy-regex.workspace = true
 urlencoding.workspace = true
 
 [target.'cfg(windows)'.dependencies]
@@ -49,5 +50,4 @@ gpui = { workspace = true, features = ["test-support"] }
 rand.workspace = true
 serde_json.workspace = true
 settings = { workspace = true, features = ["test-support"] }
-url.workspace = true
 util_macros.workspace = true

crates/terminal/src/terminal.rs 🔗

@@ -155,8 +155,8 @@ enum InternalEvent {
     ScrollToAlacPoint(AlacPoint),
     SetSelection(Option<(Selection, AlacPoint)>),
     UpdateSelection(Point<Pixels>),
-    // Adjusted mouse position, should open
     FindHyperlink(Point<Pixels>, bool),
+    ProcessHyperlink((String, bool, Match), bool),
     // Whether keep selection when copy
     Copy(Option<bool>),
     // Vi mode events
@@ -369,6 +369,7 @@ impl TerminalBuilder {
             last_content: Default::default(),
             last_mouse: None,
             matches: Vec::new(),
+
             selection_head: None,
             breadcrumb_text: String::new(),
             scroll_px: px(0.),
@@ -379,6 +380,7 @@ impl TerminalBuilder {
             is_remote_terminal: false,
             last_mouse_move_time: Instant::now(),
             last_hyperlink_search_position: None,
+            mouse_down_hyperlink: None,
             #[cfg(windows)]
             shell_program: None,
             activation_script: Vec::new(),
@@ -420,6 +422,10 @@ impl TerminalBuilder {
     ) -> Task<Result<TerminalBuilder>> {
         let version = release_channel::AppVersion::global(cx);
         let fut = async move {
+            // Remove SHLVL so the spawned shell initializes it to 1, matching
+            // the behavior of standalone terminal emulators like iTerm2/Kitty/Alacritty.
+            env.remove("SHLVL");
+
             // If the parent environment doesn't have a locale set
             // (As is the case when launched from a .app on MacOS),
             // and the Project doesn't have a locale set, then
@@ -591,6 +597,7 @@ impl TerminalBuilder {
                 last_content: Default::default(),
                 last_mouse: None,
                 matches: Vec::new(),
+
                 selection_head: None,
                 breadcrumb_text: String::new(),
                 scroll_px: px(0.),
@@ -604,6 +611,7 @@ impl TerminalBuilder {
                 is_remote_terminal,
                 last_mouse_move_time: Instant::now(),
                 last_hyperlink_search_position: None,
+                mouse_down_hyperlink: None,
                 #[cfg(windows)]
                 shell_program,
                 activation_script: activation_script.clone(),
@@ -822,6 +830,7 @@ pub struct Terminal {
     pub matches: Vec<RangeInclusive<AlacPoint>>,
     pub last_content: TerminalContent,
     pub selection_head: Option<AlacPoint>,
+
     pub breadcrumb_text: String,
     title_override: Option<String>,
     scroll_px: Pixels,
@@ -833,6 +842,7 @@ pub struct Terminal {
     is_remote_terminal: bool,
     last_mouse_move_time: Instant,
     last_hyperlink_search_position: Option<Point<Pixels>>,
+    mouse_down_hyperlink: Option<(String, bool, Match)>,
     #[cfg(windows)]
     shell_program: Option<String>,
     template: CopyTemplate,
@@ -885,6 +895,8 @@ impl TaskStatus {
     }
 }
 
+const FIND_HYPERLINK_THROTTLE_PX: Pixels = px(5.0);
+
 impl Terminal {
     fn process_event(&mut self, event: AlacTermEvent, cx: &mut Context<Self>) {
         match event {
@@ -935,7 +947,7 @@ impl Terminal {
             AlacTermEvent::Bell => {
                 cx.emit(Event::Bell);
             }
-            AlacTermEvent::Exit => self.register_task_finished(None, cx),
+            AlacTermEvent::Exit => self.register_task_finished(Some(9), cx),
             AlacTermEvent::MouseCursorDirty => {
                 //NOOP, Handled in render
             }
@@ -1143,7 +1155,6 @@ impl Terminal {
             }
             InternalEvent::FindHyperlink(position, open) => {
                 trace!("Finding hyperlink at position: position={position:?}, open={open:?}");
-                let prev_hovered_word = self.last_content.last_hovered_word.take();
 
                 let point = grid_point(
                     *position,
@@ -1157,47 +1168,53 @@ impl Terminal {
                     point,
                     &mut self.hyperlink_regex_searches,
                 ) {
-                    Some((maybe_url_or_path, is_url, url_match)) => {
-                        let target = if is_url {
-                            // Treat "file://" URLs like file paths to ensure
-                            // that line numbers at the end of the path are
-                            // handled correctly.
-                            // file://{path} should be urldecoded, returning a urldecoded {path}
-                            if let Some(path) = maybe_url_or_path.strip_prefix("file://") {
-                                let decoded_path = urlencoding::decode(path)
-                                    .map(|decoded| decoded.into_owned())
-                                    .unwrap_or(path.to_owned());
-
-                                MaybeNavigationTarget::PathLike(PathLikeTarget {
-                                    maybe_path: decoded_path,
-                                    terminal_dir: self.working_directory(),
-                                })
-                            } else {
-                                MaybeNavigationTarget::Url(maybe_url_or_path.clone())
-                            }
-                        } else {
-                            MaybeNavigationTarget::PathLike(PathLikeTarget {
-                                maybe_path: maybe_url_or_path.clone(),
-                                terminal_dir: self.working_directory(),
-                            })
-                        };
-                        if *open {
-                            cx.emit(Event::Open(target));
-                        } else {
-                            self.update_selected_word(
-                                prev_hovered_word,
-                                url_match,
-                                maybe_url_or_path,
-                                target,
-                                cx,
-                            );
-                        }
+                    Some(hyperlink) => {
+                        self.process_hyperlink(hyperlink, *open, cx);
                     }
                     None => {
                         cx.emit(Event::NewNavigationTarget(None));
                     }
                 }
             }
+            InternalEvent::ProcessHyperlink(hyperlink, open) => {
+                self.process_hyperlink(hyperlink.clone(), *open, cx);
+            }
+        }
+    }
+
+    fn process_hyperlink(
+        &mut self,
+        hyperlink: (String, bool, Match),
+        open: bool,
+        cx: &mut Context<Self>,
+    ) {
+        let (maybe_url_or_path, is_url, url_match) = hyperlink;
+        let prev_hovered_word = self.last_content.last_hovered_word.take();
+
+        let target = if is_url {
+            if let Some(path) = maybe_url_or_path.strip_prefix("file://") {
+                let decoded_path = urlencoding::decode(path)
+                    .map(|decoded| decoded.into_owned())
+                    .unwrap_or(path.to_owned());
+
+                MaybeNavigationTarget::PathLike(PathLikeTarget {
+                    maybe_path: decoded_path,
+                    terminal_dir: self.working_directory(),
+                })
+            } else {
+                MaybeNavigationTarget::Url(maybe_url_or_path.clone())
+            }
+        } else {
+            MaybeNavigationTarget::PathLike(PathLikeTarget {
+                maybe_path: maybe_url_or_path.clone(),
+                terminal_dir: self.working_directory(),
+            })
+        };
+
+        if open {
+            cx.emit(Event::Open(target));
+        } else {
+            self.update_selected_word(prev_hovered_word, url_match, maybe_url_or_path, target, cx);
         }
     }
 
@@ -1711,38 +1728,40 @@ impl Terminal {
             {
                 self.write_to_pty(bytes);
             }
-        } else if e.modifiers.secondary() {
-            self.word_from_position(e.position);
+        } else {
+            self.schedule_find_hyperlink(e.modifiers, e.position);
         }
         cx.notify();
     }
 
-    fn word_from_position(&mut self, position: Point<Pixels>) {
-        if self.selection_phase == SelectionPhase::Selecting {
+    fn schedule_find_hyperlink(&mut self, modifiers: Modifiers, position: Point<Pixels>) {
+        if self.selection_phase == SelectionPhase::Selecting
+            || !modifiers.secondary()
+            || !self.last_content.terminal_bounds.bounds.contains(&position)
+        {
             self.last_content.last_hovered_word = None;
-        } else if self.last_content.terminal_bounds.bounds.contains(&position) {
-            // Throttle hyperlink searches to avoid excessive processing
-            let now = Instant::now();
-            let should_search = if let Some(last_pos) = self.last_hyperlink_search_position {
+            return;
+        }
+
+        // Throttle hyperlink searches to avoid excessive processing
+        let now = Instant::now();
+        if self
+            .last_hyperlink_search_position
+            .map_or(true, |last_pos| {
                 // Only search if mouse moved significantly or enough time passed
-                let distance_moved =
-                    ((position.x - last_pos.x).abs() + (position.y - last_pos.y).abs()) > px(5.0);
+                let distance_moved = ((position.x - last_pos.x).abs()
+                    + (position.y - last_pos.y).abs())
+                    > FIND_HYPERLINK_THROTTLE_PX;
                 let time_elapsed = now.duration_since(self.last_mouse_move_time).as_millis() > 100;
                 distance_moved || time_elapsed
-            } else {
-                true
-            };
-
-            if should_search {
-                self.last_mouse_move_time = now;
-                self.last_hyperlink_search_position = Some(position);
-                self.events.push_back(InternalEvent::FindHyperlink(
-                    position - self.last_content.terminal_bounds.bounds.origin,
-                    false,
-                ));
-            }
-        } else {
-            self.last_content.last_hovered_word = None;
+            })
+        {
+            self.last_mouse_move_time = now;
+            self.last_hyperlink_search_position = Some(position);
+            self.events.push_back(InternalEvent::FindHyperlink(
+                position - self.last_content.terminal_bounds.bounds.origin,
+                false,
+            ));
         }
     }
 
@@ -1766,6 +1785,20 @@ impl Terminal {
     ) {
         let position = e.position - self.last_content.terminal_bounds.bounds.origin;
         if !self.mouse_mode(e.modifiers.shift) {
+            if let Some((.., hyperlink_range)) = &self.mouse_down_hyperlink {
+                let point = grid_point(
+                    position,
+                    self.last_content.terminal_bounds,
+                    self.last_content.display_offset,
+                );
+
+                if !hyperlink_range.contains(&point) {
+                    self.mouse_down_hyperlink = None;
+                } else {
+                    return;
+                }
+            }
+
             self.selection_phase = SelectionPhase::Selecting;
             // Alacritty has the same ordering, of first updating the selection
             // then scrolling 15ms later
@@ -1812,6 +1845,23 @@ impl Terminal {
             self.last_content.display_offset,
         );
 
+        if e.button == MouseButton::Left
+            && e.modifiers.secondary()
+            && !self.mouse_mode(e.modifiers.shift)
+        {
+            let term_lock = self.term.lock();
+            self.mouse_down_hyperlink = terminal_hyperlinks::find_from_grid_point(
+                &term_lock,
+                point,
+                &mut self.hyperlink_regex_searches,
+            );
+            drop(term_lock);
+
+            if self.mouse_down_hyperlink.is_some() {
+                return;
+            }
+        }
+
         if self.mouse_mode(e.modifiers.shift) {
             if let Some(bytes) =
                 mouse_button_report(point, e.button, e.modifiers, true, self.last_content.mode)
@@ -1882,6 +1932,31 @@ impl Terminal {
                 self.copy(Some(true));
             }
 
+            if let Some(mouse_down_hyperlink) = self.mouse_down_hyperlink.take() {
+                let point = grid_point(
+                    position,
+                    self.last_content.terminal_bounds,
+                    self.last_content.display_offset,
+                );
+
+                if let Some(mouse_up_hyperlink) = {
+                    let term_lock = self.term.lock();
+                    terminal_hyperlinks::find_from_grid_point(
+                        &term_lock,
+                        point,
+                        &mut self.hyperlink_regex_searches,
+                    )
+                } {
+                    if mouse_down_hyperlink == mouse_up_hyperlink {
+                        self.events
+                            .push_back(InternalEvent::ProcessHyperlink(mouse_up_hyperlink, true));
+                        self.selection_phase = SelectionPhase::Ended;
+                        self.last_mouse = None;
+                        return;
+                    }
+                }
+            }
+
             //Hyperlinks
             if self.selection_phase == SelectionPhase::Ended {
                 let mouse_cell_index =
@@ -1934,7 +2009,7 @@ impl Terminal {
     }
 
     fn refresh_hovered_word(&mut self, window: &Window) {
-        self.word_from_position(window.mouse_position());
+        self.schedule_find_hyperlink(window.modifiers(), window.mouse_position());
     }
 
     fn determine_scroll_lines(
@@ -2398,10 +2473,91 @@ mod tests {
         term::cell::Cell,
     };
     use collections::HashMap;
-    use gpui::{Pixels, Point, TestAppContext, bounds, point, size, smol_timeout};
+    use gpui::{
+        Entity, Modifiers, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, Pixels,
+        Point, TestAppContext, bounds, point, size, smol_timeout,
+    };
     use rand::{Rng, distr, rngs::ThreadRng};
     use task::ShellBuilder;
 
+    fn init_ctrl_click_hyperlink_test(cx: &mut TestAppContext, output: &[u8]) -> Entity<Terminal> {
+        cx.update(|cx| {
+            let settings_store = settings::SettingsStore::test(cx);
+            cx.set_global(settings_store);
+        });
+
+        let terminal = cx.new(|cx| {
+            TerminalBuilder::new_display_only(CursorShape::default(), AlternateScroll::On, None, 0)
+                .unwrap()
+                .subscribe(cx)
+        });
+
+        terminal.update(cx, |terminal, cx| {
+            terminal.write_output(output, cx);
+        });
+
+        cx.run_until_parked();
+
+        terminal.update(cx, |terminal, _cx| {
+            let term_lock = terminal.term.lock();
+            terminal.last_content = Terminal::make_content(&term_lock, &terminal.last_content);
+            drop(term_lock);
+
+            let terminal_bounds = TerminalBounds::new(
+                px(20.0),
+                px(10.0),
+                bounds(point(px(0.0), px(0.0)), size(px(400.0), px(400.0))),
+            );
+            terminal.last_content.terminal_bounds = terminal_bounds;
+            terminal.events.clear();
+        });
+
+        terminal
+    }
+
+    fn ctrl_mouse_down_at(
+        terminal: &mut Terminal,
+        position: Point<Pixels>,
+        cx: &mut Context<Terminal>,
+    ) {
+        let mouse_down = MouseDownEvent {
+            button: MouseButton::Left,
+            position,
+            modifiers: Modifiers::secondary_key(),
+            click_count: 1,
+            first_mouse: true,
+        };
+        terminal.mouse_down(&mouse_down, cx);
+    }
+
+    fn ctrl_mouse_move_to(
+        terminal: &mut Terminal,
+        position: Point<Pixels>,
+        cx: &mut Context<Terminal>,
+    ) {
+        let terminal_bounds = terminal.last_content.terminal_bounds.bounds;
+        let drag_event = MouseMoveEvent {
+            position,
+            pressed_button: Some(MouseButton::Left),
+            modifiers: Modifiers::secondary_key(),
+        };
+        terminal.mouse_drag(&drag_event, terminal_bounds, cx);
+    }
+
+    fn ctrl_mouse_up_at(
+        terminal: &mut Terminal,
+        position: Point<Pixels>,
+        cx: &mut Context<Terminal>,
+    ) {
+        let mouse_up = MouseUpEvent {
+            button: MouseButton::Left,
+            position,
+            modifiers: Modifiers::secondary_key(),
+            click_count: 1,
+        };
+        terminal.mouse_up(&mouse_up, cx);
+    }
+
     #[gpui::test]
     async fn test_basic_terminal(cx: &mut TestAppContext) {
         cx.executor().allow_parking();
@@ -2851,4 +3007,168 @@ mod tests {
             text
         );
     }
+
+    #[gpui::test]
+    async fn test_hyperlink_ctrl_click_same_position(cx: &mut TestAppContext) {
+        let terminal = init_ctrl_click_hyperlink_test(cx, b"Visit https://zed.dev/ for more\r\n");
+
+        terminal.update(cx, |terminal, cx| {
+            let click_position = point(px(80.0), px(10.0));
+            ctrl_mouse_down_at(terminal, click_position, cx);
+            ctrl_mouse_up_at(terminal, click_position, cx);
+
+            assert!(
+                terminal
+                    .events
+                    .iter()
+                    .any(|event| matches!(event, InternalEvent::ProcessHyperlink(_, true))),
+                "Should have ProcessHyperlink event when ctrl+clicking on same hyperlink position"
+            );
+        });
+    }
+
+    #[gpui::test]
+    async fn test_hyperlink_ctrl_click_drag_outside_bounds(cx: &mut TestAppContext) {
+        let terminal = init_ctrl_click_hyperlink_test(
+            cx,
+            b"Visit https://zed.dev/ for more\r\nThis is another line\r\n",
+        );
+
+        terminal.update(cx, |terminal, cx| {
+            let down_position = point(px(80.0), px(10.0));
+            let up_position = point(px(10.0), px(50.0));
+
+            ctrl_mouse_down_at(terminal, down_position, cx);
+            ctrl_mouse_move_to(terminal, up_position, cx);
+            ctrl_mouse_up_at(terminal, up_position, cx);
+
+            assert!(
+                !terminal
+                    .events
+                    .iter()
+                    .any(|event| matches!(event, InternalEvent::ProcessHyperlink(_, _))),
+                "Should NOT have ProcessHyperlink event when dragging outside the hyperlink"
+            );
+        });
+    }
+
+    #[gpui::test]
+    async fn test_hyperlink_ctrl_click_drag_within_bounds(cx: &mut TestAppContext) {
+        let terminal = init_ctrl_click_hyperlink_test(cx, b"Visit https://zed.dev/ for more\r\n");
+
+        terminal.update(cx, |terminal, cx| {
+            let down_position = point(px(70.0), px(10.0));
+            let up_position = point(px(130.0), px(10.0));
+
+            ctrl_mouse_down_at(terminal, down_position, cx);
+            ctrl_mouse_move_to(terminal, up_position, cx);
+            ctrl_mouse_up_at(terminal, up_position, cx);
+
+            assert!(
+                terminal
+                    .events
+                    .iter()
+                    .any(|event| matches!(event, InternalEvent::ProcessHyperlink(_, true))),
+                "Should have ProcessHyperlink event when dragging within hyperlink bounds"
+            );
+        });
+    }
+
+    mod perf {
+        use super::super::*;
+        use gpui::{
+            Entity, Point, ScrollDelta, ScrollWheelEvent, TestAppContext, VisualContext,
+            VisualTestContext, point,
+        };
+        use util::default;
+        use util_macros::perf;
+
+        async fn init_scroll_perf_test(
+            cx: &mut TestAppContext,
+        ) -> (Entity<Terminal>, &mut VisualTestContext) {
+            cx.update(|cx| {
+                let settings_store = settings::SettingsStore::test(cx);
+                cx.set_global(settings_store);
+            });
+
+            cx.executor().allow_parking();
+
+            let window = cx.add_empty_window();
+            let builder = window
+                .update(|window, cx| {
+                    let settings = TerminalSettings::get_global(cx);
+                    let test_path_hyperlink_timeout_ms = 100;
+                    TerminalBuilder::new(
+                        None,
+                        None,
+                        task::Shell::System,
+                        HashMap::default(),
+                        CursorShape::default(),
+                        AlternateScroll::On,
+                        None,
+                        settings.path_hyperlink_regexes.clone(),
+                        test_path_hyperlink_timeout_ms,
+                        false,
+                        window.window_handle().window_id().as_u64(),
+                        None,
+                        cx,
+                        vec![],
+                    )
+                })
+                .await
+                .unwrap();
+            let terminal = window.new(|cx| builder.subscribe(cx));
+
+            terminal.update(window, |term, cx| {
+                term.write_output("long line ".repeat(1000).as_bytes(), cx);
+            });
+
+            (terminal, window)
+        }
+
+        #[perf]
+        #[gpui::test]
+        async fn scroll_long_line_benchmark(cx: &mut TestAppContext) {
+            let (terminal, window) = init_scroll_perf_test(cx).await;
+            let wobble = point(FIND_HYPERLINK_THROTTLE_PX, px(0.0));
+            let mut scroll_by = |lines: i32| {
+                window.update_window_entity(&terminal, |terminal, window, cx| {
+                    let bounds = terminal.last_content.terminal_bounds.bounds;
+                    let center = bounds.origin + bounds.center();
+                    let position = center + wobble * lines as f32;
+
+                    terminal.mouse_move(
+                        &MouseMoveEvent {
+                            position,
+                            ..default()
+                        },
+                        cx,
+                    );
+
+                    terminal.scroll_wheel(
+                        &ScrollWheelEvent {
+                            position,
+                            delta: ScrollDelta::Lines(Point::new(0.0, lines as f32)),
+                            ..default()
+                        },
+                        1.0,
+                    );
+
+                    assert!(
+                        terminal
+                            .events
+                            .iter()
+                            .any(|event| matches!(event, InternalEvent::Scroll(_))),
+                        "Should have Scroll event when scrolling within terminal bounds"
+                    );
+                    terminal.sync(window, cx);
+                });
+            };
+
+            for _ in 0..20000 {
+                scroll_by(1);
+                scroll_by(-1);
+            }
+        }
+    }
 }

crates/terminal/src/terminal_hyperlinks.rs 🔗

@@ -8,12 +8,14 @@ use alacritty_terminal::{
         search::{Match, RegexIter, RegexSearch},
     },
 };
-use fancy_regex::Regex;
 use log::{info, warn};
+use regex::Regex;
 use std::{
+    iter::{once, once_with},
     ops::{Index, Range},
     time::{Duration, Instant},
 };
+use url::Url;
 
 const URL_REGEX: &str = r#"(ipfs:|ipns:|magnet:|mailto:|gemini://|gopher://|https://|http://|news:|file://|git://|ssh:|ftp://)[^\u{0000}-\u{001F}\u{007F}-\u{009F}<>"\s{-}\^⟨⟩`']+"#;
 const WIDE_CHAR_SPACERS: Flags =
@@ -128,8 +130,19 @@ pub(super) fn find_from_grid_point<T: EventListener>(
         if is_url {
             // Treat "file://" IRIs like file paths to ensure
             // that line numbers at the end of the path are
-            // handled correctly
-            if let Some(path) = maybe_url_or_path.strip_prefix("file://") {
+            // handled correctly.
+            // Use Url::to_file_path() to properly handle Windows drive letters
+            // (e.g., file:///C:/path -> C:\path)
+            if maybe_url_or_path.starts_with("file://") {
+                if let Ok(url) = Url::parse(&maybe_url_or_path) {
+                    if let Ok(path) = url.to_file_path() {
+                        return (path.to_string_lossy().into_owned(), false, word_match);
+                    }
+                }
+                // Fallback: strip file:// prefix if URL parsing fails
+                let path = maybe_url_or_path
+                    .strip_prefix("file://")
+                    .unwrap_or(&maybe_url_or_path);
                 (path.to_string(), false, word_match)
             } else {
                 (maybe_url_or_path, true, word_match)
@@ -148,8 +161,8 @@ fn sanitize_url_punctuation<T: EventListener>(
     let mut sanitized_url = url;
     let mut chars_trimmed = 0;
 
-    // First, handle parentheses balancing using single traversal
-    let (open_parens, close_parens) =
+    // Count parentheses in the URL
+    let (open_parens, mut close_parens) =
         sanitized_url
             .chars()
             .fold((0, 0), |(opens, closes), c| match c {
@@ -158,33 +171,27 @@ fn sanitize_url_punctuation<T: EventListener>(
                 _ => (opens, closes),
             });
 
-    // Trim unbalanced closing parentheses
-    if close_parens > open_parens {
-        let mut remaining_close = close_parens;
-        while sanitized_url.ends_with(')') && remaining_close > open_parens {
-            sanitized_url.pop();
-            chars_trimmed += 1;
-            remaining_close -= 1;
-        }
-    }
+    // Remove trailing characters that shouldn't be at the end of URLs
+    while let Some(last_char) = sanitized_url.chars().last() {
+        let should_remove = match last_char {
+            // These may be part of a URL but not at the end. It's not that the spec
+            // doesn't allow them, but they are frequently used in plain text as delimiters
+            // where they're not meant to be part of the URL.
+            '.' | ',' | ':' | ';' => true,
+            '(' => true,
+            ')' if close_parens > open_parens => {
+                close_parens -= 1;
+
+                true
+            }
+            _ => false,
+        };
 
-    // Handle trailing periods
-    if sanitized_url.ends_with('.') {
-        let trailing_periods = sanitized_url
-            .chars()
-            .rev()
-            .take_while(|&c| c == '.')
-            .count();
-
-        if trailing_periods > 1 {
-            sanitized_url.truncate(sanitized_url.len() - trailing_periods);
-            chars_trimmed += trailing_periods;
-        } else if trailing_periods == 1
-            && let Some(second_last_char) = sanitized_url.chars().rev().nth(1)
-            && (second_last_char.is_alphanumeric() || second_last_char == '/')
-        {
+        if should_remove {
             sanitized_url.pop();
             chars_trimmed += 1;
+        } else {
+            break;
         }
     }
 
@@ -208,7 +215,8 @@ fn path_match<T>(
     if path_hyperlink_regexes.is_empty() || path_hyperlink_timeout.as_millis() == 0 {
         return None;
     }
-
+    debug_assert!(line_start <= hovered);
+    debug_assert!(line_end >= hovered);
     let search_start_time = Instant::now();
 
     let timed_out = || {
@@ -224,21 +232,63 @@ fn path_match<T>(
     let mut line = String::with_capacity(
         (line_end.line.0 - line_start.line.0 + 1) as usize * term.grid().columns(),
     );
-    line.push(term.grid()[line_start].c);
+    let first_cell = &term.grid()[line_start];
+    let mut prev_len = 0;
+    line.push(first_cell.c);
+    let mut prev_char_is_space = first_cell.c == ' ';
+    let mut hovered_point_byte_offset = None;
+    let mut hovered_word_start_offset = None;
+    let mut hovered_word_end_offset = None;
+
+    if line_start == hovered {
+        hovered_point_byte_offset = Some(0);
+        if first_cell.c != ' ' {
+            hovered_word_start_offset = Some(0);
+        }
+    }
+
     for cell in term.grid().iter_from(line_start) {
         if cell.point > line_end {
             break;
         }
 
         if !cell.flags.intersects(WIDE_CHAR_SPACERS) {
-            line.push(match cell.c {
-                '\t' => ' ',
-                c @ _ => c,
-            });
+            prev_len = line.len();
+            match cell.c {
+                ' ' | '\t' => {
+                    if hovered_point_byte_offset.is_some() && !prev_char_is_space {
+                        if hovered_word_end_offset.is_none() {
+                            hovered_word_end_offset = Some(line.len());
+                        }
+                    }
+                    line.push(' ');
+                    prev_char_is_space = true;
+                }
+                c @ _ => {
+                    if hovered_point_byte_offset.is_none() && prev_char_is_space {
+                        hovered_word_start_offset = Some(line.len());
+                    }
+                    line.push(c);
+                    prev_char_is_space = false;
+                }
+            }
+        }
+
+        if cell.point == hovered {
+            debug_assert!(hovered_point_byte_offset.is_none());
+            hovered_point_byte_offset = Some(prev_len);
         }
     }
     let line = line.trim_ascii_end();
-
+    let hovered_point_byte_offset = hovered_point_byte_offset?;
+    let hovered_word_range = {
+        let word_start_offset = hovered_word_start_offset.unwrap_or(0);
+        (word_start_offset != 0)
+            .then_some(word_start_offset..hovered_word_end_offset.unwrap_or(line.len()))
+    };
+    if line.len() <= hovered_point_byte_offset {
+        return None;
+    }
     let found_from_range = |path_range: Range<usize>,
                             link_range: Range<usize>,
                             position: Option<(u32, Option<u32>)>| {
@@ -268,7 +318,7 @@ fn path_match<T>(
                 .expand_wide(link_end, AlacDirection::Left)
                 .sub(term, Boundary::Grid, 1);
 
-        Some((
+        (
             {
                 let mut path = line[path_range].to_string();
                 position.inspect(|(line, column)| {
@@ -278,27 +328,33 @@ fn path_match<T>(
                 path
             },
             link_match,
-        ))
+        )
     };
 
     for regex in path_hyperlink_regexes {
         let mut path_found = false;
 
-        for captures in regex.captures_iter(&line) {
-            let captures = match captures {
-                Ok(captures) => captures,
-                Err(error) => {
-                    warn!("Error '{error}' searching for path hyperlinks in line: {line}");
-                    info!(
-                        "Skipping match from path hyperlinks with regex: {}",
-                        regex.as_str()
-                    );
-                    continue;
-                }
-            };
-
+        for (line_start_offset, captures) in once(
+            regex
+                .captures_iter(&line)
+                .next()
+                .map(|captures| (0, captures)),
+        )
+        .chain(once_with(|| {
+            if let Some(hovered_word_range) = &hovered_word_range {
+                regex
+                    .captures_iter(&line[hovered_word_range.clone()])
+                    .next()
+                    .map(|captures| (hovered_word_range.start, captures))
+            } else {
+                None
+            }
+        }))
+        .flatten()
+        {
+            path_found = true;
             let match_range = captures.get(0).unwrap().range();
-            let (path_range, line_column) = if let Some(path) = captures.name("path") {
+            let (mut path_range, line_column) = if let Some(path) = captures.name("path") {
                 let parse = |name: &str| {
                     captures
                         .name(name)
@@ -312,16 +368,23 @@ fn path_match<T>(
             } else {
                 (match_range.clone(), None)
             };
-            let link_range = captures
+            let mut link_range = captures
                 .name("link")
-                .map_or(match_range, |link| link.range());
+                .map_or_else(|| match_range.clone(), |link| link.range());
+
+            path_range.start += line_start_offset;
+            path_range.end += line_start_offset;
+            link_range.start += line_start_offset;
+            link_range.end += line_start_offset;
+
+            if !link_range.contains(&hovered_point_byte_offset) {
+                // No match, just skip.
+                continue;
+            }
             let found = found_from_range(path_range, link_range, line_column);
 
-            if let Some(found) = found {
-                path_found = true;
-                if found.1.contains(&hovered) {
-                    return Some(found);
-                }
+            if found.1.contains(&hovered) {
+                return Some(found);
             }
         }
 
@@ -351,7 +414,7 @@ mod tests {
         term::{Config, cell::Flags, test::TermSize},
         vte::ansi::Handler,
     };
-    use fancy_regex::Regex;
+    use regex::Regex;
     use settings::{self, Settings, SettingsContent};
     use std::{cell::RefCell, ops::RangeInclusive, path::PathBuf, rc::Rc};
     use url::Url;
@@ -361,7 +424,7 @@ mod tests {
         let results: Vec<_> = Regex::new(re)
             .unwrap()
             .find_iter(hay)
-            .map(|m| m.unwrap().as_str())
+            .map(|m| m.as_str())
             .collect();
         assert_eq!(results, expected);
     }
@@ -387,6 +450,8 @@ mod tests {
             ("https://www.google.com/)", "https://www.google.com/"),
             ("https://example.com/path)", "https://example.com/path"),
             ("https://test.com/))", "https://test.com/"),
+            ("https://test.com/(((", "https://test.com/"),
+            ("https://test.com/(test)(", "https://test.com/(test)"),
             // Cases that should NOT be sanitized (balanced parentheses)
             (
                 "https://en.wikipedia.org/wiki/Example_(disambiguation)",
@@ -417,10 +482,10 @@ mod tests {
     }
 
     #[test]
-    fn test_url_periods_sanitization() {
-        // Test URLs with trailing periods (sentence punctuation)
+    fn test_url_punctuation_sanitization() {
+        // Test URLs with trailing punctuation (sentence/text punctuation)
+        // The sanitize_url_punctuation function removes ., ,, :, ;, from the end
         let test_cases = vec![
-            // Cases that should be sanitized (trailing periods likely punctuation)
             ("https://example.com.", "https://example.com"),
             (
                 "https://github.com/zed-industries/zed.",
@@ -440,13 +505,36 @@ mod tests {
                 "https://en.wikipedia.org/wiki/C.E.O.",
                 "https://en.wikipedia.org/wiki/C.E.O",
             ),
-            // Cases that should NOT be sanitized (periods are part of URL structure)
+            ("https://example.com,", "https://example.com"),
+            ("https://example.com/path,", "https://example.com/path"),
+            ("https://example.com,,", "https://example.com"),
+            ("https://example.com:", "https://example.com"),
+            ("https://example.com/path:", "https://example.com/path"),
+            ("https://example.com::", "https://example.com"),
+            ("https://example.com;", "https://example.com"),
+            ("https://example.com/path;", "https://example.com/path"),
+            ("https://example.com;;", "https://example.com"),
+            ("https://example.com.,", "https://example.com"),
+            ("https://example.com.:;", "https://example.com"),
+            ("https://example.com!.", "https://example.com!"),
+            ("https://example.com/).", "https://example.com/"),
+            ("https://example.com/);", "https://example.com/"),
+            ("https://example.com/;)", "https://example.com/"),
             (
                 "https://example.com/v1.0/api",
                 "https://example.com/v1.0/api",
             ),
             ("https://192.168.1.1", "https://192.168.1.1"),
             ("https://sub.domain.com", "https://sub.domain.com"),
+            (
+                "https://example.com?query=value",
+                "https://example.com?query=value",
+            ),
+            ("https://example.com?a=1&b=2", "https://example.com?a=1&b=2"),
+            (
+                "https://example.com/path:8080",
+                "https://example.com/path:8080",
+            ),
         ];
 
         for (input, expected) in test_cases {
@@ -458,7 +546,6 @@ mod tests {
             let end_point = AlacPoint::new(Line(0), Column(input.len()));
             let dummy_match = Match::new(start_point, end_point);
 
-            // This test should initially fail since we haven't implemented period sanitization yet
             let (result, _) = sanitize_url_punctuation(input.to_string(), dummy_match, &term);
             assert_eq!(result, expected, "Failed for input: {}", input);
         }
@@ -553,8 +640,6 @@ mod tests {
             test_path!("/test/cool.rs(4,2)👉:", "What is this?");
 
             // path, line, column, and description
-            test_path!("/test/cool.rs:4:2👉:Error!");
-            test_path!("/test/cool.rs:4:2:👉Error!");
             test_path!("‹«/test/co👉ol.rs»:«4»:«2»›:Error!");
             test_path!("‹«/test/co👉ol.rs»(«4»,«2»)›:Error!");
 
@@ -565,6 +650,7 @@ mod tests {
 
             // Python
             test_path!("‹«awe👉some.py»›");
+            test_path!("‹«👉a»› ");
 
             test_path!("    ‹F👉ile \"«/awesome.py»\", line «42»›: Wat?");
             test_path!("    ‹File \"«/awe👉some.py»\", line «42»›");
@@ -577,18 +663,14 @@ mod tests {
             // path, line, column and description
             test_path!("‹«/👉test/cool.rs»:«4»:«2»›:例Desc例例例");
             test_path!("‹«/test/cool.rs»:«4»:«👉2»›:例Desc例例例");
-            test_path!("/test/cool.rs:4:2:例Desc例👉例例");
             test_path!("‹«/👉test/cool.rs»(«4»,«2»)›:例Desc例例例");
             test_path!("‹«/test/cool.rs»(«4»👉,«2»)›:例Desc例例例");
-            test_path!("/test/cool.rs(4,2):例Desc例👉例例");
 
             // path, line, column and description w/extra colons
             test_path!("‹«/👉test/cool.rs»:«4»:«2»›::例Desc例例例");
             test_path!("‹«/test/cool.rs»:«4»:«👉2»›::例Desc例例例");
-            test_path!("/test/cool.rs:4:2::例Desc例👉例例");
             test_path!("‹«/👉test/cool.rs»(«4»,«2»)›::例Desc例例例");
             test_path!("‹«/test/cool.rs»(«4»,«2»👉)›::例Desc例例例");
-            test_path!("/test/cool.rs(4,2)::例Desc例👉例例");
         }
 
         #[test]
@@ -599,9 +681,6 @@ mod tests {
             test_path!(
                 "‹«🦀 multiple_👉same_line 🦀» 🚣«4» 🏛️«2»›: 🦀 multiple_same_line 🦀 🚣4 🏛️2:"
             );
-            test_path!(
-                "🦀 multiple_same_line 🦀 🚣4 🏛️2 ‹«🦀 multiple_👉same_line 🦀» 🚣«4» 🏛️«2»›:"
-            );
 
             // ls output (tab separated)
             test_path!(
@@ -633,8 +712,6 @@ mod tests {
             test_path!("‹«/test/co👉ol.rs»(«1»,«618»)›:");
             test_path!("‹«/test/co👉ol.rs»::«42»›");
             test_path!("‹«/test/co👉ol.rs»::«42»›:");
-            test_path!("‹«/test/co👉ol.rs:4:2»(«1»,«618»)›");
-            test_path!("‹«/test/co👉ol.rs:4:2»(«1»,«618»)›:");
             test_path!("‹«/test/co👉ol.rs»(«1»,«618»)›::");
         }
 
@@ -650,7 +727,7 @@ mod tests {
             test_path!("<‹«/test/co👉ol.rs»:«4»›>");
 
             test_path!("[\"‹«/test/co👉ol.rs»:«4»›\"]");
-            test_path!("'‹«(/test/co👉ol.rs:4)»›'");
+            test_path!("'(‹«/test/co👉ol.rs»:«4»›)'");
 
             test_path!("\"‹«/test/co👉ol.rs»:«4»:«2»›\"");
             test_path!("'‹«/test/co👉ol.rs»:«4»:«2»›'");
@@ -699,7 +776,7 @@ mod tests {
             test_path!("‹«/test/co👉ol.rs»:«4»›:,");
             test_path!("/test/cool.rs:4:👉,");
             test_path!("[\"‹«/test/co👉ol.rs»:«4»›\"]:,");
-            test_path!("'‹«(/test/co👉ol.rs:4),,»›'..");
+            test_path!("'(‹«/test/co👉ol.rs»:«4»›),,'...");
             test_path!("('‹«/test/co👉ol.rs»:«4»›'::: was here...)");
             test_path!("[Here's <‹«/test/co👉ol.rs»:«4»›>]::: ");
         }
@@ -824,9 +901,6 @@ mod tests {
                 test_path!(
                     "‹«test/c👉ontrollers/template_items_controller_test.rb»:«20»›:in 'block (2 levels) in <class:TemplateItemsControllerTest>'"
                 );
-                test_path!(
-                    "test/controllers/template_items_controller_test.rb:19:i👉n 'block in <class:TemplateItemsControllerTest>'"
-                );
             }
 
             #[test]
@@ -943,7 +1017,7 @@ mod tests {
             use crate::TerminalSettings;
             use alacritty_terminal::{
                 event::VoidListener,
-                grid::Dimensions,
+                grid::Scroll,
                 index::{Column, Point as AlacPoint},
                 term::test::mock_term,
                 term::{Term, search::Match},
@@ -952,14 +1026,20 @@ mod tests {
             use std::{cell::RefCell, rc::Rc};
             use util_macros::perf;
 
-            fn build_test_term(line: &str) -> (Term<VoidListener>, AlacPoint) {
-                let content = line.repeat(500);
-                let term = mock_term(&content);
-                let point = AlacPoint::new(
-                    term.grid().bottommost_line() - 1,
-                    Column(term.grid().last_column().0 / 2),
-                );
-
+            fn build_test_term(
+                line: &str,
+                repeat: usize,
+                hover_offset_column: usize,
+            ) -> (Term<VoidListener>, AlacPoint) {
+                let content = line.repeat(repeat);
+                let mut term = mock_term(&content);
+                term.resize(TermSize {
+                    columns: 1024,
+                    screen_lines: 10,
+                });
+                term.scroll_display(Scroll::Top);
+                let point =
+                    AlacPoint::new(Line(term.topmost_line().0 + 3), Column(hover_offset_column));
                 (term, point)
             }
 
@@ -968,11 +1048,14 @@ mod tests {
                 const LINE: &str = "    Compiling terminal v0.1.0 (/Hyperlinks/Bench/Source/zed-hyperlinks/crates/terminal)\r\n";
                 thread_local! {
                     static TEST_TERM_AND_POINT: (Term<VoidListener>, AlacPoint) =
-                        build_test_term(LINE);
+                        build_test_term(LINE, 500, 50);
                 }
                 TEST_TERM_AND_POINT.with(|(term, point)| {
-                    assert!(
-                        find_from_grid_point_bench(term, *point).is_some(),
+                    assert_eq!(
+                        find_from_grid_point_bench(term, *point)
+                            .map(|(path, ..)| path)
+                            .unwrap_or_default(),
+                        "/Hyperlinks/Bench/Source/zed-hyperlinks/crates/terminal",
                         "Hyperlink should have been found"
                     );
                 });
@@ -983,11 +1066,14 @@ mod tests {
                 const LINE: &str = "    --> /Hyperlinks/Bench/Source/zed-hyperlinks/crates/terminal/terminal.rs:1000:42\r\n";
                 thread_local! {
                     static TEST_TERM_AND_POINT: (Term<VoidListener>, AlacPoint) =
-                        build_test_term(LINE);
+                        build_test_term(LINE, 500, 50);
                 }
                 TEST_TERM_AND_POINT.with(|(term, point)| {
-                    assert!(
-                        find_from_grid_point_bench(term, *point).is_some(),
+                    assert_eq!(
+                        find_from_grid_point_bench(term, *point)
+                            .map(|(path, ..)| path)
+                            .unwrap_or_default(),
+                        "/Hyperlinks/Bench/Source/zed-hyperlinks/crates/terminal/terminal.rs:1000:42",
                         "Hyperlink should have been found"
                     );
                 });
@@ -998,11 +1084,111 @@ mod tests {
                 const LINE: &str = "Cargo.toml        experiments        notebooks        rust-toolchain.toml    tooling\r\n";
                 thread_local! {
                     static TEST_TERM_AND_POINT: (Term<VoidListener>, AlacPoint) =
-                        build_test_term(LINE);
+                        build_test_term(LINE, 500, 60);
                 }
                 TEST_TERM_AND_POINT.with(|(term, point)| {
-                    assert!(
-                        find_from_grid_point_bench(term, *point).is_some(),
+                    assert_eq!(
+                        find_from_grid_point_bench(term, *point)
+                            .map(|(path, ..)| path)
+                            .unwrap_or_default(),
+                        "rust-toolchain.toml",
+                        "Hyperlink should have been found"
+                    );
+                });
+            }
+
+            #[perf]
+            // https://github.com/zed-industries/zed/pull/44407
+            pub fn pr_44407_hyperlink_benchmark() {
+                const LINE: &str = "-748, 706, 163, 222, -980, 949, 381, -568, 199, 501, 760, -821, 90, -451, 183, 867, -351, -810, -762, -109, 423, 84, 14, -77, -820, -345, 74, -791, 930, -618, -900, 862, -959, 289, -19, 471, -757, 793, 155, -554, 249, 830, 402, 732, -731, -866, -720, -703, -257, -439, 731, 872, -489, 676, -167, 613, -698, 415, -80, -453, -896, 333, -511, 621, -450, 624, -309, -575, 177, 141, 891, -104, -97, -367, -599, -675, 607, -225, -760, 552, -465, 804, 55, 282, 104, -929, -252,\
+-311, 900, 550, 599, -80, 774, 553, 837, -395, 541, 953, 154, -396, -596, -111, -802, -221, -337, -633, -73, -527, -82, -658, -264, 222, 375, 434, 204, -756, -703, 303, 239, -257, -365, -351, 904, 364, -743, -484, 655, -542, 446, 888, 632, -167, -260, 716, 150, 806, 723, 513, -118, -323, -683, 983, -564, 358, -16, -287, 277, -607, 87, 365, -1, 164, 401, 257, 369, -893, 145, -969, 375, -53, 541, -408, -865, 753, 258, 337, -886, 593, -378, -528, 191, 204, 566, -61, -621, 769, 524, -628, 6,\
+249, 896, -785, -776, 321, -681, 604, -740, 886, 426, -480, -983, 23, -247, 125, -666, 913, 842, -460, -797, -483, -58, -565, -587, -206, 197, 715, 764, -97, 457, -149, -226, 261, 194, -390, 431, 180, -778, 829, -657, -668, 397, 859, 152, -178, 677, -18, 687, -247, 96, 466, -572, 478, 622, -143, -25, -471, 265, 335, 957, 152, -951, -647, 670, 57, 152, -115, 206, 87, 629, -798, -125, -725, -31, 844, 398, -876, 44, 963, -211, 518, -8, -103, -999, 948, 823, 149, -803, 769, -236, -683, 527,\
+-108, -36, 18, -437, 687, -305, -526, 972, -965, 276, 420, -259, -379, -142, -747, 600, -578, 197, 673, 890, 324, -931, 755, -765, -422, 785, -369, -110, -505, 532, -208, -438, 713, 110, 853, 996, -360, 823, 289, -699, 629, -661, 560, -329, -323, 439, 571, -537, 644, -84, 25, -536, -161, 112, 169, -922, -537, -734, -423, 37, 451, -149, 408, 18, -672, 206, -784, 444, 593, -241, 502, -259, -798, -352, -658, 712, -675, -734, 627, -620, 64, -554, 999, -537, -160, -641, 464, 894, 29, 322, 566,\
+-510, -749, 982, 204, 967, -261, -986, -136, 251, -598, 995, -831, 891, 22, 761, -783, -415, 125, 470, -919, -97, -668, 85, 205, -175, -550, 502, 652, -468, 798, 775, -216, 89, -433, -24, -621, 877, -126, 951, 809, 782, 156, -618, -841, -463, 19, -723, -904, 550, 263, 991, -758, -114, 446, -731, -623, -634, 462, 48, 851, 333, -846, 480, 892, -966, -910, -436, 317, -711, -341, -294, 124, 238, -214, -281, 467, -950, -342, 913, -90, -388, -573, 740, -883, -451, 493, -500, 863, 930, 127, 530,\
+-810, 540, 541, -664, -951, -227, -420, -476, -581, -534, 549, 253, 984, -985, -84, -521, 538, 484, -440, 371, 784, -306, -850, 530, -133, 251, -799, 446, -170, -243, -674, 769, 646, 778, -680, -714, -442, 804, 901, -774, 69, 307, -293, 755, 443, 224, -918, -771, 723, 40, 132, 568, -847, -47, 844, 69, 986, -293, -459, 313, 155, 331, 69, 280, -637, 569, 104, -119, -988, 252, 857, -590, 810, -891, 484, 566, -934, -587, -290, 566, 587, 489, 870, 280, 454, -252, 613, -701, -278, 195, -198,\
+683, 533, -372, 707, -152, 371, 866, 609, -5, -372, -30, -694, 552, 192, 452, -663, 350, -985, 10, 884, 813, -592, -331, -470, 711, -941, 928, 379, -339, 220, 999, 376, 507, 179, 916, 84, 104, 392, 192, 299, -860, 218, -698, -919, -452, 37, 850, 5, -874, 287, 123, -746, -575, 776, -909, 118, 903, -275, 450, -996, -591, -920, -850, 453, -896, 73, 83, -535, -20, 287, -765, 442, 808, 45, 445, 202, 917, -208, 783, 790, -534, 373, -129, 556, -757, -69, 459, -163, -59, 265, -563, -889, 635,\
+-583, -261, -790, 799, 826, 953, 85, 619, 334, 842, 672, -869, -4, -833, 315, 942, -524, 579, 926, 628, -404, 128, -629, 161, 568, -117, -526, 223, -876, 906, 176, -549, -317, 381, 375, -801, -416, 647, 335, 253, -386, -375, -254, 635, 352, 317, 398, -422, 111, 201, 220, 554, -972, 853, 378, 956, 942, -857, -289, -333, -180, 488, -814, -42, -595, 721, 39, 644, 721, -242, -44, 643, -457, -419, 560, -863, 974, 458, 222, -882, 526, -243, -318, -343, -707, -401, 117, 677, -489, 546, -903,\
+-960, -881, -684, 125, -928, -995, -692, -773, 647, -718, -862, -814, 671, 664, -130, -856, -674, 653, 711, 194, -685, -160, 138, -27, -128, -671, -242, 526, 494, -674, 424, -921, -778, 313, -237, 332, 913, 252, 808, -936, 289, 755, 52, -139, 57, -19, -827, -775, -561, -14, 107, -84, 622, -303, -747, 258, -942, 290, 211, -919, -207, 797, 95, 794, -830, -181, -788, 757, 75, -946, -949, -988, 152, 340, 732, 886, -891, -642, -666, 321, -910, 841, 632, 298, 55, -349, 498, 287, -711, 97, 305,\
+-974, -987, 790, -64, 605, -583, -821, 345, 887, -861, 548, 894, 288, 452, 556, -448, 813, 420, 545, 967, 127, -947, 19, -314, -607, -513, -851, 254, -290, -938, -783, -93, 474, 368, -485, -935, -539, 81, 404, -283, 779, 345, -164, 53, 563, -771, 911, -323, 522, -998, 315, 415, 460, 58, -541, -878, -152, -886, 201, -446, -810, 549, -142, -575, -632, 521, 549, 209, -681, 998, 798, -611, -919, -708, -4, 677, -172, 588, 750, -435, 508, 609, 498, -535, -691, -738, 85, 615, 705, 169, 425,\
+-669, -491, -783, 73, -847, 228, -981, -812, -229, 950, -904, 175, -438, 632, -556, 910, 173, 576, -751, -53, -169, 635, 607, -944, -13, -84, 105, -644, 984, 935, 259, -445, 620, -405, 832, 167, 114, 209, -181, -944, -496, 693, -473, 137, 38, -873, -334, -353, -57, 397, 944, 698, 811, -401, 712, -667, 905, 276, -653, 368, -543, -349, 414, 287, 894, 935, 461, 55, 741, -623, -660, -773, 617, 834, 278, -121, 52, 495, -855, -440, -210, -99, 279, -661, 540, 934, 540, 784, 895, 268, -503, 513,\
+-484, -352, 528, 341, -451, 885, -71, 799, -195, -885, -585, -233, 92, 453, 994, 464, 694, 190, -561, -116, 675, -775, -236, 556, -110, -465, 77, -781, 507, -960, -410, 229, -632, 717, 597, 429, 358, -430, -692, -825, 576, 571, 758, -891, 528, -267, 190, -869, 132, -811, 796, 750, -596, -681, 870, 360, 969, 860, -412, -567, 694, -86, -498, 38, -178, -583, -778, 412, 842, -586, 722, -192, 350, 363, 81, -677, -163, 564, 543, 671, 110, 314, 739, -552, -224, -644, 922, 685, 134, 613, 793,\
+-363, -244, -284, -257, -561, 418, 988, 333, 110, -966, 790, 927, 536, -620, -309, -358, 895, -867, -796, -357, 308, -740, 287, -732, -363, -969, 658, 711, 511, 256, 590, -574, 815, -845, -84, 546, -581, -71, -334, -890, 652, -959, 320, -236, 445, -851, 825, -756, -4, 877, 308, 573, -117, 293, 686, -483, 391, 342, -550, -982, 713, 886, 552, 474, -673, 283, -591, -383, 988, 435, -131, 708, -326, -884, 87, 680, -818, -408, -486, 813, -307, -799, 23, -497, 802, -146, -100, 541, 7, -493, 577,\
+50, -270, 672, 834, 111, -788, 247, 337, 628, -33, -964, -519, 683, 54, -703, 633, -127, -448, 759, -975, 696, 2, -870, -760, 67, 696, 306, 750, 615, 155, -933, -568, 399, 795, 164, -460, 205, 439, -526, -691, 35, -136, -481, -63, 73, -598, 748, 133, 874, -29, 4, -73, 472, 389, 962, 231, -328, 240, 149, 959, 46, -207, 72, -514, -608, 0, -14, 32, 374, -478, -806, 919, -729, -286, 652, 109, 509, -879, -979, -865, 584, -92, -346, -992, 781, 401, 575, 993, -746, -33, 684, -683, 750, -105,\
+-425, -508, -627, 27, 770, -45, 338, 921, -139, -392, -933, 634, 563, 224, -780, 921, 991, 737, 22, 64, 414, -249, -687, 869, 50, 759, -97, 515, 20, -775, -332, 957, 138, -542, -835, 591, -819, 363, -715, -146, -950, -641, -35, -435, -407, -548, -984, 383, -216, -559, 853, 4, -410, -319, -831, -459, -628, -819, -324, 755, 696, -192, 238, -234, -724, -445, 915, 302, -708, 484, 224, -641, 25, -771, 528, -106, -744, -588, 913, -554, -515, -239, -843, -812, -171, 721, 543, -269, 440, 151,\
+996, -723, -557, -522, -280, -514, -593, 208, 715, 404, 353, 270, -483, -785, 318, -313, 798, 638, 764, 748, -929, -827, -318, -56, 389, -546, -958, -398, 463, -700, 461, 311, -787, -488, 877, 456, 166, 535, -995, -189, -715, 244, 40, 484, 212, -329, -351, 638, -69, -446, -292, 801, -822, 490, -486, -185, 790, 370, -340, 401, -656, 584, 561, -749, 269, -19, -294, -111, 975, 874, -73, 851, 231, -331, -684, 460, 765, -654, -76, 10, 733, 520, 521, 416, -958, -202, -186, -167, 175, 343, -50,\
+673, -763, -854, -977, -17, -853, -122, -25, 180, 149, 268, 874, -816, -745, 747, -303, -959, 390, 509, 18, -66, 275, -277, 9, 837, -124, 989, -542, -649, -845, 894, 926, 997, -847, -809, -579, -96, -372, 766, 238, -251, 503, 559, 276, -281, -102, -735, 815, 109, 175, -10, 128, 543, -558, -707, 949, 996, -422, -506, 252, 702, -930, 552, -961, 584, -79, -177, 341, -275, 503, -21, 677, -545, 8, -956, -795, -870, -254, 170, -502, -880, 106, 174, 459, 603, -600, -963, 164, -136, -641, -309,\
+-380, -707, -727, -10, 727, 952, 997, -731, -133, 269, 287, 855, 716, -650, 479, 299, -839, -308, -782, 769, 545, 663, -536, -115, 904, -986, -258, -562, 582, 664, 408, -525, -889, 471, -370, -534, -220, 310, 766, 931, -193, -897, -192, -74, -365, -256, -359, -328, 658, -691, -431, 406, 699, 425, 713, -584, -45, -588, 289, 658, -290, -880, -987, -444, 371, 904, -155, 81, -278, -708, -189, -78, 655, 342, -998, -647, -734, -218, 726, 619, 663, 744, 518, 60, -409, 561, -727, -961, -306,\
+-147, -550, 240, -218, -393, 267, 724, 791, -548, 480, 180, -631, 825, -170, 107, 227, -691, 905, -909, 359, 227, 287, 909, 632, -89, -522, 80, -429, 37, 561, -732, -474, 565, -798, -460, 188, 507, -511, -654, 212, -314, -376, -997, -114, -708, 512, -848, 781, 126, -956, -298, 354, -400, -121, 510, 445, 926, 27, -708, 676, 248, 834, 542, 236, -105, -153, 102, 128, 96, -348, -626, 598, 8, 978, -589, -461, -38, 381, -232, -817, 467, 356, -151, -460, 429, -408, 425, 618, -611, -247, 819,\
+963, -160, 1000, 141, -647, -875, 108, 790, -127, 463, -37, -195, -542, 12, 845, -384, 770, -129, 315, 826, -942, 430, 146, -170, -583, -903, -489, 497, -559, -401, -29, -129, -411, 166, 942, -646, -862, -404, 785, 777, -111, -481, -738, 490, 741, -398, 846, -178, -509, -661, 748, 297, -658, -567, 531, 427, -201, -41, -808, -668, 782, -860, -324, 249, 835, -234, 116, 542, -201, 328, 675, 480, -906, 188, 445, 63, -525, 811, 277, 133, 779, -680, 950, -477, -306, -64, 552, -890, -956, 169,\
+442, 44, -169, -243, -242, 423, -884, -757, -403, 739, -350, 383, 429, 153, -702, -725, 51, 310, 857, -56, 538, 46, -311, 132, -620, -297, -124, 534, 884, -629, -117, 506, -837, -100, -27, -381, -735, 262, 843, 703, 260, -457, 834, 469, 9, 950, 59, 127, -820, 518, 64, -783, 659, -608, -676, 802, 30, 589, 246, -369, 361, 347, 534, -376, 68, 941, 709, 264, 384, 481, 628, 199, -568, -342, -337, 853, -804, -858, -169, -270, 641, -344, 112, 530, -773, -349, -135, -367, -350, -756, -911, 180,\
+-660, 116, -478, -265, -581, 510, 520, -986, 935, 219, 522, 744, 47, -145, 917, 638, 301, 296, 858, -721, 511, -816, 328, 473, 441, 697, -260, -673, -379, 893, 458, 154, 86, 905, 590, 231, -717, -179, 79, 272, -439, -192, 178, -200, 51, 717, -256, -358, -626, -518, -314, -825, -325, 588, 675, -892, -798, 448, -518, 603, -23, 668, -655, 845, -314, 783, -347, -496, 921, 893, -163, -748, -906, 11, -143, -64, 300, 336, 882, 646, 533, 676, -98, -148, -607, -952, -481, -959, -874, 764, 537,\
+736, -347, 646, -843, 966, -916, -718, -391, -648, 740, 755, 919, -608, 388, -655, 68, 201, 675, -855, 7, -503, 881, 760, 669, 831, 721, -564, -445, 217, 331, 970, 521, 486, -254, 25, -259, 336, -831, 252, -995, 908, -412, -240, 123, -478, 366, 264, -504, -843, 632, -288, 896, 301, 423, 185, 318, 380, 457, -450, -162, -313, 673, -963, 570, 433, -548, 107, -39, -142, -98, -884, -3, 599, -486, -926, 923, -82, 686, 290, 99, -382, -789, 16, 495, 570, 284, 474, -504, -201, -178, -1, 592, 52,\
+827, -540, -151, -991, 130, 353, -420, -467, -661, 417, -690, 942, 936, 814, -566, -251, -298, 341, -139, 786, 129, 525, -861, 680, 955, -245, -50, 331, 412, -38, -66, 611, -558, 392, -629, -471, -68, -535, 744, 495, 87, 558, 695, 260, -308, 215, -464, 239, -50, 193, -540, 184, -8, -194, 148, 898, -557, -21, 884, 644, -785, -689, -281, -737, 267, 50, 206, 292, 265, 380, -511, 310, 53, 375, -497, -40, 312, -606, -395, 142, 422, 662, -584, 72, 144, 40, -679, -593, 581, 689, -829, 442, 822,\
+977, -832, -134, -248, -207, 248, 29, 259, 189, 592, -834, -866, 102, 0, 340, 25, -354, -239, 420, -730, -992, -925, -314, 420, 914, 607, -296, -415, -30, 813, 866, 153, -90, 150, -81, 636, -392, -222, -835, 482, -631, -962, -413, -727, 280, 686, -382, 157, -404, -511, -432, 455, 58, 108, -408, 290, -829, -252, 113, 550, -935, 925, 422, 38, 789, 361, 487, -460, -769, -963, -285, 206, -799, -488, -233, 416, 143, -456, 753, 520, 599, 621, -168, 178, -841, 51, 952, 374, 166, -300, -576, 844,\
+-656, 90, 780, 371, 730, -896, -895, -386, -662, 467, -61, 130, -362, -675, -113, 135, -761, -55, 408, 822, 675, -347, 725, 114, 952, -510, -972, 390, -413, -277, -52, 315, -80, 401, -712, 147, -202, 84, 214, -178, 970, -571, -210, 525, -887, -863, 504, 192, 837, -594, 203, -876, -209, 305, -826, 377, 103, -928, -803, -956, 949, -868, -547, 824, -994, 516, 93, -524, -866, -890, -988, -501, 15, -6, 413, -825, 304, -818, -223, 525, 176, 610, 828, 391, 940, 540, -831, 650, 438, 589, 941, 57,\
+523, 126, 221, 860, -282, -262, -226, 764, 743, -640, 390, 384, -434, 608, -983, 566, -446, 618, 456, -176, -278, 215, 871, -180, 444, -931, -200, -781, 404, 881, 780, -782, 517, -739, -548, -811, 201, -95, -249, -228, 491, -299, 700, 964, -550, 108, 334, -653, 245, -293, -552, 350, -685, -415, -818, 216, -194, -255, 295, 249, 408, 351, 287, 379, 682, 231, -693, 902, -902, 574, 937, -708, -402, -460, 827, -268, 791, 343, -780, -150, -738, 920, -430, -88, -361, -588, -727, -47, -297, 662,\
+-840, -637, -635, 916, -857, 938, 132, -553, 391, -522, 640, 626, 690, 833, 867, -555, 577, 226, 686, -44, 0, -965, 651, -1, 909, 595, -646, 740, -821, -648, -962, 927, -193, 159, 490, 594, -189, 707, -884, 759, -278, -160, -566, -340, 19, 862, -440, 445, -598, 341, 664, -311, 309, -159, 19, -672, 705, -646, 976, 247, 686, -830, -27, -667, 81, 399, -423, -567, 945, 38, 51, 740, 621, 204, -199, -908, -593, 424, 250, -561, 695, 9, 520, 878, 120, -109, 42, -375, -635, -711, -687, 383, -278,\
+36, 970, 925, 864, 836, 309, 117, 89, 654, -387, 346, -53, 617, -164, -624, 184, -45, 852, 498, -513, 794, -682, -576, 13, -147, 285, -776, -886, -96, 483, 994, -188, 346, -629, -848, 738, 51, 128, -898, -753, -906, 270, -203, -577, 48, -243, -210, 666, 353, 636, -954, 862, 560, -944, -877, -137, 440, -945, -316, 274, -211, -435, 615, -635, -468, 744, 948, -589, 525, 757, -191, -431, 42, 451, -160, -827, -991, 324, 697, 342, -610, 894, -787, -384, 872, 734, 878, 70, -260, 57, 397, -518,\
+629, -510, -94, 207, 214, -625, 106, -882, -575, 908, -650, 723, -154, 45, 108, -69, -565, 927, -68, -351, 707, -282, 429, -889, -596, 848, 578, -492, 41, -822, -992, 168, -286, -780, 970, 597, -293, -12, 367, 708, -415, 194, -86, -390, 224, 69, -368, -674, 1000, -672, 356, -202, -169, 826, 476, -285, 29, -448, 545, 186, 319, 67, 705, 412, 225, -212, -351, -391, -783, -9, 875, -59, -159, -123, -151, -296, 871, -638, 359, 909, -945, 345, -16, -562, -363, -183, -625, -115, -571, -329, 514,\
+99, 263, 463, -39, 597, -652, -349, 246, 77, -127, -563, -879, -30, 756, 777, -865, 675, -813, -501, 871, -406, -627, 834, -609, -205, -812, 643, -204, 291, -251, -184, -584, -541, 410, -573, -600, 908, -871, -687, 296, -713, -139, -778, -790, 347, -52, -400, 407, -653, 670, 39, -856, 904, 433, 392, 590, -271, -144, -863, 443, 353, 468, -544, 486, -930, 458, -596, -890, 163, 822, 768, 980, -783, -792, 126, 386, 367, -264, 603, -61, 728, 160, -4, -837, 832, 591, 436, 518, 796, -622, -867,\
+-669, -947, 253, 100, -792, 841, 413, 833, -249, -550, 282, -825, 936, -348, 898, -451, -283, 818, -237, 630, 216, -499, -637, -511, 767, -396, 221, 958, -586, -920, 401, -313, -580, -145, -270, 118, 497, 426, -975, 480, -445, -150, -721, -929, 439, -893, 902, 960, -525, -793, 924, 563, 683, -727, -86, 309, 432, -762, -345, 371, -617, 149, -215, -228, 505, 593, -20, -292, 704, -999, 149, -104, 819, -414, -443, 517, -599, -5, 145, -24, -993, -283, 904, 174, -112, -276, -860, 44, -257,\
+-931, -821, -667, 540, 421, 485, 531, 407, 833, 431, -415, 878, 503, -901, 639, -608, 896, 860, 927, 424, 113, -808, -323, 729, 382, -922, 548, -791, -379, 207, 203, 559, 537, 137, 999, -913, -240, 942, 249, 616, 775, -4, 915, 855, -987, -234, -384, 948, -310, -542, 125, -289, -599, 967, -492, -349, -552, 562, -926, 632, -164, 217, -165, -496, 847, 684, -884, 457, -748, -745, -38, 93, 961, 934, 588, 366, -130, 851, -803, -811, -211, 428, 183, -469, 888, 596, -475, -899, -681, 508, 184,\
+921, 863, -610, -416, -119, -966, -686, 210, 733, 715, -889, -925, -434, -566, -455, 596, -514, 983, 755, -194, -802, -313, 91, -541, 808, -834, 243, -377, 256, 966, -402, -773, -308, -605, 266, 866, 118, -425, -531, 498, 666, 813, -267, 830, 69, -869, -496, 735, 28, 488, -645, -493, -689, 170, -940, 532, 844, -658, -617, 408, -200, 764, -665, 568, 342, 621, 908, 471, 280, 859, 709, 898, 81, -547, 406, 514, -595, 43, -824, -696, -746, -429, -59, -263, -813, 233, 279, -125, 687, -418,\
+-530, 409, 614, 803, -407, 78, -676, -39, -887, -141, -292, 270, -343, 400, 907, 588, 668, 899, 973, 103, -101, -11, 397, -16, 165, 705, -410, -585, 316, 391, -346, -336, 957, -118, -538, -441, -845, 121, 591, -359, -188, -362, -208, 27, -925, -157, -495, -177, -580, 9, 531, -752, 94, 107, 820, 769, -500, 852, 617, 145, 355, 34, -463, -265, -709, -111, -855, -405, 560, 470, 3, -177, -164, -249, 450, 662, 841, -689, -509, 987, -33, 769, 234, -2, 203, 780, 744, -895, 497, -432, -406, -264,\
+-71, 124, 778, -897, 495, 127, -76, 52, -768, 205, 464, -992, 801, -83, -806, 545, -316, 146, 772, 786, 289, -936, 145, -30, -722, -455, 270, 444, 427, -482, 383, -861, 36, 630, -404, 83, 864, 743, -351, -846, 315, -837, 357, -195, 450, -715, 227, -942, 740, -519, 476, 716, 713, 169, 492, -112, -49, -931, 866, 95, -725, 198, -50, -17, -660, 356, -142, -781, 53, 431, 720, 143, -416, 446, -497, 490, -96, 157, 239, 487, -337, -224, -445, 813, 92, -22, 603, 424, 952, -632, -367, 898, -927,\
+884, -277, -187, -777, 537, -575, -313, 347, -33, 800, 672, -919, -541, 5, -270, -94, -265, -793, -183, -761, -516, -608, -218, 57, -889, -912, 508, 93, -90, 34, 530, 201, 999, -37, -186, -62, -980, 239, 902, 983, -287, -634, 524, -772, 470, -961, 32, 162, 315, -411, 400, -235, -283, -787, -703, 869, 792, 543, -274, 239, 733, -439, 306, 349, 579, -200, -201, -824, 384, -246, 133, -508, 770, -102, 957, -825, 740, 748, -376, 183, -426, 46, 668, -886, -43, -174, 672, -419, 390, 927, 1000,\
+318, 886, 47, 908, -540, -825, -5, 314, -999, 354, -603, 966, -633, -689, 985, 534, -290, 167, -652, -797, -612, -79, 488, 622, -464, -950, 595, 897, 704, -238, -395, 125, 831, -180, 226, -379, 310, 564, 56, -978, 895, -61, 686, -251, 434, -417, 161, -512, 752, 528, -589, -425, 66, -925, -157, 1000, 96, 256, -239, -784, -882, -464, -909, 663, -177, -678, -441, 669, -564, -201, -121, -743, 187, -107, -768, -682, 355, 161, 411, 984, -954, 166, -842, -755, 267, -709, 372, -699, -272, -850,\
+403, -839, 949, 622, -62, 51, 917, 70, 528, -558, -632, 832, 276, 61, -445, -195, 960, 846, -474, 764, 879, -411, 948, -62, -592, -123, -96, -551, -555, -724, 849, 250, -808, -732, 797, -839, -554, 306, -919, 888, 484, -728, 152, -122, -287, 16, -345, -396, -268, -963, -500, 433, 343, 418, -480, 828, 594, 821, -9, 933, -230, 707, -847, -610, -748, -234, 688, 935, 713, 865, -743, 293, -143, -20, 928, -906, -762, 528, 722, 412, -70, 622, -245, 539, -686, 730, -866, -705, 28, -916, -623,\
+-768, -614, -915, -123, -183, 680, -223, 515, -37, -235, -5, 260, 347, -239, -322, -861, -848, -936, 945, 721, -580, -639, 780, -153, -26, 685, 177, 587, 307, -915, 435, 658, 539, -229, -719, -171, -858, 162, 734, -539, -437, 246, 639, 765, -477, -342, -209, -284, -779, -414, -452, 914, 338, -83, 759, 567, 266, -485, 14, 225, 347, -432, -242, 997, -365, -764, 119, -641, -416, -388, -436, -388, -54, -649, -571, -920, -477, 714, -363, 836, 369, 702, 869, 503, -287, -679, 46, -666, -202,\
+-602, 71, -259, 967, 601, -571, -830, -993, -271, 281, -494, 482, -180, 572, 587, -651, -566, -448, -228, 511, -924, 832, -52, -712, 402, -644, -533, -865, 269, 965, 56, 675, 179, -338, -272, 614, 602, -283, 303, -70, 909, -942, 117, 839, 468, 813, -765, 884, -697, -813, 352, 374, -705, -295, 633, 211, -754, 597, -941, -142, -393, -469, -653, 688, 996, 911, 214, 431, 453, -141, 874, -81, -258, -735, -3, -110, -338, -929, -182, -306, -104, -840, -588, -759, -157, -801, 848, -698, 627, 914,\
+-33, -353, 425, 150, -798, 553, 934, -778, -196, -132, 808, 745, -894, 144, 213, 662, 273, -79, 454, -60, -467, 48, -15, -807, 69, -930, 749, 559, -867, -103, 258, -677, 750, -303, 846, -227, -936, 744, -770, 770, -434, 594, -477, 589, -612, 535, 357, -623, 683, 369, 905, 980, -410, -663, 762, -888, -563, -845, 843, 353, -491, 996, -255, -336, -132, 695, -823, 289, -143, 365, 916, 877, 245, -530, -848, -804, -118, -108, 847, 620, -355, 499, 881, 92, -640, 542, 38, 626, -260, -34, -378,\
+598, 890, 305, -118, 711, -385, 600, -570, 27, -129, -893, 354, 459, 374, 816, 470, 356, 661, 877, 735, -286, -780, 620, 943, -169, -888, 978, 441, -667, -399, 662, 249, 137, 598, -863, -453, 722, -815, -251, -995, -294, -707, 901, 763, 977, 137, 431, -994, 905, 593, 694, 444, -626, -816, 252, 282, 616, 841, 360, -932, 817, -908, 50, 394, -120, -786, -338, 499, -982, -95, -454, 838, -312, 320, -127, -653, 53, 16, 988, -968, -151, -369, -836, 293, -271, 483, 18, 724, -204, -965, 245, 310,\
+987, 552, -835, -912, -861, 254, 560, 124, 145, 798, 178, 476, 138, -311, 151, -907, -886, -592, 728, -43, -489, 873, -422, -439, -489, 375, -703, -459, 338, 418, -25, 332, -454, 730, -604, -800, 37, -172, -197, -568, -563, -332, 228, -182, 994, -123, 444, -567, 98, 78, 0, -504, -150, 88, -936, 199, -651, -776, 192, 46, 526, -727, -991, 534, -659, -738, 256, -894, 965, -76, 816, 435, -418, 800, 838, 67, -733, 570, 112, -514, -416\r\
+";
+                thread_local! {
+                    static TEST_TERM_AND_POINT: (Term<VoidListener>, AlacPoint) =
+                        build_test_term(&LINE, 5, 50);
+                }
+                TEST_TERM_AND_POINT.with(|(term, point)| {
+                    assert_eq!(
+                        find_from_grid_point_bench(term, *point)
+                            .map(|(path, ..)| path)
+                            .unwrap_or_default(),
+                        "392",
+                        "Hyperlink should have been found"
+                    );
+                });
+            }
+
+            #[perf]
+            // https://github.com/zed-industries/zed/issues/44510
+            pub fn issue_44510_hyperlink_benchmark() {
+                const LINE: &str = "..............................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................\
+..............................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................\
+..............................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................\
+..............................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................\
+..............................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................\
+..............................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................\
+..............................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................\
+..............................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................\
+..............................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................\
+..............................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................\
+..............................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................\
+..............................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................\
+..............................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................\
+..............................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................\
+...............................................E.\r\
+";
+                thread_local! {
+                    static TEST_TERM_AND_POINT: (Term<VoidListener>, AlacPoint) =
+                        build_test_term(&LINE, 5, 50);
+                }
+                TEST_TERM_AND_POINT.with(|(term, point)| {
+                    assert_eq!(
+                        find_from_grid_point_bench(term, *point)
+                            .map(|(path, ..)| path)
+                            .unwrap_or_default(),
+                        LINE.trim_end_matches(['.', '\r', '\n']),
                         "Hyperlink should have been found"
                     );
                 });
@@ -1038,8 +1224,9 @@ mod tests {
     }
 
     mod file_iri {
-        // File IRIs have a ton of use cases, most of which we currently do not support. A few of
-        // those cases are documented here as tests which are expected to fail.
+        // File IRIs have a ton of use cases. Absolute file URIs are supported on all platforms,
+        // including Windows drive letters (e.g., file:///C:/path) and percent-encoded characters.
+        // Some cases like relative file IRIs are not supported.
         // See https://en.wikipedia.org/wiki/File_URI_scheme
 
         /// [**`c₀, c₁, …, cₙ;`**]ₒₚₜ := use specified terminal widths of `c₀, c₁, …, cₙ` **columns**
@@ -1059,7 +1246,6 @@ mod tests {
         mod issues {
             #[cfg(not(target_os = "windows"))]
             #[test]
-            #[should_panic(expected = "Path = «/test/Ῥόδος/», at grid cells (0, 0)..=(15, 1)")]
             fn issue_file_iri_with_percent_encoded_characters() {
                 // Non-space characters
                 // file:///test/Ῥόδος/
@@ -1088,18 +1274,12 @@ mod tests {
                 // See https://en.wikipedia.org/wiki/File_URI_scheme
                 // https://github.com/zed-industries/zed/issues/39189
                 #[test]
-                #[should_panic(
-                    expected = r#"Path = «C:\\test\\cool\\index.rs», at grid cells (0, 0)..=(9, 1)"#
-                )]
                 fn issue_39189() {
                     test_file_iri!("file:///C:/test/cool/index.rs");
                     test_file_iri!("file:///C:/test/cool/");
                 }
 
                 #[test]
-                #[should_panic(
-                    expected = r#"Path = «C:\\test\\Ῥόδος\\», at grid cells (0, 0)..=(16, 1)"#
-                )]
                 fn issue_file_iri_with_percent_encoded_characters() {
                     // Non-space characters
                     // file:///test/Ῥόδος/

crates/terminal/src/terminal_settings.rs 🔗

@@ -95,7 +95,7 @@ impl settings::Settings for TerminalSettings {
                 )
             }),
             font_features: user_content.font_features,
-            font_weight: user_content.font_weight.map(FontWeight),
+            font_weight: user_content.font_weight,
             line_height: user_content.line_height.unwrap(),
             env: project_content.env.unwrap(),
             cursor_shape: user_content.cursor_shape.unwrap().into(),

crates/terminal_view/src/terminal_element.rs 🔗

@@ -151,7 +151,14 @@ impl BatchedTextRun {
                 std::slice::from_ref(&self.style),
                 Some(dimensions.cell_width),
             )
-            .paint(pos, dimensions.line_height, window, cx);
+            .paint(
+                pos,
+                dimensions.line_height,
+                gpui::TextAlign::Left,
+                None,
+                window,
+                cx,
+            );
     }
 }
 
@@ -632,7 +639,7 @@ impl TerminalElement {
     ) -> impl Fn(&E, &mut Window, &mut App) {
         move |event, window, cx| {
             if steal_focus {
-                window.focus(&focus_handle);
+                window.focus(&focus_handle, cx);
             } else if !focus_handle.is_focused(window) {
                 return;
             }
@@ -661,7 +668,7 @@ impl TerminalElement {
             let terminal_view = terminal_view.clone();
 
             move |e, window, cx| {
-                window.focus(&focus);
+                window.focus(&focus, cx);
 
                 let scroll_top = terminal_view.read(cx).scroll_top;
                 terminal.update(cx, |terminal, cx| {
@@ -1326,8 +1333,14 @@ impl Element for TerminalElement {
                                     }],
                                     None
                                 );
-                                shaped_line
-                                    .paint(ime_position, layout.dimensions.line_height, window, cx)
+                                shaped_line.paint(
+                                    ime_position,
+                                    layout.dimensions.line_height,
+                                    gpui::TextAlign::Left,
+                                    None,
+                                    window,
+                                    cx,
+                                )
                                     .log_err();
                             }
 

crates/terminal_view/src/terminal_panel.rs 🔗

@@ -30,8 +30,8 @@ use workspace::{
     ActivateNextPane, ActivatePane, ActivatePaneDown, ActivatePaneLeft, ActivatePaneRight,
     ActivatePaneUp, ActivatePreviousPane, DraggedSelection, DraggedTab, ItemId, MoveItemToPane,
     MoveItemToPaneInDirection, MovePaneDown, MovePaneLeft, MovePaneRight, MovePaneUp, NewTerminal,
-    Pane, PaneGroup, SplitDirection, SplitDown, SplitLeft, SplitRight, SplitUp, SwapPaneDown,
-    SwapPaneLeft, SwapPaneRight, SwapPaneUp, ToggleZoom, Workspace,
+    Pane, PaneGroup, SplitDirection, SplitDown, SplitLeft, SplitMode, SplitRight, SplitUp,
+    SwapPaneDown, SwapPaneLeft, SwapPaneRight, SwapPaneUp, ToggleZoom, Workspace,
     dock::{DockPosition, Panel, PanelEvent, PanelHandle},
     item::SerializableItem,
     move_active_item, move_item, pane,
@@ -167,7 +167,7 @@ impl TerminalPanel {
                                         // hence we focus that first. Otherwise, we'd end up without a focused element, as
                                         // context menu will be gone the moment we spawn the modal.
                                         .action(
-                                            "Spawn task",
+                                            "Spawn Task",
                                             zed_actions::Spawn::modal().boxed_clone(),
                                         )
                                 });
@@ -192,10 +192,10 @@ impl TerminalPanel {
                                             split_context.clone(),
                                             |menu, split_context| menu.context(split_context),
                                         )
-                                        .action("Split Right", SplitRight.boxed_clone())
-                                        .action("Split Left", SplitLeft.boxed_clone())
-                                        .action("Split Up", SplitUp.boxed_clone())
-                                        .action("Split Down", SplitDown.boxed_clone())
+                                        .action("Split Right", SplitRight::default().boxed_clone())
+                                        .action("Split Left", SplitLeft::default().boxed_clone())
+                                        .action("Split Up", SplitUp::default().boxed_clone())
+                                        .action("Split Down", SplitDown::default().boxed_clone())
                                     })
                                     .into()
                                 }
@@ -342,7 +342,7 @@ impl TerminalPanel {
             pane::Event::RemovedItem { .. } => self.serialize(cx),
             pane::Event::Remove { focus_on_pane } => {
                 let pane_count_before_removal = self.center.panes().len();
-                let _removal_result = self.center.remove(pane);
+                let _removal_result = self.center.remove(pane, cx);
                 if pane_count_before_removal == 1 {
                     self.center.first_pane().update(cx, |pane, cx| {
                         pane.set_zoomed(false, cx);
@@ -351,7 +351,7 @@ impl TerminalPanel {
                 } else if let Some(focus_on_pane) =
                     focus_on_pane.as_ref().or_else(|| self.center.panes().pop())
                 {
-                    focus_on_pane.focus_handle(cx).focus(window);
+                    focus_on_pane.focus_handle(cx).focus(window, cx);
                 }
             }
             pane::Event::ZoomIn => {
@@ -380,44 +380,49 @@ impl TerminalPanel {
                 }
                 self.serialize(cx);
             }
-            &pane::Event::Split {
-                direction,
-                clone_active_item,
-            } => {
-                if clone_active_item {
-                    let fut = self.new_pane_with_cloned_active_terminal(window, cx);
-                    let pane = pane.clone();
-                    cx.spawn_in(window, async move |panel, cx| {
-                        let Some(new_pane) = fut.await else {
+            &pane::Event::Split { direction, mode } => {
+                match mode {
+                    SplitMode::ClonePane | SplitMode::EmptyPane => {
+                        let clone = matches!(mode, SplitMode::ClonePane);
+                        let new_pane = self.new_pane_with_active_terminal(clone, window, cx);
+                        let pane = pane.clone();
+                        cx.spawn_in(window, async move |panel, cx| {
+                            let Some(new_pane) = new_pane.await else {
+                                return;
+                            };
+                            panel
+                                .update_in(cx, |panel, window, cx| {
+                                    panel
+                                        .center
+                                        .split(&pane, &new_pane, direction, cx)
+                                        .log_err();
+                                    window.focus(&new_pane.focus_handle(cx), cx);
+                                })
+                                .ok();
+                        })
+                        .detach();
+                    }
+                    SplitMode::MovePane => {
+                        let Some(item) =
+                            pane.update(cx, |pane, cx| pane.take_active_item(window, cx))
+                        else {
                             return;
                         };
-                        panel
-                            .update_in(cx, |panel, window, cx| {
-                                panel.center.split(&pane, &new_pane, direction).log_err();
-                                window.focus(&new_pane.focus_handle(cx));
-                            })
-                            .ok();
-                    })
-                    .detach();
-                } else {
-                    let Some(item) = pane.update(cx, |pane, cx| pane.take_active_item(window, cx))
-                    else {
-                        return;
-                    };
-                    let Ok(project) = self
-                        .workspace
-                        .update(cx, |workspace, _| workspace.project().clone())
-                    else {
-                        return;
-                    };
-                    let new_pane =
-                        new_terminal_pane(self.workspace.clone(), project, false, window, cx);
-                    new_pane.update(cx, |pane, cx| {
-                        pane.add_item(item, true, true, None, window, cx);
-                    });
-                    self.center.split(&pane, &new_pane, direction).log_err();
-                    window.focus(&new_pane.focus_handle(cx));
-                }
+                        let Ok(project) = self
+                            .workspace
+                            .update(cx, |workspace, _| workspace.project().clone())
+                        else {
+                            return;
+                        };
+                        let new_pane =
+                            new_terminal_pane(self.workspace.clone(), project, false, window, cx);
+                        new_pane.update(cx, |pane, cx| {
+                            pane.add_item(item, true, true, None, window, cx);
+                        });
+                        self.center.split(&pane, &new_pane, direction, cx).log_err();
+                        window.focus(&new_pane.focus_handle(cx), cx);
+                    }
+                };
             }
             pane::Event::Focus => {
                 self.active_pane = pane.clone();
@@ -430,8 +435,9 @@ impl TerminalPanel {
         }
     }
 
-    fn new_pane_with_cloned_active_terminal(
+    fn new_pane_with_active_terminal(
         &mut self,
+        clone: bool,
         window: &mut Window,
         cx: &mut Context<Self>,
     ) -> Task<Option<Entity<Pane>>> {
@@ -443,21 +449,34 @@ impl TerminalPanel {
         let weak_workspace = self.workspace.clone();
         let project = workspace.project().clone();
         let active_pane = &self.active_pane;
-        let terminal_view = active_pane
-            .read(cx)
-            .active_item()
-            .and_then(|item| item.downcast::<TerminalView>());
-        let working_directory = terminal_view
-            .as_ref()
-            .and_then(|terminal_view| {
-                terminal_view
-                    .read(cx)
-                    .terminal()
-                    .read(cx)
-                    .working_directory()
-            })
-            .or_else(|| default_working_directory(workspace, cx));
-        let is_zoomed = active_pane.read(cx).is_zoomed();
+        let terminal_view = if clone {
+            active_pane
+                .read(cx)
+                .active_item()
+                .and_then(|item| item.downcast::<TerminalView>())
+        } else {
+            None
+        };
+        let working_directory = if clone {
+            terminal_view
+                .as_ref()
+                .and_then(|terminal_view| {
+                    terminal_view
+                        .read(cx)
+                        .terminal()
+                        .read(cx)
+                        .working_directory()
+                })
+                .or_else(|| default_working_directory(workspace, cx))
+        } else {
+            default_working_directory(workspace, cx)
+        };
+
+        let is_zoomed = if clone {
+            active_pane.read(cx).is_zoomed()
+        } else {
+            false
+        };
         cx.spawn_in(window, async move |panel, cx| {
             let terminal = project
                 .update(cx, |project, cx| match terminal_view {
@@ -550,7 +569,7 @@ impl TerminalPanel {
 
         let builder = ShellBuilder::new(&shell, is_windows);
         let command_label = builder.command_label(task.command.as_deref().unwrap_or(""));
-        let (command, args) = builder.build(task.command.clone(), &task.args);
+        let (command, args) = builder.build_no_quote(task.command.clone(), &task.args);
 
         let task = SpawnInTerminal {
             command_label,
@@ -787,8 +806,7 @@ impl TerminalPanel {
                 }
 
                 pane.update(cx, |pane, cx| {
-                    let focus = pane.has_focus(window, cx)
-                        || matches!(reveal_strategy, RevealStrategy::Always);
+                    let focus = matches!(reveal_strategy, RevealStrategy::Always);
                     pane.add_item(terminal_view, true, focus, None, window, cx);
                 });
 
@@ -850,8 +868,7 @@ impl TerminalPanel {
                         }
 
                         pane.update(cx, |pane, cx| {
-                            let focus = pane.has_focus(window, cx)
-                                || matches!(reveal_strategy, RevealStrategy::Always);
+                            let focus = matches!(reveal_strategy, RevealStrategy::Always);
                             pane.add_item(terminal_view, true, focus, None, window, cx);
                         });
 
@@ -938,7 +955,6 @@ impl TerminalPanel {
         cx: &mut Context<Self>,
     ) -> Task<Result<WeakEntity<Terminal>>> {
         let reveal = spawn_task.reveal;
-        let reveal_target = spawn_task.reveal_target;
         let task_workspace = self.workspace.clone();
         cx.spawn_in(window, async move |terminal_panel, cx| {
             let project = terminal_panel.update(cx, |this, cx| {
@@ -954,6 +970,14 @@ impl TerminalPanel {
                 terminal_to_replace.set_terminal(new_terminal.clone(), window, cx);
             })?;
 
+            let reveal_target = terminal_panel.update(cx, |panel, _| {
+                if panel.center.panes().iter().any(|p| **p == task_pane) {
+                    RevealTarget::Dock
+                } else {
+                    RevealTarget::Center
+                }
+            })?;
+
             match reveal {
                 RevealStrategy::Always => match reveal_target {
                     RevealTarget::Center => {
@@ -995,7 +1019,7 @@ impl TerminalPanel {
                 RevealStrategy::NoFocus => match reveal_target {
                     RevealTarget::Center => {
                         task_workspace.update_in(cx, |workspace, window, cx| {
-                            workspace.active_pane().focus_handle(cx).focus(window);
+                            workspace.active_pane().focus_handle(cx).focus(window, cx);
                         })?;
                     }
                     RevealTarget::Dock => {
@@ -1050,7 +1074,7 @@ impl TerminalPanel {
             .center
             .find_pane_in_direction(&self.active_pane, direction, cx)
         {
-            window.focus(&pane.focus_handle(cx));
+            window.focus(&pane.focus_handle(cx), cx);
         } else {
             self.workspace
                 .update(cx, |workspace, cx| {
@@ -1066,7 +1090,7 @@ impl TerminalPanel {
             .find_pane_in_direction(&self.active_pane, direction, cx)
             .cloned()
         {
-            self.center.swap(&self.active_pane, &to);
+            self.center.swap(&self.active_pane, &to, cx);
             cx.notify();
         }
     }
@@ -1074,7 +1098,7 @@ impl TerminalPanel {
     fn move_pane_to_border(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
         if self
             .center
-            .move_to_border(&self.active_pane, direction)
+            .move_to_border(&self.active_pane, direction, cx)
             .unwrap()
         {
             cx.notify();
@@ -1168,63 +1192,67 @@ pub fn new_terminal_pane(
                         let source = tab.pane.clone();
                         let item_id_to_move = item.item_id();
 
-                        let Ok(new_split_pane) = pane
-                            .drag_split_direction()
-                            .map(|split_direction| {
-                                drop_closure_terminal_panel.update(cx, |terminal_panel, cx| {
-                                    let is_zoomed = if terminal_panel.active_pane == this_pane {
-                                        pane.is_zoomed()
-                                    } else {
-                                        terminal_panel.active_pane.read(cx).is_zoomed()
-                                    };
-                                    let new_pane = new_terminal_pane(
-                                        workspace.clone(),
-                                        project.clone(),
-                                        is_zoomed,
-                                        window,
-                                        cx,
-                                    );
-                                    terminal_panel.apply_tab_bar_buttons(&new_pane, cx);
-                                    terminal_panel.center.split(
-                                        &this_pane,
-                                        &new_pane,
-                                        split_direction,
-                                    )?;
-                                    anyhow::Ok(new_pane)
-                                })
-                            })
-                            .transpose()
-                        else {
-                            return ControlFlow::Break(());
+                        // If no split direction, let the regular pane drop handler take care of it
+                        let Some(split_direction) = pane.drag_split_direction() else {
+                            return ControlFlow::Continue(());
                         };
 
-                        match new_split_pane.transpose() {
-                            // Source pane may be the one currently updated, so defer the move.
-                            Ok(Some(new_pane)) => cx
-                                .spawn_in(window, async move |_, cx| {
-                                    cx.update(|window, cx| {
-                                        move_item(
-                                            &source,
+                        // Gather data synchronously before deferring
+                        let is_zoomed = drop_closure_terminal_panel
+                            .upgrade()
+                            .map(|terminal_panel| {
+                                let terminal_panel = terminal_panel.read(cx);
+                                if terminal_panel.active_pane == this_pane {
+                                    pane.is_zoomed()
+                                } else {
+                                    terminal_panel.active_pane.read(cx).is_zoomed()
+                                }
+                            })
+                            .unwrap_or(false);
+
+                        let workspace = workspace.clone();
+                        let terminal_panel = drop_closure_terminal_panel.clone();
+
+                        // Defer the split operation to avoid re-entrancy panic.
+                        // The pane may be the one currently being updated, so we cannot
+                        // call mark_positions (via split) synchronously.
+                        cx.spawn_in(window, async move |_, cx| {
+                            cx.update(|window, cx| {
+                                let Ok(new_pane) =
+                                    terminal_panel.update(cx, |terminal_panel, cx| {
+                                        let new_pane = new_terminal_pane(
+                                            workspace, project, is_zoomed, window, cx,
+                                        );
+                                        terminal_panel.apply_tab_bar_buttons(&new_pane, cx);
+                                        terminal_panel.center.split(
+                                            &this_pane,
                                             &new_pane,
-                                            item_id_to_move,
-                                            new_pane.read(cx).active_item_index(),
-                                            true,
-                                            window,
+                                            split_direction,
                                             cx,
-                                        );
+                                        )?;
+                                        anyhow::Ok(new_pane)
                                     })
-                                    .ok();
-                                })
-                                .detach(),
-                            // If we drop into existing pane or current pane,
-                            // regular pane drop handler will take care of it,
-                            // using the right tab index for the operation.
-                            Ok(None) => return ControlFlow::Continue(()),
-                            err @ Err(_) => {
-                                err.log_err();
-                                return ControlFlow::Break(());
-                            }
-                        };
+                                else {
+                                    return;
+                                };
+
+                                let Some(new_pane) = new_pane.log_err() else {
+                                    return;
+                                };
+
+                                move_item(
+                                    &source,
+                                    &new_pane,
+                                    item_id_to_move,
+                                    new_pane.read(cx).active_item_index(),
+                                    true,
+                                    window,
+                                    cx,
+                                );
+                            })
+                            .ok();
+                        })
+                        .detach();
                     } else if let Some(project_path) = item.project_path(cx)
                         && let Some(entry_path) = project.read(cx).absolute_path(&project_path, cx)
                     {
@@ -1293,7 +1321,7 @@ fn add_paths_to_terminal(
         .active_item()
         .and_then(|item| item.downcast::<TerminalView>())
     {
-        window.focus(&terminal_view.focus_handle(cx));
+        window.focus(&terminal_view.focus_handle(cx), cx);
         let mut new_text = paths.iter().map(|path| format!(" {path:?}")).join("");
         new_text.push(' ');
         terminal_view.update(cx, |terminal_view, cx| {
@@ -1447,7 +1475,7 @@ impl Render for TerminalPanel {
                             .position(|pane| **pane == terminal_panel.active_pane)
                         {
                             let next_ix = (ix + 1) % panes.len();
-                            window.focus(&panes[next_ix].focus_handle(cx));
+                            window.focus(&panes[next_ix].focus_handle(cx), cx);
                         }
                     }),
                 )
@@ -1459,7 +1487,7 @@ impl Render for TerminalPanel {
                             .position(|pane| **pane == terminal_panel.active_pane)
                         {
                             let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
-                            window.focus(&panes[prev_ix].focus_handle(cx));
+                            window.focus(&panes[prev_ix].focus_handle(cx), cx);
                         }
                     },
                 ))
@@ -1467,10 +1495,10 @@ impl Render for TerminalPanel {
                     cx.listener(|terminal_panel, action: &ActivatePane, window, cx| {
                         let panes = terminal_panel.center.panes();
                         if let Some(&pane) = panes.get(action.0) {
-                            window.focus(&pane.read(cx).focus_handle(cx));
+                            window.focus(&pane.read(cx).focus_handle(cx), cx);
                         } else {
                             let future =
-                                terminal_panel.new_pane_with_cloned_active_terminal(window, cx);
+                                terminal_panel.new_pane_with_active_terminal(true, window, cx);
                             cx.spawn_in(window, async move |terminal_panel, cx| {
                                 if let Some(new_pane) = future.await {
                                     _ = terminal_panel.update_in(
@@ -1482,10 +1510,11 @@ impl Render for TerminalPanel {
                                                     &terminal_panel.active_pane,
                                                     &new_pane,
                                                     SplitDirection::Right,
+                                                    cx,
                                                 )
                                                 .log_err();
                                             let new_pane = new_pane.read(cx);
-                                            window.focus(&new_pane.focus_handle(cx));
+                                            window.focus(&new_pane.focus_handle(cx), cx);
                                         },
                                     );
                                 }

crates/terminal_view/src/terminal_scrollbar.rs 🔗

@@ -50,28 +50,24 @@ impl ScrollableHandle for TerminalScrollHandle {
         let state = self.state.borrow();
         size(
             Pixels::ZERO,
-            state
-                .total_lines
-                .checked_sub(state.viewport_lines)
-                .unwrap_or(0) as f32
-                * state.line_height,
+            state.total_lines.saturating_sub(state.viewport_lines) as f32 * state.line_height,
         )
     }
 
     fn offset(&self) -> Point<Pixels> {
         let state = self.state.borrow();
-        let scroll_offset = state.total_lines - state.viewport_lines - state.display_offset;
-        Point::new(
-            Pixels::ZERO,
-            -(scroll_offset as f32 * self.state.borrow().line_height),
-        )
+        let scroll_offset = state
+            .total_lines
+            .saturating_sub(state.viewport_lines)
+            .saturating_sub(state.display_offset);
+        Point::new(Pixels::ZERO, -(scroll_offset as f32 * state.line_height))
     }
 
     fn set_offset(&self, point: Point<Pixels>) {
         let state = self.state.borrow();
         let offset_delta = (point.y / state.line_height).round() as i32;
 
-        let max_offset = state.total_lines - state.viewport_lines;
+        let max_offset = state.total_lines.saturating_sub(state.viewport_lines);
         let display_offset = (max_offset as i32 + offset_delta).clamp(0, max_offset as i32);
 
         self.future_display_offset

crates/terminal_view/src/terminal_tab_tooltip.rs 🔗

@@ -1,36 +0,0 @@
-use gpui::{IntoElement, Render};
-use ui::{Divider, prelude::*, tooltip_container};
-
-pub struct TerminalTooltip {
-    title: SharedString,
-    pid: u32,
-}
-
-impl TerminalTooltip {
-    pub fn new(title: impl Into<SharedString>, pid: u32) -> Self {
-        Self {
-            title: title.into(),
-            pid,
-        }
-    }
-}
-
-impl Render for TerminalTooltip {
-    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
-        tooltip_container(cx, move |this, _cx| {
-            this.occlude()
-                .on_mouse_move(|_, _window, cx| cx.stop_propagation())
-                .child(
-                    v_flex()
-                        .gap_1()
-                        .child(Label::new(self.title.clone()))
-                        .child(Divider::horizontal())
-                        .child(
-                            Label::new(format!("Process ID (PID): {}", self.pid))
-                                .color(Color::Muted)
-                                .size(LabelSize::Small),
-                        ),
-                )
-        })
-    }
-}

crates/terminal_view/src/terminal_view.rs 🔗

@@ -4,13 +4,12 @@ pub mod terminal_panel;
 mod terminal_path_like_target;
 pub mod terminal_scrollbar;
 mod terminal_slash_command;
-pub mod terminal_tab_tooltip;
 
 use assistant_slash_command::SlashCommandRegistry;
 use editor::{EditorSettings, actions::SelectAll, blink_manager::BlinkManager};
 use gpui::{
-    Action, AnyElement, App, DismissEvent, Entity, EventEmitter, FocusHandle, Focusable,
-    KeyContext, KeyDownEvent, Keystroke, MouseButton, MouseDownEvent, Pixels, Render,
+    Action, AnyElement, App, ClipboardEntry, DismissEvent, Entity, EventEmitter, FocusHandle,
+    Focusable, KeyContext, KeyDownEvent, Keystroke, MouseButton, MouseDownEvent, Pixels, Render,
     ScrollWheelEvent, Styled, Subscription, Task, WeakEntity, actions, anchored, deferred, div,
 };
 use persistence::TERMINAL_DB;
@@ -32,9 +31,8 @@ use terminal_panel::TerminalPanel;
 use terminal_path_like_target::{hover_path_like_target, open_path_like_target};
 use terminal_scrollbar::TerminalScrollHandle;
 use terminal_slash_command::TerminalSlashCommand;
-use terminal_tab_tooltip::TerminalTooltip;
 use ui::{
-    ContextMenu, Icon, IconName, Label, ScrollAxes, Scrollbars, Tooltip, WithScrollbar, h_flex,
+    ContextMenu, Divider, ScrollAxes, Scrollbars, Tooltip, WithScrollbar,
     prelude::*,
     scrollbars::{self, GlobalSetting, ScrollbarVisibility},
 };
@@ -411,7 +409,7 @@ impl TerminalView {
                 )
         });
 
-        window.focus(&context_menu.focus_handle(cx));
+        window.focus(&context_menu.focus_handle(cx), cx);
         let subscription = cx.subscribe_in(
             &context_menu,
             window,
@@ -689,12 +687,32 @@ impl TerminalView {
 
     ///Attempt to paste the clipboard into the terminal
     fn paste(&mut self, _: &Paste, _: &mut Window, cx: &mut Context<Self>) {
-        if let Some(clipboard_string) = cx.read_from_clipboard().and_then(|item| item.text()) {
+        let Some(clipboard) = cx.read_from_clipboard() else {
+            return;
+        };
+
+        if clipboard.entries().iter().any(|entry| match entry {
+            ClipboardEntry::Image(image) => !image.bytes.is_empty(),
+            _ => false,
+        }) {
+            self.forward_ctrl_v(cx);
+            return;
+        }
+
+        if let Some(text) = clipboard.text() {
             self.terminal
-                .update(cx, |terminal, _cx| terminal.paste(&clipboard_string));
+                .update(cx, |terminal, _cx| terminal.paste(&text));
         }
     }
 
+    /// Emits a raw Ctrl+V so TUI agents can read the OS clipboard directly
+    /// and attach images using their native workflows.
+    fn forward_ctrl_v(&self, cx: &mut Context<Self>) {
+        self.terminal.update(cx, |term, _| {
+            term.input(vec![0x16]);
+        });
+    }
+
     fn send_text(&mut self, text: &SendText, _: &mut Window, cx: &mut Context<Self>) {
         self.clear_bell(cx);
         self.terminal.update(cx, |term, _| {
@@ -1140,14 +1158,24 @@ impl Item for TerminalView {
     type Event = ItemEvent;
 
     fn tab_tooltip_content(&self, cx: &App) -> Option<TabTooltipContent> {
-        let terminal = self.terminal().read(cx);
-        let title = terminal.title(false);
-        let pid = terminal.pid_getter()?.fallback_pid();
-
-        Some(TabTooltipContent::Custom(Box::new(move |_window, cx| {
-            cx.new(|_| TerminalTooltip::new(title.clone(), pid.as_u32()))
-                .into()
-        })))
+        Some(TabTooltipContent::Custom(Box::new(Tooltip::element({
+            let terminal = self.terminal().read(cx);
+            let title = terminal.title(false);
+            let pid = terminal.pid_getter()?.fallback_pid();
+
+            move |_, _| {
+                v_flex()
+                    .gap_1()
+                    .child(Label::new(title.clone()))
+                    .child(h_flex().flex_grow().child(Divider::horizontal()))
+                    .child(
+                        Label::new(format!("Process ID (PID): {}", pid))
+                            .color(Color::Muted)
+                            .size(LabelSize::Small),
+                    )
+                    .into_any_element()
+            }
+        }))))
     }
 
     fn tab_content(&self, params: TabContentParams, _window: &Window, cx: &App) -> AnyElement {
@@ -1434,6 +1462,7 @@ impl SearchableItem for TerminalView {
     fn update_matches(
         &mut self,
         matches: &[Self::Match],
+        _active_match_index: Option<usize>,
         _window: &mut Window,
         cx: &mut Context<Self>,
     ) {

crates/text/src/anchor.rs 🔗

@@ -8,10 +8,14 @@ use sum_tree::{Bias, Dimensions};
 /// A timestamped position in a buffer
 #[derive(Copy, Clone, Eq, PartialEq, Hash)]
 pub struct Anchor {
+    /// The timestamp of the operation that inserted the text
+    /// in which this anchor is located.
     pub timestamp: clock::Lamport,
-    /// The byte offset in the buffer
+    /// The byte offset into the text inserted in the operation
+    /// at `timestamp`.
     pub offset: usize,
-    /// Describes which character the anchor is biased towards
+    /// Whether this anchor stays attached to the character *before* or *after*
+    /// the offset.
     pub bias: Bias,
     pub buffer_id: Option<BufferId>,
 }

crates/text/src/text.rs 🔗

@@ -39,6 +39,7 @@ pub use subscription::*;
 pub use sum_tree::Bias;
 use sum_tree::{Dimensions, FilterCursor, SumTree, TreeMap, TreeSet};
 use undo_map::UndoMap;
+use util::debug_panic;
 
 #[cfg(any(test, feature = "test-support"))]
 use util::RandomCharIter;
@@ -2320,8 +2321,13 @@ impl BufferSnapshot {
         } else if anchor.is_max() {
             self.visible_text.len()
         } else {
-            debug_assert!(anchor.buffer_id == Some(self.remote_id));
-            debug_assert!(self.version.observed(anchor.timestamp));
+            debug_assert_eq!(anchor.buffer_id, Some(self.remote_id));
+            debug_assert!(
+                self.version.observed(anchor.timestamp),
+                "Anchor timestamp {:?} not observed by buffer {:?}",
+                anchor.timestamp,
+                self.version
+            );
             let anchor_key = InsertionFragmentKey {
                 timestamp: anchor.timestamp,
                 split_offset: anchor.offset,
@@ -2439,7 +2445,7 @@ impl BufferSnapshot {
         if bias == Bias::Left && offset == 0 {
             Anchor::min_for_buffer(self.remote_id)
         } else if bias == Bias::Right
-            && ((cfg!(debug_assertions) && offset >= self.len()) || offset == self.len())
+            && ((!cfg!(debug_assertions) && offset >= self.len()) || offset == self.len())
         {
             Anchor::max_for_buffer(self.remote_id)
         } else {
@@ -2453,7 +2459,15 @@ impl BufferSnapshot {
                 };
             }
             let (start, _, item) = self.fragments.find::<usize, _>(&None, &offset, bias);
-            let fragment = item.unwrap();
+            let Some(fragment) = item else {
+                // We got a bad offset, likely out of bounds
+                debug_panic!(
+                    "Failed to find fragment at offset {} (len: {})",
+                    offset,
+                    self.len()
+                );
+                return Anchor::max_for_buffer(self.remote_id);
+            };
             let overshoot = offset - start;
             Anchor {
                 timestamp: fragment.timestamp,
@@ -3374,6 +3388,25 @@ impl LineEnding {
     }
 }
 
+pub fn chunks_with_line_ending(rope: &Rope, line_ending: LineEnding) -> impl Iterator<Item = &str> {
+    rope.chunks().flat_map(move |chunk| {
+        let mut newline = false;
+        let end_with_newline = chunk.ends_with('\n').then_some(line_ending.as_str());
+        chunk
+            .lines()
+            .flat_map(move |line| {
+                let ending = if newline {
+                    Some(line_ending.as_str())
+                } else {
+                    None
+                };
+                newline = true;
+                ending.into_iter().chain([line])
+            })
+            .chain(end_with_newline)
+    })
+}
+
 #[cfg(debug_assertions)]
 pub mod debug {
     use super::*;

crates/theme/src/default_colors.rs 🔗

@@ -91,6 +91,7 @@ impl ThemeColors {
             tab_inactive_background: neutral().light().step_2(),
             tab_active_background: neutral().light().step_1(),
             search_match_background: neutral().light().step_5(),
+            search_active_match_background: neutral().light().step_7(),
             panel_background: neutral().light().step_2(),
             panel_focused_border: blue().light().step_10(),
             panel_indent_guide: neutral().light_alpha().step_5(),
@@ -228,6 +229,7 @@ impl ThemeColors {
             tab_inactive_background: neutral().dark().step_2(),
             tab_active_background: neutral().dark().step_1(),
             search_match_background: neutral().dark().step_5(),
+            search_active_match_background: neutral().dark().step_3(),
             panel_background: neutral().dark().step_2(),
             panel_focused_border: blue().dark().step_8(),
             panel_indent_guide: neutral().dark_alpha().step_4(),

crates/theme/src/fallback_themes.rs 🔗

@@ -152,6 +152,7 @@ pub(crate) fn zed_default_dark() -> Theme {
                 tab_inactive_background: bg,
                 tab_active_background: editor,
                 search_match_background: bg,
+                search_active_match_background: bg,
 
                 editor_background: editor,
                 editor_gutter_background: editor,

crates/theme/src/schema.rs 🔗

@@ -287,6 +287,15 @@ pub fn theme_colors_refinement(
         .panel_background
         .as_ref()
         .and_then(|color| try_parse_color(color).ok());
+    let search_match_background = this
+        .search_match_background
+        .as_ref()
+        .and_then(|color| try_parse_color(color).ok());
+    let search_active_match_background = this
+        .search_active_match_background
+        .as_ref()
+        .and_then(|color| try_parse_color(color).ok())
+        .or(search_match_background);
     ThemeColorsRefinement {
         border,
         border_variant: this
@@ -442,10 +451,8 @@ pub fn theme_colors_refinement(
             .tab_active_background
             .as_ref()
             .and_then(|color| try_parse_color(color).ok()),
-        search_match_background: this
-            .search_match_background
-            .as_ref()
-            .and_then(|color| try_parse_color(color).ok()),
+        search_match_background: search_match_background,
+        search_active_match_background: search_active_match_background,
         panel_background,
         panel_focused_border: this
             .panel_focused_border

crates/theme/src/styles/colors.rs 🔗

@@ -128,6 +128,7 @@ pub struct ThemeColors {
     pub tab_inactive_background: Hsla,
     pub tab_active_background: Hsla,
     pub search_match_background: Hsla,
+    pub search_active_match_background: Hsla,
     pub panel_background: Hsla,
     pub panel_focused_border: Hsla,
     pub panel_indent_guide: Hsla,
@@ -352,6 +353,7 @@ pub enum ThemeColorField {
     TabInactiveBackground,
     TabActiveBackground,
     SearchMatchBackground,
+    SearchActiveMatchBackground,
     PanelBackground,
     PanelFocusedBorder,
     PanelIndentGuide,
@@ -467,6 +469,7 @@ impl ThemeColors {
             ThemeColorField::TabInactiveBackground => self.tab_inactive_background,
             ThemeColorField::TabActiveBackground => self.tab_active_background,
             ThemeColorField::SearchMatchBackground => self.search_match_background,
+            ThemeColorField::SearchActiveMatchBackground => self.search_active_match_background,
             ThemeColorField::PanelBackground => self.panel_background,
             ThemeColorField::PanelFocusedBorder => self.panel_focused_border,
             ThemeColorField::PanelIndentGuide => self.panel_indent_guide,

crates/title_bar/build.rs 🔗

@@ -0,0 +1,28 @@
+#![allow(clippy::disallowed_methods, reason = "build scripts are exempt")]
+
+fn main() {
+    println!("cargo::rustc-check-cfg=cfg(macos_sdk_26)");
+
+    #[cfg(target_os = "macos")]
+    {
+        use std::process::Command;
+
+        let output = Command::new("xcrun")
+            .args(["--sdk", "macosx", "--show-sdk-version"])
+            .output()
+            .unwrap();
+
+        let sdk_version = String::from_utf8(output.stdout).unwrap();
+        let major_version: Option<u32> = sdk_version
+            .trim()
+            .split('.')
+            .next()
+            .and_then(|v| v.parse().ok());
+
+        if let Some(major) = major_version
+            && major >= 26
+        {
+            println!("cargo:rustc-cfg=macos_sdk_26");
+        }
+    }
+}

crates/title_bar/src/application_menu.rs 🔗

@@ -1,12 +1,7 @@
-use gpui::{Entity, OwnedMenu, OwnedMenuItem};
+use gpui::{Action, Entity, OwnedMenu, OwnedMenuItem, actions};
 use settings::Settings;
 
-#[cfg(not(target_os = "macos"))]
-use gpui::{Action, actions};
-
-#[cfg(not(target_os = "macos"))]
 use schemars::JsonSchema;
-#[cfg(not(target_os = "macos"))]
 use serde::Deserialize;
 
 use smallvec::SmallVec;
@@ -14,18 +9,23 @@ use ui::{ContextMenu, PopoverMenu, PopoverMenuHandle, Tooltip, prelude::*};
 
 use crate::title_bar_settings::TitleBarSettings;
 
-#[cfg(not(target_os = "macos"))]
 actions!(
     app_menu,
     [
-        /// Navigates to the menu item on the right.
+        /// Activates the menu on the right in the client-side application menu.
+        ///
+        /// Does not apply to platform menu bars (e.g. on macOS).
         ActivateMenuRight,
-        /// Navigates to the menu item on the left.
+        /// Activates the menu on the left in the client-side application menu.
+        ///
+        /// Does not apply to platform menu bars (e.g. on macOS).
         ActivateMenuLeft
     ]
 );
 
-#[cfg(not(target_os = "macos"))]
+/// Opens the named menu in the client-side application menu.
+///
+/// Does not apply to platform menu bars (e.g. on macOS).
 #[derive(Clone, Deserialize, JsonSchema, PartialEq, Default, Action)]
 #[action(namespace = app_menu)]
 pub struct OpenApplicationMenu(String);
@@ -151,10 +151,10 @@ impl ApplicationMenu {
 
         // Application menu must have same ids as first menu item in standard menu
         div()
-            .id(SharedString::from(format!("{}-menu-item", menu_name)))
+            .id(format!("{}-menu-item", menu_name))
             .occlude()
             .child(
-                PopoverMenu::new(SharedString::from(format!("{}-menu-popover", menu_name)))
+                PopoverMenu::new(format!("{}-menu-popover", menu_name))
                     .menu(move |window, cx| {
                         Self::build_menu_from_items(entry.clone(), window, cx).into()
                     })
@@ -184,10 +184,10 @@ impl ApplicationMenu {
             .collect();
 
         div()
-            .id(SharedString::from(format!("{}-menu-item", menu_name)))
+            .id(format!("{}-menu-item", menu_name))
             .occlude()
             .child(
-                PopoverMenu::new(SharedString::from(format!("{}-menu-popover", menu_name)))
+                PopoverMenu::new(format!("{}-menu-popover", menu_name))
                     .menu(move |window, cx| {
                         Self::build_menu_from_items(entry.clone(), window, cx).into()
                     })

crates/title_bar/src/collab.rs 🔗

@@ -8,7 +8,7 @@ use gpui::{
     AnyElement, Hsla, IntoElement, MouseButton, Path, ScreenCaptureSource, Styled, WeakEntity,
     canvas, point,
 };
-use gpui::{App, Task, Window, actions};
+use gpui::{App, Task, Window};
 use project::WorktreeSettings;
 use rpc::proto::{self};
 use settings::{Settings as _, SettingsLocation};
@@ -22,19 +22,7 @@ use workspace::notifications::DetachAndPromptErr;
 
 use crate::TitleBar;
 
-actions!(
-    collab,
-    [
-        /// Toggles screen sharing on or off.
-        ToggleScreenSharing,
-        /// Toggles microphone mute.
-        ToggleMute,
-        /// Toggles deafen mode (mute both microphone and speakers).
-        ToggleDeafen
-    ]
-);
-
-fn toggle_screen_sharing(
+pub fn toggle_screen_sharing(
     screen: anyhow::Result<Option<Rc<dyn ScreenCaptureSource>>>,
     window: &mut Window,
     cx: &mut App,
@@ -90,7 +78,7 @@ fn toggle_screen_sharing(
     toggle_screen_sharing.detach_and_prompt_err("Sharing Screen Failed", window, cx, |e, _, _| Some(format!("{:?}\n\nPlease check that you have given Zed permissions to record your screen in Settings.", e)));
 }
 
-fn toggle_mute(_: &ToggleMute, cx: &mut App) {
+pub fn toggle_mute(cx: &mut App) {
     let call = ActiveCall::global(cx).read(cx);
     if let Some(room) = call.room().cloned() {
         room.update(cx, |room, cx| {
@@ -110,7 +98,7 @@ fn toggle_mute(_: &ToggleMute, cx: &mut App) {
     }
 }
 
-fn toggle_deafen(_: &ToggleDeafen, cx: &mut App) {
+pub fn toggle_deafen(cx: &mut App) {
     if let Some(room) = ActiveCall::global(cx).read(cx).room().cloned() {
         room.update(cx, |room, cx| room.toggle_deafen(cx));
     }
@@ -182,7 +170,9 @@ impl TitleBar {
 
                     this.children(current_user_face_pile.map(|face_pile| {
                         v_flex()
-                            .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
+                            .on_mouse_down(MouseButton::Left, |_, window, _| {
+                                window.prevent_default()
+                            })
                             .child(face_pile)
                             .child(render_color_ribbon(player_colors.local().cursor))
                     }))
@@ -217,6 +207,9 @@ impl TitleBar {
                                 .child(facepile)
                                 .child(render_color_ribbon(player_color.cursor))
                                 .cursor_pointer()
+                                .on_mouse_down(MouseButton::Left, |_, window, _| {
+                                    window.prevent_default()
+                                })
                                 .on_click({
                                     let peer_id = collaborator.peer_id;
                                     cx.listener(move |this, _, window, cx| {
@@ -453,9 +446,7 @@ impl TitleBar {
                 .icon_size(IconSize::Small)
                 .toggle_state(is_muted)
                 .selected_style(ButtonStyle::Tinted(TintColor::Error))
-                .on_click(move |_, _window, cx| {
-                    toggle_mute(&Default::default(), cx);
-                })
+                .on_click(move |_, _window, cx| toggle_mute(cx))
                 .into_any_element(),
             );
         }
@@ -492,7 +483,7 @@ impl TitleBar {
                     }
                 }
             })
-            .on_click(move |_, _, cx| toggle_deafen(&Default::default(), cx))
+            .on_click(move |_, _, cx| toggle_deafen(cx))
             .into_any_element(),
         );
 

crates/title_bar/src/platforms/platform_mac.rs 🔗

@@ -1,6 +1,10 @@
-/// Use pixels here instead of a rem-based size because the macOS traffic
-/// lights are a static size, and don't scale with the rest of the UI.
-///
-/// Magic number: There is one extra pixel of padding on the left side due to
-/// the 1px border around the window on macOS apps.
+// Use pixels here instead of a rem-based size because the macOS traffic
+// lights are a static size, and don't scale with the rest of the UI.
+//
+// Magic number: There is one extra pixel of padding on the left side due to
+// the 1px border around the window on macOS apps.
+#[cfg(macos_sdk_26)]
+pub const TRAFFIC_LIGHT_PADDING: f32 = 78.;
+
+#[cfg(not(macos_sdk_26))]
 pub const TRAFFIC_LIGHT_PADDING: f32 = 71.;

crates/title_bar/src/title_bar.rs 🔗

@@ -1,5 +1,5 @@
 mod application_menu;
-mod collab;
+pub mod collab;
 mod onboarding_banner;
 pub mod platform_title_bar;
 mod platforms;
@@ -30,18 +30,20 @@ use gpui::{
     Subscription, WeakEntity, Window, actions, div,
 };
 use onboarding_banner::OnboardingBanner;
-use project::{Project, WorktreeSettings, git_store::GitStoreEvent};
+use project::{
+    Project, WorktreeSettings, git_store::GitStoreEvent, trusted_worktrees::TrustedWorktrees,
+};
 use remote::RemoteConnectionOptions;
 use settings::{Settings, SettingsLocation};
 use std::sync::Arc;
 use theme::ActiveTheme;
 use title_bar_settings::TitleBarSettings;
 use ui::{
-    Avatar, Button, ButtonLike, ButtonStyle, Chip, ContextMenu, Icon, IconName, IconSize,
-    IconWithIndicator, Indicator, PopoverMenu, PopoverMenuHandle, Tooltip, h_flex, prelude::*,
+    Avatar, ButtonLike, Chip, ContextMenu, IconWithIndicator, Indicator, PopoverMenu,
+    PopoverMenuHandle, TintColor, Tooltip, prelude::*,
 };
 use util::{ResultExt, rel_path::RelPath};
-use workspace::{Workspace, notifications::NotifyResultExt};
+use workspace::{ToggleWorktreeSecurity, Workspace, notifications::NotifyResultExt};
 use zed_actions::{OpenRecent, OpenRemote};
 
 pub use onboarding_banner::restore_banner;
@@ -163,11 +165,12 @@ impl Render for TitleBar {
                             title_bar
                                 .when(title_bar_settings.show_project_items, |title_bar| {
                                     title_bar
-                                        .children(self.render_project_host(cx))
-                                        .child(self.render_project_name(cx))
+                                        .children(self.render_restricted_mode(cx))
+                                        .children(self.render_project_host(window, cx))
+                                        .child(self.render_project_name(window, cx))
                                 })
                                 .when(title_bar_settings.show_branch_name, |title_bar| {
-                                    title_bar.children(self.render_project_branch(cx))
+                                    title_bar.children(self.render_project_repo(window, cx))
                                 })
                         })
                 })
@@ -202,9 +205,11 @@ impl Render for TitleBar {
                 .children(self.render_connection_status(status, cx))
                 .when(
                     user.is_none() && TitleBarSettings::get_global(cx).show_sign_in,
-                    |el| el.child(self.render_sign_in_button(cx)),
+                    |this| this.child(self.render_sign_in_button(cx)),
                 )
-                .child(self.render_app_menu_button(cx))
+                .when(TitleBarSettings::get_global(cx).show_user_menu, |this| {
+                    this.child(self.render_user_menu_button(cx))
+                })
                 .into_any_element(),
         );
 
@@ -289,7 +294,12 @@ impl TitleBar {
                 _ => {}
             }),
         );
-        subscriptions.push(cx.observe(&user_store, |_, _, cx| cx.notify()));
+        subscriptions.push(cx.observe(&user_store, |_a, _, cx| cx.notify()));
+        if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
+            subscriptions.push(cx.subscribe(&trusted_worktrees, |_, _, _, cx| {
+                cx.notify();
+            }));
+        }
 
         let banner = cx.new(|cx| {
             OnboardingBanner::new(
@@ -315,20 +325,54 @@ impl TitleBar {
             client,
             _subscriptions: subscriptions,
             banner,
-            screen_share_popover_handle: Default::default(),
+            screen_share_popover_handle: PopoverMenuHandle::default(),
         }
     }
 
-    fn render_remote_project_connection(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
+    fn project_name(&self, cx: &Context<Self>) -> Option<SharedString> {
+        self.project
+            .read(cx)
+            .visible_worktrees(cx)
+            .map(|worktree| {
+                let worktree = worktree.read(cx);
+                let settings_location = SettingsLocation {
+                    worktree_id: worktree.id(),
+                    path: RelPath::empty(),
+                };
+
+                let settings = WorktreeSettings::get(Some(settings_location), cx);
+                let name = match &settings.project_name {
+                    Some(name) => name.as_str(),
+                    None => worktree.root_name_str(),
+                };
+                SharedString::new(name)
+            })
+            .next()
+    }
+
+    fn render_remote_project_connection(
+        &self,
+        window: &mut Window,
+        cx: &mut Context<Self>,
+    ) -> Option<AnyElement> {
+        let workspace = self.workspace.clone();
+        let is_picker_open = self.is_picker_open(window, cx);
+
         let options = self.project.read(cx).remote_connection_options(cx)?;
         let host: SharedString = options.display_name().into();
 
-        let (nickname, icon) = match options {
-            RemoteConnectionOptions::Ssh(options) => {
-                (options.nickname.map(|nick| nick.into()), IconName::Server)
+        let (nickname, tooltip_title, icon) = match options {
+            RemoteConnectionOptions::Ssh(options) => (
+                options.nickname.map(|nick| nick.into()),
+                "Remote Project",
+                IconName::Server,
+            ),
+            RemoteConnectionOptions::Wsl(_) => (None, "Remote Project", IconName::Linux),
+            RemoteConnectionOptions::Docker(_dev_container_connection) => {
+                (None, "Dev Container", IconName::Box)
             }
-            RemoteConnectionOptions::Wsl(_) => (None, IconName::Linux),
         };
+
         let nickname = nickname.unwrap_or_else(|| host.clone());
 
         let (indicator_color, meta) = match self.project.read(cx).remote_connection_state(cx)? {
@@ -358,7 +402,7 @@ impl TitleBar {
         let meta = SharedString::from(meta);
 
         Some(
-            ButtonLike::new("ssh-server-icon")
+            ButtonLike::new("remote_project")
                 .child(
                     h_flex()
                         .gap_2()
@@ -373,34 +417,93 @@ impl TitleBar {
                         )
                         .child(Label::new(nickname).size(LabelSize::Small).truncate()),
                 )
-                .tooltip(move |_window, cx| {
-                    Tooltip::with_meta(
-                        "Remote Project",
-                        Some(&OpenRemote {
-                            from_existing_connection: false,
-                            create_new_window: false,
-                        }),
-                        meta.clone(),
-                        cx,
-                    )
+                .when(!is_picker_open, |this| {
+                    this.tooltip(move |_window, cx| {
+                        Tooltip::with_meta(
+                            tooltip_title,
+                            Some(&OpenRemote {
+                                from_existing_connection: false,
+                                create_new_window: false,
+                            }),
+                            meta.clone(),
+                            cx,
+                        )
+                    })
                 })
-                .on_click(|_, window, cx| {
-                    window.dispatch_action(
-                        OpenRemote {
-                            from_existing_connection: false,
-                            create_new_window: false,
-                        }
-                        .boxed_clone(),
-                        cx,
-                    );
+                .on_click(move |event, window, cx| {
+                    let position = event.position();
+                    let _ = workspace.update(cx, |this, cx| {
+                        this.set_next_modal_placement(workspace::ModalPlacement::Anchored {
+                            position,
+                        });
+
+                        window.dispatch_action(
+                            OpenRemote {
+                                from_existing_connection: false,
+                                create_new_window: false,
+                            }
+                            .boxed_clone(),
+                            cx,
+                        );
+                    });
                 })
                 .into_any_element(),
         )
     }
 
-    pub fn render_project_host(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
+    pub fn render_restricted_mode(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
+        let has_restricted_worktrees = TrustedWorktrees::try_get_global(cx)
+            .map(|trusted_worktrees| {
+                trusted_worktrees
+                    .read(cx)
+                    .has_restricted_worktrees(&self.project.read(cx).worktree_store(), cx)
+            })
+            .unwrap_or(false);
+        if !has_restricted_worktrees {
+            return None;
+        }
+
+        let button = Button::new("restricted_mode_trigger", "Restricted Mode")
+            .style(ButtonStyle::Tinted(TintColor::Warning))
+            .label_size(LabelSize::Small)
+            .color(Color::Warning)
+            .icon(IconName::Warning)
+            .icon_color(Color::Warning)
+            .icon_size(IconSize::Small)
+            .icon_position(IconPosition::Start)
+            .tooltip(|_, cx| {
+                Tooltip::with_meta(
+                    "You're in Restricted Mode",
+                    Some(&ToggleWorktreeSecurity),
+                    "Mark this project as trusted and unlock all features",
+                    cx,
+                )
+            })
+            .on_click({
+                cx.listener(move |this, _, window, cx| {
+                    this.workspace
+                        .update(cx, |workspace, cx| {
+                            workspace.show_worktree_trust_security_modal(true, window, cx)
+                        })
+                        .log_err();
+                })
+            });
+
+        if cfg!(macos_sdk_26) {
+            // Make up for Tahoe's traffic light buttons having less spacing around them
+            Some(div().child(button).ml_0p5().into_any_element())
+        } else {
+            Some(button.into_any_element())
+        }
+    }
+
+    pub fn render_project_host(
+        &self,
+        window: &mut Window,
+        cx: &mut Context<Self>,
+    ) -> Option<AnyElement> {
         if self.project.read(cx).is_via_remote_server() {
-            return self.render_remote_project_connection(cx);
+            return self.render_remote_project_connection(window, cx);
         }
 
         if self.project.read(cx).is_disconnected(cx) {
@@ -408,7 +511,6 @@ impl TitleBar {
                 Button::new("disconnected", "Disconnected")
                     .disabled(true)
                     .color(Color::Disabled)
-                    .style(ButtonStyle::Subtle)
                     .label_size(LabelSize::Small)
                     .into_any_element(),
             );
@@ -421,15 +523,19 @@ impl TitleBar {
             .read(cx)
             .participant_indices()
             .get(&host_user.id)?;
+
         Some(
             Button::new("project_owner_trigger", host_user.github_login.clone())
                 .color(Color::Player(participant_index.0))
-                .style(ButtonStyle::Subtle)
                 .label_size(LabelSize::Small)
-                .tooltip(Tooltip::text(format!(
-                    "{} is sharing this project. Click to follow.",
-                    host_user.github_login
-                )))
+                .tooltip(move |_, cx| {
+                    let tooltip_title = format!(
+                        "{} is sharing this project. Click to follow.",
+                        host_user.github_login
+                    );
+
+                    Tooltip::with_meta(tooltip_title, None, "Click to Follow", cx)
+                })
                 .on_click({
                     let host_peer_id = host.peer_id;
                     cx.listener(move |this, _, window, cx| {
@@ -444,46 +550,42 @@ impl TitleBar {
         )
     }
 
-    pub fn render_project_name(&self, cx: &mut Context<Self>) -> impl IntoElement {
-        let name = self
-            .project
-            .read(cx)
-            .visible_worktrees(cx)
-            .map(|worktree| {
-                let worktree = worktree.read(cx);
-                let settings_location = SettingsLocation {
-                    worktree_id: worktree.id(),
-                    path: RelPath::empty(),
-                };
+    pub fn render_project_name(
+        &self,
+        window: &mut Window,
+        cx: &mut Context<Self>,
+    ) -> impl IntoElement {
+        let workspace = self.workspace.clone();
+        let is_picker_open = self.is_picker_open(window, cx);
 
-                let settings = WorktreeSettings::get(Some(settings_location), cx);
-                match &settings.project_name {
-                    Some(name) => name.as_str(),
-                    None => worktree.root_name_str(),
-                }
-            })
-            .next();
+        let name = self.project_name(cx);
         let is_project_selected = name.is_some();
         let name = if let Some(name) = name {
-            util::truncate_and_trailoff(name, MAX_PROJECT_NAME_LENGTH)
+            util::truncate_and_trailoff(&name, MAX_PROJECT_NAME_LENGTH)
         } else {
-            "Open recent project".to_string()
+            "Open Recent Project".to_string()
         };
 
         Button::new("project_name_trigger", name)
-            .when(!is_project_selected, |b| b.color(Color::Muted))
-            .style(ButtonStyle::Subtle)
             .label_size(LabelSize::Small)
-            .tooltip(move |_window, cx| {
-                Tooltip::for_action(
-                    "Recent Projects",
-                    &zed_actions::OpenRecent {
-                        create_new_window: false,
-                    },
-                    cx,
-                )
+            .when(!is_project_selected, |s| s.color(Color::Muted))
+            .when(!is_picker_open, |this| {
+                this.tooltip(move |_window, cx| {
+                    Tooltip::for_action(
+                        "Recent Projects",
+                        &zed_actions::OpenRecent {
+                            create_new_window: false,
+                        },
+                        cx,
+                    )
+                })
             })
-            .on_click(cx.listener(move |_, _, window, cx| {
+            .on_click(move |event, window, cx| {
+                let position = event.position();
+                let _ = workspace.update(cx, |this, _cx| {
+                    this.set_next_modal_placement(workspace::ModalPlacement::Anchored { position })
+                });
+
                 window.dispatch_action(
                     OpenRecent {
                         create_new_window: false,
@@ -491,70 +593,102 @@ impl TitleBar {
                     .boxed_clone(),
                     cx,
                 );
-            }))
+            })
     }
 
-    pub fn render_project_branch(&self, cx: &mut Context<Self>) -> Option<impl IntoElement> {
-        let settings = TitleBarSettings::get_global(cx);
+    pub fn render_project_repo(
+        &self,
+        window: &mut Window,
+        cx: &mut Context<Self>,
+    ) -> Option<impl IntoElement> {
         let repository = self.project.read(cx).active_repository(cx)?;
+        let repository_count = self.project.read(cx).repositories(cx).len();
         let workspace = self.workspace.upgrade()?;
-        let repo = repository.read(cx);
-        let branch_name = repo
-            .branch
-            .as_ref()
-            .map(|branch| branch.name())
-            .map(|name| util::truncate_and_trailoff(name, MAX_BRANCH_NAME_LENGTH))
-            .or_else(|| {
-                repo.head_commit.as_ref().map(|commit| {
-                    commit
-                        .sha
-                        .chars()
-                        .take(MAX_SHORT_SHA_LENGTH)
-                        .collect::<String>()
-                })
-            })?;
+
+        let (branch_name, icon_info) = {
+            let repo = repository.read(cx);
+            let branch_name = repo
+                .branch
+                .as_ref()
+                .map(|branch| branch.name())
+                .map(|name| util::truncate_and_trailoff(name, MAX_BRANCH_NAME_LENGTH))
+                .or_else(|| {
+                    repo.head_commit.as_ref().map(|commit| {
+                        commit
+                            .sha
+                            .chars()
+                            .take(MAX_SHORT_SHA_LENGTH)
+                            .collect::<String>()
+                    })
+                });
+
+            let branch_name = branch_name?;
+
+            let project_name = self.project_name(cx);
+            let repo_name = repo
+                .work_directory_abs_path
+                .file_name()
+                .and_then(|name| name.to_str())
+                .map(SharedString::new);
+            let show_repo_name =
+                repository_count > 1 && repo.branch.is_some() && repo_name != project_name;
+            let branch_name = if let Some(repo_name) = repo_name.filter(|_| show_repo_name) {
+                format!("{repo_name}/{branch_name}")
+            } else {
+                branch_name
+            };
+
+            let status = repo.status_summary();
+            let tracked = status.index + status.worktree;
+            let icon_info = if status.conflict > 0 {
+                (IconName::Warning, Color::VersionControlConflict)
+            } else if tracked.modified > 0 {
+                (IconName::SquareDot, Color::VersionControlModified)
+            } else if tracked.added > 0 || status.untracked > 0 {
+                (IconName::SquarePlus, Color::VersionControlAdded)
+            } else if tracked.deleted > 0 {
+                (IconName::SquareMinus, Color::VersionControlDeleted)
+            } else {
+                (IconName::GitBranch, Color::Muted)
+            };
+
+            (branch_name, icon_info)
+        };
+
+        let is_picker_open = self.is_picker_open(window, cx);
+        let settings = TitleBarSettings::get_global(cx);
 
         Some(
             Button::new("project_branch_trigger", branch_name)
-                .color(Color::Muted)
-                .style(ButtonStyle::Subtle)
                 .label_size(LabelSize::Small)
-                .tooltip(move |_window, cx| {
-                    Tooltip::with_meta(
-                        "Recent Branches",
-                        Some(&zed_actions::git::Branch),
-                        "Local branches only",
-                        cx,
-                    )
-                })
-                .on_click(move |_, window, cx| {
-                    let _ = workspace.update(cx, |this, cx| {
-                        window.focus(&this.active_pane().focus_handle(cx));
-                        window.dispatch_action(zed_actions::git::Branch.boxed_clone(), cx);
-                    });
+                .color(Color::Muted)
+                .when(!is_picker_open, |this| {
+                    this.tooltip(move |_window, cx| {
+                        Tooltip::with_meta(
+                            "Recent Branches",
+                            Some(&zed_actions::git::Branch),
+                            "Local branches only",
+                            cx,
+                        )
+                    })
                 })
                 .when(settings.show_branch_icon, |branch_button| {
-                    let (icon, icon_color) = {
-                        let status = repo.status_summary();
-                        let tracked = status.index + status.worktree;
-                        if status.conflict > 0 {
-                            (IconName::Warning, Color::VersionControlConflict)
-                        } else if tracked.modified > 0 {
-                            (IconName::SquareDot, Color::VersionControlModified)
-                        } else if tracked.added > 0 || status.untracked > 0 {
-                            (IconName::SquarePlus, Color::VersionControlAdded)
-                        } else if tracked.deleted > 0 {
-                            (IconName::SquareMinus, Color::VersionControlDeleted)
-                        } else {
-                            (IconName::GitBranch, Color::Muted)
-                        }
-                    };
-
+                    let (icon, icon_color) = icon_info;
                     branch_button
                         .icon(icon)
                         .icon_position(IconPosition::Start)
                         .icon_color(icon_color)
                         .icon_size(IconSize::Indicator)
+                })
+                .on_click(move |event, window, cx| {
+                    let position = event.position();
+                    let _ = workspace.update(cx, |this, cx| {
+                        this.set_next_modal_placement(workspace::ModalPlacement::Anchored {
+                            position,
+                        });
+                        window.focus(&this.active_pane().focus_handle(cx), cx);
+                        window.dispatch_action(zed_actions::git::Branch.boxed_clone(), cx);
+                    });
                 }),
         )
     }
@@ -646,7 +780,7 @@ impl TitleBar {
 
     pub fn render_sign_in_button(&mut self, _: &mut Context<Self>) -> Button {
         let client = self.client.clone();
-        Button::new("sign_in", "Sign in")
+        Button::new("sign_in", "Sign In")
             .label_size(LabelSize::Small)
             .on_click(move |_, window, cx| {
                 let client = client.clone();
@@ -661,7 +795,7 @@ impl TitleBar {
             })
     }
 
-    pub fn render_app_menu_button(&mut self, cx: &mut Context<Self>) -> impl Element {
+    pub fn render_user_menu_button(&mut self, cx: &mut Context<Self>) -> impl Element {
         let user_store = self.user_store.read(cx);
         let user = user_store.current_user();
 
@@ -768,4 +902,10 @@ impl TitleBar {
             })
             .anchor(gpui::Corner::TopRight)
     }
+
+    fn is_picker_open(&self, window: &mut Window, cx: &mut Context<Self>) -> bool {
+        self.workspace
+            .update(cx, |workspace, cx| workspace.has_active_modal(window, cx))
+            .unwrap_or(false)
+    }
 }

crates/title_bar/src/title_bar_settings.rs 🔗

@@ -8,6 +8,7 @@ pub struct TitleBarSettings {
     pub show_branch_name: bool,
     pub show_project_items: bool,
     pub show_sign_in: bool,
+    pub show_user_menu: bool,
     pub show_menus: bool,
 }
 
@@ -21,6 +22,7 @@ impl Settings for TitleBarSettings {
             show_branch_name: content.show_branch_name.unwrap(),
             show_project_items: content.show_project_items.unwrap(),
             show_sign_in: content.show_sign_in.unwrap(),
+            show_user_menu: content.show_user_menu.unwrap(),
             show_menus: content.show_menus.unwrap(),
         }
     }

crates/toolchain_selector/src/active_toolchain.rs 🔗

@@ -124,7 +124,7 @@ impl ActiveToolchain {
                 &buffer,
                 window,
                 |this, _, event: &BufferEvent, window, cx| {
-                    if matches!(event, BufferEvent::LanguageChanged) {
+                    if matches!(event, BufferEvent::LanguageChanged(_)) {
                         this._update_toolchain_task = Self::spawn_tracker_task(window, cx);
                     }
                 },
@@ -198,10 +198,17 @@ impl ActiveToolchain {
                     .or_else(|| toolchains.toolchains.first())
                     .cloned();
                 if let Some(toolchain) = &default_choice {
+                    let worktree_root_path = project
+                        .read_with(cx, |this, cx| {
+                            this.worktree_for_id(worktree_id, cx)
+                                .map(|worktree| worktree.read(cx).abs_path())
+                        })
+                        .ok()
+                        .flatten()?;
                     workspace::WORKSPACE_DB
                         .set_toolchain(
                             workspace_id,
-                            worktree_id,
+                            worktree_root_path,
                             relative_path.clone(),
                             toolchain.clone(),
                         )

crates/toolchain_selector/src/toolchain_selector.rs 🔗

@@ -1,6 +1,7 @@
 mod active_toolchain;
 
 pub use active_toolchain::ActiveToolchain;
+use anyhow::Context as _;
 use convert_case::Casing as _;
 use editor::Editor;
 use file_finder::OpenPathDelegate;
@@ -62,6 +63,7 @@ struct AddToolchainState {
     language_name: LanguageName,
     root_path: ProjectPath,
     weak: WeakEntity<ToolchainSelector>,
+    worktree_root_path: Arc<Path>,
 }
 
 struct ScopePickerState {
@@ -99,12 +101,17 @@ impl AddToolchainState {
         root_path: ProjectPath,
         window: &mut Window,
         cx: &mut Context<ToolchainSelector>,
-    ) -> Entity<Self> {
+    ) -> anyhow::Result<Entity<Self>> {
         let weak = cx.weak_entity();
-
-        cx.new(|cx| {
+        let worktree_root_path = project
+            .read(cx)
+            .worktree_for_id(root_path.worktree_id, cx)
+            .map(|worktree| worktree.read(cx).abs_path())
+            .context("Could not find worktree")?;
+        Ok(cx.new(|cx| {
             let (lister, rx) = Self::create_path_browser_delegate(project.clone(), cx);
             let picker = cx.new(|cx| Picker::uniform_list(lister, window, cx));
+
             Self {
                 state: AddState::Path {
                     _subscription: cx.subscribe(&picker, |_, _, _: &DismissEvent, cx| {
@@ -118,8 +125,9 @@ impl AddToolchainState {
                 language_name,
                 root_path,
                 weak,
+                worktree_root_path,
             }
-        })
+        }))
     }
 
     fn create_path_browser_delegate(
@@ -128,67 +136,61 @@ impl AddToolchainState {
     ) -> (OpenPathDelegate, oneshot::Receiver<Option<Vec<PathBuf>>>) {
         let (tx, rx) = oneshot::channel();
         let weak = cx.weak_entity();
-        let path_style = project.read(cx).path_style(cx);
-        let lister =
-            OpenPathDelegate::new(tx, DirectoryLister::Project(project), false, path_style)
-                .show_hidden()
-                .with_footer(Arc::new(move |_, cx| {
-                    let error = weak
-                        .read_with(cx, |this, _| {
-                            if let AddState::Path { error, .. } = &this.state {
-                                error.clone()
-                            } else {
-                                None
+        let lister = OpenPathDelegate::new(tx, DirectoryLister::Project(project), false, cx)
+            .show_hidden()
+            .with_footer(Arc::new(move |_, cx| {
+                let error = weak
+                    .read_with(cx, |this, _| {
+                        if let AddState::Path { error, .. } = &this.state {
+                            error.clone()
+                        } else {
+                            None
+                        }
+                    })
+                    .ok()
+                    .flatten();
+                let is_loading = weak
+                    .read_with(cx, |this, _| {
+                        matches!(
+                            this.state,
+                            AddState::Path {
+                                input_state: PathInputState::Resolving(_),
+                                ..
                             }
-                        })
-                        .ok()
-                        .flatten();
-                    let is_loading = weak
-                        .read_with(cx, |this, _| {
-                            matches!(
-                                this.state,
-                                AddState::Path {
-                                    input_state: PathInputState::Resolving(_),
-                                    ..
-                                }
-                            )
-                        })
-                        .unwrap_or_default();
-                    Some(
-                        v_flex()
-                            .child(Divider::horizontal())
-                            .child(
-                                h_flex()
-                                    .p_1()
-                                    .justify_between()
-                                    .gap_2()
-                                    .child(
-                                        Label::new("Select Toolchain Path")
-                                            .color(Color::Muted)
-                                            .map(|this| {
-                                                if is_loading {
-                                                    this.with_animation(
-                                                        "select-toolchain-label",
-                                                        Animation::new(Duration::from_secs(2))
-                                                            .repeat()
-                                                            .with_easing(pulsating_between(
-                                                                0.4, 0.8,
-                                                            )),
-                                                        |label, delta| label.alpha(delta),
-                                                    )
-                                                    .into_any()
-                                                } else {
-                                                    this.into_any_element()
-                                                }
-                                            }),
-                                    )
-                                    .when_some(error, |this, error| {
-                                        this.child(Label::new(error).color(Color::Error))
-                                    }),
-                            )
-                            .into_any(),
-                    )
-                }));
+                        )
+                    })
+                    .unwrap_or_default();
+                Some(
+                    v_flex()
+                        .child(Divider::horizontal())
+                        .child(
+                            h_flex()
+                                .p_1()
+                                .justify_between()
+                                .gap_2()
+                                .child(Label::new("Select Toolchain Path").color(Color::Muted).map(
+                                    |this| {
+                                        if is_loading {
+                                            this.with_animation(
+                                                "select-toolchain-label",
+                                                Animation::new(Duration::from_secs(2))
+                                                    .repeat()
+                                                    .with_easing(pulsating_between(0.4, 0.8)),
+                                                |label, delta| label.alpha(delta),
+                                            )
+                                            .into_any()
+                                        } else {
+                                            this.into_any_element()
+                                        }
+                                    },
+                                ))
+                                .when_some(error, |this, error| {
+                                    this.child(Label::new(error).color(Color::Error))
+                                }),
+                        )
+                        .into_any(),
+                )
+            }));
 
         (lister, rx)
     }
@@ -231,7 +233,7 @@ impl AddToolchainState {
                                 );
                             });
                             *input_state = Self::wait_for_path(rx, window, cx);
-                            this.focus_handle(cx).focus(window);
+                            this.focus_handle(cx).focus(window, cx);
                         }
                     });
                     return Err(anyhow::anyhow!("Failed to resolve toolchain"));
@@ -243,7 +245,15 @@ impl AddToolchainState {
                 // Suggest a default scope based on the applicability.
                 let scope = if let Some(project_path) = resolved_toolchain_path {
                     if !root_path.path.as_ref().is_empty() && project_path.starts_with(&root_path) {
-                        ToolchainScope::Subproject(root_path.worktree_id, root_path.path)
+                        let worktree_root_path = project
+                            .read_with(cx, |this, cx| {
+                                this.worktree_for_id(root_path.worktree_id, cx)
+                                    .map(|worktree| worktree.read(cx).abs_path())
+                            })
+                            .ok()
+                            .flatten()
+                            .context("Could not find a worktree with a given worktree ID")?;
+                        ToolchainScope::Subproject(worktree_root_path, root_path.path)
                     } else {
                         ToolchainScope::Project
                     }
@@ -266,7 +276,7 @@ impl AddToolchainState {
                         toolchain,
                         scope_picker,
                     };
-                    this.focus_handle(cx).focus(window);
+                    this.focus_handle(cx).focus(window, cx);
                 });
 
                 Result::<_, anyhow::Error>::Ok(())
@@ -339,7 +349,7 @@ impl AddToolchainState {
         });
         _ = self.weak.update(cx, |this, cx| {
             this.state = State::Search((this.create_search_state)(window, cx));
-            this.focus_handle(cx).focus(window);
+            this.focus_handle(cx).focus(window, cx);
             cx.notify();
         });
     }
@@ -389,7 +399,7 @@ impl Render for AddToolchainState {
                     &weak,
                     |this: &mut ToolchainSelector, _: &menu::Cancel, window, cx| {
                         this.state = State::Search((this.create_search_state)(window, cx));
-                        this.state.focus_handle(cx).focus(window);
+                        this.state.focus_handle(cx).focus(window, cx);
                         cx.notify();
                     },
                 ))
@@ -406,7 +416,7 @@ impl Render for AddToolchainState {
                         ToolchainScope::Global,
                         ToolchainScope::Project,
                         ToolchainScope::Subproject(
-                            self.root_path.worktree_id,
+                            self.worktree_root_path.clone(),
                             self.root_path.path.clone(),
                         ),
                     ];
@@ -588,19 +598,20 @@ impl ToolchainSelector {
             .worktree_for_id(worktree_id, cx)?
             .read(cx)
             .abs_path();
-        let workspace_id = workspace.database_id()?;
         let weak = workspace.weak_handle();
         cx.spawn_in(window, async move |workspace, cx| {
-            let active_toolchain = workspace::WORKSPACE_DB
-                .toolchain(
-                    workspace_id,
-                    worktree_id,
-                    relative_path.clone(),
-                    language_name.clone(),
-                )
-                .await
-                .ok()
-                .flatten();
+            let active_toolchain = project
+                .read_with(cx, |this, cx| {
+                    this.active_toolchain(
+                        ProjectPath {
+                            worktree_id,
+                            path: relative_path.clone(),
+                        },
+                        language_name.clone(),
+                        cx,
+                    )
+                })?
+                .await;
             workspace
                 .update_in(cx, |this, window, cx| {
                     this.toggle_modal(window, cx, move |window, cx| {
@@ -618,6 +629,7 @@ impl ToolchainSelector {
                     });
                 })
                 .ok();
+            anyhow::Ok(())
         })
         .detach();
 
@@ -697,7 +709,7 @@ impl ToolchainSelector {
         cx: &mut Context<Self>,
     ) {
         if matches!(self.state, State::Search(_)) {
-            self.state = State::AddToolchain(AddToolchainState::new(
+            let Ok(state) = AddToolchainState::new(
                 self.project.clone(),
                 self.language_name.clone(),
                 ProjectPath {
@@ -706,8 +718,11 @@ impl ToolchainSelector {
                 },
                 window,
                 cx,
-            ));
-            self.state.focus_handle(cx).focus(window);
+            ) else {
+                return;
+            };
+            self.state = State::AddToolchain(state);
+            self.state.focus_handle(cx).focus(window, cx);
             cx.notify();
         }
     }
@@ -903,11 +918,17 @@ impl PickerDelegate for ToolchainSelectorDelegate {
             {
                 let workspace = self.workspace.clone();
                 let worktree_id = self.worktree_id;
+                let worktree_abs_path_root = self.worktree_abs_path_root.clone();
                 let path = self.relative_path.clone();
                 let relative_path = self.relative_path.clone();
                 cx.spawn_in(window, async move |_, cx| {
                     workspace::WORKSPACE_DB
-                        .set_toolchain(workspace_id, worktree_id, relative_path, toolchain.clone())
+                        .set_toolchain(
+                            workspace_id,
+                            worktree_abs_path_root,
+                            relative_path,
+                            toolchain.clone(),
+                        )
                         .await
                         .log_err();
                     workspace

crates/ui/src/components.rs 🔗

@@ -1,3 +1,4 @@
+mod ai;
 mod avatar;
 mod banner;
 mod button;
@@ -43,6 +44,7 @@ mod tree_view_item;
 #[cfg(feature = "stories")]
 mod stories;
 
+pub use ai::*;
 pub use avatar::*;
 pub use banner::*;
 pub use button::*;

crates/language_models/src/ui/configured_api_card.rs → crates/ui/src/components/ai/configured_api_card.rs 🔗

@@ -1,10 +1,11 @@
+use crate::{Tooltip, prelude::*};
 use gpui::{ClickEvent, IntoElement, ParentElement, SharedString};
-use ui::{Tooltip, prelude::*};
 
 #[derive(IntoElement)]
 pub struct ConfiguredApiCard {
     label: SharedString,
     button_label: Option<SharedString>,
+    button_tab_index: Option<isize>,
     tooltip_label: Option<SharedString>,
     disabled: bool,
     on_click: Option<Box<dyn Fn(&ClickEvent, &mut Window, &mut App) + 'static>>,
@@ -15,6 +16,7 @@ impl ConfiguredApiCard {
         Self {
             label: label.into(),
             button_label: None,
+            button_tab_index: None,
             tooltip_label: None,
             disabled: false,
             on_click: None,
@@ -43,6 +45,11 @@ impl ConfiguredApiCard {
         self.disabled = disabled;
         self
     }
+
+    pub fn button_tab_index(mut self, tab_index: isize) -> Self {
+        self.button_tab_index = Some(tab_index);
+        self
+    }
 }
 
 impl RenderOnce for ConfiguredApiCard {
@@ -51,23 +58,27 @@ impl RenderOnce for ConfiguredApiCard {
         let button_id = SharedString::new(format!("id-{}", button_label));
 
         h_flex()
+            .min_w_0()
             .mt_0p5()
             .p_1()
             .justify_between()
             .rounded_md()
+            .flex_wrap()
             .border_1()
             .border_color(cx.theme().colors().border)
             .bg(cx.theme().colors().background)
             .child(
                 h_flex()
-                    .flex_1()
                     .min_w_0()
                     .gap_1()
                     .child(Icon::new(IconName::Check).color(Color::Success))
-                    .child(Label::new(self.label).truncate()),
+                    .child(Label::new(self.label)),
             )
             .child(
                 Button::new(button_id, button_label)
+                    .when_some(self.button_tab_index, |elem, tab_index| {
+                        elem.tab_index(tab_index)
+                    })
                     .label_size(LabelSize::Small)
                     .icon(IconName::Undo)
                     .icon_size(IconSize::Small)

crates/ui/src/components/button.rs 🔗

@@ -1,12 +1,14 @@
 mod button;
 mod button_icon;
 mod button_like;
+mod button_link;
 mod icon_button;
 mod split_button;
 mod toggle_button;
 
 pub use button::*;
 pub use button_like::*;
+pub use button_link::*;
 pub use icon_button::*;
 pub use split_button::*;
 pub use toggle_button::*;

crates/ui/src/components/button/button_link.rs 🔗

@@ -0,0 +1,102 @@
+use gpui::{IntoElement, Window, prelude::*};
+
+use crate::{ButtonLike, prelude::*};
+
+/// A button that takes an underline to look like a regular web link.
+/// It also contains an arrow icon to communicate the link takes you out of Zed.
+///
+/// # Usage Example
+///
+/// ```
+/// use ui::ButtonLink;
+///
+/// let button_link = ButtonLink::new("Click me", "https://example.com");
+/// ```
+#[derive(IntoElement, RegisterComponent)]
+pub struct ButtonLink {
+    label: SharedString,
+    label_size: LabelSize,
+    label_color: Color,
+    link: String,
+    no_icon: bool,
+}
+
+impl ButtonLink {
+    pub fn new(label: impl Into<SharedString>, link: impl Into<String>) -> Self {
+        Self {
+            link: link.into(),
+            label: label.into(),
+            label_size: LabelSize::Default,
+            label_color: Color::Default,
+            no_icon: false,
+        }
+    }
+
+    pub fn no_icon(mut self, no_icon: bool) -> Self {
+        self.no_icon = no_icon;
+        self
+    }
+
+    pub fn label_size(mut self, label_size: LabelSize) -> Self {
+        self.label_size = label_size;
+        self
+    }
+
+    pub fn label_color(mut self, label_color: Color) -> Self {
+        self.label_color = label_color;
+        self
+    }
+}
+
+impl RenderOnce for ButtonLink {
+    fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement {
+        let id = format!("{}-{}", self.label, self.link);
+
+        ButtonLike::new(id)
+            .size(ButtonSize::None)
+            .child(
+                h_flex()
+                    .gap_0p5()
+                    .child(
+                        Label::new(self.label)
+                            .size(self.label_size)
+                            .color(self.label_color)
+                            .underline(),
+                    )
+                    .when(!self.no_icon, |this| {
+                        this.child(
+                            Icon::new(IconName::ArrowUpRight)
+                                .size(IconSize::Small)
+                                .color(Color::Muted),
+                        )
+                    }),
+            )
+            .on_click(move |_, _, cx| cx.open_url(&self.link))
+            .into_any_element()
+    }
+}
+
+impl Component for ButtonLink {
+    fn scope() -> ComponentScope {
+        ComponentScope::Navigation
+    }
+
+    fn description() -> Option<&'static str> {
+        Some("A button that opens a URL.")
+    }
+
+    fn preview(_window: &mut Window, _cx: &mut App) -> Option<AnyElement> {
+        Some(
+            v_flex()
+                .gap_6()
+                .child(
+                    example_group(vec![single_example(
+                        "Simple",
+                        ButtonLink::new("zed.dev", "https://zed.dev").into_any_element(),
+                    )])
+                    .vertical(),
+                )
+                .into_any_element(),
+        )
+    }
+}

crates/ui/src/components/button/split_button.rs 🔗

@@ -4,7 +4,7 @@ use gpui::{
 };
 use theme::ActiveTheme;
 
-use crate::{ElevationIndex, h_flex};
+use crate::{ElevationIndex, IconButton, h_flex};
 
 use super::ButtonLike;
 
@@ -15,6 +15,23 @@ pub enum SplitButtonStyle {
     Transparent,
 }
 
+pub enum SplitButtonKind {
+    ButtonLike(ButtonLike),
+    IconButton(IconButton),
+}
+
+impl From<IconButton> for SplitButtonKind {
+    fn from(icon_button: IconButton) -> Self {
+        Self::IconButton(icon_button)
+    }
+}
+
+impl From<ButtonLike> for SplitButtonKind {
+    fn from(button_like: ButtonLike) -> Self {
+        Self::ButtonLike(button_like)
+    }
+}
+
 /// /// A button with two parts: a primary action on the left and a secondary action on the right.
 ///
 /// The left side is a [`ButtonLike`] with the main action, while the right side can contain
@@ -23,15 +40,15 @@ pub enum SplitButtonStyle {
 /// The two sections are visually separated by a divider, but presented as a unified control.
 #[derive(IntoElement)]
 pub struct SplitButton {
-    pub left: ButtonLike,
-    pub right: AnyElement,
+    left: SplitButtonKind,
+    right: AnyElement,
     style: SplitButtonStyle,
 }
 
 impl SplitButton {
-    pub fn new(left: ButtonLike, right: AnyElement) -> Self {
+    pub fn new(left: impl Into<SplitButtonKind>, right: AnyElement) -> Self {
         Self {
-            left,
+            left: left.into(),
             right,
             style: SplitButtonStyle::Filled,
         }
@@ -56,7 +73,10 @@ impl RenderOnce for SplitButton {
                 this.border_1()
                     .border_color(cx.theme().colors().border.opacity(0.8))
             })
-            .child(div().flex_grow().child(self.left))
+            .child(div().flex_grow().child(match self.left {
+                SplitButtonKind::ButtonLike(button) => button.into_any_element(),
+                SplitButtonKind::IconButton(icon) => icon.into_any_element(),
+            }))
             .child(
                 div()
                     .h_full()

crates/ui/src/components/callout.rs 🔗

@@ -121,7 +121,7 @@ impl RenderOnce for Callout {
             Severity::Info => (
                 IconName::Info,
                 Color::Muted,
-                cx.theme().colors().panel_background.opacity(0.),
+                cx.theme().status().info_background.opacity(0.1),
             ),
             Severity::Success => (
                 IconName::Check,

crates/ui/src/components/context_menu.rs 🔗

@@ -562,7 +562,7 @@ impl ContextMenu {
             action: Some(action.boxed_clone()),
             handler: Rc::new(move |context, window, cx| {
                 if let Some(context) = &context {
-                    window.focus(context);
+                    window.focus(context, cx);
                 }
                 window.dispatch_action(action.boxed_clone(), cx);
             }),
@@ -594,7 +594,7 @@ impl ContextMenu {
             action: Some(action.boxed_clone()),
             handler: Rc::new(move |context, window, cx| {
                 if let Some(context) = &context {
-                    window.focus(context);
+                    window.focus(context, cx);
                 }
                 window.dispatch_action(action.boxed_clone(), cx);
             }),
@@ -893,39 +893,57 @@ impl ContextMenu {
                 entry_render,
                 handler,
                 selectable,
+                documentation_aside,
                 ..
             } => {
                 let handler = handler.clone();
                 let menu = cx.entity().downgrade();
                 let selectable = *selectable;
-                ListItem::new(ix)
-                    .inset(true)
-                    .toggle_state(if selectable {
-                        Some(ix) == self.selected_index
-                    } else {
-                        false
+
+                div()
+                    .id(("context-menu-child", ix))
+                    .when_some(documentation_aside.clone(), |this, documentation_aside| {
+                        this.occlude()
+                            .on_hover(cx.listener(move |menu, hovered, _, cx| {
+                            if *hovered {
+                                menu.documentation_aside = Some((ix, documentation_aside.clone()));
+                            } else if matches!(menu.documentation_aside, Some((id, _)) if id == ix)
+                            {
+                                menu.documentation_aside = None;
+                            }
+                            cx.notify();
+                        }))
                     })
-                    .selectable(selectable)
-                    .when(selectable, |item| {
-                        item.on_click({
-                            let context = self.action_context.clone();
-                            let keep_open_on_confirm = self.keep_open_on_confirm;
-                            move |_, window, cx| {
-                                handler(context.as_ref(), window, cx);
-                                menu.update(cx, |menu, cx| {
-                                    menu.clicked = true;
-
-                                    if keep_open_on_confirm {
-                                        menu.rebuild(window, cx);
-                                    } else {
-                                        cx.emit(DismissEvent);
+                    .child(
+                        ListItem::new(ix)
+                            .inset(true)
+                            .toggle_state(if selectable {
+                                Some(ix) == self.selected_index
+                            } else {
+                                false
+                            })
+                            .selectable(selectable)
+                            .when(selectable, |item| {
+                                item.on_click({
+                                    let context = self.action_context.clone();
+                                    let keep_open_on_confirm = self.keep_open_on_confirm;
+                                    move |_, window, cx| {
+                                        handler(context.as_ref(), window, cx);
+                                        menu.update(cx, |menu, cx| {
+                                            menu.clicked = true;
+
+                                            if keep_open_on_confirm {
+                                                menu.rebuild(window, cx);
+                                            } else {
+                                                cx.emit(DismissEvent);
+                                            }
+                                        })
+                                        .ok();
                                     }
                                 })
-                                .ok();
-                            }
-                        })
-                    })
-                    .child(entry_render(window, cx))
+                            })
+                            .child(entry_render(window, cx)),
+                    )
                     .into_any_element()
             }
         }

crates/ui/src/components/data_table.rs 🔗

@@ -485,6 +485,7 @@ pub struct Table<const COLS: usize = 3> {
     interaction_state: Option<WeakEntity<TableInteractionState>>,
     col_widths: Option<TableWidths<COLS>>,
     map_row: Option<Rc<dyn Fn((usize, Stateful<Div>), &mut Window, &mut App) -> AnyElement>>,
+    use_ui_font: bool,
     empty_table_callback: Option<Rc<dyn Fn(&mut Window, &mut App) -> AnyElement>>,
 }
 
@@ -498,6 +499,7 @@ impl<const COLS: usize> Table<COLS> {
             rows: TableContents::Vec(Vec::new()),
             interaction_state: None,
             map_row: None,
+            use_ui_font: true,
             empty_table_callback: None,
             col_widths: None,
         }
@@ -590,6 +592,11 @@ impl<const COLS: usize> Table<COLS> {
         self
     }
 
+    pub fn no_ui_font(mut self) -> Self {
+        self.use_ui_font = false;
+        self
+    }
+
     pub fn map_row(
         mut self,
         callback: impl Fn((usize, Stateful<Div>), &mut Window, &mut App) -> AnyElement + 'static,
@@ -618,8 +625,8 @@ fn base_cell_style(width: Option<Length>) -> Div {
         .overflow_hidden()
 }
 
-fn base_cell_style_text(width: Option<Length>, cx: &App) -> Div {
-    base_cell_style(width).text_ui(cx)
+fn base_cell_style_text(width: Option<Length>, use_ui_font: bool, cx: &App) -> Div {
+    base_cell_style(width).when(use_ui_font, |el| el.text_ui(cx))
 }
 
 pub fn render_table_row<const COLS: usize>(
@@ -656,7 +663,12 @@ pub fn render_table_row<const COLS: usize>(
             .map(IntoElement::into_any_element)
             .into_iter()
             .zip(column_widths)
-            .map(|(cell, width)| base_cell_style_text(width, cx).px_1().py_0p5().child(cell)),
+            .map(|(cell, width)| {
+                base_cell_style_text(width, table_context.use_ui_font, cx)
+                    .px_1()
+                    .py_0p5()
+                    .child(cell)
+            }),
     );
 
     let row = if let Some(map_row) = table_context.map_row {
@@ -700,7 +712,7 @@ pub fn render_table_header<const COLS: usize>(
         .border_color(cx.theme().colors().border)
         .children(headers.into_iter().enumerate().zip(column_widths).map(
             |((header_idx, h), width)| {
-                base_cell_style_text(width, cx)
+                base_cell_style_text(width, table_context.use_ui_font, cx)
                     .child(h)
                     .id(ElementId::NamedInteger(
                         shared_element_id.clone(),
@@ -739,6 +751,7 @@ pub struct TableRenderContext<const COLS: usize> {
     pub total_row_count: usize,
     pub column_widths: Option<[Length; COLS]>,
     pub map_row: Option<Rc<dyn Fn((usize, Stateful<Div>), &mut Window, &mut App) -> AnyElement>>,
+    pub use_ui_font: bool,
 }
 
 impl<const COLS: usize> TableRenderContext<COLS> {
@@ -748,6 +761,7 @@ impl<const COLS: usize> TableRenderContext<COLS> {
             total_row_count: table.rows.len(),
             column_widths: table.col_widths.as_ref().map(|widths| widths.lengths(cx)),
             map_row: table.map_row.clone(),
+            use_ui_font: table.use_ui_font,
         }
     }
 }

crates/ui/src/components/divider.rs 🔗

@@ -144,12 +144,16 @@ impl Divider {
 impl RenderOnce for Divider {
     fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
         let base = match self.direction {
-            DividerDirection::Horizontal => {
-                div().h_px().w_full().when(self.inset, |this| this.mx_1p5())
-            }
-            DividerDirection::Vertical => {
-                div().w_px().h_full().when(self.inset, |this| this.my_1p5())
-            }
+            DividerDirection::Horizontal => div()
+                .min_w_0()
+                .h_px()
+                .w_full()
+                .when(self.inset, |this| this.mx_1p5()),
+            DividerDirection::Vertical => div()
+                .min_w_0()
+                .w_px()
+                .h_full()
+                .when(self.inset, |this| this.my_1p5()),
         };
 
         match self.style {

crates/ui/src/components/icon.rs 🔗

@@ -126,17 +126,6 @@ enum IconSource {
     ExternalSvg(SharedString),
 }
 
-impl IconSource {
-    fn from_path(path: impl Into<SharedString>) -> Self {
-        let path = path.into();
-        if path.starts_with("icons/") {
-            Self::Embedded(path)
-        } else {
-            Self::External(Arc::from(PathBuf::from(path.as_ref())))
-        }
-    }
-}
-
 #[derive(IntoElement, RegisterComponent)]
 pub struct Icon {
     source: IconSource,
@@ -155,9 +144,18 @@ impl Icon {
         }
     }
 
+    /// Create an icon from a path. Uses a heuristic to determine if it's embedded or external:
+    /// - Paths starting with "icons/" are treated as embedded SVGs
+    /// - Other paths are treated as external raster images (from icon themes)
     pub fn from_path(path: impl Into<SharedString>) -> Self {
+        let path = path.into();
+        let source = if path.starts_with("icons/") {
+            IconSource::Embedded(path)
+        } else {
+            IconSource::External(Arc::from(PathBuf::from(path.as_ref())))
+        };
         Self {
-            source: IconSource::from_path(path),
+            source,
             color: Color::default(),
             size: IconSize::default().rems(),
             transformation: Transformation::default(),

crates/ui/src/components/keybinding_hint.rs 🔗

@@ -234,9 +234,7 @@ impl RenderOnce for KeybindingHint {
 
         let mut base = h_flex();
 
-        base.text_style()
-            .get_or_insert_with(Default::default)
-            .font_style = Some(FontStyle::Italic);
+        base.text_style().font_style = Some(FontStyle::Italic);
 
         base.gap_1()
             .font_buffer(cx)

crates/ui/src/components/label/label.rs 🔗

@@ -56,6 +56,12 @@ impl Label {
     pub fn set_text(&mut self, text: impl Into<SharedString>) {
         self.label = text.into();
     }
+
+    /// Truncates the label from the start, keeping the end visible.
+    pub fn truncate_start(mut self) -> Self {
+        self.base = self.base.truncate_start();
+        self
+    }
 }
 
 // Style methods.
@@ -256,7 +262,8 @@ impl Component for Label {
                         "Special Cases",
                         vec![
                             single_example("Single Line", Label::new("Line 1\nLine 2\nLine 3").single_line().into_any_element()),
-                            single_example("Text Ellipsis", div().max_w_24().child(Label::new("This is a very long file name that should be truncated: very_long_file_name_with_many_words.rs").truncate()).into_any_element()),
+                            single_example("Regular Truncation", div().max_w_24().child(Label::new("This is a very long file name that should be truncated: very_long_file_name_with_many_words.rs").truncate()).into_any_element()),
+                            single_example("Start Truncation", div().max_w_24().child(Label::new("zed/crates/ui/src/components/label/truncate/label/label.rs").truncate_start()).into_any_element()),
                         ],
                     ),
                 ])

crates/ui/src/components/label/label_like.rs 🔗

@@ -56,7 +56,7 @@ pub trait LabelCommon {
     /// Sets the alpha property of the label, overwriting the alpha value of the color.
     fn alpha(self, alpha: f32) -> Self;
 
-    /// Truncates overflowing text with an ellipsis (`…`) if needed.
+    /// Truncates overflowing text with an ellipsis (`…`) at the end if needed.
     fn truncate(self) -> Self;
 
     /// Sets the label to render as a single line.
@@ -88,6 +88,7 @@ pub struct LabelLike {
     underline: bool,
     single_line: bool,
     truncate: bool,
+    truncate_start: bool,
 }
 
 impl Default for LabelLike {
@@ -113,6 +114,7 @@ impl LabelLike {
             underline: false,
             single_line: false,
             truncate: false,
+            truncate_start: false,
         }
     }
 }
@@ -126,6 +128,12 @@ impl LabelLike {
     gpui::margin_style_methods!({
         visibility: pub
     });
+
+    /// Truncates overflowing text with an ellipsis (`…`) at the start if needed.
+    pub fn truncate_start(mut self) -> Self {
+        self.truncate_start = true;
+        self
+    }
 }
 
 impl LabelCommon for LabelLike {
@@ -169,7 +177,7 @@ impl LabelCommon for LabelLike {
         self
     }
 
-    /// Truncates overflowing text with an ellipsis (`…`) if needed.
+    /// Truncates overflowing text with an ellipsis (`…`) at the end if needed.
     fn truncate(mut self) -> Self {
         self.truncate = true;
         self
@@ -223,11 +231,9 @@ impl RenderOnce for LabelLike {
             })
             .when(self.italic, |this| this.italic())
             .when(self.underline, |mut this| {
-                this.text_style()
-                    .get_or_insert_with(Default::default)
-                    .underline = Some(UnderlineStyle {
+                this.text_style().underline = Some(UnderlineStyle {
                     thickness: px(1.),
-                    color: None,
+                    color: Some(cx.theme().colors().text_muted.opacity(0.4)),
                     wavy: false,
                 });
                 this
@@ -235,7 +241,16 @@ impl RenderOnce for LabelLike {
             .when(self.strikethrough, |this| this.line_through())
             .when(self.single_line, |this| this.whitespace_nowrap())
             .when(self.truncate, |this| {
-                this.overflow_x_hidden().text_ellipsis()
+                this.min_w_0()
+                    .overflow_x_hidden()
+                    .whitespace_nowrap()
+                    .text_ellipsis()
+            })
+            .when(self.truncate_start, |this| {
+                this.min_w_0()
+                    .overflow_x_hidden()
+                    .whitespace_nowrap()
+                    .text_ellipsis_start()
             })
             .text_color(color)
             .font_weight(

crates/ui/src/components/list/list_bullet_item.rs 🔗

@@ -1,18 +1,33 @@
-use crate::{ListItem, prelude::*};
-use component::{Component, ComponentScope, example_group_with_title, single_example};
+use crate::{ButtonLink, ListItem, prelude::*};
+use component::{Component, ComponentScope, example_group, single_example};
 use gpui::{IntoElement, ParentElement, SharedString};
 
 #[derive(IntoElement, RegisterComponent)]
 pub struct ListBulletItem {
     label: SharedString,
+    label_color: Option<Color>,
+    children: Vec<AnyElement>,
 }
 
 impl ListBulletItem {
     pub fn new(label: impl Into<SharedString>) -> Self {
         Self {
             label: label.into(),
+            label_color: None,
+            children: Vec::new(),
         }
     }
+
+    pub fn label_color(mut self, color: Color) -> Self {
+        self.label_color = Some(color);
+        self
+    }
+}
+
+impl ParentElement for ListBulletItem {
+    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
+        self.children.extend(elements)
+    }
 }
 
 impl RenderOnce for ListBulletItem {
@@ -34,7 +49,18 @@ impl RenderOnce for ListBulletItem {
                                 .color(Color::Hidden),
                         ),
                     )
-                    .child(div().w_full().min_w_0().child(Label::new(self.label))),
+                    .map(|this| {
+                        if !self.children.is_empty() {
+                            this.child(h_flex().gap_0p5().flex_wrap().children(self.children))
+                        } else {
+                            this.child(
+                                div().w_full().min_w_0().child(
+                                    Label::new(self.label)
+                                        .color(self.label_color.unwrap_or(Color::Default)),
+                                ),
+                            )
+                        }
+                    }),
             )
             .into_any_element()
     }
@@ -46,37 +72,43 @@ impl Component for ListBulletItem {
     }
 
     fn description() -> Option<&'static str> {
-        Some("A list item with a bullet point indicator for unordered lists.")
+        Some("A list item with a dash indicator for unordered lists.")
     }
 
     fn preview(_window: &mut Window, _cx: &mut App) -> Option<AnyElement> {
+        let basic_examples = vec![
+            single_example(
+                "Simple",
+                ListBulletItem::new("First bullet item").into_any_element(),
+            ),
+            single_example(
+                "Multiple Lines",
+                v_flex()
+                    .child(ListBulletItem::new("First item"))
+                    .child(ListBulletItem::new("Second item"))
+                    .child(ListBulletItem::new("Third item"))
+                    .into_any_element(),
+            ),
+            single_example(
+                "Long Text",
+                ListBulletItem::new(
+                    "A longer bullet item that demonstrates text wrapping behavior",
+                )
+                .into_any_element(),
+            ),
+            single_example(
+                "With Link",
+                ListBulletItem::new("")
+                    .child(Label::new("Create a Zed account by"))
+                    .child(ButtonLink::new("visiting the website", "https://zed.dev"))
+                    .into_any_element(),
+            ),
+        ];
+
         Some(
             v_flex()
                 .gap_6()
-                .child(example_group_with_title(
-                    "Bullet Items",
-                    vec![
-                        single_example(
-                            "Simple",
-                            ListBulletItem::new("First bullet item").into_any_element(),
-                        ),
-                        single_example(
-                            "Multiple Lines",
-                            v_flex()
-                                .child(ListBulletItem::new("First item"))
-                                .child(ListBulletItem::new("Second item"))
-                                .child(ListBulletItem::new("Third item"))
-                                .into_any_element(),
-                        ),
-                        single_example(
-                            "Long Text",
-                            ListBulletItem::new(
-                                "A longer bullet item that demonstrates text wrapping behavior",
-                            )
-                            .into_any_element(),
-                        ),
-                    ],
-                ))
+                .child(example_group(basic_examples).vertical())
                 .into_any_element(),
         )
     }

crates/ui/src/components/navigable.rs 🔗

@@ -75,7 +75,7 @@ impl RenderOnce for Navigable {
                         })
                         .unwrap_or(0);
                     if let Some(entry) = children.get(target) {
-                        entry.focus_handle.focus(window);
+                        entry.focus_handle.focus(window, cx);
                         if let Some(anchor) = &entry.scroll_anchor {
                             anchor.scroll_to(window, cx);
                         }
@@ -89,7 +89,7 @@ impl RenderOnce for Navigable {
                         .and_then(|index| index.checked_sub(1))
                         .or(children.len().checked_sub(1));
                     if let Some(entry) = target.and_then(|target| children.get(target)) {
-                        entry.focus_handle.focus(window);
+                        entry.focus_handle.focus(window, cx);
                         if let Some(anchor) = &entry.scroll_anchor {
                             anchor.scroll_to(window, cx);
                         }

crates/ui/src/components/notification/alert_modal.rs 🔗

@@ -1,73 +1,161 @@
 use crate::component_prelude::*;
 use crate::prelude::*;
+use crate::{Checkbox, ListBulletItem, ToggleState};
+use gpui::Action;
+use gpui::FocusHandle;
 use gpui::IntoElement;
+use gpui::Stateful;
 use smallvec::{SmallVec, smallvec};
+use theme::ActiveTheme;
+
+type ActionHandler = Box<dyn FnOnce(Stateful<Div>) -> Stateful<Div>>;
 
 #[derive(IntoElement, RegisterComponent)]
 pub struct AlertModal {
     id: ElementId,
+    header: Option<AnyElement>,
     children: SmallVec<[AnyElement; 2]>,
-    title: SharedString,
-    primary_action: SharedString,
-    dismiss_label: SharedString,
+    footer: Option<AnyElement>,
+    title: Option<SharedString>,
+    primary_action: Option<SharedString>,
+    dismiss_label: Option<SharedString>,
+    width: Option<DefiniteLength>,
+    key_context: Option<String>,
+    action_handlers: Vec<ActionHandler>,
+    focus_handle: Option<FocusHandle>,
 }
 
 impl AlertModal {
-    pub fn new(id: impl Into<ElementId>, title: impl Into<SharedString>) -> Self {
+    pub fn new(id: impl Into<ElementId>) -> Self {
         Self {
             id: id.into(),
+            header: None,
             children: smallvec![],
-            title: title.into(),
-            primary_action: "Ok".into(),
-            dismiss_label: "Cancel".into(),
+            footer: None,
+            title: None,
+            primary_action: None,
+            dismiss_label: None,
+            width: None,
+            key_context: None,
+            action_handlers: Vec::new(),
+            focus_handle: None,
         }
     }
 
+    pub fn title(mut self, title: impl Into<SharedString>) -> Self {
+        self.title = Some(title.into());
+        self
+    }
+
+    pub fn header(mut self, header: impl IntoElement) -> Self {
+        self.header = Some(header.into_any_element());
+        self
+    }
+
+    pub fn footer(mut self, footer: impl IntoElement) -> Self {
+        self.footer = Some(footer.into_any_element());
+        self
+    }
+
     pub fn primary_action(mut self, primary_action: impl Into<SharedString>) -> Self {
-        self.primary_action = primary_action.into();
+        self.primary_action = Some(primary_action.into());
         self
     }
 
     pub fn dismiss_label(mut self, dismiss_label: impl Into<SharedString>) -> Self {
-        self.dismiss_label = dismiss_label.into();
+        self.dismiss_label = Some(dismiss_label.into());
+        self
+    }
+
+    pub fn width(mut self, width: impl Into<DefiniteLength>) -> Self {
+        self.width = Some(width.into());
+        self
+    }
+
+    pub fn key_context(mut self, key_context: impl Into<String>) -> Self {
+        self.key_context = Some(key_context.into());
+        self
+    }
+
+    pub fn on_action<A: Action>(
+        mut self,
+        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
+    ) -> Self {
+        self.action_handlers
+            .push(Box::new(move |div| div.on_action(listener)));
+        self
+    }
+
+    pub fn track_focus(mut self, focus_handle: &gpui::FocusHandle) -> Self {
+        self.focus_handle = Some(focus_handle.clone());
         self
     }
 }
 
 impl RenderOnce for AlertModal {
     fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
-        v_flex()
+        let width = self.width.unwrap_or_else(|| px(440.).into());
+        let has_default_footer = self.primary_action.is_some() || self.dismiss_label.is_some();
+
+        let mut modal = v_flex()
+            .when_some(self.key_context, |this, key_context| {
+                this.key_context(key_context.as_str())
+            })
+            .when_some(self.focus_handle, |this, focus_handle| {
+                this.track_focus(&focus_handle)
+            })
             .id(self.id)
             .elevation_3(cx)
-            .w(px(440.))
-            .p_5()
-            .child(
+            .w(width)
+            .bg(cx.theme().colors().elevated_surface_background)
+            .overflow_hidden();
+
+        for handler in self.action_handlers {
+            modal = handler(modal);
+        }
+
+        if let Some(header) = self.header {
+            modal = modal.child(header);
+        } else if let Some(title) = self.title {
+            modal = modal.child(
+                v_flex()
+                    .pt_3()
+                    .pr_3()
+                    .pl_3()
+                    .pb_1()
+                    .child(Headline::new(title).size(HeadlineSize::Small)),
+            );
+        }
+
+        if !self.children.is_empty() {
+            modal = modal.child(
                 v_flex()
+                    .p_3()
                     .text_ui(cx)
                     .text_color(Color::Muted.color(cx))
                     .gap_1()
-                    .child(Headline::new(self.title).size(HeadlineSize::Small))
                     .children(self.children),
-            )
-            .child(
+            );
+        }
+
+        if let Some(footer) = self.footer {
+            modal = modal.child(footer);
+        } else if has_default_footer {
+            let primary_action = self.primary_action.unwrap_or_else(|| "Ok".into());
+            let dismiss_label = self.dismiss_label.unwrap_or_else(|| "Cancel".into());
+
+            modal = modal.child(
                 h_flex()
-                    .h(rems(1.75))
+                    .p_3()
                     .items_center()
-                    .child(div().flex_1())
-                    .child(
-                        h_flex()
-                            .items_center()
-                            .gap_1()
-                            .child(
-                                Button::new(self.dismiss_label.clone(), self.dismiss_label.clone())
-                                    .color(Color::Muted),
-                            )
-                            .child(Button::new(
-                                self.primary_action.clone(),
-                                self.primary_action,
-                            )),
-                    ),
-            )
+                    .justify_end()
+                    .gap_1()
+                    .child(Button::new(dismiss_label.clone(), dismiss_label).color(Color::Muted))
+                    .child(Button::new(primary_action.clone(), primary_action)),
+            );
+        }
+
+        modal
     }
 }
 
@@ -90,24 +178,75 @@ impl Component for AlertModal {
         Some("A modal dialog that presents an alert message with primary and dismiss actions.")
     }
 
-    fn preview(_window: &mut Window, _cx: &mut App) -> Option<AnyElement> {
+    fn preview(_window: &mut Window, cx: &mut App) -> Option<AnyElement> {
         Some(
             v_flex()
                 .gap_6()
                 .p_4()
-                .children(vec![example_group(
-                    vec![
-                        single_example(
-                            "Basic Alert",
-                            AlertModal::new("simple-modal", "Do you want to leave the current call?")
-                                .child("The current window will be closed, and connections to any shared projects will be terminated."
-                                )
-                                .primary_action("Leave Call")
-                                .into_any_element(),
-                        )
-                    ],
-                )])
-                .into_any_element()
+                .children(vec![
+                    example_group(vec![single_example(
+                        "Basic Alert",
+                        AlertModal::new("simple-modal")
+                            .title("Do you want to leave the current call?")
+                            .child(
+                                "The current window will be closed, and connections to any shared projects will be terminated."
+                            )
+                            .primary_action("Leave Call")
+                            .dismiss_label("Cancel")
+                            .into_any_element(),
+                    )]),
+                    example_group(vec![single_example(
+                        "Custom Header",
+                        AlertModal::new("custom-header-modal")
+                            .header(
+                                v_flex()
+                                    .p_3()
+                                    .bg(cx.theme().colors().background)
+                                    .gap_1()
+                                    .child(
+                                        h_flex()
+                                            .gap_1()
+                                            .child(Icon::new(IconName::Warning).color(Color::Warning))
+                                            .child(Headline::new("Unrecognized Workspace").size(HeadlineSize::Small))
+                                    )
+                                    .child(
+                                        h_flex()
+                                            .pl(IconSize::default().rems() + rems(0.5))
+                                            .child(Label::new("~/projects/my-project").color(Color::Muted))
+                                    )
+                            )
+                            .child(
+                                "Untrusted workspaces are opened in Restricted Mode to protect your system.
+Review .zed/settings.json for any extensions or commands configured by this project.",
+                            )
+                            .child(
+                                v_flex()
+                                    .mt_1()
+                                    .child(Label::new("Restricted mode prevents:").color(Color::Muted))
+                                    .child(ListBulletItem::new("Project settings from being applied"))
+                                    .child(ListBulletItem::new("Language servers from running"))
+                                    .child(ListBulletItem::new("MCP integrations from installing"))
+                            )
+                            .footer(
+                                h_flex()
+                                    .p_3()
+                                    .justify_between()
+                                    .child(
+                                        Checkbox::new("trust-parent", ToggleState::Unselected)
+                                            .label("Trust all projects in parent directory")
+                                    )
+                                    .child(
+                                        h_flex()
+                                            .gap_1()
+                                            .child(Button::new("restricted", "Stay in Restricted Mode").color(Color::Muted))
+                                            .child(Button::new("trust", "Trust and Continue").style(ButtonStyle::Filled))
+                                    )
+                            )
+                            .width(rems(40.))
+                            .into_any_element(),
+                    )]),
+                ])
+                .into_any_element(),
         )
     }
 }

crates/ui/src/components/popover_menu.rs 🔗

@@ -281,13 +281,25 @@ fn show_menu<M: ManagedView>(
             if modal.focus_handle(cx).contains_focused(window, cx)
                 && let Some(previous_focus_handle) = previous_focus_handle.as_ref()
             {
-                window.focus(previous_focus_handle);
+                window.focus(previous_focus_handle, cx);
             }
             *menu2.borrow_mut() = None;
             window.refresh();
         })
         .detach();
-    window.focus(&new_menu.focus_handle(cx));
+
+    // Since menus are rendered in a deferred fashion, their focus handles are
+    // not linked in the dispatch tree until after the deferred draw callback
+    // runs. We need to wait for that to happen before focusing it, so that
+    // calling `contains_focused` on the parent's focus handle returns `true`
+    // when the menu is focused. This prevents the pane's tab bar buttons from
+    // flickering when opening popover menus.
+    let focus_handle = new_menu.focus_handle(cx);
+    window.on_next_frame(move |window, _cx| {
+        window.on_next_frame(move |window, cx| {
+            window.focus(&focus_handle, cx);
+        });
+    });
     *menu.borrow_mut() = Some(new_menu);
     window.refresh();
 

crates/ui/src/components/right_click_menu.rs 🔗

@@ -253,13 +253,25 @@ impl<M: ManagedView> Element for RightClickMenu<M> {
                                     && let Some(previous_focus_handle) =
                                         previous_focus_handle.as_ref()
                                 {
-                                    window.focus(previous_focus_handle);
+                                    window.focus(previous_focus_handle, cx);
                                 }
                                 *menu2.borrow_mut() = None;
                                 window.refresh();
                             })
                             .detach();
-                        window.focus(&new_menu.focus_handle(cx));
+
+                        // Since menus are rendered in a deferred fashion, their focus handles are
+                        // not linked in the dispatch tree until after the deferred draw callback
+                        // runs. We need to wait for that to happen before focusing it, so that
+                        // calling `contains_focused` on the parent's focus handle returns `true`
+                        // when the menu is focused. This prevents the pane's tab bar buttons from
+                        // flickering when opening menus.
+                        let focus_handle = new_menu.focus_handle(cx);
+                        window.on_next_frame(move |window, _cx| {
+                            window.on_next_frame(move |window, cx| {
+                                window.focus(&focus_handle, cx);
+                            });
+                        });
                         *menu.borrow_mut() = Some(new_menu);
                         *position.borrow_mut() = if let Some(child_bounds) = child_bounds {
                             if let Some(attach) = attach {

crates/ui/src/components/tab_bar.rs 🔗

@@ -10,6 +10,7 @@ pub struct TabBar {
     start_children: SmallVec<[AnyElement; 2]>,
     children: SmallVec<[AnyElement; 2]>,
     end_children: SmallVec<[AnyElement; 2]>,
+    pre_end_children: SmallVec<[AnyElement; 2]>,
     scroll_handle: Option<ScrollHandle>,
 }
 
@@ -20,6 +21,7 @@ impl TabBar {
             start_children: SmallVec::new(),
             children: SmallVec::new(),
             end_children: SmallVec::new(),
+            pre_end_children: SmallVec::new(),
             scroll_handle: None,
         }
     }
@@ -70,6 +72,15 @@ impl TabBar {
         self
     }
 
+    pub fn pre_end_child(mut self, end_child: impl IntoElement) -> Self
+    where
+        Self: Sized,
+    {
+        self.pre_end_children
+            .push(end_child.into_element().into_any());
+        self
+    }
+
     pub fn end_children(mut self, end_children: impl IntoIterator<Item = impl IntoElement>) -> Self
     where
         Self: Sized,
@@ -137,18 +148,32 @@ impl RenderOnce for TabBar {
                             .children(self.children),
                     ),
             )
-            .when(!self.end_children.is_empty(), |this| {
-                this.child(
-                    h_flex()
-                        .flex_none()
-                        .gap(DynamicSpacing::Base04.rems(cx))
-                        .px(DynamicSpacing::Base06.rems(cx))
-                        .border_b_1()
-                        .border_l_1()
-                        .border_color(cx.theme().colors().border)
-                        .children(self.end_children),
-                )
-            })
+            .when(
+                !self.end_children.is_empty() || !self.pre_end_children.is_empty(),
+                |this| {
+                    this.child(
+                        h_flex()
+                            .flex_none()
+                            .gap(DynamicSpacing::Base04.rems(cx))
+                            .px(DynamicSpacing::Base06.rems(cx))
+                            .children(self.pre_end_children)
+                            .border_color(cx.theme().colors().border)
+                            .border_b_1()
+                            .when(!self.end_children.is_empty(), |div| {
+                                div.child(
+                                    h_flex()
+                                        .h_full()
+                                        .flex_none()
+                                        .pl(DynamicSpacing::Base04.rems(cx))
+                                        .gap(DynamicSpacing::Base04.rems(cx))
+                                        .border_l_1()
+                                        .border_color(cx.theme().colors().border)
+                                        .children(self.end_children),
+                                )
+                            }),
+                    )
+                },
+            )
     }
 }
 

crates/ui/src/components/toggle.rs 🔗

@@ -44,15 +44,16 @@ pub enum ToggleStyle {
 pub struct Checkbox {
     id: ElementId,
     toggle_state: ToggleState,
+    style: ToggleStyle,
     disabled: bool,
     placeholder: bool,
-    on_click: Option<Box<dyn Fn(&ToggleState, &ClickEvent, &mut Window, &mut App) + 'static>>,
     filled: bool,
-    style: ToggleStyle,
-    tooltip: Option<Box<dyn Fn(&mut Window, &mut App) -> AnyView>>,
+    visualization: bool,
     label: Option<SharedString>,
     label_size: LabelSize,
     label_color: Color,
+    tooltip: Option<Box<dyn Fn(&mut Window, &mut App) -> AnyView>>,
+    on_click: Option<Box<dyn Fn(&ToggleState, &ClickEvent, &mut Window, &mut App) + 'static>>,
 }
 
 impl Checkbox {
@@ -61,15 +62,16 @@ impl Checkbox {
         Self {
             id: id.into(),
             toggle_state: checked,
+            style: ToggleStyle::default(),
             disabled: false,
-            on_click: None,
+            placeholder: false,
             filled: false,
-            style: ToggleStyle::default(),
-            tooltip: None,
+            visualization: false,
             label: None,
             label_size: LabelSize::Default,
             label_color: Color::Muted,
-            placeholder: false,
+            tooltip: None,
+            on_click: None,
         }
     }
 
@@ -110,6 +112,13 @@ impl Checkbox {
         self
     }
 
+    /// Makes the checkbox look enabled but without pointer cursor and hover styles.
+    /// Primarily used for uninteractive markdown previews.
+    pub fn visualization_only(mut self, visualization: bool) -> Self {
+        self.visualization = visualization;
+        self
+    }
+
     /// Sets the style of the checkbox using the specified [`ToggleStyle`].
     pub fn style(mut self, style: ToggleStyle) -> Self {
         self.style = style;
@@ -209,11 +218,10 @@ impl RenderOnce for Checkbox {
         let size = Self::container_size();
 
         let checkbox = h_flex()
+            .group(group_id.clone())
             .id(self.id.clone())
-            .justify_center()
-            .items_center()
             .size(size)
-            .group(group_id.clone())
+            .justify_center()
             .child(
                 div()
                     .flex()
@@ -230,7 +238,7 @@ impl RenderOnce for Checkbox {
                     .when(self.disabled, |this| {
                         this.bg(cx.theme().colors().element_disabled.opacity(0.6))
                     })
-                    .when(!self.disabled, |this| {
+                    .when(!self.disabled && !self.visualization, |this| {
                         this.group_hover(group_id.clone(), |el| el.border_color(hover_border_color))
                     })
                     .when(self.placeholder, |this| {
@@ -250,20 +258,14 @@ impl RenderOnce for Checkbox {
             .map(|this| {
                 if self.disabled {
                     this.cursor_not_allowed()
+                } else if self.visualization {
+                    this.cursor_default()
                 } else {
                     this.cursor_pointer()
                 }
             })
             .gap(DynamicSpacing::Base06.rems(cx))
             .child(checkbox)
-            .when_some(
-                self.on_click.filter(|_| !self.disabled),
-                |this, on_click| {
-                    this.on_click(move |click, window, cx| {
-                        on_click(&self.toggle_state.inverse(), click, window, cx)
-                    })
-                },
-            )
             .when_some(self.label, |this, label| {
                 this.child(
                     Label::new(label)
@@ -274,6 +276,14 @@ impl RenderOnce for Checkbox {
             .when_some(self.tooltip, |this, tooltip| {
                 this.tooltip(move |window, cx| tooltip(window, cx))
             })
+            .when_some(
+                self.on_click.filter(|_| !self.disabled),
+                |this, on_click| {
+                    this.on_click(move |click, window, cx| {
+                        on_click(&self.toggle_state.inverse(), click, window, cx)
+                    })
+                },
+            )
     }
 }
 
@@ -281,11 +291,7 @@ impl RenderOnce for Checkbox {
 #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy, Default)]
 pub enum SwitchColor {
     #[default]
-    Default,
     Accent,
-    Error,
-    Warning,
-    Success,
     Custom(Hsla),
 }
 
@@ -299,27 +305,10 @@ impl SwitchColor {
         }
 
         match self {
-            SwitchColor::Default => {
-                let colors = cx.theme().colors();
-                let base_color = colors.text;
-                let bg_color = colors.element_background.blend(base_color.opacity(0.08));
-                (bg_color, colors.border_variant)
-            }
             SwitchColor::Accent => {
                 let status = cx.theme().status();
-                (status.info.opacity(0.4), status.info.opacity(0.2))
-            }
-            SwitchColor::Error => {
-                let status = cx.theme().status();
-                (status.error.opacity(0.4), status.error.opacity(0.2))
-            }
-            SwitchColor::Warning => {
-                let status = cx.theme().status();
-                (status.warning.opacity(0.4), status.warning.opacity(0.2))
-            }
-            SwitchColor::Success => {
-                let status = cx.theme().status();
-                (status.success.opacity(0.4), status.success.opacity(0.2))
+                let colors = cx.theme().colors();
+                (status.info.opacity(0.4), colors.text_accent.opacity(0.2))
             }
             SwitchColor::Custom(color) => (*color, color.opacity(0.6)),
         }
@@ -329,11 +318,7 @@ impl SwitchColor {
 impl From<SwitchColor> for Color {
     fn from(color: SwitchColor) -> Self {
         match color {
-            SwitchColor::Default => Color::Default,
             SwitchColor::Accent => Color::Accent,
-            SwitchColor::Error => Color::Error,
-            SwitchColor::Warning => Color::Warning,
-            SwitchColor::Success => Color::Success,
             SwitchColor::Custom(_) => Color::Default,
         }
     }
@@ -939,6 +924,15 @@ impl Component for Checkbox {
                                 .into_any_element(),
                         )],
                     ),
+                    example_group_with_title(
+                        "Extra",
+                        vec![single_example(
+                            "Visualization-Only",
+                            Checkbox::new("viz_only", ToggleState::Selected)
+                                .visualization_only(true)
+                                .into_any_element(),
+                        )],
+                    ),
                 ])
                 .into_any_element(),
         )
@@ -980,37 +974,8 @@ impl Component for Switch {
                         "Colors",
                         vec![
                             single_example(
-                                "Default",
-                                Switch::new("switch_default_style", ToggleState::Selected)
-                                    .color(SwitchColor::Default)
-                                    .on_click(|_, _, _cx| {})
-                                    .into_any_element(),
-                            ),
-                            single_example(
-                                "Accent",
+                                "Accent (Default)",
                                 Switch::new("switch_accent_style", ToggleState::Selected)
-                                    .color(SwitchColor::Accent)
-                                    .on_click(|_, _, _cx| {})
-                                    .into_any_element(),
-                            ),
-                            single_example(
-                                "Error",
-                                Switch::new("switch_error_style", ToggleState::Selected)
-                                    .color(SwitchColor::Error)
-                                    .on_click(|_, _, _cx| {})
-                                    .into_any_element(),
-                            ),
-                            single_example(
-                                "Warning",
-                                Switch::new("switch_warning_style", ToggleState::Selected)
-                                    .color(SwitchColor::Warning)
-                                    .on_click(|_, _, _cx| {})
-                                    .into_any_element(),
-                            ),
-                            single_example(
-                                "Success",
-                                Switch::new("switch_success_style", ToggleState::Selected)
-                                    .color(SwitchColor::Success)
                                     .on_click(|_, _, _cx| {})
                                     .into_any_element(),
                             ),

crates/ui_input/src/number_field.rs 🔗

@@ -5,8 +5,11 @@ use std::{
     str::FromStr,
 };
 
-use editor::{Editor, EditorStyle};
-use gpui::{ClickEvent, Entity, FocusHandle, Focusable, FontWeight, Modifiers};
+use editor::{Editor, actions::MoveDown, actions::MoveUp};
+use gpui::{
+    ClickEvent, Entity, FocusHandle, Focusable, FontWeight, Modifiers, TextAlign,
+    TextStyleRefinement, WeakEntity,
+};
 
 use settings::{CenteredPaddingSettings, CodeFade, DelayMs, InactiveOpacity, MinimumContrast};
 use ui::prelude::*;
@@ -235,12 +238,14 @@ impl_numeric_stepper_nonzero_int!(NonZeroU32, u32);
 impl_numeric_stepper_nonzero_int!(NonZeroU64, u64);
 impl_numeric_stepper_nonzero_int!(NonZero<usize>, usize);
 
-#[derive(RegisterComponent)]
-pub struct NumberField<T = usize> {
+#[derive(IntoElement, RegisterComponent)]
+pub struct NumberField<T: NumberFieldType = usize> {
     id: ElementId,
     value: T,
     focus_handle: FocusHandle,
     mode: Entity<NumberFieldMode>,
+    /// Stores a weak reference to the editor when in edit mode, so buttons can update its text
+    edit_editor: Entity<Option<WeakEntity<Editor>>>,
     format: Box<dyn FnOnce(&T) -> String>,
     large_step: T,
     small_step: T,
@@ -256,15 +261,17 @@ impl<T: NumberFieldType> NumberField<T> {
     pub fn new(id: impl Into<ElementId>, value: T, window: &mut Window, cx: &mut App) -> Self {
         let id = id.into();
 
-        let (mode, focus_handle) = window.with_id(id.clone(), |window| {
+        let (mode, focus_handle, edit_editor) = window.with_id(id.clone(), |window| {
             let mode = window.use_state(cx, |_, _| NumberFieldMode::default());
             let focus_handle = window.use_state(cx, |_, cx| cx.focus_handle());
-            (mode, focus_handle)
+            let edit_editor = window.use_state(cx, |_, _| None);
+            (mode, focus_handle, edit_editor)
         });
 
         Self {
             id,
             mode,
+            edit_editor,
             value,
             focus_handle: focus_handle.read(cx).clone(),
             format: Box::new(T::default_format),
@@ -309,6 +316,11 @@ impl<T: NumberFieldType> NumberField<T> {
         self
     }
 
+    pub fn mode(self, mode: NumberFieldMode, cx: &mut App) -> Self {
+        self.mode.write(cx, mode);
+        self
+    }
+
     pub fn on_reset(
         mut self,
         on_reset: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
@@ -328,17 +340,16 @@ impl<T: NumberFieldType> NumberField<T> {
     }
 }
 
-impl<T: NumberFieldType> IntoElement for NumberField<T> {
-    type Element = gpui::Component<Self>;
-
-    fn into_element(self) -> Self::Element {
-        gpui::Component::new(self)
-    }
+#[derive(Clone, Copy)]
+enum ValueChangeDirection {
+    Increment,
+    Decrement,
 }
 
 impl<T: NumberFieldType> RenderOnce for NumberField<T> {
     fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
         let mut tab_index = self.tab_index;
+        let is_edit_mode = matches!(*self.mode.read(cx), NumberFieldMode::Edit);
 
         let get_step = {
             let large_step = self.large_step;
@@ -355,6 +366,67 @@ impl<T: NumberFieldType> RenderOnce for NumberField<T> {
             }
         };
 
+        let clamp_value = {
+            let min = self.min_value;
+            let max = self.max_value;
+            move |value: T| -> T {
+                if value < min {
+                    min
+                } else if value > max {
+                    max
+                } else {
+                    value
+                }
+            }
+        };
+
+        let change_value = {
+            move |current: T, step: T, direction: ValueChangeDirection| -> T {
+                let new_value = match direction {
+                    ValueChangeDirection::Increment => current.saturating_add(step),
+                    ValueChangeDirection::Decrement => current.saturating_sub(step),
+                };
+                clamp_value(new_value)
+            }
+        };
+
+        let get_current_value = {
+            let value = self.value;
+            let edit_editor = self.edit_editor.clone();
+
+            Rc::new(move |cx: &App| -> T {
+                if !is_edit_mode {
+                    return value;
+                }
+                edit_editor
+                    .read(cx)
+                    .as_ref()
+                    .and_then(|weak| weak.upgrade())
+                    .and_then(|editor| editor.read(cx).text(cx).parse::<T>().ok())
+                    .unwrap_or(value)
+            })
+        };
+
+        let update_editor_text = {
+            let edit_editor = self.edit_editor.clone();
+
+            Rc::new(move |new_value: T, window: &mut Window, cx: &mut App| {
+                if !is_edit_mode {
+                    return;
+                }
+                let Some(editor) = edit_editor
+                    .read(cx)
+                    .as_ref()
+                    .and_then(|weak| weak.upgrade())
+                else {
+                    return;
+                };
+                editor.update(cx, |editor, cx| {
+                    editor.set_text(format!("{}", new_value), window, cx);
+                });
+            })
+        };
+
         let bg_color = cx.theme().colors().surface_background;
         let hover_bg_color = cx.theme().colors().element_hover;
 
@@ -395,13 +467,20 @@ impl<T: NumberFieldType> RenderOnce for NumberField<T> {
                 h_flex()
                     .map(|decrement| {
                         let decrement_handler = {
-                            let value = self.value;
                             let on_change = self.on_change.clone();
-                            let min = self.min_value;
+                            let get_current_value = get_current_value.clone();
+                            let update_editor_text = update_editor_text.clone();
+
                             move |click: &ClickEvent, window: &mut Window, cx: &mut App| {
+                                let current_value = get_current_value(cx);
                                 let step = get_step(click.modifiers());
-                                let new_value = value.saturating_sub(step);
-                                let new_value = if new_value < min { min } else { new_value };
+                                let new_value = change_value(
+                                    current_value,
+                                    step,
+                                    ValueChangeDirection::Decrement,
+                                );
+
+                                update_editor_text(new_value, window, cx);
                                 on_change(&new_value, window, cx);
                             }
                         };
@@ -438,46 +517,97 @@ impl<T: NumberFieldType> RenderOnce for NumberField<T> {
                                     .justify_center()
                                     .child(Label::new((self.format)(&self.value)))
                                     .into_any_element(),
-                                // Edit mode is disabled until we implement center text alignment for editor
-                                // mode.write(cx, NumberFieldMode::Edit);
-                                //
-                                // When we get to making Edit mode work, we shouldn't even focus the decrement/increment buttons.
-                                // Focus should go instead straight to the editor, avoiding any double-step focus.
-                                // In this world, the buttons become a mouse-only interaction, given users should be able
-                                // to do everything they'd do with the buttons straight in the editor anyway.
                                 NumberFieldMode::Edit => h_flex()
                                     .flex_1()
                                     .child(window.use_state(cx, {
                                         |window, cx| {
-                                            let previous_focus_handle = window.focused(cx);
                                             let mut editor = Editor::single_line(window, cx);
-                                            let mut style = EditorStyle::default();
-                                            style.text.text_align = gpui::TextAlign::Right;
-                                            editor.set_style(style, window, cx);
+
+                                            editor.set_text_style_refinement(TextStyleRefinement {
+                                                text_align: Some(TextAlign::Center),
+                                                ..Default::default()
+                                            });
 
                                             editor.set_text(format!("{}", self.value), window, cx);
+
+                                            let editor_weak = cx.entity().downgrade();
+
+                                            self.edit_editor.update(cx, |state, _| {
+                                                *state = Some(editor_weak);
+                                            });
+
+                                            editor
+                                                .register_action::<MoveUp>({
+                                                    let on_change = self.on_change.clone();
+                                                    let editor_handle = cx.entity().downgrade();
+                                                    move |_, window, cx| {
+                                                        let Some(editor) = editor_handle.upgrade()
+                                                        else {
+                                                            return;
+                                                        };
+                                                        editor.update(cx, |editor, cx| {
+                                                            if let Ok(current_value) =
+                                                                editor.text(cx).parse::<T>()
+                                                            {
+                                                                let step =
+                                                                    get_step(window.modifiers());
+                                                                let new_value = change_value(
+                                                                    current_value,
+                                                                    step,
+                                                                    ValueChangeDirection::Increment,
+                                                                );
+                                                                editor.set_text(
+                                                                    format!("{}", new_value),
+                                                                    window,
+                                                                    cx,
+                                                                );
+                                                                on_change(&new_value, window, cx);
+                                                            }
+                                                        });
+                                                    }
+                                                })
+                                                .detach();
+
+                                            editor
+                                                .register_action::<MoveDown>({
+                                                    let on_change = self.on_change.clone();
+                                                    let editor_handle = cx.entity().downgrade();
+                                                    move |_, window, cx| {
+                                                        let Some(editor) = editor_handle.upgrade()
+                                                        else {
+                                                            return;
+                                                        };
+                                                        editor.update(cx, |editor, cx| {
+                                                            if let Ok(current_value) =
+                                                                editor.text(cx).parse::<T>()
+                                                            {
+                                                                let step =
+                                                                    get_step(window.modifiers());
+                                                                let new_value = change_value(
+                                                                    current_value,
+                                                                    step,
+                                                                    ValueChangeDirection::Decrement,
+                                                                );
+                                                                editor.set_text(
+                                                                    format!("{}", new_value),
+                                                                    window,
+                                                                    cx,
+                                                                );
+                                                                on_change(&new_value, window, cx);
+                                                            }
+                                                        });
+                                                    }
+                                                })
+                                                .detach();
+
                                             cx.on_focus_out(&editor.focus_handle(cx), window, {
                                                 let mode = self.mode.clone();
-                                                let min = self.min_value;
-                                                let max = self.max_value;
                                                 let on_change = self.on_change.clone();
                                                 move |this, _, window, cx| {
-                                                    if let Ok(new_value) =
+                                                    if let Ok(parsed_value) =
                                                         this.text(cx).parse::<T>()
                                                     {
-                                                        let new_value = if new_value < min {
-                                                            min
-                                                        } else if new_value > max {
-                                                            max
-                                                        } else {
-                                                            new_value
-                                                        };
-
-                                                        if let Some(previous) =
-                                                            previous_focus_handle.as_ref()
-                                                        {
-                                                            window.focus(previous);
-                                                        }
+                                                        let new_value = clamp_value(parsed_value);
                                                         on_change(&new_value, window, cx);
                                                     };
                                                     mode.write(cx, NumberFieldMode::Read);
@@ -485,7 +615,7 @@ impl<T: NumberFieldType> RenderOnce for NumberField<T> {
                                             })
                                             .detach();
 
-                                            window.focus(&editor.focus_handle(cx));
+                                            window.focus(&editor.focus_handle(cx), cx);
 
                                             editor
                                         }
@@ -500,13 +630,20 @@ impl<T: NumberFieldType> RenderOnce for NumberField<T> {
                     )
                     .map(|increment| {
                         let increment_handler = {
-                            let value = self.value;
                             let on_change = self.on_change.clone();
-                            let max = self.max_value;
+                            let get_current_value = get_current_value.clone();
+                            let update_editor_text = update_editor_text.clone();
+
                             move |click: &ClickEvent, window: &mut Window, cx: &mut App| {
+                                let current_value = get_current_value(cx);
                                 let step = get_step(click.modifiers());
-                                let new_value = value.saturating_add(step);
-                                let new_value = if new_value > max { max } else { new_value };
+                                let new_value = change_value(
+                                    current_value,
+                                    step,
+                                    ValueChangeDirection::Increment,
+                                );
+
+                                update_editor_text(new_value, window, cx);
                                 on_change(&new_value, window, cx);
                             }
                         };
@@ -541,36 +678,42 @@ impl Component for NumberField<usize> {
         "Number Field"
     }
 
-    fn sort_name() -> &'static str {
-        Self::name()
-    }
-
     fn description() -> Option<&'static str> {
         Some("A numeric input element with increment and decrement buttons.")
     }
 
     fn preview(window: &mut Window, cx: &mut App) -> Option<AnyElement> {
-        let stepper_example = window.use_state(cx, |_, _| 100.0);
+        let default_ex = window.use_state(cx, |_, _| 100.0);
+        let edit_ex = window.use_state(cx, |_, _| 500.0);
 
         Some(
             v_flex()
                 .gap_6()
-                .children(vec![single_example(
-                    "Default Numeric Stepper",
-                    NumberField::new(
-                        "numeric-stepper-component-preview",
-                        *stepper_example.read(cx),
-                        window,
-                        cx,
-                    )
-                    .on_change({
-                        let stepper_example = stepper_example.clone();
-                        move |value, _, cx| stepper_example.write(cx, *value)
-                    })
-                    .min(1.0)
-                    .max(100.0)
-                    .into_any_element(),
-                )])
+                .children(vec![
+                    single_example(
+                        "Button-Only Number Field",
+                        NumberField::new("number-field", *default_ex.read(cx), window, cx)
+                            .on_change({
+                                let default_ex = default_ex.clone();
+                                move |value, _, cx| default_ex.write(cx, *value)
+                            })
+                            .min(1.0)
+                            .max(100.0)
+                            .into_any_element(),
+                    ),
+                    single_example(
+                        "Editable Number Field",
+                        NumberField::new("editable-number-field", *edit_ex.read(cx), window, cx)
+                            .on_change({
+                                let edit_ex = edit_ex.clone();
+                                move |value, _, cx| edit_ex.write(cx, *value)
+                            })
+                            .min(100.0)
+                            .max(500.0)
+                            .mode(NumberFieldMode::Edit, cx)
+                            .into_any_element(),
+                    ),
+                ])
                 .into_any_element(),
         )
     }

crates/util/src/archive.rs 🔗

@@ -109,7 +109,9 @@ pub async fn extract_seekable_zip<R: AsyncRead + AsyncSeek + Unpin>(
                 .await
                 .with_context(|| format!("extracting into file {path:?}"))?;
 
-            if let Some(perms) = entry.unix_permissions() {
+            if let Some(perms) = entry.unix_permissions()
+                && perms != 0o000
+            {
                 use std::os::unix::fs::PermissionsExt;
                 let permissions = std::fs::Permissions::from_mode(u32::from(perms));
                 file.set_permissions(permissions)
@@ -132,7 +134,8 @@ mod tests {
 
     use super::*;
 
-    async fn compress_zip(src_dir: &Path, dst: &Path) -> Result<()> {
+    #[allow(unused_variables)]
+    async fn compress_zip(src_dir: &Path, dst: &Path, keep_file_permissions: bool) -> Result<()> {
         let mut out = smol::fs::File::create(dst).await?;
         let mut writer = ZipFileWriter::new(&mut out);
 
@@ -155,8 +158,8 @@ mod tests {
                     ZipEntryBuilder::new(filename.into(), async_zip::Compression::Deflate);
                 use std::os::unix::fs::PermissionsExt;
                 let metadata = std::fs::metadata(path)?;
-                let perms = metadata.permissions().mode() as u16;
-                builder = builder.unix_permissions(perms);
+                let perms = keep_file_permissions.then(|| metadata.permissions().mode() as u16);
+                builder = builder.unix_permissions(perms.unwrap_or_default());
                 writer.write_entry_whole(builder, &data).await?;
             }
             #[cfg(not(unix))]
@@ -206,7 +209,9 @@ mod tests {
         let zip_file = test_dir.path().join("test.zip");
 
         smol::block_on(async {
-            compress_zip(test_dir.path(), &zip_file).await.unwrap();
+            compress_zip(test_dir.path(), &zip_file, true)
+                .await
+                .unwrap();
             let reader = read_archive(&zip_file).await;
 
             let dir = tempfile::tempdir().unwrap();
@@ -237,7 +242,9 @@ mod tests {
 
             // Create zip
             let zip_file = test_dir.path().join("test.zip");
-            compress_zip(test_dir.path(), &zip_file).await.unwrap();
+            compress_zip(test_dir.path(), &zip_file, true)
+                .await
+                .unwrap();
 
             // Extract to new location
             let extract_dir = tempfile::tempdir().unwrap();
@@ -251,4 +258,39 @@ mod tests {
             assert_eq!(extracted_perms.mode() & 0o777, 0o755);
         });
     }
+
+    #[cfg(unix)]
+    #[test]
+    fn test_extract_zip_sets_default_permissions() {
+        use std::os::unix::fs::PermissionsExt;
+
+        smol::block_on(async {
+            let test_dir = tempfile::tempdir().unwrap();
+            let executable_path = test_dir.path().join("my_script");
+
+            // Create an executable file
+            std::fs::write(&executable_path, "#!/bin/bash\necho 'Hello'").unwrap();
+
+            // Create zip
+            let zip_file = test_dir.path().join("test.zip");
+            compress_zip(test_dir.path(), &zip_file, false)
+                .await
+                .unwrap();
+
+            // Extract to new location
+            let extract_dir = tempfile::tempdir().unwrap();
+            let reader = read_archive(&zip_file).await;
+            extract_zip(extract_dir.path(), reader).await.unwrap();
+
+            // Check permissions are preserved
+            let extracted_path = extract_dir.path().join("my_script");
+            assert!(extracted_path.exists());
+            let extracted_perms = std::fs::metadata(&extracted_path).unwrap().permissions();
+            assert_eq!(
+                extracted_perms.mode() & 0o777,
+                0o644,
+                "Expected default set of permissions for unzipped file with no permissions set."
+            );
+        });
+    }
 }

crates/util/src/command.rs 🔗

@@ -58,7 +58,7 @@ pub fn new_smol_command(program: impl AsRef<OsStr>) -> smol::process::Command {
 }
 
 #[cfg(target_os = "macos")]
-fn reset_exception_ports() {
+pub fn reset_exception_ports() {
     use mach2::exception_types::{
         EXC_MASK_ALL, EXCEPTION_DEFAULT, exception_behavior_t, exception_mask_t,
     };

crates/util/src/paths.rs 🔗

@@ -227,9 +227,16 @@ impl SanitizedPath {
         #[cfg(not(target_os = "windows"))]
         return unsafe { mem::transmute::<Arc<Path>, Arc<Self>>(path) };
 
-        // TODO: could avoid allocating here if dunce::simplified results in the same path
         #[cfg(target_os = "windows")]
-        return Self::new(&path).into();
+        {
+            let simplified = dunce::simplified(path.as_ref());
+            if simplified == path.as_ref() {
+                // safe because `Path` and `SanitizedPath` have the same repr and Drop impl
+                unsafe { mem::transmute::<Arc<Path>, Arc<Self>>(path) }
+            } else {
+                Self::unchecked_new(simplified).into()
+            }
+        }
     }
 
     pub fn new_arc<T: AsRef<Path> + ?Sized>(path: &T) -> Arc<Self> {

crates/util/src/redact.rs 🔗

@@ -1,3 +1,9 @@
+use std::sync::LazyLock;
+
+static REDACT_REGEX: LazyLock<regex::Regex> = LazyLock::new(|| {
+    regex::Regex::new(r#"([A-Z_][A-Z0-9_]*)=("(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|\S+)"#).unwrap()
+});
+
 /// Whether a given environment variable name should have its value redacted
 pub fn should_redact(env_var_name: &str) -> bool {
     const REDACTED_SUFFIXES: &[&str] = &[
@@ -13,3 +19,31 @@ pub fn should_redact(env_var_name: &str) -> bool {
         .iter()
         .any(|suffix| env_var_name.ends_with(suffix))
 }
+
+/// Redact a string which could include a command with environment variables
+pub fn redact_command(command: &str) -> String {
+    REDACT_REGEX
+        .replace_all(command, |caps: &regex::Captures| {
+            let var_name = &caps[1];
+            let value = &caps[2];
+            if should_redact(var_name) {
+                format!(r#"{}="[REDACTED]""#, var_name)
+            } else {
+                format!("{}={}", var_name, value)
+            }
+        })
+        .to_string()
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    #[test]
+    fn test_redact_string_with_multiple_env_vars() {
+        let input = r#"failed to spawn command cd "/code/something" && ANTHROPIC_API_KEY="sk-ant-api03-WOOOO" COMMAND_MODE="unix2003" GEMINI_API_KEY="AIGEMINIFACE" HOME="/Users/foo""#;
+        let result = redact_command(input);
+        let expected = r#"failed to spawn command cd "/code/something" && ANTHROPIC_API_KEY="[REDACTED]" COMMAND_MODE="unix2003" GEMINI_API_KEY="[REDACTED]" HOME="/Users/foo""#;
+        assert_eq!(result, expected);
+    }
+}

crates/util/src/rel_path.rs 🔗

@@ -161,7 +161,7 @@ impl RelPath {
         false
     }
 
-    pub fn strip_prefix<'a>(&'a self, other: &Self) -> Result<&'a Self> {
+    pub fn strip_prefix<'a>(&'a self, other: &Self) -> Result<&'a Self, StripPrefixError> {
         if other.is_empty() {
             return Ok(self);
         }
@@ -172,7 +172,7 @@ impl RelPath {
                 return Ok(Self::empty());
             }
         }
-        Err(anyhow!("failed to strip prefix: {other:?} from {self:?}"))
+        Err(StripPrefixError)
     }
 
     pub fn len(&self) -> usize {
@@ -251,6 +251,9 @@ impl RelPath {
     }
 }
 
+#[derive(Debug)]
+pub struct StripPrefixError;
+
 impl ToOwned for RelPath {
     type Owned = RelPathBuf;
 

crates/util/src/schemars.rs 🔗

@@ -53,3 +53,20 @@ impl schemars::transform::Transform for DefaultDenyUnknownFields {
         transform_subschemas(self, schema);
     }
 }
+
+/// Defaults `allowTrailingCommas` to `true`, for use with `json-language-server`.
+/// This can be applied to any schema that will be treated as `jsonc`.
+///
+/// Note that this is non-recursive and only applied to the root schema.
+#[derive(Clone)]
+pub struct AllowTrailingCommas;
+
+impl schemars::transform::Transform for AllowTrailingCommas {
+    fn transform(&mut self, schema: &mut schemars::Schema) {
+        if let Some(object) = schema.as_object_mut()
+            && !object.contains_key("allowTrailingCommas")
+        {
+            object.insert("allowTrailingCommas".to_string(), true.into());
+        }
+    }
+}

crates/util/src/shell.rs 🔗

@@ -56,7 +56,10 @@ pub enum ShellKind {
     Tcsh,
     Rc,
     Fish,
+    /// Pre-installed "legacy" powershell for windows
     PowerShell,
+    /// PowerShell 7.x
+    Pwsh,
     Nushell,
     Cmd,
     Xonsh,
@@ -238,6 +241,7 @@ impl fmt::Display for ShellKind {
             ShellKind::Tcsh => write!(f, "tcsh"),
             ShellKind::Fish => write!(f, "fish"),
             ShellKind::PowerShell => write!(f, "powershell"),
+            ShellKind::Pwsh => write!(f, "pwsh"),
             ShellKind::Nushell => write!(f, "nu"),
             ShellKind::Cmd => write!(f, "cmd"),
             ShellKind::Rc => write!(f, "rc"),
@@ -260,7 +264,8 @@ impl ShellKind {
             .to_string_lossy();
 
         match &*program {
-            "powershell" | "pwsh" => ShellKind::PowerShell,
+            "powershell" => ShellKind::PowerShell,
+            "pwsh" => ShellKind::Pwsh,
             "cmd" => ShellKind::Cmd,
             "nu" => ShellKind::Nushell,
             "fish" => ShellKind::Fish,
@@ -279,7 +284,7 @@ impl ShellKind {
 
     pub fn to_shell_variable(self, input: &str) -> String {
         match self {
-            Self::PowerShell => Self::to_powershell_variable(input),
+            Self::PowerShell | Self::Pwsh => Self::to_powershell_variable(input),
             Self::Cmd => Self::to_cmd_variable(input),
             Self::Posix => input.to_owned(),
             Self::Fish => input.to_owned(),
@@ -407,8 +412,12 @@ impl ShellKind {
 
     pub fn args_for_shell(&self, interactive: bool, combined_command: String) -> Vec<String> {
         match self {
-            ShellKind::PowerShell => vec!["-C".to_owned(), combined_command],
-            ShellKind::Cmd => vec!["/C".to_owned(), combined_command],
+            ShellKind::PowerShell | ShellKind::Pwsh => vec!["-C".to_owned(), combined_command],
+            ShellKind::Cmd => vec![
+                "/S".to_owned(),
+                "/C".to_owned(),
+                format!("\"{combined_command}\""),
+            ],
             ShellKind::Posix
             | ShellKind::Nushell
             | ShellKind::Fish
@@ -426,7 +435,7 @@ impl ShellKind {
 
     pub const fn command_prefix(&self) -> Option<char> {
         match self {
-            ShellKind::PowerShell => Some('&'),
+            ShellKind::PowerShell | ShellKind::Pwsh => Some('&'),
             ShellKind::Nushell => Some('^'),
             ShellKind::Posix
             | ShellKind::Csh
@@ -457,6 +466,7 @@ impl ShellKind {
             | ShellKind::Rc
             | ShellKind::Fish
             | ShellKind::PowerShell
+            | ShellKind::Pwsh
             | ShellKind::Nushell
             | ShellKind::Xonsh
             | ShellKind::Elvish => ';',
@@ -471,6 +481,7 @@ impl ShellKind {
             | ShellKind::Tcsh
             | ShellKind::Rc
             | ShellKind::Fish
+            | ShellKind::Pwsh
             | ShellKind::PowerShell
             | ShellKind::Xonsh => "&&",
             ShellKind::Nushell | ShellKind::Elvish => ";",
@@ -478,11 +489,10 @@ impl ShellKind {
     }
 
     pub fn try_quote<'a>(&self, arg: &'a str) -> Option<Cow<'a, str>> {
-        shlex::try_quote(arg).ok().map(|arg| match self {
-            // If we are running in PowerShell, we want to take extra care when escaping strings.
-            // In particular, we want to escape strings with a backtick (`) rather than a backslash (\).
-            ShellKind::PowerShell => Cow::Owned(arg.replace("\\\"", "`\"").replace("\\\\", "\\")),
-            ShellKind::Cmd => Cow::Owned(arg.replace("\\\\", "\\")),
+        match self {
+            ShellKind::PowerShell => Some(Self::quote_powershell(arg)),
+            ShellKind::Pwsh => Some(Self::quote_pwsh(arg)),
+            ShellKind::Cmd => Some(Self::quote_cmd(arg)),
             ShellKind::Posix
             | ShellKind::Csh
             | ShellKind::Tcsh
@@ -490,8 +500,173 @@ impl ShellKind {
             | ShellKind::Fish
             | ShellKind::Nushell
             | ShellKind::Xonsh
-            | ShellKind::Elvish => arg,
-        })
+            | ShellKind::Elvish => shlex::try_quote(arg).ok(),
+        }
+    }
+
+    fn quote_windows(arg: &str, enclose: bool) -> Cow<'_, str> {
+        if arg.is_empty() {
+            return Cow::Borrowed("\"\"");
+        }
+
+        let needs_quoting = arg.chars().any(|c| c == ' ' || c == '\t' || c == '"');
+        if !needs_quoting {
+            return Cow::Borrowed(arg);
+        }
+
+        let mut result = String::with_capacity(arg.len() + 2);
+
+        if enclose {
+            result.push('"');
+        }
+
+        let chars: Vec<char> = arg.chars().collect();
+        let mut i = 0;
+
+        while i < chars.len() {
+            if chars[i] == '\\' {
+                let mut num_backslashes = 0;
+                while i < chars.len() && chars[i] == '\\' {
+                    num_backslashes += 1;
+                    i += 1;
+                }
+
+                if i < chars.len() && chars[i] == '"' {
+                    // Backslashes followed by quote: double the backslashes and escape the quote
+                    for _ in 0..(num_backslashes * 2 + 1) {
+                        result.push('\\');
+                    }
+                    result.push('"');
+                    i += 1;
+                } else if i >= chars.len() {
+                    // Trailing backslashes: double them (they precede the closing quote)
+                    for _ in 0..(num_backslashes * 2) {
+                        result.push('\\');
+                    }
+                } else {
+                    // Backslashes not followed by quote: output as-is
+                    for _ in 0..num_backslashes {
+                        result.push('\\');
+                    }
+                }
+            } else if chars[i] == '"' {
+                // Quote not preceded by backslash: escape it
+                result.push('\\');
+                result.push('"');
+                i += 1;
+            } else {
+                result.push(chars[i]);
+                i += 1;
+            }
+        }
+
+        if enclose {
+            result.push('"');
+        }
+        Cow::Owned(result)
+    }
+
+    fn needs_quoting_powershell(s: &str) -> bool {
+        s.is_empty()
+            || s.chars().any(|c| {
+                c.is_whitespace()
+                    || matches!(
+                        c,
+                        '"' | '`'
+                            | '$'
+                            | '&'
+                            | '|'
+                            | '<'
+                            | '>'
+                            | ';'
+                            | '('
+                            | ')'
+                            | '['
+                            | ']'
+                            | '{'
+                            | '}'
+                            | ','
+                            | '\''
+                            | '@'
+                    )
+            })
+    }
+
+    fn need_quotes_powershell(arg: &str) -> bool {
+        let mut quote_count = 0;
+        for c in arg.chars() {
+            if c == '"' {
+                quote_count += 1;
+            } else if c.is_whitespace() && (quote_count % 2 == 0) {
+                return true;
+            }
+        }
+        false
+    }
+
+    fn escape_powershell_quotes(s: &str) -> String {
+        let mut result = String::with_capacity(s.len() + 4);
+        result.push('\'');
+        for c in s.chars() {
+            if c == '\'' {
+                result.push('\'');
+            }
+            result.push(c);
+        }
+        result.push('\'');
+        result
+    }
+
+    pub fn quote_powershell(arg: &str) -> Cow<'_, str> {
+        let ps_will_quote = Self::need_quotes_powershell(arg);
+        let crt_quoted = Self::quote_windows(arg, !ps_will_quote);
+
+        if !Self::needs_quoting_powershell(arg) {
+            return crt_quoted;
+        }
+
+        Cow::Owned(Self::escape_powershell_quotes(&crt_quoted))
+    }
+
+    pub fn quote_pwsh(arg: &str) -> Cow<'_, str> {
+        if arg.is_empty() {
+            return Cow::Borrowed("''");
+        }
+
+        if !Self::needs_quoting_powershell(arg) {
+            return Cow::Borrowed(arg);
+        }
+
+        Cow::Owned(Self::escape_powershell_quotes(arg))
+    }
+
+    pub fn quote_cmd(arg: &str) -> Cow<'_, str> {
+        let crt_quoted = Self::quote_windows(arg, true);
+
+        let needs_cmd_escaping = crt_quoted.contains('"')
+            || crt_quoted.contains('%')
+            || crt_quoted
+                .chars()
+                .any(|c| matches!(c, '^' | '<' | '>' | '&' | '|' | '(' | ')'));
+
+        if !needs_cmd_escaping {
+            return crt_quoted;
+        }
+
+        let mut result = String::with_capacity(crt_quoted.len() * 2);
+        for c in crt_quoted.chars() {
+            match c {
+                '^' | '"' | '<' | '>' | '&' | '|' | '(' | ')' => {
+                    result.push('^');
+                    result.push(c);
+                }
+                '%' => {
+                    result.push_str("%%cd:~,%");
+                }
+                _ => result.push(c),
+            }
+        }
+        Cow::Owned(result)
     }
 
     /// Quotes the given argument if necessary, taking into account the command prefix.
@@ -527,7 +702,10 @@ impl ShellKind {
                     .map(|quoted| Cow::Owned(self.prepend_command_prefix(&quoted).into_owned()));
             }
         }
-        self.try_quote(arg)
+        self.try_quote(arg).map(|quoted| match quoted {
+            unquoted @ Cow::Borrowed(_) => unquoted,
+            Cow::Owned(quoted) => Cow::Owned(self.prepend_command_prefix(&quoted).into_owned()),
+        })
     }
 
     pub fn split(&self, input: &str) -> Option<Vec<String>> {
@@ -538,7 +716,7 @@ impl ShellKind {
         match self {
             ShellKind::Cmd => "",
             ShellKind::Nushell => "overlay use",
-            ShellKind::PowerShell => ".",
+            ShellKind::PowerShell | ShellKind::Pwsh => ".",
             ShellKind::Fish
             | ShellKind::Csh
             | ShellKind::Tcsh
@@ -558,6 +736,7 @@ impl ShellKind {
             | ShellKind::Rc
             | ShellKind::Fish
             | ShellKind::PowerShell
+            | ShellKind::Pwsh
             | ShellKind::Nushell
             | ShellKind::Xonsh
             | ShellKind::Elvish => "clear",
@@ -576,6 +755,7 @@ impl ShellKind {
             | ShellKind::Rc
             | ShellKind::Fish
             | ShellKind::PowerShell
+            | ShellKind::Pwsh
             | ShellKind::Nushell
             | ShellKind::Xonsh
             | ShellKind::Elvish => true,
@@ -605,7 +785,7 @@ mod tests {
                 .try_quote("C:\\Users\\johndoe\\dev\\python\\39007\\tests\\.venv\\Scripts\\python.exe -m pytest \"test_foo.py::test_foo\"")
                 .unwrap()
                 .into_owned(),
-            "\"C:\\Users\\johndoe\\dev\\python\\39007\\tests\\.venv\\Scripts\\python.exe -m pytest `\"test_foo.py::test_foo`\"\"".to_string()
+            "'C:\\Users\\johndoe\\dev\\python\\39007\\tests\\.venv\\Scripts\\python.exe -m pytest \\\"test_foo.py::test_foo\\\"'".to_string()
         );
     }
 
@@ -617,7 +797,113 @@ mod tests {
                 .try_quote("C:\\Users\\johndoe\\dev\\python\\39007\\tests\\.venv\\Scripts\\python.exe -m pytest \"test_foo.py::test_foo\"")
                 .unwrap()
                 .into_owned(),
-            "\"C:\\Users\\johndoe\\dev\\python\\39007\\tests\\.venv\\Scripts\\python.exe -m pytest \\\"test_foo.py::test_foo\\\"\"".to_string()
+            "^\"C:\\Users\\johndoe\\dev\\python\\39007\\tests\\.venv\\Scripts\\python.exe -m pytest \\^\"test_foo.py::test_foo\\^\"^\"".to_string()
+        );
+    }
+
+    #[test]
+    fn test_try_quote_powershell_edge_cases() {
+        let shell_kind = ShellKind::PowerShell;
+
+        // Empty string
+        assert_eq!(
+            shell_kind.try_quote("").unwrap().into_owned(),
+            "'\"\"'".to_string()
+        );
+
+        // String without special characters (no quoting needed)
+        assert_eq!(shell_kind.try_quote("simple").unwrap(), "simple");
+
+        // String with spaces
+        assert_eq!(
+            shell_kind.try_quote("hello world").unwrap().into_owned(),
+            "'hello world'".to_string()
+        );
+
+        // String with dollar signs
+        assert_eq!(
+            shell_kind.try_quote("$variable").unwrap().into_owned(),
+            "'$variable'".to_string()
+        );
+
+        // String with backticks
+        assert_eq!(
+            shell_kind.try_quote("test`command").unwrap().into_owned(),
+            "'test`command'".to_string()
+        );
+
+        // String with multiple special characters
+        assert_eq!(
+            shell_kind
+                .try_quote("test `\"$var`\" end")
+                .unwrap()
+                .into_owned(),
+            "'test `\\\"$var`\\\" end'".to_string()
+        );
+
+        // String with backslashes and colon (path without spaces doesn't need quoting)
+        assert_eq!(
+            shell_kind.try_quote("C:\\path\\to\\file").unwrap(),
+            "C:\\path\\to\\file"
+        );
+    }
+
+    #[test]
+    fn test_try_quote_cmd_edge_cases() {
+        let shell_kind = ShellKind::Cmd;
+
+        // Empty string
+        assert_eq!(
+            shell_kind.try_quote("").unwrap().into_owned(),
+            "^\"^\"".to_string()
+        );
+
+        // String without special characters (no quoting needed)
+        assert_eq!(shell_kind.try_quote("simple").unwrap(), "simple");
+
+        // String with spaces
+        assert_eq!(
+            shell_kind.try_quote("hello world").unwrap().into_owned(),
+            "^\"hello world^\"".to_string()
+        );
+
+        // String with space and backslash (backslash not at end, so not doubled)
+        assert_eq!(
+            shell_kind.try_quote("path\\ test").unwrap().into_owned(),
+            "^\"path\\ test^\"".to_string()
+        );
+
+        // String ending with backslash (must be doubled before closing quote)
+        assert_eq!(
+            shell_kind.try_quote("test path\\").unwrap().into_owned(),
+            "^\"test path\\\\^\"".to_string()
+        );
+
+        // String ending with multiple backslashes (all doubled before closing quote)
+        assert_eq!(
+            shell_kind.try_quote("test path\\\\").unwrap().into_owned(),
+            "^\"test path\\\\\\\\^\"".to_string()
+        );
+
+        // String with embedded quote (quote is escaped, backslash before it is doubled)
+        assert_eq!(
+            shell_kind.try_quote("test\\\"quote").unwrap().into_owned(),
+            "^\"test\\\\\\^\"quote^\"".to_string()
+        );
+
+        // String with multiple backslashes before embedded quote (all doubled)
+        assert_eq!(
+            shell_kind
+                .try_quote("test\\\\\"quote")
+                .unwrap()
+                .into_owned(),
+            "^\"test\\\\\\\\\\^\"quote^\"".to_string()
+        );
+
+        // String with backslashes not before quotes (path without spaces doesn't need quoting)
+        assert_eq!(
+            shell_kind.try_quote("C:\\path\\to\\file").unwrap(),
+            "C:\\path\\to\\file"
         );
     }
 
@@ -633,7 +919,7 @@ mod tests {
                 .try_quote_prefix_aware("'uname'")
                 .unwrap()
                 .into_owned(),
-            "\"'uname'\"".to_string()
+            "^\"'uname'\"".to_string()
         );
         assert_eq!(
             shell_kind.try_quote("^uname").unwrap().into_owned(),
@@ -666,7 +952,7 @@ mod tests {
                 .try_quote_prefix_aware("'uname a'")
                 .unwrap()
                 .into_owned(),
-            "\"'uname a'\"".to_string()
+            "^\"'uname a'\"".to_string()
         );
         assert_eq!(
             shell_kind.try_quote("^'uname a'").unwrap().into_owned(),

crates/util/src/shell_builder.rs 🔗

@@ -1,3 +1,5 @@
+use std::borrow::Cow;
+
 use crate::shell::get_system_shell;
 use crate::shell::{Shell, ShellKind};
 
@@ -42,7 +44,7 @@ impl ShellBuilder {
             self.program.clone()
         } else {
             match self.kind {
-                ShellKind::PowerShell => {
+                ShellKind::PowerShell | ShellKind::Pwsh => {
                     format!("{} -C '{}'", self.program, command_to_use_in_label)
                 }
                 ShellKind::Cmd => {
@@ -76,6 +78,64 @@ impl ShellBuilder {
         mut self,
         task_command: Option<String>,
         task_args: &[String],
+    ) -> (String, Vec<String>) {
+        if let Some(task_command) = task_command {
+            let task_command = if !task_args.is_empty() {
+                match self.kind.try_quote_prefix_aware(&task_command) {
+                    Some(task_command) => task_command.into_owned(),
+                    None => task_command,
+                }
+            } else {
+                task_command
+            };
+            let mut combined_command = task_args.iter().fold(task_command, |mut command, arg| {
+                command.push(' ');
+                let shell_variable = self.kind.to_shell_variable(arg);
+                command.push_str(&match self.kind.try_quote(&shell_variable) {
+                    Some(shell_variable) => shell_variable,
+                    None => Cow::Owned(shell_variable),
+                });
+                command
+            });
+            if self.redirect_stdin {
+                match self.kind {
+                    ShellKind::Fish => {
+                        combined_command.insert_str(0, "begin; ");
+                        combined_command.push_str("; end </dev/null");
+                    }
+                    ShellKind::Posix
+                    | ShellKind::Nushell
+                    | ShellKind::Csh
+                    | ShellKind::Tcsh
+                    | ShellKind::Rc
+                    | ShellKind::Xonsh
+                    | ShellKind::Elvish => {
+                        combined_command.insert(0, '(');
+                        combined_command.push_str(") </dev/null");
+                    }
+                    ShellKind::PowerShell | ShellKind::Pwsh => {
+                        combined_command.insert_str(0, "$null | & {");
+                        combined_command.push_str("}");
+                    }
+                    ShellKind::Cmd => {
+                        combined_command.push_str("< NUL");
+                    }
+                }
+            }
+
+            self.args
+                .extend(self.kind.args_for_shell(self.interactive, combined_command));
+        }
+
+        (self.program, self.args)
+    }
+
+    // This should not exist, but our task infra is broken beyond repair right now
+    #[doc(hidden)]
+    pub fn build_no_quote(
+        mut self,
+        task_command: Option<String>,
+        task_args: &[String],
     ) -> (String, Vec<String>) {
         if let Some(task_command) = task_command {
             let mut combined_command = task_args.iter().fold(task_command, |mut command, arg| {
@@ -99,7 +159,7 @@ impl ShellBuilder {
                         combined_command.insert(0, '(');
                         combined_command.push_str(") </dev/null");
                     }
-                    ShellKind::PowerShell => {
+                    ShellKind::PowerShell | ShellKind::Pwsh => {
                         combined_command.insert_str(0, "$null | & {");
                         combined_command.push_str("}");
                     }
@@ -115,6 +175,48 @@ impl ShellBuilder {
 
         (self.program, self.args)
     }
+
+    /// Builds a command with the given task command and arguments.
+    ///
+    /// Prefer this over manually constructing a command with the output of `Self::build`,
+    /// as this method handles `cmd` weirdness on windows correctly.
+    pub fn build_command(
+        self,
+        mut task_command: Option<String>,
+        task_args: &[String],
+    ) -> smol::process::Command {
+        #[cfg(windows)]
+        let kind = self.kind;
+        if task_args.is_empty() {
+            task_command = task_command
+                .as_ref()
+                .map(|cmd| self.kind.try_quote_prefix_aware(&cmd).map(Cow::into_owned))
+                .unwrap_or(task_command);
+        }
+        let (program, args) = self.build(task_command, task_args);
+
+        let mut child = crate::command::new_smol_command(program);
+
+        #[cfg(windows)]
+        if kind == ShellKind::Cmd {
+            use smol::process::windows::CommandExt;
+
+            for arg in args {
+                child.raw_arg(arg);
+            }
+        } else {
+            child.args(args);
+        }
+
+        #[cfg(not(windows))]
+        child.args(args);
+
+        child
+    }
+
+    pub fn kind(&self) -> ShellKind {
+        self.kind
+    }
 }
 
 #[cfg(test)]
@@ -144,7 +246,7 @@ mod test {
             vec![
                 "-i",
                 "-c",
-                "echo $env.hello $env.world nothing --($env.something) $ ${test"
+                "echo '$env.hello' '$env.world' nothing '--($env.something)' '$' '${test'"
             ]
         );
     }
@@ -174,4 +276,23 @@ mod test {
         assert_eq!(program, "fish");
         assert_eq!(args, vec!["-i", "-c", "begin; echo test; end </dev/null"]);
     }
+
+    #[test]
+    fn does_not_quote_sole_command_only() {
+        let shell = Shell::Program("fish".to_owned());
+        let shell_builder = ShellBuilder::new(&shell, false);
+
+        let (program, args) = shell_builder.build(Some("echo".into()), &[]);
+
+        assert_eq!(program, "fish");
+        assert_eq!(args, vec!["-i", "-c", "echo"]);
+
+        let shell = Shell::Program("fish".to_owned());
+        let shell_builder = ShellBuilder::new(&shell, false);
+
+        let (program, args) = shell_builder.build(Some("echo oo".into()), &[]);
+
+        assert_eq!(program, "fish");
+        assert_eq!(args, vec!["-i", "-c", "echo oo"]);
+    }
 }

crates/util/src/shell_env.rs 🔗

@@ -132,7 +132,7 @@ async fn spawn_and_read_fd(
 #[cfg(windows)]
 async fn capture_windows(
     shell_path: &Path,
-    _args: &[String],
+    args: &[String],
     directory: &Path,
 ) -> Result<collections::HashMap<String, String>> {
     use std::process::Stdio;
@@ -141,17 +141,17 @@ async fn capture_windows(
         std::env::current_exe().context("Failed to determine current zed executable path.")?;
 
     let shell_kind = ShellKind::new(shell_path, true);
-    if let ShellKind::Csh | ShellKind::Tcsh | ShellKind::Rc | ShellKind::Fish | ShellKind::Xonsh =
-        shell_kind
-    {
-        return Err(anyhow::anyhow!("unsupported shell kind"));
-    }
     let mut cmd = crate::command::new_smol_command(shell_path);
+    cmd.args(args);
     let cmd = match shell_kind {
-        ShellKind::Csh | ShellKind::Tcsh | ShellKind::Rc | ShellKind::Fish | ShellKind::Xonsh => {
-            unreachable!()
-        }
-        ShellKind::Posix => cmd.args([
+        ShellKind::Csh
+        | ShellKind::Tcsh
+        | ShellKind::Rc
+        | ShellKind::Fish
+        | ShellKind::Xonsh
+        | ShellKind::Posix => cmd.args([
+            "-l",
+            "-i",
             "-c",
             &format!(
                 "cd '{}'; '{}' --printenv",
@@ -159,7 +159,7 @@ async fn capture_windows(
                 zed_path.display()
             ),
         ]),
-        ShellKind::PowerShell => cmd.args([
+        ShellKind::PowerShell | ShellKind::Pwsh => cmd.args([
             "-NonInteractive",
             "-NoProfile",
             "-Command",

crates/util/src/util.rs 🔗

@@ -390,6 +390,8 @@ pub fn set_pre_exec_to_start_new_session(
         use std::os::unix::process::CommandExt;
         command.pre_exec(|| {
             libc::setsid();
+            #[cfg(target_os = "macos")]
+            crate::command::reset_exception_ports();
             Ok(())
         });
     };

crates/vim/Cargo.toml 🔗

@@ -63,8 +63,10 @@ indoc.workspace = true
 language = { workspace = true, features = ["test-support"] }
 project = { workspace = true, features = ["test-support"] }
 lsp = { workspace = true, features = ["test-support"] }
+markdown_preview.workspace = true
 parking_lot.workspace = true
 project_panel.workspace = true
+outline_panel.workspace = true
 release_channel.workspace = true
 semver.workspace = true
 settings_ui.workspace = true

crates/vim/src/command.rs 🔗

@@ -230,6 +230,14 @@ struct VimEdit {
     pub filename: String,
 }
 
+/// Pastes the specified file's contents.
+#[derive(Clone, PartialEq, Action)]
+#[action(namespace = vim, no_json, no_register)]
+struct VimRead {
+    pub range: Option<CommandRange>,
+    pub filename: String,
+}
+
 #[derive(Clone, PartialEq, Action)]
 #[action(namespace = vim, no_json, no_register)]
 struct VimNorm {
@@ -330,10 +338,12 @@ pub fn register(editor: &mut Editor, cx: &mut Context<Vim>) {
                 let Some(range) = range.buffer_range(vim, editor, window, cx).ok() else {
                     return;
                 };
-                let Some((line_ending, text, whole_buffer)) = editor.buffer().update(cx, |multi, cx| {
+                let Some((line_ending, encoding, has_bom, text, whole_buffer)) = editor.buffer().update(cx, |multi, cx| {
                     Some(multi.as_singleton()?.update(cx, |buffer, _| {
                         (
                             buffer.line_ending(),
+                            buffer.encoding(),
+                            buffer.has_bom(),
                             buffer.as_rope().slice_rows(range.start.0..range.end.0 + 1),
                             range.start.0 == 0 && range.end.0 + 1 >= buffer.row_count(),
                         )
@@ -429,7 +439,7 @@ pub fn register(editor: &mut Editor, cx: &mut Context<Vim>) {
                                     return;
                                 };
                                 worktree
-                                    .write_file(path.into_arc(), text.clone(), line_ending, cx)
+                                    .write_file(path.into_arc(), text.clone(), line_ending, encoding, has_bom, cx)
                                     .detach_and_prompt_err("Failed to write lines", window, cx, |_, _, _| None);
                             });
                         })
@@ -641,6 +651,107 @@ pub fn register(editor: &mut Editor, cx: &mut Context<Vim>) {
         });
     });
 
+    Vim::action(editor, cx, |vim, action: &VimRead, window, cx| {
+        vim.update_editor(cx, |vim, editor, cx| {
+            let snapshot = editor.buffer().read(cx).snapshot(cx);
+            let end = if let Some(range) = action.range.clone() {
+                let Some(multi_range) = range.buffer_range(vim, editor, window, cx).log_err()
+                else {
+                    return;
+                };
+
+                match &range.start {
+                    // inserting text above the first line uses the command ":0r {name}"
+                    Position::Line { row: 0, offset: 0 } if range.end.is_none() => {
+                        snapshot.clip_point(Point::new(0, 0), Bias::Right)
+                    }
+                    _ => snapshot.clip_point(Point::new(multi_range.end.0 + 1, 0), Bias::Right),
+                }
+            } else {
+                let end_row = editor
+                    .selections
+                    .newest::<Point>(&editor.display_snapshot(cx))
+                    .range()
+                    .end
+                    .row;
+                snapshot.clip_point(Point::new(end_row + 1, 0), Bias::Right)
+            };
+            let is_end_of_file = end == snapshot.max_point();
+            let edit_range = snapshot.anchor_before(end)..snapshot.anchor_before(end);
+
+            let mut text = if is_end_of_file {
+                String::from('\n')
+            } else {
+                String::new()
+            };
+
+            let mut task = None;
+            if action.filename.is_empty() {
+                text.push_str(
+                    &editor
+                        .buffer()
+                        .read(cx)
+                        .as_singleton()
+                        .map(|buffer| buffer.read(cx).text())
+                        .unwrap_or_default(),
+                );
+            } else {
+                if let Some(project) = editor.project().cloned() {
+                    project.update(cx, |project, cx| {
+                        let Some(worktree) = project.visible_worktrees(cx).next() else {
+                            return;
+                        };
+                        let path_style = worktree.read(cx).path_style();
+                        let Some(path) =
+                            RelPath::new(Path::new(&action.filename), path_style).log_err()
+                        else {
+                            return;
+                        };
+                        task =
+                            Some(worktree.update(cx, |worktree, cx| worktree.load_file(&path, cx)));
+                    });
+                } else {
+                    return;
+                }
+            };
+
+            cx.spawn_in(window, async move |editor, cx| {
+                if let Some(task) = task {
+                    text.push_str(
+                        &task
+                            .await
+                            .log_err()
+                            .map(|loaded_file| loaded_file.text)
+                            .unwrap_or_default(),
+                    );
+                }
+
+                if !text.is_empty() && !is_end_of_file {
+                    text.push('\n');
+                }
+
+                let _ = editor.update_in(cx, |editor, window, cx| {
+                    editor.transact(window, cx, |editor, window, cx| {
+                        editor.edit([(edit_range.clone(), text)], cx);
+                        let snapshot = editor.buffer().read(cx).snapshot(cx);
+                        editor.change_selections(Default::default(), window, cx, |s| {
+                            let point = if is_end_of_file {
+                                Point::new(
+                                    edit_range.start.to_point(&snapshot).row.saturating_add(1),
+                                    0,
+                                )
+                            } else {
+                                Point::new(edit_range.start.to_point(&snapshot).row, 0)
+                            };
+                            s.select_ranges([point..point]);
+                        })
+                    });
+                });
+            })
+            .detach();
+        });
+    });
+
     Vim::action(editor, cx, |vim, action: &VimNorm, window, cx| {
         let keystrokes = action
             .command
@@ -1336,24 +1447,49 @@ fn generate_commands(_: &App) -> Vec<VimCommand> {
         VimCommand::new(("e", "dit"), editor::actions::ReloadFile)
             .bang(editor::actions::ReloadFile)
             .filename(|_, filename| Some(VimEdit { filename }.boxed_clone())),
-        VimCommand::new(("sp", "lit"), workspace::SplitHorizontal).filename(|_, filename| {
-            Some(
-                VimSplit {
-                    vertical: false,
-                    filename,
-                }
-                .boxed_clone(),
-            )
-        }),
-        VimCommand::new(("vs", "plit"), workspace::SplitVertical).filename(|_, filename| {
+        VimCommand::new(
+            ("r", "ead"),
+            VimRead {
+                range: None,
+                filename: "".into(),
+            },
+        )
+        .filename(|_, filename| {
             Some(
-                VimSplit {
-                    vertical: true,
+                VimRead {
+                    range: None,
                     filename,
                 }
                 .boxed_clone(),
             )
+        })
+        .range(|action, range| {
+            let mut action: VimRead = action.as_any().downcast_ref::<VimRead>().unwrap().clone();
+            action.range.replace(range.clone());
+            Some(Box::new(action))
         }),
+        VimCommand::new(("sp", "lit"), workspace::SplitHorizontal::default()).filename(
+            |_, filename| {
+                Some(
+                    VimSplit {
+                        vertical: false,
+                        filename,
+                    }
+                    .boxed_clone(),
+                )
+            },
+        ),
+        VimCommand::new(("vs", "plit"), workspace::SplitVertical::default()).filename(
+            |_, filename| {
+                Some(
+                    VimSplit {
+                        vertical: true,
+                        filename,
+                    }
+                    .boxed_clone(),
+                )
+            },
+        ),
         VimCommand::new(("tabe", "dit"), workspace::NewFile)
             .filename(|_action, filename| Some(VimEdit { filename }.boxed_clone())),
         VimCommand::new(("tabnew", ""), workspace::NewFile)
@@ -2573,6 +2709,76 @@ mod test {
         assert_eq!(fs.load(path).await.unwrap().replace("\r\n", "\n"), "@@\n");
     }
 
+    #[gpui::test]
+    async fn test_command_read(cx: &mut TestAppContext) {
+        let mut cx = VimTestContext::new(cx, true).await;
+
+        let fs = cx.workspace(|workspace, _, cx| workspace.project().read(cx).fs().clone());
+        let path = Path::new(path!("/root/dir/other.rs"));
+        fs.as_fake().insert_file(path, "1\n2\n3".into()).await;
+
+        cx.workspace(|workspace, _, cx| {
+            assert_active_item(workspace, path!("/root/dir/file.rs"), "", cx);
+        });
+
+        // File without trailing newline
+        cx.set_state("one\ntwo\nthreeˇ", Mode::Normal);
+        cx.simulate_keystrokes(": r space d i r / o t h e r . r s");
+        cx.simulate_keystrokes("enter");
+        cx.assert_state("one\ntwo\nthree\nˇ1\n2\n3", Mode::Normal);
+
+        cx.set_state("oneˇ\ntwo\nthree", Mode::Normal);
+        cx.simulate_keystrokes(": r space d i r / o t h e r . r s");
+        cx.simulate_keystrokes("enter");
+        cx.assert_state("one\nˇ1\n2\n3\ntwo\nthree", Mode::Normal);
+
+        cx.set_state("one\nˇtwo\nthree", Mode::Normal);
+        cx.simulate_keystrokes(": 0 r space d i r / o t h e r . r s");
+        cx.simulate_keystrokes("enter");
+        cx.assert_state("ˇ1\n2\n3\none\ntwo\nthree", Mode::Normal);
+
+        cx.set_state("one\n«ˇtwo\nthree\nfour»\nfive", Mode::Visual);
+        cx.simulate_keystrokes(": r space d i r / o t h e r . r s");
+        cx.simulate_keystrokes("enter");
+        cx.run_until_parked();
+        cx.assert_state("one\ntwo\nthree\nfour\nˇ1\n2\n3\nfive", Mode::Normal);
+
+        // Empty filename
+        cx.set_state("oneˇ\ntwo\nthree", Mode::Normal);
+        cx.simulate_keystrokes(": r");
+        cx.simulate_keystrokes("enter");
+        cx.assert_state("one\nˇone\ntwo\nthree\ntwo\nthree", Mode::Normal);
+
+        // File with trailing newline
+        fs.as_fake().insert_file(path, "1\n2\n3\n".into()).await;
+        cx.set_state("one\ntwo\nthreeˇ", Mode::Normal);
+        cx.simulate_keystrokes(": r space d i r / o t h e r . r s");
+        cx.simulate_keystrokes("enter");
+        cx.assert_state("one\ntwo\nthree\nˇ1\n2\n3\n", Mode::Normal);
+
+        cx.set_state("oneˇ\ntwo\nthree", Mode::Normal);
+        cx.simulate_keystrokes(": r space d i r / o t h e r . r s");
+        cx.simulate_keystrokes("enter");
+        cx.assert_state("one\nˇ1\n2\n3\n\ntwo\nthree", Mode::Normal);
+
+        cx.set_state("one\n«ˇtwo\nthree\nfour»\nfive", Mode::Visual);
+        cx.simulate_keystrokes(": r space d i r / o t h e r . r s");
+        cx.simulate_keystrokes("enter");
+        cx.assert_state("one\ntwo\nthree\nfour\nˇ1\n2\n3\n\nfive", Mode::Normal);
+
+        cx.set_state("«one\ntwo\nthreeˇ»", Mode::Visual);
+        cx.simulate_keystrokes(": r space d i r / o t h e r . r s");
+        cx.simulate_keystrokes("enter");
+        cx.assert_state("one\ntwo\nthree\nˇ1\n2\n3\n", Mode::Normal);
+
+        // Empty file
+        fs.as_fake().insert_file(path, "".into()).await;
+        cx.set_state("ˇone\ntwo\nthree", Mode::Normal);
+        cx.simulate_keystrokes(": r space d i r / o t h e r . r s");
+        cx.simulate_keystrokes("enter");
+        cx.assert_state("one\nˇtwo\nthree", Mode::Normal);
+    }
+
     #[gpui::test]
     async fn test_command_quit(cx: &mut TestAppContext) {
         let mut cx = VimTestContext::new(cx, true).await;

crates/vim/src/helix.rs 🔗

@@ -1389,11 +1389,12 @@ mod test {
             Mode::HelixNormal,
         );
         cx.simulate_keystrokes("x");
+        // Adjacent line selections stay separate (not merged)
         cx.assert_state(
             indoc! {"
             «line one
             line two
-            line three
+            ˇ»«line three
             line four
             ˇ»line five"},
             Mode::HelixNormal,

crates/vim/src/motion.rs 🔗

@@ -1,5 +1,5 @@
 use editor::{
-    Anchor, Bias, BufferOffset, DisplayPoint, Editor, MultiBufferOffset, RowExt, ToOffset, ToPoint,
+    Anchor, Bias, BufferOffset, DisplayPoint, Editor, MultiBufferOffset, RowExt, ToOffset,
     display_map::{DisplayRow, DisplaySnapshot, FoldPoint, ToDisplayPoint},
     movement::{
         self, FindRange, TextLayoutDetails, find_boundary, find_preceding_boundary_display_point,
@@ -2262,7 +2262,6 @@ fn go_to_line(map: &DisplaySnapshot, display_point: DisplayPoint, line: usize) -
             .offset_to_point(excerpt.map_offset_from_buffer(BufferOffset(offset)));
         return map.clip_point(map.point_to_display_point(point, Bias::Left), Bias::Left);
     }
-    let mut last_position = None;
     for (excerpt, buffer, range) in map.buffer_snapshot().excerpts() {
         let excerpt_range = language::ToOffset::to_offset(&range.context.start, buffer)
             ..language::ToOffset::to_offset(&range.context.end, buffer);
@@ -2273,14 +2272,9 @@ fn go_to_line(map: &DisplaySnapshot, display_point: DisplayPoint, line: usize) -
         } else if offset <= excerpt_range.start {
             let anchor = Anchor::in_buffer(excerpt, range.context.start);
             return anchor.to_display_point(map);
-        } else {
-            last_position = Some(Anchor::in_buffer(excerpt, range.context.end));
         }
     }
 
-    let mut last_point = last_position.unwrap().to_point(&map.buffer_snapshot());
-    last_point.column = point.column;
-
     map.clip_point(
         map.point_to_display_point(
             map.buffer_snapshot().clip_point(point, Bias::Left),
@@ -2388,10 +2382,16 @@ fn matching(map: &DisplaySnapshot, display_point: DisplayPoint) -> DisplayPoint
         .or_else(|| snapshot.innermost_enclosing_bracket_ranges(offset..offset, None));
 
     if let Some((opening_range, closing_range)) = bracket_ranges {
-        if opening_range.contains(&offset) {
-            return closing_range.start.to_display_point(map);
-        } else if closing_range.contains(&offset) {
-            return opening_range.start.to_display_point(map);
+        let mut chars = map.buffer_snapshot().chars_at(offset);
+        match chars.next() {
+            Some('/') => {}
+            _ => {
+                if opening_range.contains(&offset) {
+                    return closing_range.start.to_display_point(map);
+                } else if closing_range.contains(&offset) {
+                    return opening_range.start.to_display_point(map);
+                }
+            }
         }
     }
 
@@ -3443,6 +3443,23 @@ mod test {
                 test = "test"
             />
         </a>"#});
+
+        // test nested closing tag
+        cx.set_shared_state(indoc! {r#"<html>
+            <bˇody>
+            </body>
+        </html>"#})
+            .await;
+        cx.simulate_shared_keystrokes("%").await;
+        cx.shared_state().await.assert_eq(indoc! {r#"<html>
+            <body>
+            <ˇ/body>
+        </html>"#});
+        cx.simulate_shared_keystrokes("%").await;
+        cx.shared_state().await.assert_eq(indoc! {r#"<html>
+            <ˇbody>
+            </body>
+        </html>"#});
     }
 
     #[gpui::test]

crates/vim/src/normal/change.rs 🔗

@@ -121,7 +121,11 @@ impl Vim {
                     });
                 });
                 if objects_found {
-                    vim.copy_selections_content(editor, MotionKind::Exclusive, window, cx);
+                    let kind = match object.target_visual_mode(vim.mode, around) {
+                        Mode::VisualLine => MotionKind::Linewise,
+                        _ => MotionKind::Exclusive,
+                    };
+                    vim.copy_selections_content(editor, kind, window, cx);
                     editor.insert("", window, cx);
                     editor.refresh_edit_prediction(true, false, window, cx);
                 }

crates/vim/src/normal/mark.rs 🔗

@@ -372,9 +372,12 @@ pub fn jump_motion(
 
 #[cfg(test)]
 mod test {
+    use crate::test::{NeovimBackedTestContext, VimTestContext};
+    use editor::Editor;
     use gpui::TestAppContext;
-
-    use crate::test::NeovimBackedTestContext;
+    use std::path::Path;
+    use util::path;
+    use workspace::{CloseActiveItem, OpenOptions};
 
     #[gpui::test]
     async fn test_quote_mark(cx: &mut TestAppContext) {
@@ -394,4 +397,69 @@ mod test {
         cx.simulate_shared_keystrokes("^ ` `").await;
         cx.shared_state().await.assert_eq("Hello, worldˇ!");
     }
+
+    #[gpui::test]
+    async fn test_global_mark_overwrite(cx: &mut TestAppContext) {
+        let mut cx = VimTestContext::new(cx, true).await;
+
+        let path = Path::new(path!("/first.rs"));
+        let fs = cx.workspace(|workspace, _, cx| workspace.project().read(cx).fs().clone());
+        fs.as_fake().insert_file(path, "one".into()).await;
+        let path = Path::new(path!("/second.rs"));
+        fs.as_fake().insert_file(path, "two".into()).await;
+
+        let _ = cx
+            .workspace(|workspace, window, cx| {
+                workspace.open_abs_path(
+                    path!("/first.rs").into(),
+                    OpenOptions::default(),
+                    window,
+                    cx,
+                )
+            })
+            .await;
+
+        cx.simulate_keystrokes("m A");
+
+        let _ = cx
+            .workspace(|workspace, window, cx| {
+                workspace.open_abs_path(
+                    path!("/second.rs").into(),
+                    OpenOptions::default(),
+                    window,
+                    cx,
+                )
+            })
+            .await;
+
+        cx.simulate_keystrokes("m A");
+
+        let _ = cx
+            .workspace(|workspace, window, cx| {
+                workspace.active_pane().update(cx, |pane, cx| {
+                    pane.close_active_item(&CloseActiveItem::default(), window, cx)
+                })
+            })
+            .await;
+
+        cx.simulate_keystrokes("m B");
+
+        cx.simulate_keystrokes("' A");
+
+        cx.workspace(|workspace, _, cx| {
+            let active_editor = workspace.active_item_as::<Editor>(cx).unwrap();
+
+            let buffer = active_editor
+                .read(cx)
+                .buffer()
+                .read(cx)
+                .as_singleton()
+                .unwrap();
+
+            let file = buffer.read(cx).file().unwrap();
+            let file_path = file.as_local().unwrap().abs_path(cx);
+
+            assert_eq!(file_path.to_str().unwrap(), path!("/second.rs"));
+        })
+    }
 }

crates/vim/src/normal/paste.rs 🔗

@@ -717,7 +717,7 @@ mod test {
         cx.update_global(|store: &mut SettingsStore, cx| {
             store.update_user_settings(cx, |settings| {
                 settings.project.all_languages.languages.0.insert(
-                    LanguageName::new("Rust").0,
+                    LanguageName::new_static("Rust").0,
                     LanguageSettingsContent {
                         auto_indent_on_paste: Some(false),
                         ..Default::default()
@@ -773,6 +773,52 @@ mod test {
         "});
     }
 
+    #[gpui::test]
+    async fn test_paste_system_clipboard_never(cx: &mut gpui::TestAppContext) {
+        let mut cx = VimTestContext::new(cx, true).await;
+
+        cx.update_global(|store: &mut SettingsStore, cx| {
+            store.update_user_settings(cx, |s| {
+                s.vim.get_or_insert_default().use_system_clipboard = Some(UseSystemClipboard::Never)
+            });
+        });
+
+        cx.set_state(
+            indoc! {"
+                ˇThe quick brown
+                fox jumps over
+                the lazy dog"},
+            Mode::Normal,
+        );
+
+        cx.write_to_clipboard(ClipboardItem::new_string("something else".to_string()));
+
+        cx.simulate_keystrokes("d d");
+        cx.assert_state(
+            indoc! {"
+                ˇfox jumps over
+                the lazy dog"},
+            Mode::Normal,
+        );
+
+        cx.simulate_keystrokes("shift-v p");
+        cx.assert_state(
+            indoc! {"
+                ˇThe quick brown
+                the lazy dog"},
+            Mode::Normal,
+        );
+
+        cx.simulate_keystrokes("shift-v");
+        cx.dispatch_action(editor::actions::Paste);
+        cx.assert_state(
+            indoc! {"
+                ˇsomething else
+                the lazy dog"},
+            Mode::Normal,
+        );
+    }
+
     #[gpui::test]
     async fn test_numbered_registers(cx: &mut gpui::TestAppContext) {
         let mut cx = NeovimBackedTestContext::new(cx).await;

crates/vim/src/normal/scroll.rs 🔗

@@ -294,11 +294,10 @@ mod test {
     async fn test_scroll(cx: &mut gpui::TestAppContext) {
         let mut cx = VimTestContext::new(cx, true).await;
 
-        let (line_height, visible_line_count) = cx.editor(|editor, window, _cx| {
+        let (line_height, visible_line_count) = cx.update_editor(|editor, window, cx| {
             (
                 editor
-                    .style()
-                    .unwrap()
+                    .style(cx)
                     .text
                     .line_height_in_pixels(window.rem_size()),
                 editor.visible_line_count().unwrap(),

crates/vim/src/normal/yank.rs 🔗

@@ -11,7 +11,6 @@ use editor::{ClipboardSelection, Editor, SelectionEffects};
 use gpui::Context;
 use gpui::Window;
 use language::Point;
-use multi_buffer::MultiBufferRow;
 use settings::Settings;
 
 struct HighlightOnYank;
@@ -81,7 +80,11 @@ impl Vim {
                         start_positions.insert(selection.id, start_position);
                     });
                 });
-                vim.yank_selections_content(editor, MotionKind::Exclusive, window, cx);
+                let kind = match object.target_visual_mode(vim.mode, around) {
+                    Mode::VisualLine => MotionKind::Linewise,
+                    _ => MotionKind::Exclusive,
+                };
+                vim.yank_selections_content(editor, kind, window, cx);
                 editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
                     s.move_with(|_, selection| {
                         let (head, goal) = start_positions.remove(&selection.id).unwrap();
@@ -194,11 +197,14 @@ impl Vim {
                 if kind.linewise() {
                     text.push('\n');
                 }
-                clipboard_selections.push(ClipboardSelection {
-                    len: text.len() - initial_len,
-                    is_entire_line: false,
-                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
-                });
+                clipboard_selections.push(ClipboardSelection::for_buffer(
+                    text.len() - initial_len,
+                    false,
+                    start..end,
+                    &buffer,
+                    editor.project(),
+                    cx,
+                ));
             }
         }
 
@@ -223,7 +229,7 @@ impl Vim {
 
         editor.highlight_background::<HighlightOnYank>(
             &ranges_to_highlight,
-            |colors| colors.colors().editor_document_highlight_read_background,
+            |_, colors| colors.colors().editor_document_highlight_read_background,
             cx,
         );
         cx.spawn(async move |this, cx| {

crates/vim/src/object.rs 🔗

@@ -911,7 +911,7 @@ pub fn surrounding_html_tag(
     while let Some(cur_node) = last_child_node {
         if cur_node.child_count() >= 2 {
             let first_child = cur_node.child(0);
-            let last_child = cur_node.child(cur_node.child_count() - 1);
+            let last_child = cur_node.child(cur_node.child_count() as u32 - 1);
             if let (Some(first_child), Some(last_child)) = (first_child, last_child) {
                 let open_tag = open_tag(buffer.chars_for_range(first_child.byte_range()));
                 let close_tag = close_tag(buffer.chars_for_range(last_child.byte_range()));
@@ -2382,9 +2382,10 @@ mod test {
             Mode::Insert,
         );
 
-        cx.set_state("let a = (test::call(), 'p', my_macro!{ˇ});", Mode::Normal);
-        cx.simulate_keystrokes("c a a");
-        cx.assert_state("let a = (test::call(), 'p'ˇ);", Mode::Insert);
+        // TODO regressed with the up-to-date Rust grammar.
+        // cx.set_state("let a = (test::call(), 'p', my_macro!{ˇ});", Mode::Normal);
+        // cx.simulate_keystrokes("c a a");
+        // cx.assert_state("let a = (test::call(), 'p'ˇ);", Mode::Insert);
 
         cx.set_state("let a = [test::call(ˇ), 300];", Mode::Normal);
         cx.simulate_keystrokes("c i a");
@@ -2806,9 +2807,8 @@ mod test {
 
         for (keystrokes, initial_state, expected_state, expected_mode) in TEST_CASES {
             cx.set_state(initial_state, Mode::Normal);
-
+            cx.buffer(|buffer, _| buffer.parsing_idle()).await;
             cx.simulate_keystrokes(keystrokes);
-
             cx.assert_state(expected_state, *expected_mode);
         }
 
@@ -2829,9 +2829,8 @@ mod test {
 
         for (keystrokes, initial_state, mode) in INVALID_CASES {
             cx.set_state(initial_state, Mode::Normal);
-
+            cx.buffer(|buffer, _| buffer.parsing_idle()).await;
             cx.simulate_keystrokes(keystrokes);
-
             cx.assert_state(initial_state, *mode);
         }
     }
@@ -3184,9 +3183,8 @@ mod test {
 
         for (keystrokes, initial_state, expected_state, expected_mode) in TEST_CASES {
             cx.set_state(initial_state, Mode::Normal);
-
+            cx.buffer(|buffer, _| buffer.parsing_idle()).await;
             cx.simulate_keystrokes(keystrokes);
-
             cx.assert_state(expected_state, *expected_mode);
         }
 
@@ -3207,9 +3205,8 @@ mod test {
 
         for (keystrokes, initial_state, mode) in INVALID_CASES {
             cx.set_state(initial_state, Mode::Normal);
-
+            cx.buffer(|buffer, _| buffer.parsing_idle()).await;
             cx.simulate_keystrokes(keystrokes);
-
             cx.assert_state(initial_state, *mode);
         }
     }
@@ -3410,4 +3407,390 @@ mod test {
             .assert_eq("    ˇf = (x: unknown) => {");
         cx.shared_clipboard().await.assert_eq("const ");
     }
+
+    #[gpui::test]
+    async fn test_arrow_function_text_object(cx: &mut gpui::TestAppContext) {
+        let mut cx = VimTestContext::new_typescript(cx).await;
+
+        cx.set_state(
+            indoc! {"
+                const foo = () => {
+                    return ˇ1;
+                };
+            "},
+            Mode::Normal,
+        );
+        cx.simulate_keystrokes("v a f");
+        cx.assert_state(
+            indoc! {"
+                «const foo = () => {
+                    return 1;
+                };ˇ»
+            "},
+            Mode::VisualLine,
+        );
+
+        cx.set_state(
+            indoc! {"
+                arr.map(() => {
+                    return ˇ1;
+                });
+            "},
+            Mode::Normal,
+        );
+        cx.simulate_keystrokes("v a f");
+        cx.assert_state(
+            indoc! {"
+                arr.map(«() => {
+                    return 1;
+                }ˇ»);
+            "},
+            Mode::VisualLine,
+        );
+
+        cx.set_state(
+            indoc! {"
+                const foo = () => {
+                    return ˇ1;
+                };
+            "},
+            Mode::Normal,
+        );
+        cx.simulate_keystrokes("v i f");
+        cx.assert_state(
+            indoc! {"
+                const foo = () => {
+                    «return 1;ˇ»
+                };
+            "},
+            Mode::Visual,
+        );
+
+        cx.set_state(
+            indoc! {"
+                (() => {
+                    console.log(ˇ1);
+                })();
+            "},
+            Mode::Normal,
+        );
+        cx.simulate_keystrokes("v a f");
+        cx.assert_state(
+            indoc! {"
+                («() => {
+                    console.log(1);
+                }ˇ»)();
+            "},
+            Mode::VisualLine,
+        );
+
+        cx.set_state(
+            indoc! {"
+                const foo = () => {
+                    return ˇ1;
+                };
+                export { foo };
+            "},
+            Mode::Normal,
+        );
+        cx.simulate_keystrokes("v a f");
+        cx.assert_state(
+            indoc! {"
+                «const foo = () => {
+                    return 1;
+                };ˇ»
+                export { foo };
+            "},
+            Mode::VisualLine,
+        );
+
+        cx.set_state(
+            indoc! {"
+                let bar = () => {
+                    return ˇ2;
+                };
+            "},
+            Mode::Normal,
+        );
+        cx.simulate_keystrokes("v a f");
+        cx.assert_state(
+            indoc! {"
+                «let bar = () => {
+                    return 2;
+                };ˇ»
+            "},
+            Mode::VisualLine,
+        );
+
+        cx.set_state(
+            indoc! {"
+                var baz = () => {
+                    return ˇ3;
+                };
+            "},
+            Mode::Normal,
+        );
+        cx.simulate_keystrokes("v a f");
+        cx.assert_state(
+            indoc! {"
+                «var baz = () => {
+                    return 3;
+                };ˇ»
+            "},
+            Mode::VisualLine,
+        );
+
+        cx.set_state(
+            indoc! {"
+                const add = (a, b) => a + ˇb;
+            "},
+            Mode::Normal,
+        );
+        cx.simulate_keystrokes("v a f");
+        cx.assert_state(
+            indoc! {"
+                «const add = (a, b) => a + b;ˇ»
+            "},
+            Mode::VisualLine,
+        );
+
+        cx.set_state(
+            indoc! {"
+                const add = ˇ(a, b) => a + b;
+            "},
+            Mode::Normal,
+        );
+        cx.simulate_keystrokes("v a f");
+        cx.assert_state(
+            indoc! {"
+                «const add = (a, b) => a + b;ˇ»
+            "},
+            Mode::VisualLine,
+        );
+
+        cx.set_state(
+            indoc! {"
+                const add = (a, b) => a + bˇ;
+            "},
+            Mode::Normal,
+        );
+        cx.simulate_keystrokes("v a f");
+        cx.assert_state(
+            indoc! {"
+                «const add = (a, b) => a + b;ˇ»
+            "},
+            Mode::VisualLine,
+        );
+
+        cx.set_state(
+            indoc! {"
+                const add = (a, b) =ˇ> a + b;
+            "},
+            Mode::Normal,
+        );
+        cx.simulate_keystrokes("v a f");
+        cx.assert_state(
+            indoc! {"
+                «const add = (a, b) => a + b;ˇ»
+            "},
+            Mode::VisualLine,
+        );
+    }
+
+    #[gpui::test]
+    async fn test_arrow_function_in_jsx(cx: &mut gpui::TestAppContext) {
+        let mut cx = VimTestContext::new_tsx(cx).await;
+
+        cx.set_state(
+            indoc! {r#"
+                export const MyComponent = () => {
+                  return (
+                    <div>
+                      <div onClick={() => {
+                        alert("Hello world!");
+                        console.log(ˇ"clicked");
+                      }}>Hello world!</div>
+                    </div>
+                  );
+                };
+            "#},
+            Mode::Normal,
+        );
+        cx.simulate_keystrokes("v a f");
+        cx.assert_state(
+            indoc! {r#"
+                export const MyComponent = () => {
+                  return (
+                    <div>
+                      <div onClick={«() => {
+                        alert("Hello world!");
+                        console.log("clicked");
+                      }ˇ»}>Hello world!</div>
+                    </div>
+                  );
+                };
+            "#},
+            Mode::VisualLine,
+        );
+
+        cx.set_state(
+            indoc! {r#"
+                export const MyComponent = () => {
+                  return (
+                    <div>
+                      <div onClick={() => console.log("clickˇed")}>Hello world!</div>
+                    </div>
+                  );
+                };
+            "#},
+            Mode::Normal,
+        );
+        cx.simulate_keystrokes("v a f");
+        cx.assert_state(
+            indoc! {r#"
+                export const MyComponent = () => {
+                  return (
+                    <div>
+                      <div onClick={«() => console.log("clicked")ˇ»}>Hello world!</div>
+                    </div>
+                  );
+                };
+            "#},
+            Mode::VisualLine,
+        );
+
+        cx.set_state(
+            indoc! {r#"
+                export const MyComponent = () => {
+                  return (
+                    <div>
+                      <div onClick={ˇ() => console.log("clicked")}>Hello world!</div>
+                    </div>
+                  );
+                };
+            "#},
+            Mode::Normal,
+        );
+        cx.simulate_keystrokes("v a f");
+        cx.assert_state(
+            indoc! {r#"
+                export const MyComponent = () => {
+                  return (
+                    <div>
+                      <div onClick={«() => console.log("clicked")ˇ»}>Hello world!</div>
+                    </div>
+                  );
+                };
+            "#},
+            Mode::VisualLine,
+        );
+
+        cx.set_state(
+            indoc! {r#"
+                export const MyComponent = () => {
+                  return (
+                    <div>
+                      <div onClick={() => console.log("clicked"ˇ)}>Hello world!</div>
+                    </div>
+                  );
+                };
+            "#},
+            Mode::Normal,
+        );
+        cx.simulate_keystrokes("v a f");
+        cx.assert_state(
+            indoc! {r#"
+                export const MyComponent = () => {
+                  return (
+                    <div>
+                      <div onClick={«() => console.log("clicked")ˇ»}>Hello world!</div>
+                    </div>
+                  );
+                };
+            "#},
+            Mode::VisualLine,
+        );
+
+        cx.set_state(
+            indoc! {r#"
+                export const MyComponent = () => {
+                  return (
+                    <div>
+                      <div onClick={() =ˇ> console.log("clicked")}>Hello world!</div>
+                    </div>
+                  );
+                };
+            "#},
+            Mode::Normal,
+        );
+        cx.simulate_keystrokes("v a f");
+        cx.assert_state(
+            indoc! {r#"
+                export const MyComponent = () => {
+                  return (
+                    <div>
+                      <div onClick={«() => console.log("clicked")ˇ»}>Hello world!</div>
+                    </div>
+                  );
+                };
+            "#},
+            Mode::VisualLine,
+        );
+
+        cx.set_state(
+            indoc! {r#"
+                export const MyComponent = () => {
+                  return (
+                    <div>
+                      <div onClick={() => {
+                        console.log("cliˇcked");
+                      }}>Hello world!</div>
+                    </div>
+                  );
+                };
+            "#},
+            Mode::Normal,
+        );
+        cx.simulate_keystrokes("v a f");
+        cx.assert_state(
+            indoc! {r#"
+                export const MyComponent = () => {
+                  return (
+                    <div>
+                      <div onClick={«() => {
+                        console.log("clicked");
+                      }ˇ»}>Hello world!</div>
+                    </div>
+                  );
+                };
+            "#},
+            Mode::VisualLine,
+        );
+
+        cx.set_state(
+            indoc! {r#"
+                export const MyComponent = () => {
+                  return (
+                    <div>
+                      <div onClick={() => fˇoo()}>Hello world!</div>
+                    </div>
+                  );
+                };
+            "#},
+            Mode::Normal,
+        );
+        cx.simulate_keystrokes("v a f");
+        cx.assert_state(
+            indoc! {r#"
+                export const MyComponent = () => {
+                  return (
+                    <div>
+                      <div onClick={«() => foo()ˇ»}>Hello world!</div>
+                    </div>
+                  );
+                };
+            "#},
+            Mode::VisualLine,
+        );
+    }
 }

crates/vim/src/replace.rs 🔗

@@ -273,7 +273,7 @@ impl Vim {
             let ranges = [new_range];
             editor.highlight_background::<VimExchange>(
                 &ranges,
-                |theme| theme.colors().editor_document_highlight_read_background,
+                |_, theme| theme.colors().editor_document_highlight_read_background,
                 cx,
             );
         }

crates/vim/src/state.rs 🔗

@@ -550,6 +550,10 @@ impl MarksState {
         let buffer = multibuffer.read(cx).as_singleton();
         let abs_path = buffer.as_ref().and_then(|b| self.path_for_buffer(b, cx));
 
+        if self.is_global_mark(&name) && self.global_marks.contains_key(&name) {
+            self.delete_mark(name.clone(), multibuffer, cx);
+        }
+
         let Some(abs_path) = abs_path else {
             self.multibuffer_marks
                 .entry(multibuffer.entity_id())
@@ -573,7 +577,7 @@ impl MarksState {
 
         let buffer_id = buffer.read(cx).remote_id();
         self.buffer_marks.entry(buffer_id).or_default().insert(
-            name,
+            name.clone(),
             anchors
                 .into_iter()
                 .map(|anchor| anchor.text_anchor)
@@ -582,6 +586,10 @@ impl MarksState {
         if !self.watched_buffers.contains_key(&buffer_id) {
             self.watch_buffer(MarkLocation::Path(abs_path.clone()), &buffer, cx)
         }
+        if self.is_global_mark(&name) {
+            self.global_marks
+                .insert(name, MarkLocation::Path(abs_path.clone()));
+        }
         self.serialize_buffer_marks(abs_path, &buffer, cx)
     }
 

crates/vim/src/test.rs 🔗

@@ -2253,6 +2253,79 @@ async fn test_paragraph_multi_delete(cx: &mut gpui::TestAppContext) {
     cx.shared_state().await.assert_eq(indoc! {"ˇ"});
 }
 
+#[perf]
+#[gpui::test]
+async fn test_yank_paragraph_with_paste(cx: &mut gpui::TestAppContext) {
+    let mut cx = NeovimBackedTestContext::new(cx).await;
+    cx.set_shared_state(indoc! {
+        "
+        first paragraph
+        ˇstill first
+
+        second paragraph
+        still second
+
+        third paragraph
+        "
+    })
+    .await;
+
+    cx.simulate_shared_keystrokes("y a p").await;
+    cx.shared_clipboard()
+        .await
+        .assert_eq("first paragraph\nstill first\n\n");
+
+    cx.simulate_shared_keystrokes("j j p").await;
+    cx.shared_state().await.assert_eq(indoc! {
+        "
+        first paragraph
+        still first
+
+        ˇfirst paragraph
+        still first
+
+        second paragraph
+        still second
+
+        third paragraph
+        "
+    });
+}
+
+#[perf]
+#[gpui::test]
+async fn test_change_paragraph(cx: &mut gpui::TestAppContext) {
+    let mut cx = NeovimBackedTestContext::new(cx).await;
+    cx.set_shared_state(indoc! {
+        "
+        first paragraph
+        ˇstill first
+
+        second paragraph
+        still second
+
+        third paragraph
+        "
+    })
+    .await;
+
+    cx.simulate_shared_keystrokes("c a p").await;
+    cx.shared_clipboard()
+        .await
+        .assert_eq("first paragraph\nstill first\n\n");
+
+    cx.simulate_shared_keystrokes("escape").await;
+    cx.shared_state().await.assert_eq(indoc! {
+        "
+        ˇ
+        second paragraph
+        still second
+
+        third paragraph
+        "
+    });
+}
+
 #[perf]
 #[gpui::test]
 async fn test_multi_cursor_replay(cx: &mut gpui::TestAppContext) {
@@ -2326,7 +2399,7 @@ async fn test_clipping_on_mode_change(cx: &mut gpui::TestAppContext) {
             .end;
         editor.last_bounds().unwrap().origin
             + editor
-                .display_to_pixel_point(current_head, &snapshot, window)
+                .display_to_pixel_point(current_head, &snapshot, window, cx)
                 .unwrap()
     });
     pixel_position.x += px(100.);

crates/vim/src/test/neovim_backed_test_context.rs 🔗

@@ -304,11 +304,10 @@ impl NeovimBackedTestContext {
         self.neovim.set_option(&format!("scrolloff={}", 3)).await;
         // +2 to account for the vim command UI at the bottom.
         self.neovim.set_option(&format!("lines={}", rows + 2)).await;
-        let (line_height, visible_line_count) = self.editor(|editor, window, _cx| {
+        let (line_height, visible_line_count) = self.update_editor(|editor, window, cx| {
             (
                 editor
-                    .style()
-                    .unwrap()
+                    .style(cx)
                     .text
                     .line_height_in_pixels(window.rem_size()),
                 editor.visible_line_count().unwrap(),

crates/vim/src/test/vim_test_context.rs 🔗

@@ -23,11 +23,13 @@ impl VimTestContext {
             release_channel::init(Version::new(0, 0, 0), cx);
             command_palette::init(cx);
             project_panel::init(cx);
+            outline_panel::init(cx);
             git_ui::init(cx);
             crate::init(cx);
             search::init(cx);
             theme::init(theme::LoadThemes::JustBase, cx);
             settings_ui::init(cx);
+            markdown_preview::init(cx);
         });
     }
 

crates/vim/src/vim.rs 🔗

@@ -924,6 +924,7 @@ impl Vim {
                 |vim, _: &editor::actions::Paste, window, cx| match vim.mode {
                     Mode::Replace => vim.paste_replace(window, cx),
                     Mode::Visual | Mode::VisualLine | Mode::VisualBlock => {
+                        vim.selected_register.replace('+');
                         vim.paste(&VimPaste::default(), window, cx);
                     }
                     _ => {
@@ -1942,6 +1943,7 @@ impl Vim {
             editor.set_collapse_matches(collapse_matches);
             editor.set_input_enabled(vim.editor_input_enabled());
             editor.set_autoindent(vim.should_autoindent());
+            editor.set_cursor_offset_on_selection(vim.mode.is_visual());
             editor
                 .selections
                 .set_line_mode(matches!(vim.mode, Mode::VisualLine));

crates/vim/src/visual.rs 🔗

@@ -522,12 +522,16 @@ impl Vim {
                                             selection.start = original_point.to_display_point(map)
                                         }
                                     } else {
-                                        selection.end = movement::saturating_right(
-                                            map,
-                                            original_point.to_display_point(map),
-                                        );
-                                        if original_point.column > 0 {
-                                            selection.reversed = true
+                                        let original_display_point =
+                                            original_point.to_display_point(map);
+                                        if selection.end <= original_display_point {
+                                            selection.end = movement::saturating_right(
+                                                map,
+                                                original_display_point,
+                                            );
+                                            if original_point.column > 0 {
+                                                selection.reversed = true
+                                            }
                                         }
                                     }
                                 }

crates/vim/test_data/test_change_paragraph.json 🔗

@@ -0,0 +1,8 @@
+{"Put":{"state":"first paragraph\nˇstill first\n\nsecond paragraph\nstill second\n\nthird paragraph\n"}}
+{"Key":"c"}
+{"Key":"a"}
+{"Key":"p"}
+{"Get":{"state":"ˇ\nsecond paragraph\nstill second\n\nthird paragraph\n","mode":"Insert"}}
+{"ReadRegister":{"name":"\"","value":"first paragraph\nstill first\n\n"}}
+{"Key":"escape"}
+{"Get":{"state":"ˇ\nsecond paragraph\nstill second\n\nthird paragraph\n","mode":"Normal"}}

crates/vim/test_data/test_matching_tags.json 🔗

@@ -13,3 +13,8 @@
 {"Put":{"state":"<a>\n    <br\n        test = \"test\"\n    /ˇ>\n</a>"}}
 {"Key":"%"}
 {"Get":{"state":"<a>\n    ˇ<br\n        test = \"test\"\n    />\n</a>","mode":"Normal"}}
+{"Put":{"state":"<html>\n    <bˇody>\n    </body>\n</html>"}}
+{"Key":"%"}
+{"Get":{"state":"<html>\n    <body>\n    <ˇ/body>\n</html>","mode":"Normal"}}
+{"Key":"%"}
+{"Get":{"state":"<html>\n    <ˇbody>\n    </body>\n</html>","mode":"Normal"}}

crates/vim/test_data/test_yank_paragraph_with_paste.json 🔗

@@ -0,0 +1,10 @@
+{"Put":{"state":"first paragraph\nˇstill first\n\nsecond paragraph\nstill second\n\nthird paragraph\n"}}
+{"Key":"y"}
+{"Key":"a"}
+{"Key":"p"}
+{"Get":{"state":"ˇfirst paragraph\nstill first\n\nsecond paragraph\nstill second\n\nthird paragraph\n","mode":"Normal"}}
+{"ReadRegister":{"name":"\"","value":"first paragraph\nstill first\n\n"}}
+{"Key":"j"}
+{"Key":"j"}
+{"Key":"p"}
+{"Get":{"state":"first paragraph\nstill first\n\nˇfirst paragraph\nstill first\n\nsecond paragraph\nstill second\n\nthird paragraph\n","mode":"Normal"}}

crates/which_key/Cargo.toml 🔗

@@ -0,0 +1,23 @@
+[package]
+name = "which_key"
+version = "0.1.0"
+edition.workspace = true
+publish.workspace = true
+license = "GPL-3.0-or-later"
+
+[lints]
+workspace = true
+
+[lib]
+path = "src/which_key.rs"
+doctest = false
+
+[dependencies]
+command_palette.workspace = true
+gpui.workspace = true
+serde.workspace = true
+settings.workspace = true
+theme.workspace = true
+ui.workspace = true
+util.workspace = true
+workspace.workspace = true

crates/which_key/src/which_key.rs 🔗

@@ -0,0 +1,98 @@
+//! Which-key support for Zed.
+
+mod which_key_modal;
+mod which_key_settings;
+
+use gpui::{App, Keystroke};
+use settings::Settings;
+use std::{sync::LazyLock, time::Duration};
+use util::ResultExt;
+use which_key_modal::WhichKeyModal;
+use which_key_settings::WhichKeySettings;
+use workspace::Workspace;
+
+pub fn init(cx: &mut App) {
+    WhichKeySettings::register(cx);
+
+    cx.observe_new(|_: &mut Workspace, window, cx| {
+        let Some(window) = window else {
+            return;
+        };
+        let mut timer = None;
+        cx.observe_pending_input(window, move |workspace, window, cx| {
+            if window.pending_input_keystrokes().is_none() {
+                if let Some(modal) = workspace.active_modal::<WhichKeyModal>(cx) {
+                    modal.update(cx, |modal, cx| modal.dismiss(cx));
+                };
+                timer.take();
+                return;
+            }
+
+            let which_key_settings = WhichKeySettings::get_global(cx);
+            if !which_key_settings.enabled {
+                return;
+            }
+
+            let delay_ms = which_key_settings.delay_ms;
+
+            timer.replace(cx.spawn_in(window, async move |workspace_handle, cx| {
+                cx.background_executor()
+                    .timer(Duration::from_millis(delay_ms))
+                    .await;
+                workspace_handle
+                    .update_in(cx, |workspace, window, cx| {
+                        if workspace.active_modal::<WhichKeyModal>(cx).is_some() {
+                            return;
+                        };
+
+                        workspace.toggle_modal(window, cx, |window, cx| {
+                            WhichKeyModal::new(workspace_handle.clone(), window, cx)
+                        });
+                    })
+                    .log_err();
+            }));
+        })
+        .detach();
+    })
+    .detach();
+}
+
+// Hard-coded list of keystrokes to filter out from which-key display
+pub static FILTERED_KEYSTROKES: LazyLock<Vec<Vec<Keystroke>>> = LazyLock::new(|| {
+    [
+        // Modifiers on normal vim commands
+        "g h",
+        "g j",
+        "g k",
+        "g l",
+        "g $",
+        "g ^",
+        // Duplicate keys with "ctrl" held, e.g. "ctrl-w ctrl-a" is duplicate of "ctrl-w a"
+        "ctrl-w ctrl-a",
+        "ctrl-w ctrl-c",
+        "ctrl-w ctrl-h",
+        "ctrl-w ctrl-j",
+        "ctrl-w ctrl-k",
+        "ctrl-w ctrl-l",
+        "ctrl-w ctrl-n",
+        "ctrl-w ctrl-o",
+        "ctrl-w ctrl-p",
+        "ctrl-w ctrl-q",
+        "ctrl-w ctrl-s",
+        "ctrl-w ctrl-v",
+        "ctrl-w ctrl-w",
+        "ctrl-w ctrl-]",
+        "ctrl-w ctrl-shift-w",
+        "ctrl-w ctrl-g t",
+        "ctrl-w ctrl-g shift-t",
+    ]
+    .iter()
+    .filter_map(|s| {
+        let keystrokes: Result<Vec<_>, _> = s
+            .split(' ')
+            .map(|keystroke_str| Keystroke::parse(keystroke_str))
+            .collect();
+        keystrokes.ok()
+    })
+    .collect()
+});

crates/which_key/src/which_key_modal.rs 🔗

@@ -0,0 +1,308 @@
+//! Modal implementation for the which-key display.
+
+use gpui::prelude::FluentBuilder;
+use gpui::{
+    App, Context, DismissEvent, EventEmitter, FocusHandle, Focusable, FontWeight, Keystroke,
+    ScrollHandle, Subscription, WeakEntity, Window,
+};
+use settings::Settings;
+use std::collections::HashMap;
+use theme::ThemeSettings;
+use ui::{
+    Divider, DividerColor, DynamicSpacing, LabelSize, WithScrollbar, prelude::*,
+    text_for_keystrokes,
+};
+use workspace::{ModalView, Workspace};
+
+use crate::FILTERED_KEYSTROKES;
+
+pub struct WhichKeyModal {
+    _workspace: WeakEntity<Workspace>,
+    focus_handle: FocusHandle,
+    scroll_handle: ScrollHandle,
+    bindings: Vec<(SharedString, SharedString)>,
+    pending_keys: SharedString,
+    _pending_input_subscription: Subscription,
+    _focus_out_subscription: Subscription,
+}
+
+impl WhichKeyModal {
+    pub fn new(
+        workspace: WeakEntity<Workspace>,
+        window: &mut Window,
+        cx: &mut Context<Self>,
+    ) -> Self {
+        // Keep focus where it currently is
+        let focus_handle = window.focused(cx).unwrap_or(cx.focus_handle());
+
+        let handle = cx.weak_entity();
+        let mut this = Self {
+            _workspace: workspace,
+            focus_handle: focus_handle.clone(),
+            scroll_handle: ScrollHandle::new(),
+            bindings: Vec::new(),
+            pending_keys: SharedString::new_static(""),
+            _pending_input_subscription: cx.observe_pending_input(
+                window,
+                |this: &mut Self, window, cx| {
+                    this.update_pending_keys(window, cx);
+                },
+            ),
+            _focus_out_subscription: window.on_focus_out(&focus_handle, cx, move |_, _, cx| {
+                handle.update(cx, |_, cx| cx.emit(DismissEvent)).ok();
+            }),
+        };
+        this.update_pending_keys(window, cx);
+        this
+    }
+
+    pub fn dismiss(&self, cx: &mut Context<Self>) {
+        cx.emit(DismissEvent)
+    }
+
+    fn update_pending_keys(&mut self, window: &mut Window, cx: &mut Context<Self>) {
+        let Some(pending_keys) = window.pending_input_keystrokes() else {
+            cx.emit(DismissEvent);
+            return;
+        };
+        let bindings = window.possible_bindings_for_input(pending_keys);
+
+        let mut binding_data = bindings
+            .iter()
+            .map(|binding| {
+                // Map to keystrokes
+                (
+                    binding
+                        .keystrokes()
+                        .iter()
+                        .map(|k| k.inner().to_owned())
+                        .collect::<Vec<_>>(),
+                    binding.action(),
+                )
+            })
+            .filter(|(keystrokes, _action)| {
+                // Check if this binding matches any filtered keystroke pattern
+                !FILTERED_KEYSTROKES.iter().any(|filtered| {
+                    keystrokes.len() >= filtered.len()
+                        && keystrokes[..filtered.len()] == filtered[..]
+                })
+            })
+            .map(|(keystrokes, action)| {
+                // Map to remaining keystrokes and action name
+                let remaining_keystrokes = keystrokes[pending_keys.len()..].to_vec();
+                let action_name: SharedString =
+                    command_palette::humanize_action_name(action.name()).into();
+                (remaining_keystrokes, action_name)
+            })
+            .collect();
+
+        binding_data = group_bindings(binding_data);
+
+        // Sort bindings from shortest to longest, with groups last
+        // Using stable sort to preserve relative order of equal elements
+        binding_data.sort_by(|(keystrokes_a, action_a), (keystrokes_b, action_b)| {
+            // Groups (actions starting with "+") should go last
+            let is_group_a = action_a.starts_with('+');
+            let is_group_b = action_b.starts_with('+');
+
+            // First, separate groups from non-groups
+            let group_cmp = is_group_a.cmp(&is_group_b);
+            if group_cmp != std::cmp::Ordering::Equal {
+                return group_cmp;
+            }
+
+            // Then sort by keystroke count
+            let keystroke_cmp = keystrokes_a.len().cmp(&keystrokes_b.len());
+            if keystroke_cmp != std::cmp::Ordering::Equal {
+                return keystroke_cmp;
+            }
+
+            // Finally sort by text length, then lexicographically for full stability
+            let text_a = text_for_keystrokes(keystrokes_a, cx);
+            let text_b = text_for_keystrokes(keystrokes_b, cx);
+            let text_len_cmp = text_a.len().cmp(&text_b.len());
+            if text_len_cmp != std::cmp::Ordering::Equal {
+                return text_len_cmp;
+            }
+            text_a.cmp(&text_b)
+        });
+        binding_data.dedup();
+        self.pending_keys = text_for_keystrokes(&pending_keys, cx).into();
+        self.bindings = binding_data
+            .into_iter()
+            .map(|(keystrokes, action)| (text_for_keystrokes(&keystrokes, cx).into(), action))
+            .collect();
+    }
+}
+
+impl Render for WhichKeyModal {
+    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
+        let has_rows = !self.bindings.is_empty();
+        let viewport_size = window.viewport_size();
+
+        let max_panel_width = px((f32::from(viewport_size.width) * 0.5).min(480.0));
+        let max_content_height = px(f32::from(viewport_size.height) * 0.4);
+
+        // Push above status bar when visible
+        let status_height = self
+            ._workspace
+            .upgrade()
+            .and_then(|workspace| {
+                workspace.read_with(cx, |workspace, cx| {
+                    if workspace.status_bar_visible(cx) {
+                        Some(
+                            DynamicSpacing::Base04.px(cx) * 2.0
+                                + ThemeSettings::get_global(cx).ui_font_size(cx),
+                        )
+                    } else {
+                        None
+                    }
+                })
+            })
+            .unwrap_or(px(0.));
+
+        let margin_bottom = px(16.);
+        let bottom_offset = margin_bottom + status_height;
+
+        // Title section
+        let title_section = {
+            let mut column = v_flex().gap(px(0.)).child(
+                div()
+                    .child(
+                        Label::new(self.pending_keys.clone())
+                            .size(LabelSize::Default)
+                            .weight(FontWeight::MEDIUM)
+                            .color(Color::Accent),
+                    )
+                    .mb(px(2.)),
+            );
+
+            if has_rows {
+                column = column.child(
+                    div()
+                        .child(Divider::horizontal().color(DividerColor::BorderFaded))
+                        .mb(px(2.)),
+                );
+            }
+
+            column
+        };
+
+        let content = h_flex()
+            .items_start()
+            .id("which-key-content")
+            .gap(px(8.))
+            .overflow_y_scroll()
+            .track_scroll(&self.scroll_handle)
+            .h_full()
+            .max_h(max_content_height)
+            .child(
+                // Keystrokes column
+                v_flex()
+                    .gap(px(4.))
+                    .flex_shrink_0()
+                    .children(self.bindings.iter().map(|(keystrokes, _)| {
+                        div()
+                            .child(
+                                Label::new(keystrokes.clone())
+                                    .size(LabelSize::Default)
+                                    .color(Color::Accent),
+                            )
+                            .text_align(gpui::TextAlign::Right)
+                    })),
+            )
+            .child(
+                // Actions column
+                v_flex()
+                    .gap(px(4.))
+                    .flex_1()
+                    .min_w_0()
+                    .children(self.bindings.iter().map(|(_, action_name)| {
+                        let is_group = action_name.starts_with('+');
+                        let label_color = if is_group {
+                            Color::Success
+                        } else {
+                            Color::Default
+                        };
+
+                        div().child(
+                            Label::new(action_name.clone())
+                                .size(LabelSize::Default)
+                                .color(label_color)
+                                .single_line()
+                                .truncate(),
+                        )
+                    })),
+            );
+
+        div()
+            .id("which-key-buffer-panel-scroll")
+            .occlude()
+            .absolute()
+            .bottom(bottom_offset)
+            .right(px(16.))
+            .min_w(px(220.))
+            .max_w(max_panel_width)
+            .elevation_3(cx)
+            .px(px(12.))
+            .child(v_flex().child(title_section).when(has_rows, |el| {
+                el.child(
+                    div()
+                        .max_h(max_content_height)
+                        .child(content)
+                        .vertical_scrollbar_for(&self.scroll_handle, window, cx),
+                )
+            }))
+    }
+}
+
+impl EventEmitter<DismissEvent> for WhichKeyModal {}
+
+impl Focusable for WhichKeyModal {
+    fn focus_handle(&self, _cx: &App) -> gpui::FocusHandle {
+        self.focus_handle.clone()
+    }
+}
+
+impl ModalView for WhichKeyModal {
+    fn render_bare(&self) -> bool {
+        true
+    }
+}
+
+fn group_bindings(
+    binding_data: Vec<(Vec<Keystroke>, SharedString)>,
+) -> Vec<(Vec<Keystroke>, SharedString)> {
+    let mut groups: HashMap<Option<Keystroke>, Vec<(Vec<Keystroke>, SharedString)>> =
+        HashMap::new();
+
+    // Group bindings by their first keystroke
+    for (remaining_keystrokes, action_name) in binding_data {
+        let first_key = remaining_keystrokes.first().cloned();
+        groups
+            .entry(first_key)
+            .or_default()
+            .push((remaining_keystrokes, action_name));
+    }
+
+    let mut result = Vec::new();
+
+    for (first_key, mut group_bindings) in groups {
+        // Remove duplicates within each group
+        group_bindings.dedup_by_key(|(keystrokes, _)| keystrokes.clone());
+
+        if let Some(first_key) = first_key
+            && group_bindings.len() > 1
+        {
+            // This is a group - create a single entry with just the first keystroke
+            let first_keystroke = vec![first_key];
+            let count = group_bindings.len();
+            result.push((first_keystroke, format!("+{} keybinds", count).into()));
+        } else {
+            // Not a group or empty keystrokes - add all bindings as-is
+            result.append(&mut group_bindings);
+        }
+    }
+
+    result
+}

crates/which_key/src/which_key_settings.rs 🔗

@@ -0,0 +1,18 @@
+use settings::{RegisterSetting, Settings, SettingsContent, WhichKeySettingsContent};
+
+#[derive(Debug, Clone, Copy, RegisterSetting)]
+pub struct WhichKeySettings {
+    pub enabled: bool,
+    pub delay_ms: u64,
+}
+
+impl Settings for WhichKeySettings {
+    fn from_settings(content: &SettingsContent) -> Self {
+        let which_key: &WhichKeySettingsContent = content.which_key.as_ref().unwrap();
+
+        Self {
+            enabled: which_key.enabled.unwrap(),
+            delay_ms: which_key.delay_ms.unwrap(),
+        }
+    }
+}

crates/workspace/Cargo.toml 🔗

@@ -35,14 +35,17 @@ clock.workspace = true
 collections.workspace = true
 component.workspace = true
 db.workspace = true
+feature_flags.workspace = true
 fs.workspace = true
 futures.workspace = true
+git.workspace = true
 gpui.workspace = true
 http_client.workspace = true
 itertools.workspace = true
 language.workspace = true
 log.workspace = true
 menu.workspace = true
+markdown.workspace = true
 node_runtime.workspace = true
 parking_lot.workspace = true
 postage.workspace = true

crates/workspace/src/dock.rs 🔗

@@ -3,6 +3,7 @@ use crate::{DraggedDock, Event, ModalLayer, Pane};
 use crate::{Workspace, status_bar::StatusItemView};
 use anyhow::Context as _;
 use client::proto;
+
 use gpui::{
     Action, AnyView, App, Axis, Context, Corner, Entity, EntityId, EventEmitter, FocusHandle,
     Focusable, IntoElement, KeyContext, MouseButton, MouseDownEvent, MouseUpEvent, ParentElement,
@@ -13,6 +14,7 @@ use settings::SettingsStore;
 use std::sync::Arc;
 use ui::{ContextMenu, Divider, DividerColor, IconButton, Tooltip, h_flex};
 use ui::{prelude::*, right_click_menu};
+use util::ResultExt as _;
 
 pub(crate) const RESIZE_HANDLE_SIZE: Pixels = px(6.);
 
@@ -25,6 +27,72 @@ pub enum PanelEvent {
 
 pub use proto::PanelId;
 
+pub struct MinimizePane;
+pub struct ClosePane;
+
+pub trait UtilityPane: EventEmitter<MinimizePane> + EventEmitter<ClosePane> + Render {
+    fn position(&self, window: &Window, cx: &App) -> UtilityPanePosition;
+    /// The icon to render in the adjacent pane's tab bar for toggling this utility pane
+    fn toggle_icon(&self, cx: &App) -> IconName;
+    fn expanded(&self, cx: &App) -> bool;
+    fn set_expanded(&mut self, expanded: bool, cx: &mut Context<Self>);
+    fn width(&self, cx: &App) -> Pixels;
+    fn set_width(&mut self, width: Option<Pixels>, cx: &mut Context<Self>);
+}
+
+pub trait UtilityPaneHandle: 'static + Send + Sync {
+    fn position(&self, window: &Window, cx: &App) -> UtilityPanePosition;
+    fn toggle_icon(&self, cx: &App) -> IconName;
+    fn expanded(&self, cx: &App) -> bool;
+    fn set_expanded(&self, expanded: bool, cx: &mut App);
+    fn width(&self, cx: &App) -> Pixels;
+    fn set_width(&self, width: Option<Pixels>, cx: &mut App);
+    fn to_any(&self) -> AnyView;
+    fn box_clone(&self) -> Box<dyn UtilityPaneHandle>;
+}
+
+impl<T> UtilityPaneHandle for Entity<T>
+where
+    T: UtilityPane,
+{
+    fn position(&self, window: &Window, cx: &App) -> UtilityPanePosition {
+        self.read(cx).position(window, cx)
+    }
+
+    fn toggle_icon(&self, cx: &App) -> IconName {
+        self.read(cx).toggle_icon(cx)
+    }
+
+    fn expanded(&self, cx: &App) -> bool {
+        self.read(cx).expanded(cx)
+    }
+
+    fn set_expanded(&self, expanded: bool, cx: &mut App) {
+        self.update(cx, |this, cx| this.set_expanded(expanded, cx))
+    }
+
+    fn width(&self, cx: &App) -> Pixels {
+        self.read(cx).width(cx)
+    }
+
+    fn set_width(&self, width: Option<Pixels>, cx: &mut App) {
+        self.update(cx, |this, cx| this.set_width(width, cx))
+    }
+
+    fn to_any(&self) -> AnyView {
+        self.clone().into()
+    }
+
+    fn box_clone(&self) -> Box<dyn UtilityPaneHandle> {
+        Box::new(self.clone())
+    }
+}
+
+pub enum UtilityPanePosition {
+    Left,
+    Right,
+}
+
 pub trait Panel: Focusable + EventEmitter<PanelEvent> + Render + Sized {
     fn persistent_name() -> &'static str;
     fn panel_key() -> &'static str;
@@ -281,7 +349,7 @@ impl Dock {
             let focus_subscription =
                 cx.on_focus(&focus_handle, window, |dock: &mut Dock, window, cx| {
                     if let Some(active_entry) = dock.active_panel_entry() {
-                        active_entry.panel.panel_focus_handle(cx).focus(window)
+                        active_entry.panel.panel_focus_handle(cx).focus(window, cx)
                     }
                 });
             let zoom_subscription = cx.subscribe(&workspace, |dock, workspace, e: &Event, cx| {
@@ -384,6 +452,13 @@ impl Dock {
             .position(|entry| entry.panel.remote_id() == Some(panel_id))
     }
 
+    pub fn panel_for_id(&self, panel_id: EntityId) -> Option<&Arc<dyn PanelHandle>> {
+        self.panel_entries
+            .iter()
+            .find(|entry| entry.panel.panel_id() == panel_id)
+            .map(|entry| &entry.panel)
+    }
+
     pub fn first_enabled_panel_idx(&mut self, cx: &mut Context<Self>) -> anyhow::Result<usize> {
         self.panel_entries
             .iter()
@@ -491,6 +566,9 @@ impl Dock {
 
                     new_dock.update(cx, |new_dock, cx| {
                         new_dock.remove_panel(&panel, window, cx);
+                    });
+
+                    new_dock.update(cx, |new_dock, cx| {
                         let index =
                             new_dock.add_panel(panel.clone(), workspace.clone(), window, cx);
                         if was_visible {
@@ -498,6 +576,12 @@ impl Dock {
                             new_dock.activate_panel(index, window, cx);
                         }
                     });
+
+                    workspace
+                        .update(cx, |workspace, cx| {
+                            workspace.serialize_workspace(window, cx);
+                        })
+                        .ok();
                 }
             }),
             cx.subscribe_in(
@@ -508,7 +592,7 @@ impl Dock {
                         this.set_panel_zoomed(&panel.to_any(), true, window, cx);
                         if !PanelHandle::panel_focus_handle(panel, cx).contains_focused(window, cx)
                         {
-                            window.focus(&panel.focus_handle(cx));
+                            window.focus(&panel.focus_handle(cx), cx);
                         }
                         workspace
                             .update(cx, |workspace, cx| {
@@ -540,7 +624,7 @@ impl Dock {
                         {
                             this.set_open(true, window, cx);
                             this.activate_panel(ix, window, cx);
-                            window.focus(&panel.read(cx).focus_handle(cx));
+                            window.focus(&panel.read(cx).focus_handle(cx), cx);
                         }
                     }
                     PanelEvent::Close => {
@@ -586,6 +670,7 @@ impl Dock {
         );
 
         self.restore_state(window, cx);
+
         if panel.read(cx).starts_open(window, cx) {
             self.activate_panel(index, window, cx);
             self.set_open(true, window, cx);
@@ -619,7 +704,7 @@ impl Dock {
         panel: &Entity<T>,
         window: &mut Window,
         cx: &mut Context<Self>,
-    ) {
+    ) -> bool {
         if let Some(panel_ix) = self
             .panel_entries
             .iter()
@@ -637,8 +722,13 @@ impl Dock {
                     std::cmp::Ordering::Greater => {}
                 }
             }
+
             self.panel_entries.remove(panel_ix);
             cx.notify();
+
+            true
+        } else {
+            false
         }
     }
 
@@ -891,7 +981,13 @@ impl Render for PanelButtons {
             .enumerate()
             .filter_map(|(i, entry)| {
                 let icon = entry.panel.icon(window, cx)?;
-                let icon_tooltip = entry.panel.icon_tooltip(window, cx)?;
+                let icon_tooltip = entry
+                    .panel
+                    .icon_tooltip(window, cx)
+                    .ok_or_else(|| {
+                        anyhow::anyhow!("can't render a panel button without an icon tooltip")
+                    })
+                    .log_err()?;
                 let name = entry.panel.persistent_name();
                 let panel = entry.panel.clone();
 
@@ -941,7 +1037,9 @@ impl Render for PanelButtons {
                         .anchor(menu_anchor)
                         .attach(menu_attach)
                         .trigger(move |is_active, _window, _cx| {
-                            IconButton::new(name, icon)
+                            // Include active state in element ID to invalidate the cached
+                            // tooltip when panel state changes (e.g., via keyboard shortcut)
+                            IconButton::new((name, is_active_button as u64), icon)
                                 .icon_size(IconSize::Small)
                                 .toggle_state(is_active_button)
                                 .on_click({
@@ -952,7 +1050,7 @@ impl Render for PanelButtons {
                                             name = name,
                                             toggle_state = !is_open
                                         );
-                                        window.focus(&focus_handle);
+                                        window.focus(&focus_handle, cx);
                                         window.dispatch_action(action.boxed_clone(), cx)
                                     }
                                 })

crates/workspace/src/invalid_item_view.rs 🔗

@@ -11,6 +11,7 @@ use zed_actions::workspace::OpenWithSystem;
 use crate::Item;
 
 /// A view to display when a certain buffer/image/other item fails to open.
+#[derive(Debug)]
 pub struct InvalidItemView {
     /// Which path was attempted to open.
     pub abs_path: Arc<Path>,

crates/workspace/src/item.rs 🔗

@@ -64,15 +64,25 @@ pub struct ItemSettings {
 #[derive(RegisterSetting)]
 pub struct PreviewTabsSettings {
     pub enabled: bool,
+    pub enable_preview_from_project_panel: bool,
     pub enable_preview_from_file_finder: bool,
-    pub enable_preview_from_code_navigation: bool,
+    pub enable_preview_from_multibuffer: bool,
+    pub enable_preview_multibuffer_from_code_navigation: bool,
+    pub enable_preview_file_from_code_navigation: bool,
+    pub enable_keep_preview_on_code_navigation: bool,
 }
 
 impl Settings for ItemSettings {
     fn from_settings(content: &settings::SettingsContent) -> Self {
         let tabs = content.tabs.as_ref().unwrap();
         Self {
-            git_status: tabs.git_status.unwrap(),
+            git_status: tabs.git_status.unwrap()
+                && content
+                    .git
+                    .unwrap()
+                    .enabled
+                    .unwrap()
+                    .is_git_status_enabled(),
             close_position: tabs.close_position.unwrap(),
             activate_on_close: tabs.activate_on_close.unwrap(),
             file_icons: tabs.file_icons.unwrap(),
@@ -87,9 +97,19 @@ impl Settings for PreviewTabsSettings {
         let preview_tabs = content.preview_tabs.as_ref().unwrap();
         Self {
             enabled: preview_tabs.enabled.unwrap(),
+            enable_preview_from_project_panel: preview_tabs
+                .enable_preview_from_project_panel
+                .unwrap(),
             enable_preview_from_file_finder: preview_tabs.enable_preview_from_file_finder.unwrap(),
-            enable_preview_from_code_navigation: preview_tabs
-                .enable_preview_from_code_navigation
+            enable_preview_from_multibuffer: preview_tabs.enable_preview_from_multibuffer.unwrap(),
+            enable_preview_multibuffer_from_code_navigation: preview_tabs
+                .enable_preview_multibuffer_from_code_navigation
+                .unwrap(),
+            enable_preview_file_from_code_navigation: preview_tabs
+                .enable_preview_file_from_code_navigation
+                .unwrap(),
+            enable_keep_preview_on_code_navigation: preview_tabs
+                .enable_keep_preview_on_code_navigation
                 .unwrap(),
         }
     }
@@ -869,8 +889,18 @@ impl<T: Item> ItemHandle for Entity<T> {
                     if let Some(item) = weak_item.upgrade()
                         && item.workspace_settings(cx).autosave == AutosaveSetting::OnFocusChange
                     {
-                        Pane::autosave_item(&item, workspace.project.clone(), window, cx)
-                            .detach_and_log_err(cx);
+                        // Only trigger autosave if focus has truly left the item.
+                        // If focus is still within the item's hierarchy (e.g., moved to a context menu),
+                        // don't trigger autosave to avoid unwanted formatting and cursor jumps.
+                        // Also skip autosave if focus moved to a modal (e.g., command palette),
+                        // since the user is still interacting with the workspace.
+                        let focus_handle = item.item_focus_handle(cx);
+                        if !focus_handle.contains_focused(window, cx)
+                            && !workspace.has_active_modal(window, cx)
+                        {
+                            Pane::autosave_item(&item, workspace.project.clone(), window, cx)
+                                .detach_and_log_err(cx);
+                        }
                     }
                 },
             )
@@ -1022,7 +1052,7 @@ impl<T: Item> ItemHandle for Entity<T> {
 
     fn relay_action(&self, action: Box<dyn Action>, window: &mut Window, cx: &mut App) {
         self.update(cx, |this, cx| {
-            this.focus_handle(cx).focus(window);
+            this.focus_handle(cx).focus(window, cx);
             window.dispatch_action(action, cx);
         })
     }

crates/workspace/src/modal_layer.rs 🔗

@@ -1,9 +1,18 @@
 use gpui::{
     AnyView, DismissEvent, Entity, EventEmitter, FocusHandle, Focusable as _, ManagedView,
-    MouseButton, Subscription,
+    MouseButton, Pixels, Point, Subscription,
 };
 use ui::prelude::*;
 
+#[derive(Debug, Clone, Copy, Default)]
+pub enum ModalPlacement {
+    #[default]
+    Centered,
+    Anchored {
+        position: Point<Pixels>,
+    },
+}
+
 #[derive(Debug)]
 pub enum DismissDecision {
     Dismiss(bool),
@@ -22,12 +31,17 @@ pub trait ModalView: ManagedView {
     fn fade_out_background(&self) -> bool {
         false
     }
+
+    fn render_bare(&self) -> bool {
+        false
+    }
 }
 
 trait ModalViewHandle {
     fn on_before_dismiss(&mut self, window: &mut Window, cx: &mut App) -> DismissDecision;
     fn view(&self) -> AnyView;
     fn fade_out_background(&self, cx: &mut App) -> bool;
+    fn render_bare(&self, cx: &mut App) -> bool;
 }
 
 impl<V: ModalView> ModalViewHandle for Entity<V> {
@@ -42,6 +56,10 @@ impl<V: ModalView> ModalViewHandle for Entity<V> {
     fn fade_out_background(&self, cx: &mut App) -> bool {
         self.read(cx).fade_out_background()
     }
+
+    fn render_bare(&self, cx: &mut App) -> bool {
+        self.read(cx).render_bare()
+    }
 }
 
 pub struct ActiveModal {
@@ -49,6 +67,7 @@ pub struct ActiveModal {
     _subscriptions: [Subscription; 2],
     previous_focus_handle: Option<FocusHandle>,
     focus_handle: FocusHandle,
+    placement: ModalPlacement,
 }
 
 pub struct ModalLayer {
@@ -78,6 +97,19 @@ impl ModalLayer {
     where
         V: ModalView,
         B: FnOnce(&mut Window, &mut Context<V>) -> V,
+    {
+        self.toggle_modal_with_placement(window, cx, ModalPlacement::Centered, build_view);
+    }
+
+    pub fn toggle_modal_with_placement<V, B>(
+        &mut self,
+        window: &mut Window,
+        cx: &mut Context<Self>,
+        placement: ModalPlacement,
+        build_view: B,
+    ) where
+        V: ModalView,
+        B: FnOnce(&mut Window, &mut Context<V>) -> V,
     {
         if let Some(active_modal) = &self.active_modal {
             let is_close = active_modal.modal.view().downcast::<V>().is_ok();
@@ -87,12 +119,17 @@ impl ModalLayer {
             }
         }
         let new_modal = cx.new(|cx| build_view(window, cx));
-        self.show_modal(new_modal, window, cx);
+        self.show_modal(new_modal, placement, window, cx);
         cx.emit(ModalOpenedEvent);
     }
 
-    fn show_modal<V>(&mut self, new_modal: Entity<V>, window: &mut Window, cx: &mut Context<Self>)
-    where
+    fn show_modal<V>(
+        &mut self,
+        new_modal: Entity<V>,
+        placement: ModalPlacement,
+        window: &mut Window,
+        cx: &mut Context<Self>,
+    ) where
         V: ModalView,
     {
         let focus_handle = cx.focus_handle();
@@ -114,9 +151,10 @@ impl ModalLayer {
             ],
             previous_focus_handle: window.focused(cx),
             focus_handle,
+            placement,
         });
         cx.defer_in(window, move |_, window, cx| {
-            window.focus(&new_modal.focus_handle(cx));
+            window.focus(&new_modal.focus_handle(cx), cx);
         });
         cx.notify();
     }
@@ -144,7 +182,7 @@ impl ModalLayer {
             if let Some(previous_focus) = active_modal.previous_focus_handle
                 && active_modal.focus_handle.contains_focused(window, cx)
             {
-                previous_focus.focus(window);
+                previous_focus.focus(window, cx);
             }
             cx.notify();
         }
@@ -167,19 +205,46 @@ impl ModalLayer {
 impl Render for ModalLayer {
     fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
         let Some(active_modal) = &self.active_modal else {
-            return div();
+            return div().into_any_element();
         };
 
-        div()
+        if active_modal.modal.render_bare(cx) {
+            return active_modal.modal.view().into_any_element();
+        }
+
+        let content = h_flex()
             .occlude()
+            .child(active_modal.modal.view())
+            .on_mouse_down(MouseButton::Left, |_, _, cx| {
+                cx.stop_propagation();
+            });
+
+        let positioned = match active_modal.placement {
+            ModalPlacement::Centered => v_flex()
+                .h(px(0.0))
+                .top_20()
+                .items_center()
+                .track_focus(&active_modal.focus_handle)
+                .child(content)
+                .into_any_element(),
+            ModalPlacement::Anchored { position } => div()
+                .absolute()
+                .left(position.x)
+                .top(position.y - px(20.))
+                .track_focus(&active_modal.focus_handle)
+                .child(content)
+                .into_any_element(),
+        };
+
+        div()
             .absolute()
             .size_full()
-            .top_0()
-            .left_0()
-            .when(active_modal.modal.fade_out_background(cx), |el| {
+            .inset_0()
+            .occlude()
+            .when(active_modal.modal.fade_out_background(cx), |this| {
                 let mut background = cx.theme().colors().elevated_surface_background;
                 background.fade_out(0.2);
-                el.bg(background)
+                this.bg(background)
             })
             .on_mouse_down(
                 MouseButton::Left,
@@ -187,22 +252,7 @@ impl Render for ModalLayer {
                     this.hide_modal(window, cx);
                 }),
             )
-            .child(
-                v_flex()
-                    .h(px(0.0))
-                    .top_20()
-                    .flex()
-                    .flex_col()
-                    .items_center()
-                    .track_focus(&active_modal.focus_handle)
-                    .child(
-                        h_flex()
-                            .occlude()
-                            .child(active_modal.modal.view())
-                            .on_mouse_down(MouseButton::Left, |_, _, cx| {
-                                cx.stop_propagation();
-                            }),
-                    ),
-            )
+            .child(positioned)
+            .into_any_element()
     }
 }

crates/workspace/src/notifications.rs 🔗

@@ -3,9 +3,12 @@ use anyhow::Context as _;
 use gpui::{
     AnyView, App, AppContext as _, AsyncWindowContext, ClickEvent, ClipboardItem, Context,
     DismissEvent, Entity, EventEmitter, FocusHandle, Focusable, PromptLevel, Render, ScrollHandle,
-    Task, svg,
+    Task, TextStyleRefinement, UnderlineStyle, svg,
 };
+use markdown::{Markdown, MarkdownElement, MarkdownStyle};
 use parking_lot::Mutex;
+use settings::Settings;
+use theme::ThemeSettings;
 
 use std::ops::Deref;
 use std::sync::{Arc, LazyLock};
@@ -41,7 +44,7 @@ pub enum NotificationId {
 
 impl NotificationId {
     /// Returns a unique [`NotificationId`] for the given type.
-    pub fn unique<T: 'static>() -> Self {
+    pub const fn unique<T: 'static>() -> Self {
         Self::Unique(TypeId::of::<T>())
     }
 
@@ -216,6 +219,7 @@ pub struct LanguageServerPrompt {
     focus_handle: FocusHandle,
     request: Option<project::LanguageServerPromptRequest>,
     scroll_handle: ScrollHandle,
+    markdown: Entity<Markdown>,
 }
 
 impl Focusable for LanguageServerPrompt {
@@ -228,10 +232,13 @@ impl Notification for LanguageServerPrompt {}
 
 impl LanguageServerPrompt {
     pub fn new(request: project::LanguageServerPromptRequest, cx: &mut App) -> Self {
+        let markdown = cx.new(|cx| Markdown::new(request.message.clone().into(), None, None, cx));
+
         Self {
             focus_handle: cx.focus_handle(),
             request: Some(request),
             scroll_handle: ScrollHandle::new(),
+            markdown,
         }
     }
 
@@ -262,7 +269,7 @@ impl Render for LanguageServerPrompt {
         };
 
         let (icon, color) = match request.level {
-            PromptLevel::Info => (IconName::Info, Color::Accent),
+            PromptLevel::Info => (IconName::Info, Color::Muted),
             PromptLevel::Warning => (IconName::Warning, Color::Warning),
             PromptLevel::Critical => (IconName::XCircle, Color::Error),
         };
@@ -291,16 +298,15 @@ impl Render for LanguageServerPrompt {
                     .child(
                         h_flex()
                             .justify_between()
-                            .items_start()
                             .child(
                                 h_flex()
                                     .gap_2()
-                                    .child(Icon::new(icon).color(color))
+                                    .child(Icon::new(icon).color(color).size(IconSize::Small))
                                     .child(Label::new(request.lsp_name.clone())),
                             )
                             .child(
                                 h_flex()
-                                    .gap_2()
+                                    .gap_1()
                                     .child(
                                         IconButton::new("copy", IconName::Copy)
                                             .on_click({
@@ -317,15 +323,17 @@ impl Render for LanguageServerPrompt {
                                         IconButton::new(close_id, close_icon)
                                             .tooltip(move |_window, cx| {
                                                 if suppress {
-                                                    Tooltip::for_action(
-                                                        "Suppress.\nClose with click.",
-                                                        &SuppressNotification,
+                                                    Tooltip::with_meta(
+                                                        "Suppress",
+                                                        Some(&SuppressNotification),
+                                                        "Click to close",
                                                         cx,
                                                     )
                                                 } else {
-                                                    Tooltip::for_action(
-                                                        "Close.\nSuppress with shift-click.",
-                                                        &menu::Cancel,
+                                                    Tooltip::with_meta(
+                                                        "Close",
+                                                        Some(&menu::Cancel),
+                                                        "Suppress with shift-click",
                                                         cx,
                                                     )
                                                 }
@@ -342,7 +350,16 @@ impl Render for LanguageServerPrompt {
                                     ),
                             ),
                     )
-                    .child(Label::new(request.message.to_string()).size(LabelSize::Small))
+                    .child(
+                        MarkdownElement::new(self.markdown.clone(), markdown_style(window, cx))
+                            .text_size(TextSize::Small.rems(cx))
+                            .code_block_renderer(markdown::CodeBlockRenderer::Default {
+                                copy_button: false,
+                                copy_button_on_hover: false,
+                                border: false,
+                            })
+                            .on_url_click(|link, _, cx| cx.open_url(&link)),
+                    )
                     .children(request.actions.iter().enumerate().map(|(ix, action)| {
                         let this_handle = cx.entity();
                         Button::new(ix, action.title.clone())
@@ -369,6 +386,42 @@ fn workspace_error_notification_id() -> NotificationId {
     NotificationId::unique::<WorkspaceErrorNotification>()
 }
 
+fn markdown_style(window: &Window, cx: &App) -> MarkdownStyle {
+    let settings = ThemeSettings::get_global(cx);
+    let ui_font_family = settings.ui_font.family.clone();
+    let ui_font_fallbacks = settings.ui_font.fallbacks.clone();
+    let buffer_font_family = settings.buffer_font.family.clone();
+    let buffer_font_fallbacks = settings.buffer_font.fallbacks.clone();
+
+    let mut base_text_style = window.text_style();
+    base_text_style.refine(&TextStyleRefinement {
+        font_family: Some(ui_font_family),
+        font_fallbacks: ui_font_fallbacks,
+        color: Some(cx.theme().colors().text),
+        ..Default::default()
+    });
+
+    MarkdownStyle {
+        base_text_style,
+        selection_background_color: cx.theme().colors().element_selection_background,
+        inline_code: TextStyleRefinement {
+            background_color: Some(cx.theme().colors().editor_background.opacity(0.5)),
+            font_family: Some(buffer_font_family),
+            font_fallbacks: buffer_font_fallbacks,
+            ..Default::default()
+        },
+        link: TextStyleRefinement {
+            underline: Some(UnderlineStyle {
+                thickness: px(1.),
+                color: Some(cx.theme().colors().text_accent),
+                wavy: false,
+            }),
+            ..Default::default()
+        },
+        ..Default::default()
+    }
+}
+
 #[derive(Debug, Clone)]
 pub struct ErrorMessagePrompt {
     message: SharedString,

crates/workspace/src/pane.rs 🔗

@@ -1,7 +1,7 @@
 use crate::{
     CloseWindow, NewFile, NewTerminal, OpenInTerminal, OpenOptions, OpenTerminal, OpenVisible,
     SplitDirection, ToggleFileFinder, ToggleProjectSymbols, ToggleZoom, Workspace,
-    WorkspaceItemBuilder,
+    WorkspaceItemBuilder, ZoomIn, ZoomOut,
     invalid_item_view::InvalidItemView,
     item::{
         ActivateOnClose, ClosePosition, Item, ItemBufferKind, ItemHandle, ItemSettings,
@@ -11,10 +11,12 @@ use crate::{
     move_item,
     notifications::NotifyResultExt,
     toolbar::Toolbar,
+    utility_pane::UtilityPaneSlot,
     workspace_settings::{AutosaveSetting, TabBarSettings, WorkspaceSettings},
 };
 use anyhow::Result;
 use collections::{BTreeSet, HashMap, HashSet, VecDeque};
+use feature_flags::{AgentV2FeatureFlag, FeatureFlagAppExt};
 use futures::{StreamExt, stream::FuturesUnordered};
 use gpui::{
     Action, AnyElement, App, AsyncWindowContext, ClickEvent, ClipboardItem, Context, Corner, Div,
@@ -45,10 +47,9 @@ use std::{
 };
 use theme::ThemeSettings;
 use ui::{
-    ButtonSize, Color, ContextMenu, ContextMenuEntry, ContextMenuItem, DecoratedIcon, IconButton,
-    IconButtonShape, IconDecoration, IconDecorationKind, IconName, IconSize, Indicator, Label,
-    PopoverMenu, PopoverMenuHandle, Tab, TabBar, TabPosition, Tooltip, prelude::*,
-    right_click_menu,
+    ContextMenu, ContextMenuEntry, ContextMenuItem, DecoratedIcon, IconButtonShape, IconDecoration,
+    IconDecorationKind, Indicator, PopoverMenu, PopoverMenuHandle, Tab, TabBar, TabPosition,
+    Tooltip, prelude::*, right_click_menu,
 };
 use util::{ResultExt, debug_panic, maybe, paths::PathStyle, truncate_and_remove_front};
 
@@ -196,6 +197,41 @@ pub struct DeploySearch {
     pub excluded_files: Option<String>,
 }
 
+#[derive(Clone, Copy, PartialEq, Debug, Deserialize, JsonSchema, Default)]
+#[serde(deny_unknown_fields)]
+pub enum SplitMode {
+    /// Clone the current pane.
+    #[default]
+    ClonePane,
+    /// Create an empty new pane.
+    EmptyPane,
+    /// Move the item into a new pane. This will map to nop if only one pane exists.
+    MovePane,
+}
+
+macro_rules! split_structs {
+    ($($name:ident => $doc:literal),* $(,)?) => {
+        $(
+            #[doc = $doc]
+            #[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Default, Action)]
+            #[action(namespace = pane)]
+            #[serde(deny_unknown_fields, default)]
+            pub struct $name {
+                pub mode: SplitMode,
+            }
+        )*
+    };
+}
+
+split_structs!(
+    SplitLeft => "Splits the pane to the left.",
+    SplitRight => "Splits the pane to the right.",
+    SplitUp => "Splits the pane upward.",
+    SplitDown => "Splits the pane downward.",
+    SplitHorizontal => "Splits the pane horizontally.",
+    SplitVertical => "Splits the pane vertically."
+);
+
 actions!(
     pane,
     [
@@ -217,14 +253,6 @@ actions!(
         JoinAll,
         /// Reopens the most recently closed item.
         ReopenClosedItem,
-        /// Splits the pane to the left, cloning the current item.
-        SplitLeft,
-        /// Splits the pane upward, cloning the current item.
-        SplitUp,
-        /// Splits the pane to the right, cloning the current item.
-        SplitRight,
-        /// Splits the pane downward, cloning the current item.
-        SplitDown,
         /// Splits the pane to the left, moving the current item.
         SplitAndMoveLeft,
         /// Splits the pane upward, moving the current item.
@@ -233,10 +261,6 @@ actions!(
         SplitAndMoveRight,
         /// Splits the pane downward, moving the current item.
         SplitAndMoveDown,
-        /// Splits the pane horizontally.
-        SplitHorizontal,
-        /// Splits the pane vertically.
-        SplitVertical,
         /// Swaps the current item with the one to the left.
         SwapItemLeft,
         /// Swaps the current item with the one to the right.
@@ -278,7 +302,7 @@ pub enum Event {
     },
     Split {
         direction: SplitDirection,
-        clone_active_item: bool,
+        mode: SplitMode,
     },
     ItemPinned,
     ItemUnpinned,
@@ -310,13 +334,10 @@ impl fmt::Debug for Event {
                 .debug_struct("RemovedItem")
                 .field("item", &item.item_id())
                 .finish(),
-            Event::Split {
-                direction,
-                clone_active_item,
-            } => f
+            Event::Split { direction, mode } => f
                 .debug_struct("Split")
                 .field("direction", direction)
-                .field("clone_active_item", clone_active_item)
+                .field("mode", mode)
                 .finish(),
             Event::JoinAll => f.write_str("JoinAll"),
             Event::JoinIntoNext => f.write_str("JoinIntoNext"),
@@ -396,6 +417,11 @@ pub struct Pane {
     diagnostic_summary_update: Task<()>,
     /// If a certain project item wants to get recreated with specific data, it can persist its data before the recreation here.
     pub project_item_restoration_data: HashMap<ProjectItemKind, Box<dyn Any + Send>>,
+    welcome_page: Option<Entity<crate::welcome::WelcomePage>>,
+
+    pub in_center_group: bool,
+    pub is_upper_left: bool,
+    pub is_upper_right: bool,
 }
 
 pub struct ActivationHistoryEntry {
@@ -540,6 +566,10 @@ impl Pane {
             zoom_out_on_close: true,
             diagnostic_summary_update: Task::ready(()),
             project_item_restoration_data: HashMap::default(),
+            welcome_page: None,
+            in_center_group: false,
+            is_upper_left: false,
+            is_upper_right: false,
         }
     }
 
@@ -615,17 +645,21 @@ impl Pane {
                     self.last_focus_handle_by_item.get(&active_item.item_id())
                     && let Some(focus_handle) = weak_last_focus_handle.upgrade()
                 {
-                    focus_handle.focus(window);
+                    focus_handle.focus(window, cx);
                     return;
                 }
 
-                active_item.item_focus_handle(cx).focus(window);
+                active_item.item_focus_handle(cx).focus(window, cx);
             } else if let Some(focused) = window.focused(cx)
                 && !self.context_menu_focused(window, cx)
             {
                 self.last_focus_handle_by_item
                     .insert(active_item.item_id(), focused.downgrade());
             }
+        } else if let Some(welcome_page) = self.welcome_page.as_ref() {
+            if self.focus_handle.is_focused(window) {
+                welcome_page.read(cx).focus_handle(cx).focus(window, cx);
+            }
         }
     }
 
@@ -873,10 +907,35 @@ impl Pane {
         self.preview_item_id == Some(item_id)
     }
 
+    /// Promotes the item with the given ID to not be a preview item.
+    /// This does nothing if it wasn't already a preview item.
+    pub fn unpreview_item_if_preview(&mut self, item_id: EntityId) {
+        if self.is_active_preview_item(item_id) {
+            self.preview_item_id = None;
+        }
+    }
+
     /// Marks the item with the given ID as the preview item.
     /// This will be ignored if the global setting `preview_tabs` is disabled.
-    pub fn set_preview_item_id(&mut self, item_id: Option<EntityId>, cx: &App) {
-        if PreviewTabsSettings::get_global(cx).enabled {
+    ///
+    /// The old preview item (if there was one) is closed and its index is returned.
+    pub fn replace_preview_item_id(
+        &mut self,
+        item_id: EntityId,
+        window: &mut Window,
+        cx: &mut Context<Self>,
+    ) -> Option<usize> {
+        let idx = self.close_current_preview_item(window, cx);
+        self.set_preview_item_id(Some(item_id), cx);
+        idx
+    }
+
+    /// Marks the item with the given ID as the preview item.
+    /// This will be ignored if the global setting `preview_tabs` is disabled.
+    ///
+    /// This is a low-level method. Prefer `unpreview_item_if_preview()` or `set_new_preview_item()`.
+    pub(crate) fn set_preview_item_id(&mut self, item_id: Option<EntityId>, cx: &App) {
+        if item_id.is_none() || PreviewTabsSettings::get_global(cx).enabled {
             self.preview_item_id = item_id;
         }
     }
@@ -895,7 +954,7 @@ impl Pane {
             && preview_item.item_id() == item_id
             && !preview_item.preserve_preview(cx)
         {
-            self.set_preview_item_id(None, cx);
+            self.unpreview_item_if_preview(item_id);
         }
     }
 
@@ -936,14 +995,8 @@ impl Pane {
 
         let set_up_existing_item =
             |index: usize, pane: &mut Self, window: &mut Window, cx: &mut Context<Self>| {
-                // If the item is already open, and the item is a preview item
-                // and we are not allowing items to open as preview, mark the item as persistent.
-                if let Some(preview_item_id) = pane.preview_item_id
-                    && let Some(tab) = pane.items.get(index)
-                    && tab.item_id() == preview_item_id
-                    && !allow_preview
-                {
-                    pane.set_preview_item_id(None, cx);
+                if !allow_preview && let Some(item) = pane.items.get(index) {
+                    pane.unpreview_item_if_preview(item.item_id());
                 }
                 if activate {
                     pane.activate_item(index, focus_item, focus_item, window, cx);
@@ -955,7 +1008,7 @@ impl Pane {
                                window: &mut Window,
                                cx: &mut Context<Self>| {
             if allow_preview {
-                pane.set_preview_item_id(Some(new_item.item_id()), cx);
+                pane.replace_preview_item_id(new_item.item_id(), window, cx);
             }
 
             if let Some(text) = new_item.telemetry_event_text(cx) {
@@ -1036,6 +1089,7 @@ impl Pane {
     ) -> Option<usize> {
         let item_idx = self.preview_item_idx()?;
         let id = self.preview_item_id()?;
+        self.set_preview_item_id(None, cx);
 
         let prev_active_item_index = self.active_item_index;
         self.remove_item(id, false, false, window, cx);
@@ -1277,6 +1331,25 @@ impl Pane {
         }
     }
 
+    pub fn zoom_in(&mut self, _: &ZoomIn, window: &mut Window, cx: &mut Context<Self>) {
+        if !self.can_toggle_zoom {
+            cx.propagate();
+        } else if !self.zoomed && !self.items.is_empty() {
+            if !self.focus_handle.contains_focused(window, cx) {
+                cx.focus_self(window);
+            }
+            cx.emit(Event::ZoomIn);
+        }
+    }
+
+    pub fn zoom_out(&mut self, _: &ZoomOut, _window: &mut Window, cx: &mut Context<Self>) {
+        if !self.can_toggle_zoom {
+            cx.propagate();
+        } else if self.zoomed {
+            cx.emit(Event::ZoomOut);
+        }
+    }
+
     pub fn activate_item(
         &mut self,
         index: usize,
@@ -1793,6 +1866,7 @@ impl Pane {
             }
 
             for item_to_close in items_to_close {
+                let mut should_close = true;
                 let mut should_save = true;
                 if save_intent == SaveIntent::Close {
                     workspace.update(cx, |workspace, cx| {
@@ -1808,7 +1882,7 @@ impl Pane {
                     {
                         Ok(success) => {
                             if !success {
-                                break;
+                                should_close = false;
                             }
                         }
                         Err(err) => {
@@ -1827,23 +1901,25 @@ impl Pane {
                             })?;
                             match answer.await {
                                 Ok(0) => {}
-                                Ok(1..) | Err(_) => break,
+                                Ok(1..) | Err(_) => should_close = false,
                             }
                         }
                     }
                 }
 
                 // Remove the item from the pane.
-                pane.update_in(cx, |pane, window, cx| {
-                    pane.remove_item(
-                        item_to_close.item_id(),
-                        false,
-                        pane.close_pane_if_empty,
-                        window,
-                        cx,
-                    );
-                })
-                .ok();
+                if should_close {
+                    pane.update_in(cx, |pane, window, cx| {
+                        pane.remove_item(
+                            item_to_close.item_id(),
+                            false,
+                            pane.close_pane_if_empty,
+                            window,
+                            cx,
+                        );
+                    })
+                    .ok();
+                }
             }
 
             pane.update(cx, |_, cx| cx.notify()).ok();
@@ -1946,7 +2022,7 @@ impl Pane {
 
             let should_activate = activate_pane || self.has_focus(window, cx);
             if self.items.len() == 1 && should_activate {
-                self.focus_handle.focus(window);
+                self.focus_handle.focus(window, cx);
             } else {
                 self.activate_item(
                     index_to_activate,
@@ -1981,9 +2057,7 @@ impl Pane {
         item.on_removed(cx);
         self.nav_history.set_mode(mode);
 
-        if self.is_active_preview_item(item.item_id()) {
-            self.set_preview_item_id(None, cx);
-        }
+        self.unpreview_item_if_preview(item.item_id());
 
         if let Some(path) = item.project_path(cx) {
             let abs_path = self
@@ -2194,9 +2268,7 @@ impl Pane {
 
             if can_save {
                 pane.update_in(cx, |pane, window, cx| {
-                    if pane.is_active_preview_item(item.item_id()) {
-                        pane.set_preview_item_id(None, cx);
-                    }
+                    pane.unpreview_item_if_preview(item.item_id());
                     item.save(
                         SaveOptions {
                             format: should_format,
@@ -2243,10 +2315,7 @@ impl Pane {
                 let save_task = if let Some(project_path) = project_path {
                     let (worktree, path) = project_path.await?;
                     let worktree_id = worktree.read_with(cx, |worktree, _| worktree.id())?;
-                    let new_path = ProjectPath {
-                        worktree_id,
-                        path: path,
-                    };
+                    let new_path = ProjectPath { worktree_id, path };
 
                     pane.update_in(cx, |pane, window, cx| {
                         if let Some(item) = pane.item_for_path(new_path.clone(), cx) {
@@ -2301,23 +2370,34 @@ impl Pane {
     pub fn focus_active_item(&mut self, window: &mut Window, cx: &mut Context<Self>) {
         if let Some(active_item) = self.active_item() {
             let focus_handle = active_item.item_focus_handle(cx);
-            window.focus(&focus_handle);
+            window.focus(&focus_handle, cx);
         }
     }
 
-    pub fn split(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
-        cx.emit(Event::Split {
-            direction,
-            clone_active_item: true,
-        });
-    }
-
-    pub fn split_and_move(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
-        if self.items.len() > 1 {
+    pub fn split(
+        &mut self,
+        direction: SplitDirection,
+        mode: SplitMode,
+        window: &mut Window,
+        cx: &mut Context<Self>,
+    ) {
+        if self.items.len() <= 1 && mode == SplitMode::MovePane {
+            // MovePane with only one pane present behaves like a SplitEmpty in the opposite direction
+            let active_item = self.active_item();
             cx.emit(Event::Split {
-                direction,
-                clone_active_item: false,
+                direction: direction.opposite(),
+                mode: SplitMode::EmptyPane,
             });
+            // ensure that we focus the moved pane
+            // in this case we know that the window is the same as the active_item
+            if let Some(active_item) = active_item {
+                cx.defer_in(window, move |_, window, cx| {
+                    let focus_handle = active_item.item_focus_handle(cx);
+                    window.focus(&focus_handle, cx);
+                });
+            }
+        } else {
+            cx.emit(Event::Split { direction, mode });
         }
     }
 
@@ -2450,8 +2530,8 @@ impl Pane {
             let id = self.item_for_index(ix)?.item_id();
             let should_activate = ix == self.active_item_index;
 
-            if matches!(operation, PinOperation::Pin) && self.is_active_preview_item(id) {
-                self.set_preview_item_id(None, cx);
+            if matches!(operation, PinOperation::Pin) {
+                self.unpreview_item_if_preview(id);
             }
 
             match operation {
@@ -2591,6 +2671,7 @@ impl Pane {
         let close_side = &settings.close_position;
         let show_close_button = &settings.show_close_button;
         let indicator = render_item_indicator(item.boxed_clone(), cx);
+        let tab_tooltip_content = item.tab_tooltip_content(cx);
         let item_id = item.item_id();
         let is_first_item = ix == 0;
         let is_last_item = ix == self.items.len() - 1;
@@ -2623,12 +2704,9 @@ impl Pane {
             )
             .on_mouse_down(
                 MouseButton::Left,
-                cx.listener(move |pane, event: &MouseDownEvent, _, cx| {
-                    if let Some(id) = pane.preview_item_id
-                        && id == item_id
-                        && event.click_count > 1
-                    {
-                        pane.set_preview_item_id(None, cx);
+                cx.listener(move |pane, event: &MouseDownEvent, _, _| {
+                    if event.click_count > 1 {
+                        pane.unpreview_item_if_preview(item_id);
                     }
                 }),
             )
@@ -2678,12 +2756,6 @@ impl Pane {
                 this.drag_split_direction = None;
                 this.handle_external_paths_drop(paths, window, cx)
             }))
-            .when_some(item.tab_tooltip_content(cx), |tab, content| match content {
-                TabTooltipContent::Text(text) => tab.tooltip(Tooltip::text(text)),
-                TabTooltipContent::Custom(element_fn) => {
-                    tab.tooltip(move |window, cx| element_fn(window, cx))
-                }
-            })
             .start_slot::<Indicator>(indicator)
             .map(|this| {
                 let end_slot_action: &'static dyn Action;
@@ -2750,7 +2822,15 @@ impl Pane {
                         })
                         .flatten(),
                     )
-                    .child(label),
+                    .child(label)
+                    .id(("pane-tab-content", ix))
+                    .map(|this| match tab_tooltip_content {
+                        Some(TabTooltipContent::Text(text)) => this.tooltip(Tooltip::text(text)),
+                        Some(TabTooltipContent::Custom(element_fn)) => {
+                            this.tooltip(move |window, cx| element_fn(window, cx))
+                        }
+                        None => this,
+                    }),
             );
 
         let single_entry_to_resolve = (self.items[ix].buffer_kind(cx) == ItemBufferKind::Singleton)
@@ -3017,7 +3097,13 @@ impl Pane {
     }
 
     fn render_tab_bar(&mut self, window: &mut Window, cx: &mut Context<Pane>) -> AnyElement {
+        let Some(workspace) = self.workspace.upgrade() else {
+            return gpui::Empty.into_any();
+        };
+
         let focus_handle = self.focus_handle.clone();
+        let is_pane_focused = self.has_focus(window, cx);
+
         let navigate_backward = IconButton::new("navigate_backward", IconName::ArrowLeft)
             .icon_size(IconSize::Small)
             .on_click({
@@ -3041,6 +3127,70 @@ impl Pane {
                 }
             });
 
+        let open_aside_left = {
+            let workspace = workspace.read(cx);
+            workspace.utility_pane(UtilityPaneSlot::Left).map(|pane| {
+                let toggle_icon = pane.toggle_icon(cx);
+                let workspace_handle = self.workspace.clone();
+
+                h_flex()
+                    .h_full()
+                    .pr_1p5()
+                    .border_r_1()
+                    .border_color(cx.theme().colors().border)
+                    .child(
+                        IconButton::new("open_aside_left", toggle_icon)
+                            .icon_size(IconSize::Small)
+                            .tooltip(Tooltip::text("Toggle Agent Pane")) // TODO: Probably want to make this generic
+                            .on_click(move |_, window, cx| {
+                                workspace_handle
+                                    .update(cx, |workspace, cx| {
+                                        workspace.toggle_utility_pane(
+                                            UtilityPaneSlot::Left,
+                                            window,
+                                            cx,
+                                        )
+                                    })
+                                    .ok();
+                            }),
+                    )
+                    .into_any_element()
+            })
+        };
+
+        let open_aside_right = {
+            let workspace = workspace.read(cx);
+            workspace.utility_pane(UtilityPaneSlot::Right).map(|pane| {
+                let toggle_icon = pane.toggle_icon(cx);
+                let workspace_handle = self.workspace.clone();
+
+                h_flex()
+                    .h_full()
+                    .when(is_pane_focused, |this| {
+                        this.pl(DynamicSpacing::Base04.rems(cx))
+                            .border_l_1()
+                            .border_color(cx.theme().colors().border)
+                    })
+                    .child(
+                        IconButton::new("open_aside_right", toggle_icon)
+                            .icon_size(IconSize::Small)
+                            .tooltip(Tooltip::text("Toggle Agent Pane")) // TODO: Probably want to make this generic
+                            .on_click(move |_, window, cx| {
+                                workspace_handle
+                                    .update(cx, |workspace, cx| {
+                                        workspace.toggle_utility_pane(
+                                            UtilityPaneSlot::Right,
+                                            window,
+                                            cx,
+                                        )
+                                    })
+                                    .ok();
+                            }),
+                    )
+                    .into_any_element()
+            })
+        };
+
         let navigate_forward = IconButton::new("navigate_forward", IconName::ArrowRight)
             .icon_size(IconSize::Small)
             .on_click({
@@ -3087,7 +3237,44 @@ impl Pane {
         let unpinned_tabs = tab_items.split_off(self.pinned_tab_count);
         let pinned_tabs = tab_items;
 
+        let render_aside_toggle_left = cx.has_flag::<AgentV2FeatureFlag>()
+            && self
+                .is_upper_left
+                .then(|| {
+                    self.workspace.upgrade().and_then(|entity| {
+                        let workspace = entity.read(cx);
+                        workspace
+                            .utility_pane(UtilityPaneSlot::Left)
+                            .map(|pane| !pane.expanded(cx))
+                    })
+                })
+                .flatten()
+                .unwrap_or(false);
+
+        let render_aside_toggle_right = cx.has_flag::<AgentV2FeatureFlag>()
+            && self
+                .is_upper_right
+                .then(|| {
+                    self.workspace.upgrade().and_then(|entity| {
+                        let workspace = entity.read(cx);
+                        workspace
+                            .utility_pane(UtilityPaneSlot::Right)
+                            .map(|pane| !pane.expanded(cx))
+                    })
+                })
+                .flatten()
+                .unwrap_or(false);
+
         TabBar::new("tab_bar")
+            .map(|tab_bar| {
+                if let Some(open_aside_left) = open_aside_left
+                    && render_aside_toggle_left
+                {
+                    tab_bar.start_child(open_aside_left)
+                } else {
+                    tab_bar
+                }
+            })
             .when(
                 self.display_nav_history_buttons.unwrap_or_default(),
                 |tab_bar| {
@@ -3180,6 +3367,15 @@ impl Pane {
                             })),
                     ),
             )
+            .map(|tab_bar| {
+                if let Some(open_aside_right) = open_aside_right
+                    && render_aside_toggle_right
+                {
+                    tab_bar.end_child(open_aside_right)
+                } else {
+                    tab_bar
+                }
+            })
             .into_any_element()
     }
 
@@ -3269,11 +3465,7 @@ impl Pane {
         let mut to_pane = cx.entity();
         let split_direction = self.drag_split_direction;
         let item_id = dragged_tab.item.item_id();
-        if let Some(preview_item_id) = self.preview_item_id
-            && item_id == preview_item_id
-        {
-            self.set_preview_item_id(None, cx);
-        }
+        self.unpreview_item_if_preview(item_id);
 
         let is_clone = cfg!(target_os = "macos") && window.modifiers().alt
             || cfg!(not(target_os = "macos")) && window.modifiers().control;
@@ -3660,16 +3852,17 @@ fn default_render_tab_bar_buttons(
                 .with_handle(pane.split_item_context_menu_handle.clone())
                 .menu(move |window, cx| {
                     ContextMenu::build(window, cx, |menu, _, _| {
+                        let mode = SplitMode::MovePane;
                         if can_split_move {
-                            menu.action("Split Right", SplitAndMoveRight.boxed_clone())
-                                .action("Split Left", SplitAndMoveLeft.boxed_clone())
-                                .action("Split Up", SplitAndMoveUp.boxed_clone())
-                                .action("Split Down", SplitAndMoveDown.boxed_clone())
+                            menu.action("Split Right", SplitRight { mode }.boxed_clone())
+                                .action("Split Left", SplitLeft { mode }.boxed_clone())
+                                .action("Split Up", SplitUp { mode }.boxed_clone())
+                                .action("Split Down", SplitDown { mode }.boxed_clone())
                         } else {
-                            menu.action("Split Right", SplitRight.boxed_clone())
-                                .action("Split Left", SplitLeft.boxed_clone())
-                                .action("Split Up", SplitUp.boxed_clone())
-                                .action("Split Down", SplitDown.boxed_clone())
+                            menu.action("Split Right", SplitRight::default().boxed_clone())
+                                .action("Split Left", SplitLeft::default().boxed_clone())
+                                .action("Split Up", SplitUp::default().boxed_clone())
+                                .action("Split Down", SplitDown::default().boxed_clone())
                         }
                     })
                     .into()
@@ -3728,33 +3921,35 @@ impl Render for Pane {
             .size_full()
             .flex_none()
             .overflow_hidden()
-            .on_action(
-                cx.listener(|pane, _: &SplitLeft, _, cx| pane.split(SplitDirection::Left, cx)),
-            )
-            .on_action(cx.listener(|pane, _: &SplitUp, _, cx| pane.split(SplitDirection::Up, cx)))
-            .on_action(cx.listener(|pane, _: &SplitHorizontal, _, cx| {
-                pane.split(SplitDirection::horizontal(cx), cx)
+            .on_action(cx.listener(|pane, split: &SplitLeft, window, cx| {
+                pane.split(SplitDirection::Left, split.mode, window, cx)
             }))
-            .on_action(cx.listener(|pane, _: &SplitVertical, _, cx| {
-                pane.split(SplitDirection::vertical(cx), cx)
+            .on_action(cx.listener(|pane, split: &SplitUp, window, cx| {
+                pane.split(SplitDirection::Up, split.mode, window, cx)
             }))
-            .on_action(
-                cx.listener(|pane, _: &SplitRight, _, cx| pane.split(SplitDirection::Right, cx)),
-            )
-            .on_action(
-                cx.listener(|pane, _: &SplitDown, _, cx| pane.split(SplitDirection::Down, cx)),
-            )
-            .on_action(cx.listener(|pane, _: &SplitAndMoveUp, _, cx| {
-                pane.split_and_move(SplitDirection::Up, cx)
+            .on_action(cx.listener(|pane, split: &SplitHorizontal, window, cx| {
+                pane.split(SplitDirection::horizontal(cx), split.mode, window, cx)
+            }))
+            .on_action(cx.listener(|pane, split: &SplitVertical, window, cx| {
+                pane.split(SplitDirection::vertical(cx), split.mode, window, cx)
+            }))
+            .on_action(cx.listener(|pane, split: &SplitRight, window, cx| {
+                pane.split(SplitDirection::Right, split.mode, window, cx)
+            }))
+            .on_action(cx.listener(|pane, split: &SplitDown, window, cx| {
+                pane.split(SplitDirection::Down, split.mode, window, cx)
             }))
-            .on_action(cx.listener(|pane, _: &SplitAndMoveDown, _, cx| {
-                pane.split_and_move(SplitDirection::Down, cx)
+            .on_action(cx.listener(|pane, _: &SplitAndMoveUp, window, cx| {
+                pane.split(SplitDirection::Up, SplitMode::MovePane, window, cx)
             }))
-            .on_action(cx.listener(|pane, _: &SplitAndMoveLeft, _, cx| {
-                pane.split_and_move(SplitDirection::Left, cx)
+            .on_action(cx.listener(|pane, _: &SplitAndMoveDown, window, cx| {
+                pane.split(SplitDirection::Down, SplitMode::MovePane, window, cx)
             }))
-            .on_action(cx.listener(|pane, _: &SplitAndMoveRight, _, cx| {
-                pane.split_and_move(SplitDirection::Right, cx)
+            .on_action(cx.listener(|pane, _: &SplitAndMoveLeft, window, cx| {
+                pane.split(SplitDirection::Left, SplitMode::MovePane, window, cx)
+            }))
+            .on_action(cx.listener(|pane, _: &SplitAndMoveRight, window, cx| {
+                pane.split(SplitDirection::Right, SplitMode::MovePane, window, cx)
             }))
             .on_action(cx.listener(|_, _: &JoinIntoNext, _, cx| {
                 cx.emit(Event::JoinIntoNext);
@@ -3763,6 +3958,8 @@ impl Render for Pane {
                 cx.emit(Event::JoinAll);
             }))
             .on_action(cx.listener(Pane::toggle_zoom))
+            .on_action(cx.listener(Pane::zoom_in))
+            .on_action(cx.listener(Pane::zoom_out))
             .on_action(cx.listener(Self::navigate_backward))
             .on_action(cx.listener(Self::navigate_forward))
             .on_action(
@@ -3785,15 +3982,17 @@ impl Render for Pane {
             .on_action(cx.listener(Self::toggle_pin_tab))
             .on_action(cx.listener(Self::unpin_all_tabs))
             .when(PreviewTabsSettings::get_global(cx).enabled, |this| {
-                this.on_action(cx.listener(|pane: &mut Pane, _: &TogglePreviewTab, _, cx| {
-                    if let Some(active_item_id) = pane.active_item().map(|i| i.item_id()) {
-                        if pane.is_active_preview_item(active_item_id) {
-                            pane.set_preview_item_id(None, cx);
-                        } else {
-                            pane.set_preview_item_id(Some(active_item_id), cx);
+                this.on_action(
+                    cx.listener(|pane: &mut Pane, _: &TogglePreviewTab, window, cx| {
+                        if let Some(active_item_id) = pane.active_item().map(|i| i.item_id()) {
+                            if pane.is_active_preview_item(active_item_id) {
+                                pane.unpreview_item_if_preview(active_item_id);
+                            } else {
+                                pane.replace_preview_item_id(active_item_id, window, cx);
+                            }
                         }
-                    }
-                }))
+                    }),
+                )
             })
             .on_action(
                 cx.listener(|pane: &mut Self, action: &CloseActiveItem, window, cx| {
@@ -3901,10 +4100,15 @@ impl Render for Pane {
                             if has_worktrees {
                                 placeholder
                             } else {
-                                placeholder.child(
-                                    Label::new("Open a file or project to get started.")
-                                        .color(Color::Muted),
-                                )
+                                if self.welcome_page.is_none() {
+                                    let workspace = self.workspace.clone();
+                                    self.welcome_page = Some(cx.new(|cx| {
+                                        crate::welcome::WelcomePage::new(
+                                            workspace, true, window, cx,
+                                        )
+                                    }));
+                                }
+                                placeholder.child(self.welcome_page.clone().unwrap())
                             }
                         }
                     })
@@ -4270,11 +4474,14 @@ impl Render for DraggedTab {
 
 #[cfg(test)]
 mod tests {
-    use std::num::NonZero;
+    use std::{iter::zip, num::NonZero};
 
     use super::*;
-    use crate::item::test::{TestItem, TestProjectItem};
-    use gpui::{TestAppContext, VisualTestContext, size};
+    use crate::{
+        Member,
+        item::test::{TestItem, TestProjectItem},
+    };
+    use gpui::{AppContext, Axis, TestAppContext, VisualTestContext, size};
     use project::FakeFs;
     use settings::SettingsStore;
     use theme::LoadThemes;
@@ -6444,6 +6651,60 @@ mod tests {
         cx.simulate_prompt_answer("Discard all");
         save.await.unwrap();
         assert_item_labels(&pane, [], cx);
+
+        add_labeled_item(&pane, "A", true, cx).update(cx, |item, cx| {
+            item.project_items
+                .push(TestProjectItem::new_dirty(1, "A.txt", cx))
+        });
+        add_labeled_item(&pane, "B", true, cx).update(cx, |item, cx| {
+            item.project_items
+                .push(TestProjectItem::new_dirty(2, "B.txt", cx))
+        });
+        add_labeled_item(&pane, "C", true, cx).update(cx, |item, cx| {
+            item.project_items
+                .push(TestProjectItem::new_dirty(3, "C.txt", cx))
+        });
+        assert_item_labels(&pane, ["A^", "B^", "C*^"], cx);
+
+        let close_task = pane.update_in(cx, |pane, window, cx| {
+            pane.close_all_items(
+                &CloseAllItems {
+                    save_intent: None,
+                    close_pinned: false,
+                },
+                window,
+                cx,
+            )
+        });
+
+        cx.executor().run_until_parked();
+        cx.simulate_prompt_answer("Discard all");
+        close_task.await.unwrap();
+        assert_item_labels(&pane, [], cx);
+
+        add_labeled_item(&pane, "Clean1", false, cx);
+        add_labeled_item(&pane, "Dirty", true, cx).update(cx, |item, cx| {
+            item.project_items
+                .push(TestProjectItem::new_dirty(1, "Dirty.txt", cx))
+        });
+        add_labeled_item(&pane, "Clean2", false, cx);
+        assert_item_labels(&pane, ["Clean1", "Dirty^", "Clean2*"], cx);
+
+        let close_task = pane.update_in(cx, |pane, window, cx| {
+            pane.close_all_items(
+                &CloseAllItems {
+                    save_intent: None,
+                    close_pinned: false,
+                },
+                window,
+                cx,
+            )
+        });
+
+        cx.executor().run_until_parked();
+        cx.simulate_prompt_answer("Cancel");
+        close_task.await.unwrap();
+        assert_item_labels(&pane, ["Dirty*^"], cx);
     }
 
     #[gpui::test]
@@ -6645,13 +6906,13 @@ mod tests {
         let tab_bar_scroll_handle =
             pane.update_in(cx, |pane, _window, _cx| pane.tab_bar_scroll_handle.clone());
         assert_eq!(tab_bar_scroll_handle.children_count(), 6);
-        let tab_bounds = cx.debug_bounds("TAB-3").unwrap();
+        let tab_bounds = cx.debug_bounds("TAB-4").unwrap();
         let new_tab_button_bounds = cx.debug_bounds("ICON-Plus").unwrap();
         let scroll_bounds = tab_bar_scroll_handle.bounds();
         let scroll_offset = tab_bar_scroll_handle.offset();
-        assert!(tab_bounds.right() <= scroll_bounds.right() + scroll_offset.x);
-        // -39.5 is the magic number for this setup
-        assert_eq!(scroll_offset.x, px(-39.5));
+        assert!(tab_bounds.right() <= scroll_bounds.right());
+        // -43.0 is the magic number for this setup
+        assert_eq!(scroll_offset.x, px(-43.0));
         assert!(
             !tab_bounds.intersects(&new_tab_button_bounds),
             "Tab should not overlap with the new tab button, if this is failing check if there's been a redesign!"
@@ -6898,6 +7159,32 @@ mod tests {
         assert_item_labels(&pane, ["A", "C*", "B"], cx);
     }
 
+    #[gpui::test]
+    async fn test_split_empty(cx: &mut TestAppContext) {
+        for split_direction in SplitDirection::all() {
+            test_single_pane_split(["A"], split_direction, SplitMode::EmptyPane, cx).await;
+        }
+    }
+
+    #[gpui::test]
+    async fn test_split_clone(cx: &mut TestAppContext) {
+        for split_direction in SplitDirection::all() {
+            test_single_pane_split(["A"], split_direction, SplitMode::ClonePane, cx).await;
+        }
+    }
+
+    #[gpui::test]
+    async fn test_split_move_right_on_single_pane(cx: &mut TestAppContext) {
+        test_single_pane_split(["A"], SplitDirection::Right, SplitMode::MovePane, cx).await;
+    }
+
+    #[gpui::test]
+    async fn test_split_move(cx: &mut TestAppContext) {
+        for split_direction in SplitDirection::all() {
+            test_single_pane_split(["A", "B"], split_direction, SplitMode::MovePane, cx).await;
+        }
+    }
+
     fn init_test(cx: &mut TestAppContext) {
         cx.update(|cx| {
             let settings_store = SettingsStore::test(cx);
@@ -6993,4 +7280,163 @@ mod tests {
             "pane items do not match expectation"
         );
     }
+
+    // Assert the item label, with the active item label expected active index
+    #[track_caller]
+    fn assert_item_labels_active_index(
+        pane: &Entity<Pane>,
+        expected_states: &[&str],
+        expected_active_idx: usize,
+        cx: &mut VisualTestContext,
+    ) {
+        let actual_states = pane.update(cx, |pane, cx| {
+            pane.items
+                .iter()
+                .enumerate()
+                .map(|(ix, item)| {
+                    let mut state = item
+                        .to_any_view()
+                        .downcast::<TestItem>()
+                        .unwrap()
+                        .read(cx)
+                        .label
+                        .clone();
+                    if ix == pane.active_item_index {
+                        assert_eq!(ix, expected_active_idx);
+                    }
+                    if item.is_dirty(cx) {
+                        state.push('^');
+                    }
+                    if pane.is_tab_pinned(ix) {
+                        state.push('!');
+                    }
+                    state
+                })
+                .collect::<Vec<_>>()
+        });
+        assert_eq!(
+            actual_states, expected_states,
+            "pane items do not match expectation"
+        );
+    }
+
+    #[track_caller]
+    fn assert_pane_ids_on_axis<const COUNT: usize>(
+        workspace: &Entity<Workspace>,
+        expected_ids: [&EntityId; COUNT],
+        expected_axis: Axis,
+        cx: &mut VisualTestContext,
+    ) {
+        workspace.read_with(cx, |workspace, _| match &workspace.center.root {
+            Member::Axis(axis) => {
+                assert_eq!(axis.axis, expected_axis);
+                assert_eq!(axis.members.len(), expected_ids.len());
+                assert!(
+                    zip(expected_ids, &axis.members).all(|(e, a)| {
+                        if let Member::Pane(p) = a {
+                            p.entity_id() == *e
+                        } else {
+                            false
+                        }
+                    }),
+                    "pane ids do not match expectation: {expected_ids:?} != {actual_ids:?}",
+                    actual_ids = axis.members
+                );
+            }
+            Member::Pane(_) => panic!("expected axis"),
+        });
+    }
+
+    async fn test_single_pane_split<const COUNT: usize>(
+        pane_labels: [&str; COUNT],
+        direction: SplitDirection,
+        operation: SplitMode,
+        cx: &mut TestAppContext,
+    ) {
+        init_test(cx);
+        let fs = FakeFs::new(cx.executor());
+        let project = Project::test(fs, None, cx).await;
+        let (workspace, cx) =
+            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
+
+        let mut pane_before =
+            workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
+        for label in pane_labels {
+            add_labeled_item(&pane_before, label, false, cx);
+        }
+        pane_before.update_in(cx, |pane, window, cx| {
+            pane.split(direction, operation, window, cx)
+        });
+        cx.executor().run_until_parked();
+        let pane_after = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
+
+        let num_labels = pane_labels.len();
+        let last_as_active = format!("{}*", String::from(pane_labels[num_labels - 1]));
+
+        // check labels for all split operations
+        match operation {
+            SplitMode::EmptyPane => {
+                assert_item_labels_active_index(&pane_before, &pane_labels, num_labels - 1, cx);
+                assert_item_labels(&pane_after, [], cx);
+            }
+            SplitMode::ClonePane => {
+                assert_item_labels_active_index(&pane_before, &pane_labels, num_labels - 1, cx);
+                assert_item_labels(&pane_after, [&last_as_active], cx);
+            }
+            SplitMode::MovePane => {
+                let head = &pane_labels[..(num_labels - 1)];
+                if num_labels == 1 {
+                    // We special-case this behavior and actually execute an empty pane command
+                    // followed by a refocus of the old pane for this case.
+                    pane_before = workspace.read_with(cx, |workspace, _cx| {
+                        workspace
+                            .panes()
+                            .into_iter()
+                            .find(|pane| *pane != &pane_after)
+                            .unwrap()
+                            .clone()
+                    });
+                };
+
+                assert_item_labels_active_index(
+                    &pane_before,
+                    &head,
+                    head.len().saturating_sub(1),
+                    cx,
+                );
+                assert_item_labels(&pane_after, [&last_as_active], cx);
+                pane_after.update_in(cx, |pane, window, cx| {
+                    window.focused(cx).is_some_and(|focus_handle| {
+                        focus_handle == pane.active_item().unwrap().item_focus_handle(cx)
+                    })
+                });
+            }
+        }
+
+        // expected axis depends on split direction
+        let expected_axis = match direction {
+            SplitDirection::Right | SplitDirection::Left => Axis::Horizontal,
+            SplitDirection::Up | SplitDirection::Down => Axis::Vertical,
+        };
+
+        // expected ids depends on split direction
+        let expected_ids = match direction {
+            SplitDirection::Right | SplitDirection::Down => {
+                [&pane_before.entity_id(), &pane_after.entity_id()]
+            }
+            SplitDirection::Left | SplitDirection::Up => {
+                [&pane_after.entity_id(), &pane_before.entity_id()]
+            }
+        };
+
+        // check pane axes for all operations
+        match operation {
+            SplitMode::EmptyPane | SplitMode::ClonePane => {
+                assert_pane_ids_on_axis(&workspace, expected_ids, expected_axis, cx);
+            }
+            SplitMode::MovePane => {
+                assert_pane_ids_on_axis(&workspace, expected_ids, expected_axis, cx);
+            }
+        }
+    }
 }

crates/workspace/src/pane_group.rs 🔗

@@ -28,6 +28,7 @@ const VERTICAL_MIN_SIZE: f32 = 100.;
 #[derive(Clone)]
 pub struct PaneGroup {
     pub root: Member,
+    pub is_center: bool,
 }
 
 pub struct PaneRenderResult {
@@ -37,22 +38,31 @@ pub struct PaneRenderResult {
 
 impl PaneGroup {
     pub fn with_root(root: Member) -> Self {
-        Self { root }
+        Self {
+            root,
+            is_center: false,
+        }
     }
 
     pub fn new(pane: Entity<Pane>) -> Self {
         Self {
             root: Member::Pane(pane),
+            is_center: false,
         }
     }
 
+    pub fn set_is_center(&mut self, is_center: bool) {
+        self.is_center = is_center;
+    }
+
     pub fn split(
         &mut self,
         old_pane: &Entity<Pane>,
         new_pane: &Entity<Pane>,
         direction: SplitDirection,
+        cx: &mut App,
     ) -> Result<()> {
-        match &mut self.root {
+        let result = match &mut self.root {
             Member::Pane(pane) => {
                 if pane == old_pane {
                     self.root = Member::new_axis(old_pane.clone(), new_pane.clone(), direction);
@@ -62,7 +72,11 @@ impl PaneGroup {
                 }
             }
             Member::Axis(axis) => axis.split(old_pane, new_pane, direction),
+        };
+        if result.is_ok() {
+            self.mark_positions(cx);
         }
+        result
     }
 
     pub fn bounding_box_for_pane(&self, pane: &Entity<Pane>) -> Option<Bounds<Pixels>> {
@@ -90,6 +104,7 @@ impl PaneGroup {
         &mut self,
         active_pane: &Entity<Pane>,
         direction: SplitDirection,
+        cx: &mut App,
     ) -> Result<bool> {
         if let Some(pane) = self.find_pane_at_border(direction)
             && pane == active_pane
@@ -97,7 +112,7 @@ impl PaneGroup {
             return Ok(false);
         }
 
-        if !self.remove(active_pane)? {
+        if !self.remove_internal(active_pane)? {
             return Ok(false);
         }
 
@@ -110,6 +125,7 @@ impl PaneGroup {
                 0
             };
             root.insert_pane(idx, active_pane);
+            self.mark_positions(cx);
             return Ok(true);
         }
 
@@ -119,6 +135,7 @@ impl PaneGroup {
             vec![Member::Pane(active_pane.clone()), self.root.clone()]
         };
         self.root = Member::Axis(PaneAxis::new(direction.axis(), members));
+        self.mark_positions(cx);
         Ok(true)
     }
 
@@ -133,7 +150,15 @@ impl PaneGroup {
     /// - Ok(true) if it found and removed a pane
     /// - Ok(false) if it found but did not remove the pane
     /// - Err(_) if it did not find the pane
-    pub fn remove(&mut self, pane: &Entity<Pane>) -> Result<bool> {
+    pub fn remove(&mut self, pane: &Entity<Pane>, cx: &mut App) -> Result<bool> {
+        let result = self.remove_internal(pane);
+        if let Ok(true) = result {
+            self.mark_positions(cx);
+        }
+        result
+    }
+
+    fn remove_internal(&mut self, pane: &Entity<Pane>) -> Result<bool> {
         match &mut self.root {
             Member::Pane(_) => Ok(false),
             Member::Axis(axis) => {
@@ -151,6 +176,7 @@ impl PaneGroup {
         direction: Axis,
         amount: Pixels,
         bounds: &Bounds<Pixels>,
+        cx: &mut App,
     ) {
         match &mut self.root {
             Member::Pane(_) => {}
@@ -158,22 +184,29 @@ impl PaneGroup {
                 let _ = axis.resize(pane, direction, amount, bounds);
             }
         };
+        self.mark_positions(cx);
     }
 
-    pub fn reset_pane_sizes(&mut self) {
+    pub fn reset_pane_sizes(&mut self, cx: &mut App) {
         match &mut self.root {
             Member::Pane(_) => {}
             Member::Axis(axis) => {
                 let _ = axis.reset_pane_sizes();
             }
         };
+        self.mark_positions(cx);
     }
 
-    pub fn swap(&mut self, from: &Entity<Pane>, to: &Entity<Pane>) {
+    pub fn swap(&mut self, from: &Entity<Pane>, to: &Entity<Pane>, cx: &mut App) {
         match &mut self.root {
             Member::Pane(_) => {}
             Member::Axis(axis) => axis.swap(from, to),
         };
+        self.mark_positions(cx);
+    }
+
+    pub fn mark_positions(&mut self, cx: &mut App) {
+        self.root.mark_positions(self.is_center, true, true, cx);
     }
 
     pub fn render(
@@ -232,8 +265,9 @@ impl PaneGroup {
         self.pane_at_pixel_position(target)
     }
 
-    pub fn invert_axies(&mut self) {
+    pub fn invert_axies(&mut self, cx: &mut App) {
         self.root.invert_pane_axies();
+        self.mark_positions(cx);
     }
 }
 
@@ -243,6 +277,43 @@ pub enum Member {
     Pane(Entity<Pane>),
 }
 
+impl Member {
+    pub fn mark_positions(
+        &mut self,
+        in_center_group: bool,
+        is_upper_left: bool,
+        is_upper_right: bool,
+        cx: &mut App,
+    ) {
+        match self {
+            Member::Axis(pane_axis) => {
+                let len = pane_axis.members.len();
+                for (idx, member) in pane_axis.members.iter_mut().enumerate() {
+                    let member_upper_left = match pane_axis.axis {
+                        Axis::Vertical => is_upper_left && idx == 0,
+                        Axis::Horizontal => is_upper_left && idx == 0,
+                    };
+                    let member_upper_right = match pane_axis.axis {
+                        Axis::Vertical => is_upper_right && idx == 0,
+                        Axis::Horizontal => is_upper_right && idx == len - 1,
+                    };
+                    member.mark_positions(
+                        in_center_group,
+                        member_upper_left,
+                        member_upper_right,
+                        cx,
+                    );
+                }
+            }
+            Member::Pane(entity) => entity.update(cx, |pane, _| {
+                pane.in_center_group = in_center_group;
+                pane.is_upper_left = is_upper_left;
+                pane.is_upper_right = is_upper_right;
+            }),
+        }
+    }
+}
+
 #[derive(Clone, Copy)]
 pub struct PaneRenderContext<'a> {
     pub project: &'a Entity<Project>,

crates/workspace/src/persistence.rs 🔗

@@ -9,18 +9,25 @@ use std::{
 };
 
 use anyhow::{Context as _, Result, bail};
-use collections::{HashMap, IndexSet};
+use collections::{HashMap, HashSet, IndexSet};
 use db::{
+    kvp::KEY_VALUE_STORE,
     query,
     sqlez::{connection::Connection, domain::Domain},
     sqlez_macros::sql,
 };
-use gpui::{Axis, Bounds, Task, WindowBounds, WindowId, point, size};
-use project::debugger::breakpoint_store::{BreakpointState, SourceBreakpoint};
+use gpui::{Axis, Bounds, Entity, Task, WindowBounds, WindowId, point, size};
+use project::{
+    debugger::breakpoint_store::{BreakpointState, SourceBreakpoint},
+    trusted_worktrees::{PathTrust, RemoteHostLocation, find_worktree_in_store},
+    worktree_store::WorktreeStore,
+};
 
 use language::{LanguageName, Toolchain, ToolchainScope};
-use project::WorktreeId;
-use remote::{RemoteConnectionOptions, SshConnectionOptions, WslConnectionOptions};
+use remote::{
+    DockerConnectionOptions, RemoteConnectionOptions, SshConnectionOptions, WslConnectionOptions,
+};
+use serde::{Deserialize, Serialize};
 use sqlez::{
     bindable::{Bind, Column, StaticColumnCount},
     statement::Statement,
@@ -44,6 +51,11 @@ use model::{
 
 use self::model::{DockStructure, SerializedWorkspaceLocation};
 
+// https://www.sqlite.org/limits.html
+// > <..> the maximum value of a host parameter number is SQLITE_MAX_VARIABLE_NUMBER,
+// > which defaults to <..> 32766 for SQLite versions after 3.32.0.
+const MAX_QUERY_PLACEHOLDERS: usize = 32000;
+
 #[derive(Copy, Clone, Debug, PartialEq)]
 pub(crate) struct SerializedAxis(pub(crate) gpui::Axis);
 impl sqlez::bindable::StaticColumnCount for SerializedAxis {}
@@ -152,6 +164,124 @@ impl Column for SerializedWindowBounds {
     }
 }
 
+const DEFAULT_WINDOW_BOUNDS_KEY: &str = "default_window_bounds";
+
+pub fn read_default_window_bounds() -> Option<(Uuid, WindowBounds)> {
+    let json_str = KEY_VALUE_STORE
+        .read_kvp(DEFAULT_WINDOW_BOUNDS_KEY)
+        .log_err()
+        .flatten()?;
+
+    let (display_uuid, persisted) =
+        serde_json::from_str::<(Uuid, WindowBoundsJson)>(&json_str).ok()?;
+    Some((display_uuid, persisted.into()))
+}
+
+pub async fn write_default_window_bounds(
+    bounds: WindowBounds,
+    display_uuid: Uuid,
+) -> anyhow::Result<()> {
+    let persisted = WindowBoundsJson::from(bounds);
+    let json_str = serde_json::to_string(&(display_uuid, persisted))?;
+    KEY_VALUE_STORE
+        .write_kvp(DEFAULT_WINDOW_BOUNDS_KEY.to_string(), json_str)
+        .await?;
+    Ok(())
+}
+
+#[derive(Serialize, Deserialize)]
+pub enum WindowBoundsJson {
+    Windowed {
+        x: i32,
+        y: i32,
+        width: i32,
+        height: i32,
+    },
+    Maximized {
+        x: i32,
+        y: i32,
+        width: i32,
+        height: i32,
+    },
+    Fullscreen {
+        x: i32,
+        y: i32,
+        width: i32,
+        height: i32,
+    },
+}
+
+impl From<WindowBounds> for WindowBoundsJson {
+    fn from(b: WindowBounds) -> Self {
+        match b {
+            WindowBounds::Windowed(bounds) => {
+                let origin = bounds.origin;
+                let size = bounds.size;
+                WindowBoundsJson::Windowed {
+                    x: f32::from(origin.x).round() as i32,
+                    y: f32::from(origin.y).round() as i32,
+                    width: f32::from(size.width).round() as i32,
+                    height: f32::from(size.height).round() as i32,
+                }
+            }
+            WindowBounds::Maximized(bounds) => {
+                let origin = bounds.origin;
+                let size = bounds.size;
+                WindowBoundsJson::Maximized {
+                    x: f32::from(origin.x).round() as i32,
+                    y: f32::from(origin.y).round() as i32,
+                    width: f32::from(size.width).round() as i32,
+                    height: f32::from(size.height).round() as i32,
+                }
+            }
+            WindowBounds::Fullscreen(bounds) => {
+                let origin = bounds.origin;
+                let size = bounds.size;
+                WindowBoundsJson::Fullscreen {
+                    x: f32::from(origin.x).round() as i32,
+                    y: f32::from(origin.y).round() as i32,
+                    width: f32::from(size.width).round() as i32,
+                    height: f32::from(size.height).round() as i32,
+                }
+            }
+        }
+    }
+}
+
+impl From<WindowBoundsJson> for WindowBounds {
+    fn from(n: WindowBoundsJson) -> Self {
+        match n {
+            WindowBoundsJson::Windowed {
+                x,
+                y,
+                width,
+                height,
+            } => WindowBounds::Windowed(Bounds {
+                origin: point(px(x as f32), px(y as f32)),
+                size: size(px(width as f32), px(height as f32)),
+            }),
+            WindowBoundsJson::Maximized {
+                x,
+                y,
+                width,
+                height,
+            } => WindowBounds::Maximized(Bounds {
+                origin: point(px(x as f32), px(y as f32)),
+                size: size(px(width as f32), px(height as f32)),
+            }),
+            WindowBoundsJson::Fullscreen {
+                x,
+                y,
+                width,
+                height,
+            } => WindowBounds::Fullscreen(Bounds {
+                origin: point(px(x as f32), px(y as f32)),
+                size: size(px(width as f32), px(height as f32)),
+            }),
+        }
+    }
+}
+
 #[derive(Debug)]
 pub struct Breakpoint {
     pub position: u32,
@@ -702,6 +832,56 @@ impl Domain for WorkspaceDb {
         sql!(
             DROP TABLE ssh_connections;
         ),
+        sql!(
+            ALTER TABLE remote_connections ADD COLUMN name TEXT;
+            ALTER TABLE remote_connections ADD COLUMN container_id TEXT;
+        ),
+        sql!(
+            CREATE TABLE IF NOT EXISTS trusted_worktrees (
+                trust_id INTEGER PRIMARY KEY AUTOINCREMENT,
+                absolute_path TEXT,
+                user_name TEXT,
+                host_name TEXT
+            ) STRICT;
+        ),
+        sql!(CREATE TABLE toolchains2 (
+            workspace_id INTEGER,
+            worktree_root_path TEXT NOT NULL,
+            language_name TEXT NOT NULL,
+            name TEXT NOT NULL,
+            path TEXT NOT NULL,
+            raw_json TEXT NOT NULL,
+            relative_worktree_path TEXT NOT NULL,
+            PRIMARY KEY (workspace_id, worktree_root_path, language_name, relative_worktree_path)) STRICT;
+            INSERT OR REPLACE INTO toolchains2
+                // The `instr(paths, '\n') = 0` part allows us to find all
+                // workspaces that have a single worktree, as `\n` is used as a
+                // separator when serializing the workspace paths, so if no `\n` is
+                // found, we know we have a single worktree.
+                SELECT toolchains.workspace_id, paths, language_name, name, path, raw_json, relative_worktree_path FROM toolchains INNER JOIN workspaces ON toolchains.workspace_id = workspaces.workspace_id AND instr(paths, '\n') = 0;
+            DROP TABLE toolchains;
+            ALTER TABLE toolchains2 RENAME TO toolchains;
+        ),
+        sql!(CREATE TABLE user_toolchains2 (
+            remote_connection_id INTEGER,
+            workspace_id INTEGER NOT NULL,
+            worktree_root_path TEXT NOT NULL,
+            relative_worktree_path TEXT NOT NULL,
+            language_name TEXT NOT NULL,
+            name TEXT NOT NULL,
+            path TEXT NOT NULL,
+            raw_json TEXT NOT NULL,
+
+            PRIMARY KEY (workspace_id, worktree_root_path, relative_worktree_path, language_name, name, path, raw_json)) STRICT;
+            INSERT OR REPLACE INTO user_toolchains2
+                // The `instr(paths, '\n') = 0` part allows us to find all
+                // workspaces that have a single worktree, as `\n` is used as a
+                // separator when serializing the workspace paths, so if no `\n` is
+                // found, we know we have a single worktree.
+                SELECT user_toolchains.remote_connection_id, user_toolchains.workspace_id, paths, relative_worktree_path, language_name, name, path, raw_json  FROM user_toolchains INNER JOIN workspaces ON user_toolchains.workspace_id = workspaces.workspace_id AND instr(paths, '\n') = 0;
+            DROP TABLE user_toolchains;
+            ALTER TABLE user_toolchains2 RENAME TO user_toolchains;
+        ),
     ];
 
     // Allow recovering from bad migration that was initially shipped to nightly
@@ -728,9 +908,9 @@ impl WorkspaceDb {
     pub(crate) fn remote_workspace_for_roots<P: AsRef<Path>>(
         &self,
         worktree_roots: &[P],
-        ssh_project_id: RemoteConnectionId,
+        remote_project_id: RemoteConnectionId,
     ) -> Option<SerializedWorkspace> {
-        self.workspace_for_roots_internal(worktree_roots, Some(ssh_project_id))
+        self.workspace_for_roots_internal(worktree_roots, Some(remote_project_id))
     }
 
     pub(crate) fn workspace_for_roots_internal<P: AsRef<Path>>(
@@ -806,9 +986,20 @@ impl WorkspaceDb {
             order: paths_order,
         });
 
+        let remote_connection_options = if let Some(remote_connection_id) = remote_connection_id {
+            self.remote_connection(remote_connection_id)
+                .context("Get remote connection")
+                .log_err()
+        } else {
+            None
+        };
+
         Some(SerializedWorkspace {
             id: workspace_id,
-            location: SerializedWorkspaceLocation::Local,
+            location: match remote_connection_options {
+                Some(options) => SerializedWorkspaceLocation::Remote(options),
+                None => SerializedWorkspaceLocation::Local,
+            },
             paths,
             center_group: self
                 .get_center_pane_group(workspace_id)
@@ -876,11 +1067,11 @@ impl WorkspaceDb {
         workspace_id: WorkspaceId,
         remote_connection_id: Option<RemoteConnectionId>,
     ) -> BTreeMap<ToolchainScope, IndexSet<Toolchain>> {
-        type RowKind = (WorkspaceId, u64, String, String, String, String, String);
+        type RowKind = (WorkspaceId, String, String, String, String, String, String);
 
         let toolchains: Vec<RowKind> = self
             .select_bound(sql! {
-                SELECT workspace_id, worktree_id, relative_worktree_path,
+                SELECT workspace_id, worktree_root_path, relative_worktree_path,
                 language_name, name, path, raw_json
                 FROM user_toolchains WHERE remote_connection_id IS ?1 AND (
                       workspace_id IN (0, ?2)
@@ -894,7 +1085,7 @@ impl WorkspaceDb {
 
         for (
             _workspace_id,
-            worktree_id,
+            worktree_root_path,
             relative_worktree_path,
             language_name,
             name,
@@ -904,22 +1095,24 @@ impl WorkspaceDb {
         {
             // INTEGER's that are primary keys (like workspace ids, remote connection ids and such) start at 1, so we're safe to
             let scope = if _workspace_id == WorkspaceId(0) {
-                debug_assert_eq!(worktree_id, u64::MAX);
+                debug_assert_eq!(worktree_root_path, String::default());
                 debug_assert_eq!(relative_worktree_path, String::default());
                 ToolchainScope::Global
             } else {
                 debug_assert_eq!(workspace_id, _workspace_id);
                 debug_assert_eq!(
-                    worktree_id == u64::MAX,
+                    worktree_root_path == String::default(),
                     relative_worktree_path == String::default()
                 );
 
                 let Some(relative_path) = RelPath::unix(&relative_worktree_path).log_err() else {
                     continue;
                 };
-                if worktree_id != u64::MAX && relative_worktree_path != String::default() {
+                if worktree_root_path != String::default()
+                    && relative_worktree_path != String::default()
+                {
                     ToolchainScope::Subproject(
-                        WorktreeId::from_usize(worktree_id as usize),
+                        Arc::from(worktree_root_path.as_ref()),
                         relative_path.into(),
                     )
                 } else {
@@ -1005,13 +1198,13 @@ impl WorkspaceDb {
 
                 for (scope, toolchains) in workspace.user_toolchains {
                     for toolchain in toolchains {
-                        let query = sql!(INSERT OR REPLACE INTO user_toolchains(remote_connection_id, workspace_id, worktree_id, relative_worktree_path, language_name, name, path, raw_json) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8));
-                        let (workspace_id, worktree_id, relative_worktree_path) = match scope {
-                            ToolchainScope::Subproject(worktree_id, ref path) => (Some(workspace.id), Some(worktree_id), Some(path.as_unix_str().to_owned())),
+                        let query = sql!(INSERT OR REPLACE INTO user_toolchains(remote_connection_id, workspace_id, worktree_root_path, relative_worktree_path, language_name, name, path, raw_json) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8));
+                        let (workspace_id, worktree_root_path, relative_worktree_path) = match scope {
+                            ToolchainScope::Subproject(ref worktree_root_path, ref path) => (Some(workspace.id), Some(worktree_root_path.to_string_lossy().into_owned()), Some(path.as_unix_str().to_owned())),
                             ToolchainScope::Project => (Some(workspace.id), None, None),
                             ToolchainScope::Global => (None, None, None),
                         };
-                        let args = (remote_connection_id, workspace_id.unwrap_or(WorkspaceId(0)), worktree_id.map_or(usize::MAX,|id| id.to_usize()), relative_worktree_path.unwrap_or_default(),
+                        let args = (remote_connection_id, workspace_id.unwrap_or(WorkspaceId(0)), worktree_root_path.unwrap_or_default(), relative_worktree_path.unwrap_or_default(),
                         toolchain.language_name.as_ref().to_owned(), toolchain.name.to_string(), toolchain.path.to_string(), toolchain.as_json.to_string());
                         if let Err(err) = conn.exec_bound(query)?(args) {
                             log::error!("{err}");
@@ -1110,14 +1303,16 @@ impl WorkspaceDb {
         options: RemoteConnectionOptions,
     ) -> Result<RemoteConnectionId> {
         let kind;
-        let user;
+        let mut user = None;
         let mut host = None;
         let mut port = None;
         let mut distro = None;
+        let mut name = None;
+        let mut container_id = None;
         match options {
             RemoteConnectionOptions::Ssh(options) => {
                 kind = RemoteConnectionKind::Ssh;
-                host = Some(options.host);
+                host = Some(options.host.to_string());
                 port = options.port;
                 user = options.username;
             }
@@ -1126,8 +1321,22 @@ impl WorkspaceDb {
                 distro = Some(options.distro_name);
                 user = options.user;
             }
+            RemoteConnectionOptions::Docker(options) => {
+                kind = RemoteConnectionKind::Docker;
+                container_id = Some(options.container_id);
+                name = Some(options.name);
+            }
         }
-        Self::get_or_create_remote_connection_query(this, kind, host, port, user, distro)
+        Self::get_or_create_remote_connection_query(
+            this,
+            kind,
+            host,
+            port,
+            user,
+            distro,
+            name,
+            container_id,
+        )
     }
 
     fn get_or_create_remote_connection_query(
@@ -1137,6 +1346,8 @@ impl WorkspaceDb {
         port: Option<u16>,
         user: Option<String>,
         distro: Option<String>,
+        name: Option<String>,
+        container_id: Option<String>,
     ) -> Result<RemoteConnectionId> {
         if let Some(id) = this.select_row_bound(sql!(
             SELECT id
@@ -1146,7 +1357,9 @@ impl WorkspaceDb {
                 host IS ? AND
                 port IS ? AND
                 user IS ? AND
-                distro IS ?
+                distro IS ? AND
+                name IS ? AND
+                container_id IS ?
             LIMIT 1
         ))?((
             kind.serialize(),
@@ -1154,6 +1367,8 @@ impl WorkspaceDb {
             port,
             user.clone(),
             distro.clone(),
+            name.clone(),
+            container_id.clone(),
         ))? {
             Ok(RemoteConnectionId(id))
         } else {
@@ -1163,10 +1378,20 @@ impl WorkspaceDb {
                     host,
                     port,
                     user,
-                    distro
-                ) VALUES (?1, ?2, ?3, ?4, ?5)
+                    distro,
+                    name,
+                    container_id
+                ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)
                 RETURNING id
-            ))?((kind.serialize(), host, port, user, distro))?
+            ))?((
+                kind.serialize(),
+                host,
+                port,
+                user,
+                distro,
+                name,
+                container_id,
+            ))?
             .context("failed to insert remote project")?;
             Ok(RemoteConnectionId(id))
         }
@@ -1249,15 +1474,23 @@ impl WorkspaceDb {
     fn remote_connections(&self) -> Result<HashMap<RemoteConnectionId, RemoteConnectionOptions>> {
         Ok(self.select(sql!(
             SELECT
-                id, kind, host, port, user, distro
+                id, kind, host, port, user, distro, container_id, name
             FROM
                 remote_connections
         ))?()?
         .into_iter()
-        .filter_map(|(id, kind, host, port, user, distro)| {
+        .filter_map(|(id, kind, host, port, user, distro, container_id, name)| {
             Some((
                 RemoteConnectionId(id),
-                Self::remote_connection_from_row(kind, host, port, user, distro)?,
+                Self::remote_connection_from_row(
+                    kind,
+                    host,
+                    port,
+                    user,
+                    distro,
+                    container_id,
+                    name,
+                )?,
             ))
         })
         .collect())
@@ -1267,13 +1500,13 @@ impl WorkspaceDb {
         &self,
         id: RemoteConnectionId,
     ) -> Result<RemoteConnectionOptions> {
-        let (kind, host, port, user, distro) = self.select_row_bound(sql!(
-            SELECT kind, host, port, user, distro
+        let (kind, host, port, user, distro, container_id, name) = self.select_row_bound(sql!(
+            SELECT kind, host, port, user, distro, container_id, name
             FROM remote_connections
             WHERE id = ?
         ))?(id.0)?
         .context("no such remote connection")?;
-        Self::remote_connection_from_row(kind, host, port, user, distro)
+        Self::remote_connection_from_row(kind, host, port, user, distro, container_id, name)
             .context("invalid remote_connection row")
     }
 
@@ -1283,6 +1516,8 @@ impl WorkspaceDb {
         port: Option<u16>,
         user: Option<String>,
         distro: Option<String>,
+        container_id: Option<String>,
+        name: Option<String>,
     ) -> Option<RemoteConnectionOptions> {
         match RemoteConnectionKind::deserialize(&kind)? {
             RemoteConnectionKind::Wsl => Some(RemoteConnectionOptions::Wsl(WslConnectionOptions {
@@ -1290,32 +1525,21 @@ impl WorkspaceDb {
                 user: user,
             })),
             RemoteConnectionKind::Ssh => Some(RemoteConnectionOptions::Ssh(SshConnectionOptions {
-                host: host?,
+                host: host?.into(),
                 port,
                 username: user,
                 ..Default::default()
             })),
+            RemoteConnectionKind::Docker => {
+                Some(RemoteConnectionOptions::Docker(DockerConnectionOptions {
+                    container_id: container_id?,
+                    name: name?,
+                    upload_binary_over_docker_exec: false,
+                }))
+            }
         }
     }
 
-    pub(crate) fn last_window(
-        &self,
-    ) -> anyhow::Result<(Option<Uuid>, Option<SerializedWindowBounds>)> {
-        let mut prepared_query =
-            self.select::<(Option<Uuid>, Option<SerializedWindowBounds>)>(sql!(
-                SELECT
-                display,
-                window_state, window_x, window_y, window_width, window_height
-                FROM workspaces
-                WHERE paths
-                IS NOT NULL
-                ORDER BY timestamp DESC
-                LIMIT 1
-            ))?;
-        let result = prepared_query()?;
-        Ok(result.into_iter().next().unwrap_or((None, None)))
-    }
-
     query! {
         pub async fn delete_workspace_by_id(id: WorkspaceId) -> Result<()> {
             DELETE FROM workspaces
@@ -1359,11 +1583,11 @@ impl WorkspaceDb {
             // If a local workspace points to WSL, this check will cause us to wait for the
             // WSL VM and file server to boot up. This can block for many seconds.
             // Supported scenarios use remote workspaces.
-            if !has_wsl_path
-                && paths.paths().iter().all(|path| path.exists())
-                && paths.paths().iter().any(|path| path.is_dir())
-            {
-                result.push((id, SerializedWorkspaceLocation::Local, paths));
+            if !has_wsl_path && paths.paths().iter().all(|path| path.exists()) {
+                // Only show directories in recent projects
+                if paths.paths().iter().any(|path| path.is_dir()) {
+                    result.push((id, SerializedWorkspaceLocation::Local, paths));
+                }
             } else {
                 delete_tasks.push(self.delete_workspace_by_id(id));
             }
@@ -1656,70 +1880,27 @@ impl WorkspaceDb {
         }
     }
 
-    pub async fn toolchain(
-        &self,
-        workspace_id: WorkspaceId,
-        worktree_id: WorktreeId,
-        relative_worktree_path: Arc<RelPath>,
-        language_name: LanguageName,
-    ) -> Result<Option<Toolchain>> {
-        self.write(move |this| {
-            let mut select = this
-                .select_bound(sql!(
-                    SELECT
-                        name, path, raw_json
-                    FROM toolchains
-                    WHERE
-                        workspace_id = ? AND
-                        language_name = ? AND
-                        worktree_id = ? AND
-                        relative_worktree_path = ?
-                ))
-                .context("select toolchain")?;
-
-            let toolchain: Vec<(String, String, String)> = select((
-                workspace_id,
-                language_name.as_ref().to_string(),
-                worktree_id.to_usize(),
-                relative_worktree_path.as_unix_str().to_string(),
-            ))?;
-
-            Ok(toolchain
-                .into_iter()
-                .next()
-                .and_then(|(name, path, raw_json)| {
-                    Some(Toolchain {
-                        name: name.into(),
-                        path: path.into(),
-                        language_name,
-                        as_json: serde_json::Value::from_str(&raw_json).ok()?,
-                    })
-                }))
-        })
-        .await
-    }
-
     pub(crate) async fn toolchains(
         &self,
         workspace_id: WorkspaceId,
-    ) -> Result<Vec<(Toolchain, WorktreeId, Arc<RelPath>)>> {
+    ) -> Result<Vec<(Toolchain, Arc<Path>, Arc<RelPath>)>> {
         self.write(move |this| {
             let mut select = this
                 .select_bound(sql!(
                     SELECT
-                        name, path, worktree_id, relative_worktree_path, language_name, raw_json
+                        name, path, worktree_root_path, relative_worktree_path, language_name, raw_json
                     FROM toolchains
                     WHERE workspace_id = ?
                 ))
                 .context("select toolchains")?;
 
-            let toolchain: Vec<(String, String, u64, String, String, String)> =
+            let toolchain: Vec<(String, String, String, String, String, String)> =
                 select(workspace_id)?;
 
             Ok(toolchain
                 .into_iter()
                 .filter_map(
-                    |(name, path, worktree_id, relative_worktree_path, language, json)| {
+                    |(name, path, worktree_root_path, relative_worktree_path, language, json)| {
                         Some((
                             Toolchain {
                                 name: name.into(),
@@ -1727,7 +1908,7 @@ impl WorkspaceDb {
                                 language_name: LanguageName::new(&language),
                                 as_json: serde_json::Value::from_str(&json).ok()?,
                             },
-                            WorktreeId::from_proto(worktree_id),
+                           Arc::from(worktree_root_path.as_ref()),
                             RelPath::from_proto(&relative_worktree_path).log_err()?,
                         ))
                     },
@@ -1740,18 +1921,18 @@ impl WorkspaceDb {
     pub async fn set_toolchain(
         &self,
         workspace_id: WorkspaceId,
-        worktree_id: WorktreeId,
+        worktree_root_path: Arc<Path>,
         relative_worktree_path: Arc<RelPath>,
         toolchain: Toolchain,
     ) -> Result<()> {
         log::debug!(
-            "Setting toolchain for workspace, worktree: {worktree_id:?}, relative path: {relative_worktree_path:?}, toolchain: {}",
+            "Setting toolchain for workspace, worktree: {worktree_root_path:?}, relative path: {relative_worktree_path:?}, toolchain: {}",
             toolchain.name
         );
         self.write(move |conn| {
             let mut insert = conn
                 .exec_bound(sql!(
-                    INSERT INTO toolchains(workspace_id, worktree_id, relative_worktree_path, language_name, name, path, raw_json) VALUES (?, ?, ?, ?, ?,  ?, ?)
+                    INSERT INTO toolchains(workspace_id, worktree_root_path, relative_worktree_path, language_name, name, path, raw_json) VALUES (?, ?, ?, ?, ?,  ?, ?)
                     ON CONFLICT DO
                     UPDATE SET
                         name = ?5,
@@ -1762,7 +1943,7 @@ impl WorkspaceDb {
 
             insert((
                 workspace_id,
-                worktree_id.to_usize(),
+                worktree_root_path.to_string_lossy().into_owned(),
                 relative_worktree_path.as_unix_str(),
                 toolchain.language_name.as_ref(),
                 toolchain.name.as_ref(),
@@ -1773,6 +1954,135 @@ impl WorkspaceDb {
             Ok(())
         }).await
     }
+
+    pub(crate) async fn save_trusted_worktrees(
+        &self,
+        trusted_worktrees: HashMap<Option<RemoteHostLocation>, HashSet<PathBuf>>,
+    ) -> anyhow::Result<()> {
+        use anyhow::Context as _;
+        use db::sqlez::statement::Statement;
+        use itertools::Itertools as _;
+
+        DB.clear_trusted_worktrees()
+            .await
+            .context("clearing previous trust state")?;
+
+        let trusted_worktrees = trusted_worktrees
+            .into_iter()
+            .flat_map(|(host, abs_paths)| {
+                abs_paths
+                    .into_iter()
+                    .map(move |abs_path| (Some(abs_path), host.clone()))
+            })
+            .collect::<Vec<_>>();
+        let mut first_worktree;
+        let mut last_worktree = 0_usize;
+        for (count, placeholders) in std::iter::once("(?, ?, ?)")
+            .cycle()
+            .take(trusted_worktrees.len())
+            .chunks(MAX_QUERY_PLACEHOLDERS / 3)
+            .into_iter()
+            .map(|chunk| {
+                let mut count = 0;
+                let placeholders = chunk
+                    .inspect(|_| {
+                        count += 1;
+                    })
+                    .join(", ");
+                (count, placeholders)
+            })
+            .collect::<Vec<_>>()
+        {
+            first_worktree = last_worktree;
+            last_worktree = last_worktree + count;
+            let query = format!(
+                r#"INSERT INTO trusted_worktrees(absolute_path, user_name, host_name)
+VALUES {placeholders};"#
+            );
+
+            let trusted_worktrees = trusted_worktrees[first_worktree..last_worktree].to_vec();
+            self.write(move |conn| {
+                let mut statement = Statement::prepare(conn, query)?;
+                let mut next_index = 1;
+                for (abs_path, host) in trusted_worktrees {
+                    let abs_path = abs_path.as_ref().map(|abs_path| abs_path.to_string_lossy());
+                    next_index = statement.bind(
+                        &abs_path.as_ref().map(|abs_path| abs_path.as_ref()),
+                        next_index,
+                    )?;
+                    next_index = statement.bind(
+                        &host
+                            .as_ref()
+                            .and_then(|host| Some(host.user_name.as_ref()?.as_str())),
+                        next_index,
+                    )?;
+                    next_index = statement.bind(
+                        &host.as_ref().map(|host| host.host_identifier.as_str()),
+                        next_index,
+                    )?;
+                }
+                statement.exec()
+            })
+            .await
+            .context("inserting new trusted state")?;
+        }
+        Ok(())
+    }
+
+    pub fn fetch_trusted_worktrees(
+        &self,
+        worktree_store: Option<Entity<WorktreeStore>>,
+        host: Option<RemoteHostLocation>,
+        cx: &App,
+    ) -> Result<HashMap<Option<RemoteHostLocation>, HashSet<PathTrust>>> {
+        let trusted_worktrees = DB.trusted_worktrees()?;
+        Ok(trusted_worktrees
+            .into_iter()
+            .filter_map(|(abs_path, user_name, host_name)| {
+                let db_host = match (user_name, host_name) {
+                    (_, None) => None,
+                    (None, Some(host_name)) => Some(RemoteHostLocation {
+                        user_name: None,
+                        host_identifier: SharedString::new(host_name),
+                    }),
+                    (Some(user_name), Some(host_name)) => Some(RemoteHostLocation {
+                        user_name: Some(SharedString::new(user_name)),
+                        host_identifier: SharedString::new(host_name),
+                    }),
+                };
+
+                let abs_path = abs_path?;
+                Some(if db_host != host {
+                    (db_host, PathTrust::AbsPath(abs_path))
+                } else if let Some(worktree_store) = &worktree_store {
+                    find_worktree_in_store(worktree_store.read(cx), &abs_path, cx)
+                        .map(PathTrust::Worktree)
+                        .map(|trusted_worktree| (host.clone(), trusted_worktree))
+                        .unwrap_or_else(|| (db_host.clone(), PathTrust::AbsPath(abs_path)))
+                } else {
+                    (db_host, PathTrust::AbsPath(abs_path))
+                })
+            })
+            .fold(HashMap::default(), |mut acc, (remote_host, path_trust)| {
+                acc.entry(remote_host)
+                    .or_insert_with(HashSet::default)
+                    .insert(path_trust);
+                acc
+            }))
+    }
+
+    query! {
+        fn trusted_worktrees() -> Result<Vec<(Option<PathBuf>, Option<String>, Option<String>)>> {
+            SELECT absolute_path, user_name, host_name
+            FROM trusted_worktrees
+        }
+    }
+
+    query! {
+        pub async fn clear_trusted_worktrees() -> Result<()> {
+            DELETE FROM trusted_worktrees
+        }
+    }
 }
 
 pub fn delete_unloaded_items(
@@ -2480,7 +2790,7 @@ mod tests {
 
         let connection_id = db
             .get_or_create_remote_connection(RemoteConnectionOptions::Ssh(SshConnectionOptions {
-                host: "my-host".to_string(),
+                host: "my-host".into(),
                 port: Some(1234),
                 ..Default::default()
             }))
@@ -2669,7 +2979,7 @@ mod tests {
         .into_iter()
         .map(|(host, user)| async {
             let options = RemoteConnectionOptions::Ssh(SshConnectionOptions {
-                host: host.to_string(),
+                host: host.into(),
                 username: Some(user.to_string()),
                 ..Default::default()
             });
@@ -2760,7 +3070,7 @@ mod tests {
 
         let connection_id = db
             .get_or_create_remote_connection(RemoteConnectionOptions::Ssh(SshConnectionOptions {
-                host: host.clone(),
+                host: host.clone().into(),
                 port,
                 username: user.clone(),
                 ..Default::default()
@@ -2771,7 +3081,7 @@ mod tests {
         // Test that calling the function again with the same parameters returns the same project
         let same_connection = db
             .get_or_create_remote_connection(RemoteConnectionOptions::Ssh(SshConnectionOptions {
-                host: host.clone(),
+                host: host.clone().into(),
                 port,
                 username: user.clone(),
                 ..Default::default()
@@ -2788,7 +3098,7 @@ mod tests {
 
         let different_connection = db
             .get_or_create_remote_connection(RemoteConnectionOptions::Ssh(SshConnectionOptions {
-                host: host2.clone(),
+                host: host2.clone().into(),
                 port: port2,
                 username: user2.clone(),
                 ..Default::default()
@@ -2807,7 +3117,7 @@ mod tests {
 
         let connection_id = db
             .get_or_create_remote_connection(RemoteConnectionOptions::Ssh(SshConnectionOptions {
-                host: host.clone(),
+                host: host.clone().into(),
                 port,
                 username: None,
                 ..Default::default()
@@ -2817,7 +3127,7 @@ mod tests {
 
         let same_connection_id = db
             .get_or_create_remote_connection(RemoteConnectionOptions::Ssh(SshConnectionOptions {
-                host: host.clone(),
+                host: host.clone().into(),
                 port,
                 username: user.clone(),
                 ..Default::default()
@@ -2847,7 +3157,7 @@ mod tests {
             ids.push(
                 db.get_or_create_remote_connection(RemoteConnectionOptions::Ssh(
                     SshConnectionOptions {
-                        host: host.clone(),
+                        host: host.clone().into(),
                         port: *port,
                         username: user.clone(),
                         ..Default::default()
@@ -3025,4 +3335,53 @@ mod tests {
 
         assert_eq!(workspace.center_group, new_workspace.center_group);
     }
+
+    #[gpui::test]
+    async fn test_empty_workspace_window_bounds() {
+        zlog::init_test();
+
+        let db = WorkspaceDb::open_test_db("test_empty_workspace_window_bounds").await;
+        let id = db.next_id().await.unwrap();
+
+        // Create a workspace with empty paths (empty workspace)
+        let empty_paths: &[&str] = &[];
+        let display_uuid = Uuid::new_v4();
+        let window_bounds = SerializedWindowBounds(WindowBounds::Windowed(Bounds {
+            origin: point(px(100.0), px(200.0)),
+            size: size(px(800.0), px(600.0)),
+        }));
+
+        let workspace = SerializedWorkspace {
+            id,
+            paths: PathList::new(empty_paths),
+            location: SerializedWorkspaceLocation::Local,
+            center_group: Default::default(),
+            window_bounds: None,
+            display: None,
+            docks: Default::default(),
+            breakpoints: Default::default(),
+            centered_layout: false,
+            session_id: None,
+            window_id: None,
+            user_toolchains: Default::default(),
+        };
+
+        // Save the workspace (this creates the record with empty paths)
+        db.save_workspace(workspace.clone()).await;
+
+        // Save window bounds separately (as the actual code does via set_window_open_status)
+        db.set_window_open_status(id, window_bounds, display_uuid)
+            .await
+            .unwrap();
+
+        // Retrieve it using empty paths
+        let retrieved = db.workspace_for_roots(empty_paths).unwrap();
+
+        // Verify window bounds were persisted
+        assert_eq!(retrieved.id, id);
+        assert!(retrieved.window_bounds.is_some());
+        assert_eq!(retrieved.window_bounds.unwrap().0, window_bounds.0);
+        assert!(retrieved.display.is_some());
+        assert_eq!(retrieved.display.unwrap(), display_uuid);
+    }
 }

crates/workspace/src/persistence/model.rs 🔗

@@ -32,6 +32,7 @@ pub(crate) struct RemoteConnectionId(pub u64);
 pub(crate) enum RemoteConnectionKind {
     Ssh,
     Wsl,
+    Docker,
 }
 
 #[derive(Debug, PartialEq, Clone)]
@@ -75,6 +76,7 @@ impl RemoteConnectionKind {
         match self {
             RemoteConnectionKind::Ssh => "ssh",
             RemoteConnectionKind::Wsl => "wsl",
+            RemoteConnectionKind::Docker => "docker",
         }
     }
 
@@ -82,6 +84,7 @@ impl RemoteConnectionKind {
         match text {
             "ssh" => Some(Self::Ssh),
             "wsl" => Some(Self::Wsl),
+            "docker" => Some(Self::Docker),
             _ => None,
         }
     }

crates/workspace/src/searchable.rs 🔗

@@ -96,6 +96,7 @@ pub trait SearchableItem: Item + EventEmitter<SearchEvent> {
     fn update_matches(
         &mut self,
         matches: &[Self::Match],
+        active_match_index: Option<usize>,
         window: &mut Window,
         cx: &mut Context<Self>,
     );
@@ -179,7 +180,13 @@ pub trait SearchableItemHandle: ItemHandle {
         handler: Box<dyn Fn(&SearchEvent, &mut Window, &mut App) + Send>,
     ) -> Subscription;
     fn clear_matches(&self, window: &mut Window, cx: &mut App);
-    fn update_matches(&self, matches: &AnyVec<dyn Send>, window: &mut Window, cx: &mut App);
+    fn update_matches(
+        &self,
+        matches: &AnyVec<dyn Send>,
+        active_match_index: Option<usize>,
+        window: &mut Window,
+        cx: &mut App,
+    );
     fn query_suggestion(&self, window: &mut Window, cx: &mut App) -> String;
     fn activate_match(
         &self,
@@ -264,10 +271,16 @@ impl<T: SearchableItem> SearchableItemHandle for Entity<T> {
     fn clear_matches(&self, window: &mut Window, cx: &mut App) {
         self.update(cx, |this, cx| this.clear_matches(window, cx));
     }
-    fn update_matches(&self, matches: &AnyVec<dyn Send>, window: &mut Window, cx: &mut App) {
+    fn update_matches(
+        &self,
+        matches: &AnyVec<dyn Send>,
+        active_match_index: Option<usize>,
+        window: &mut Window,
+        cx: &mut App,
+    ) {
         let matches = matches.downcast_ref().unwrap();
         self.update(cx, |this, cx| {
-            this.update_matches(matches.as_slice(), window, cx)
+            this.update_matches(matches.as_slice(), active_match_index, window, cx)
         });
     }
     fn query_suggestion(&self, window: &mut Window, cx: &mut App) -> String {

crates/workspace/src/security_modal.rs 🔗

@@ -0,0 +1,334 @@
+//! A UI interface for managing the [`TrustedWorktrees`] data.
+
+use std::{
+    borrow::Cow,
+    path::{Path, PathBuf},
+    sync::Arc,
+};
+
+use collections::{HashMap, HashSet};
+use gpui::{DismissEvent, EventEmitter, FocusHandle, Focusable, WeakEntity};
+
+use project::{
+    WorktreeId,
+    trusted_worktrees::{PathTrust, RemoteHostLocation, TrustedWorktrees},
+    worktree_store::WorktreeStore,
+};
+use smallvec::SmallVec;
+use theme::ActiveTheme;
+use ui::{
+    AlertModal, Checkbox, FluentBuilder, KeyBinding, ListBulletItem, ToggleState, prelude::*,
+};
+
+use crate::{DismissDecision, ModalView, ToggleWorktreeSecurity};
+
+pub struct SecurityModal {
+    restricted_paths: HashMap<WorktreeId, RestrictedPath>,
+    home_dir: Option<PathBuf>,
+    trust_parents: bool,
+    worktree_store: WeakEntity<WorktreeStore>,
+    remote_host: Option<RemoteHostLocation>,
+    focus_handle: FocusHandle,
+    trusted: Option<bool>,
+}
+
+#[derive(Debug, PartialEq, Eq)]
+struct RestrictedPath {
+    abs_path: Arc<Path>,
+    is_file: bool,
+    host: Option<RemoteHostLocation>,
+}
+
+impl Focusable for SecurityModal {
+    fn focus_handle(&self, _: &ui::App) -> FocusHandle {
+        self.focus_handle.clone()
+    }
+}
+
+impl EventEmitter<DismissEvent> for SecurityModal {}
+
+impl ModalView for SecurityModal {
+    fn fade_out_background(&self) -> bool {
+        true
+    }
+
+    fn on_before_dismiss(&mut self, _: &mut Window, _: &mut Context<Self>) -> DismissDecision {
+        match self.trusted {
+            Some(false) => telemetry::event!("Open in Restricted", source = "Worktree Trust Modal"),
+            Some(true) => telemetry::event!("Trust and Continue", source = "Worktree Trust Modal"),
+            None => telemetry::event!("Dismissed", source = "Worktree Trust Modal"),
+        }
+        DismissDecision::Dismiss(true)
+    }
+}
+
+impl Render for SecurityModal {
+    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
+        if self.restricted_paths.is_empty() {
+            self.dismiss(cx);
+            return v_flex().into_any_element();
+        }
+
+        let header_label = if self.restricted_paths.len() == 1 {
+            "Unrecognized Project"
+        } else {
+            "Unrecognized Projects"
+        };
+
+        let trust_label = self.build_trust_label();
+
+        AlertModal::new("security-modal")
+            .width(rems(40.))
+            .key_context("SecurityModal")
+            .track_focus(&self.focus_handle(cx))
+            .on_action(cx.listener(|this, _: &menu::Confirm, _window, cx| {
+                this.trust_and_dismiss(cx);
+            }))
+            .on_action(cx.listener(|security_modal, _: &ToggleWorktreeSecurity, _window, cx| {
+                security_modal.trusted = Some(false);
+                security_modal.dismiss(cx);
+            }))
+            .header(
+                v_flex()
+                    .p_3()
+                    .gap_1()
+                    .rounded_t_md()
+                    .bg(cx.theme().colors().editor_background.opacity(0.5))
+                    .border_b_1()
+                    .border_color(cx.theme().colors().border_variant)
+                    .child(
+                        h_flex()
+                            .gap_2()
+                            .child(Icon::new(IconName::Warning).color(Color::Warning))
+                            .child(Label::new(header_label)),
+                    )
+                    .children(self.restricted_paths.values().filter_map(|restricted_path| {
+                        let abs_path = if restricted_path.is_file {
+                            restricted_path.abs_path.parent()
+                        } else {
+                            Some(restricted_path.abs_path.as_ref())
+                        }?;
+                        let label = match &restricted_path.host {
+                            Some(remote_host) => match &remote_host.user_name {
+                                Some(user_name) => format!(
+                                    "{} ({}@{})",
+                                    self.shorten_path(abs_path).display(),
+                                    user_name,
+                                    remote_host.host_identifier
+                                ),
+                                None => format!(
+                                    "{} ({})",
+                                    self.shorten_path(abs_path).display(),
+                                    remote_host.host_identifier
+                                ),
+                            },
+                            None => self.shorten_path(abs_path).display().to_string(),
+                        };
+                        Some(h_flex()
+                            .pl(IconSize::default().rems() + rems(0.5))
+                            .child(Label::new(label).color(Color::Muted)))
+                    })),
+            )
+            .child(
+                v_flex()
+                    .gap_2()
+                    .child(
+                        v_flex()
+                            .child(
+                                Label::new(
+                                    "Untrusted projects are opened in Restricted Mode to protect your system.",
+                                )
+                                .color(Color::Muted),
+                            )
+                            .child(
+                                Label::new(
+                                    "Review .zed/settings.json for any extensions or commands configured by this project.",
+                                )
+                                .color(Color::Muted),
+                            ),
+                    )
+                    .child(
+                        v_flex()
+                            .child(Label::new("Restricted Mode prevents:").color(Color::Muted))
+                            .child(ListBulletItem::new("Project settings from being applied"))
+                            .child(ListBulletItem::new("Language servers from running"))
+                            .child(ListBulletItem::new("MCP Server integrations from installing")),
+                    )
+                    .map(|this| match trust_label {
+                        Some(trust_label) => this.child(
+                            Checkbox::new("trust-parents", ToggleState::from(self.trust_parents))
+                                .label(trust_label)
+                                .on_click(cx.listener(
+                                    |security_modal, state: &ToggleState, _, cx| {
+                                        security_modal.trust_parents = state.selected();
+                                        cx.notify();
+                                        cx.stop_propagation();
+                                    },
+                                )),
+                        ),
+                        None => this,
+                    }),
+            )
+            .footer(
+                h_flex()
+                    .px_3()
+                    .pb_3()
+                    .gap_1()
+                    .justify_end()
+                    .child(
+                        Button::new("rm", "Stay in Restricted Mode")
+                            .key_binding(
+                                KeyBinding::for_action(
+                                    &ToggleWorktreeSecurity,
+                                    cx,
+                                )
+                                .map(|kb| kb.size(rems_from_px(12.))),
+                            )
+                            .on_click(cx.listener(move |security_modal, _, _, cx| {
+                                security_modal.trusted = Some(false);
+                                security_modal.dismiss(cx);
+                                cx.stop_propagation();
+                            })),
+                    )
+                    .child(
+                        Button::new("tc", "Trust and Continue")
+                            .style(ButtonStyle::Filled)
+                            .layer(ui::ElevationIndex::ModalSurface)
+                            .key_binding(
+                                KeyBinding::for_action(&menu::Confirm, cx)
+                                    .map(|kb| kb.size(rems_from_px(12.))),
+                            )
+                            .on_click(cx.listener(move |security_modal, _, _, cx| {
+                                security_modal.trust_and_dismiss(cx);
+                                cx.stop_propagation();
+                            })),
+                    ),
+            )
+            .into_any_element()
+    }
+}
+
+impl SecurityModal {
+    pub fn new(
+        worktree_store: WeakEntity<WorktreeStore>,
+        remote_host: Option<impl Into<RemoteHostLocation>>,
+        cx: &mut Context<Self>,
+    ) -> Self {
+        let mut this = Self {
+            worktree_store,
+            remote_host: remote_host.map(|host| host.into()),
+            restricted_paths: HashMap::default(),
+            focus_handle: cx.focus_handle(),
+            trust_parents: false,
+            home_dir: std::env::home_dir(),
+            trusted: None,
+        };
+        this.refresh_restricted_paths(cx);
+
+        this
+    }
+
+    fn build_trust_label(&self) -> Option<Cow<'static, str>> {
+        let mut has_restricted_files = false;
+        let available_parents = self
+            .restricted_paths
+            .values()
+            .filter(|restricted_path| {
+                has_restricted_files |= restricted_path.is_file;
+                !restricted_path.is_file
+            })
+            .filter_map(|restricted_path| restricted_path.abs_path.parent())
+            .collect::<SmallVec<[_; 2]>>();
+        match available_parents.len() {
+            0 => {
+                if has_restricted_files {
+                    Some(Cow::Borrowed("Trust all single files"))
+                } else {
+                    None
+                }
+            }
+            1 => Some(Cow::Owned(format!(
+                "Trust all projects in the {:} folder",
+                self.shorten_path(available_parents[0]).display()
+            ))),
+            _ => Some(Cow::Borrowed("Trust all projects in the parent folders")),
+        }
+    }
+
+    fn shorten_path<'a>(&self, path: &'a Path) -> Cow<'a, Path> {
+        match &self.home_dir {
+            Some(home_dir) => path
+                .strip_prefix(home_dir)
+                .map(|stripped| Path::new("~").join(stripped))
+                .map(Cow::Owned)
+                .unwrap_or(Cow::Borrowed(path)),
+            None => Cow::Borrowed(path),
+        }
+    }
+
+    fn trust_and_dismiss(&mut self, cx: &mut Context<Self>) {
+        if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
+            trusted_worktrees.update(cx, |trusted_worktrees, cx| {
+                let mut paths_to_trust = self
+                    .restricted_paths
+                    .keys()
+                    .copied()
+                    .map(PathTrust::Worktree)
+                    .collect::<HashSet<_>>();
+                if self.trust_parents {
+                    paths_to_trust.extend(self.restricted_paths.values().filter_map(
+                        |restricted_paths| {
+                            if restricted_paths.is_file {
+                                None
+                            } else {
+                                let parent_abs_path =
+                                    restricted_paths.abs_path.parent()?.to_owned();
+                                Some(PathTrust::AbsPath(parent_abs_path))
+                            }
+                        },
+                    ));
+                }
+                trusted_worktrees.trust(paths_to_trust, self.remote_host.clone(), cx);
+            });
+        }
+
+        self.trusted = Some(true);
+        self.dismiss(cx);
+    }
+
+    pub fn dismiss(&mut self, cx: &mut Context<Self>) {
+        cx.emit(DismissEvent);
+    }
+
+    pub fn refresh_restricted_paths(&mut self, cx: &mut Context<Self>) {
+        if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
+            if let Some(worktree_store) = self.worktree_store.upgrade() {
+                let new_restricted_worktrees = trusted_worktrees
+                    .read(cx)
+                    .restricted_worktrees(worktree_store.read(cx), cx)
+                    .into_iter()
+                    .filter_map(|(worktree_id, abs_path)| {
+                        let worktree = worktree_store.read(cx).worktree_for_id(worktree_id, cx)?;
+                        Some((
+                            worktree_id,
+                            RestrictedPath {
+                                abs_path,
+                                is_file: worktree.read(cx).is_single_file(),
+                                host: self.remote_host.clone(),
+                            },
+                        ))
+                    })
+                    .collect::<HashMap<_, _>>();
+
+                if self.restricted_paths != new_restricted_worktrees {
+                    self.trust_parents = false;
+                    self.restricted_paths = new_restricted_worktrees;
+                    cx.notify();
+                }
+            }
+        } else if !self.restricted_paths.is_empty() {
+            self.restricted_paths.clear();
+            cx.notify();
+        }
+    }
+}

crates/workspace/src/shared_screen.rs 🔗

@@ -42,6 +42,11 @@ impl SharedScreen {
         })
         .detach();
 
+        cx.observe_release(&room, |_, _, cx| {
+            cx.emit(Event::Close);
+        })
+        .detach();
+
         let view = cx.new(|cx| RemoteVideoTrackView::new(track.clone(), window, cx));
         cx.subscribe(&view, |_, _, ev, cx| match ev {
             call::RemoteVideoTrackViewEvent::Close => cx.emit(Event::Close),

crates/workspace/src/utility_pane.rs 🔗

@@ -0,0 +1,282 @@
+use gpui::{
+    AppContext as _, EntityId, MouseButton, Pixels, Render, StatefulInteractiveElement,
+    Subscription, WeakEntity, deferred, px,
+};
+use ui::{
+    ActiveTheme as _, Context, FluentBuilder as _, InteractiveElement as _, IntoElement,
+    ParentElement as _, RenderOnce, Styled as _, Window, div,
+};
+
+use crate::{
+    DockPosition, Workspace,
+    dock::{ClosePane, MinimizePane, UtilityPane, UtilityPaneHandle},
+};
+
+pub(crate) const UTILITY_PANE_RESIZE_HANDLE_SIZE: Pixels = px(6.0);
+pub(crate) const UTILITY_PANE_MIN_WIDTH: Pixels = px(20.0);
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+pub enum UtilityPaneSlot {
+    Left,
+    Right,
+}
+
+struct UtilityPaneSlotState {
+    panel_id: EntityId,
+    utility_pane: Box<dyn UtilityPaneHandle>,
+    _subscriptions: Vec<Subscription>,
+}
+
+#[derive(Default)]
+pub struct UtilityPaneState {
+    left_slot: Option<UtilityPaneSlotState>,
+    right_slot: Option<UtilityPaneSlotState>,
+}
+
+#[derive(Clone)]
+pub struct DraggedUtilityPane(pub UtilityPaneSlot);
+
+impl Render for DraggedUtilityPane {
+    fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
+        gpui::Empty
+    }
+}
+
+pub fn utility_slot_for_dock_position(position: DockPosition) -> UtilityPaneSlot {
+    match position {
+        DockPosition::Left => UtilityPaneSlot::Left,
+        DockPosition::Right => UtilityPaneSlot::Right,
+        DockPosition::Bottom => UtilityPaneSlot::Left,
+    }
+}
+
+impl Workspace {
+    pub fn utility_pane(&self, slot: UtilityPaneSlot) -> Option<&dyn UtilityPaneHandle> {
+        match slot {
+            UtilityPaneSlot::Left => self
+                .utility_panes
+                .left_slot
+                .as_ref()
+                .map(|s| s.utility_pane.as_ref()),
+            UtilityPaneSlot::Right => self
+                .utility_panes
+                .right_slot
+                .as_ref()
+                .map(|s| s.utility_pane.as_ref()),
+        }
+    }
+
+    pub fn toggle_utility_pane(
+        &mut self,
+        slot: UtilityPaneSlot,
+        window: &mut Window,
+        cx: &mut Context<Self>,
+    ) {
+        if let Some(handle) = self.utility_pane(slot) {
+            let current = handle.expanded(cx);
+            handle.set_expanded(!current, cx);
+        }
+        cx.notify();
+        self.serialize_workspace(window, cx);
+    }
+
+    pub fn register_utility_pane<T: UtilityPane>(
+        &mut self,
+        slot: UtilityPaneSlot,
+        panel_id: EntityId,
+        handle: gpui::Entity<T>,
+        cx: &mut Context<Self>,
+    ) {
+        let minimize_subscription =
+            cx.subscribe(&handle, move |this, _, _event: &MinimizePane, cx| {
+                if let Some(handle) = this.utility_pane(slot) {
+                    handle.set_expanded(false, cx);
+                }
+                cx.notify();
+            });
+
+        let close_subscription = cx.subscribe(&handle, move |this, _, _event: &ClosePane, cx| {
+            this.clear_utility_pane(slot, cx);
+        });
+
+        let subscriptions = vec![minimize_subscription, close_subscription];
+        let boxed_handle: Box<dyn UtilityPaneHandle> = Box::new(handle);
+
+        match slot {
+            UtilityPaneSlot::Left => {
+                self.utility_panes.left_slot = Some(UtilityPaneSlotState {
+                    panel_id,
+                    utility_pane: boxed_handle,
+                    _subscriptions: subscriptions,
+                });
+            }
+            UtilityPaneSlot::Right => {
+                self.utility_panes.right_slot = Some(UtilityPaneSlotState {
+                    panel_id,
+                    utility_pane: boxed_handle,
+                    _subscriptions: subscriptions,
+                });
+            }
+        }
+        cx.notify();
+    }
+
+    pub fn clear_utility_pane(&mut self, slot: UtilityPaneSlot, cx: &mut Context<Self>) {
+        match slot {
+            UtilityPaneSlot::Left => {
+                self.utility_panes.left_slot = None;
+            }
+            UtilityPaneSlot::Right => {
+                self.utility_panes.right_slot = None;
+            }
+        }
+        cx.notify();
+    }
+
+    pub fn clear_utility_pane_if_provider(
+        &mut self,
+        slot: UtilityPaneSlot,
+        provider_panel_id: EntityId,
+        cx: &mut Context<Self>,
+    ) {
+        let should_clear = match slot {
+            UtilityPaneSlot::Left => self
+                .utility_panes
+                .left_slot
+                .as_ref()
+                .is_some_and(|slot| slot.panel_id == provider_panel_id),
+            UtilityPaneSlot::Right => self
+                .utility_panes
+                .right_slot
+                .as_ref()
+                .is_some_and(|slot| slot.panel_id == provider_panel_id),
+        };
+
+        if should_clear {
+            self.clear_utility_pane(slot, cx);
+        }
+    }
+
+    pub fn resize_utility_pane(
+        &mut self,
+        slot: UtilityPaneSlot,
+        new_width: Pixels,
+        window: &mut Window,
+        cx: &mut Context<Self>,
+    ) {
+        if let Some(handle) = self.utility_pane(slot) {
+            let max_width = self.max_utility_pane_width(window, cx);
+            let width = new_width.max(UTILITY_PANE_MIN_WIDTH).min(max_width);
+            handle.set_width(Some(width), cx);
+            cx.notify();
+            self.serialize_workspace(window, cx);
+        }
+    }
+
+    pub fn reset_utility_pane_width(
+        &mut self,
+        slot: UtilityPaneSlot,
+        window: &mut Window,
+        cx: &mut Context<Self>,
+    ) {
+        if let Some(handle) = self.utility_pane(slot) {
+            handle.set_width(None, cx);
+            cx.notify();
+            self.serialize_workspace(window, cx);
+        }
+    }
+}
+
+#[derive(IntoElement)]
+pub struct UtilityPaneFrame {
+    workspace: WeakEntity<Workspace>,
+    slot: UtilityPaneSlot,
+    handle: Box<dyn UtilityPaneHandle>,
+}
+
+impl UtilityPaneFrame {
+    pub fn new(
+        slot: UtilityPaneSlot,
+        handle: Box<dyn UtilityPaneHandle>,
+        cx: &mut Context<Workspace>,
+    ) -> Self {
+        let workspace = cx.weak_entity();
+        Self {
+            workspace,
+            slot,
+            handle,
+        }
+    }
+}
+
+impl RenderOnce for UtilityPaneFrame {
+    fn render(self, _window: &mut Window, cx: &mut ui::App) -> impl IntoElement {
+        let workspace = self.workspace.clone();
+        let slot = self.slot;
+        let width = self.handle.width(cx);
+
+        let create_resize_handle = || {
+            let workspace_handle = workspace.clone();
+            let handle = div()
+                .id(match slot {
+                    UtilityPaneSlot::Left => "utility-pane-resize-handle-left",
+                    UtilityPaneSlot::Right => "utility-pane-resize-handle-right",
+                })
+                .on_drag(DraggedUtilityPane(slot), move |pane, _, _, cx| {
+                    cx.stop_propagation();
+                    cx.new(|_| pane.clone())
+                })
+                .on_mouse_down(MouseButton::Left, move |_, _, cx| {
+                    cx.stop_propagation();
+                })
+                .on_mouse_up(
+                    MouseButton::Left,
+                    move |e: &gpui::MouseUpEvent, window, cx| {
+                        if e.click_count == 2 {
+                            workspace_handle
+                                .update(cx, |workspace, cx| {
+                                    workspace.reset_utility_pane_width(slot, window, cx);
+                                })
+                                .ok();
+                            cx.stop_propagation();
+                        }
+                    },
+                )
+                .occlude();
+
+            match slot {
+                UtilityPaneSlot::Left => deferred(
+                    handle
+                        .absolute()
+                        .right(-UTILITY_PANE_RESIZE_HANDLE_SIZE / 2.)
+                        .top(px(0.))
+                        .h_full()
+                        .w(UTILITY_PANE_RESIZE_HANDLE_SIZE)
+                        .cursor_col_resize(),
+                ),
+                UtilityPaneSlot::Right => deferred(
+                    handle
+                        .absolute()
+                        .left(-UTILITY_PANE_RESIZE_HANDLE_SIZE / 2.)
+                        .top(px(0.))
+                        .h_full()
+                        .w(UTILITY_PANE_RESIZE_HANDLE_SIZE)
+                        .cursor_col_resize(),
+                ),
+            }
+        };
+
+        div()
+            .h_full()
+            .bg(cx.theme().colors().tab_bar_background)
+            .w(width)
+            .border_color(cx.theme().colors().border)
+            .when(self.slot == UtilityPaneSlot::Left, |this| this.border_r_1())
+            .when(self.slot == UtilityPaneSlot::Right, |this| {
+                this.border_l_1()
+            })
+            .child(create_resize_handle())
+            .child(self.handle.to_any())
+            .into_any_element()
+    }
+}

crates/workspace/src/welcome.rs 🔗

@@ -0,0 +1,568 @@
+use crate::{
+    NewFile, Open, PathList, SerializedWorkspaceLocation, WORKSPACE_DB, Workspace, WorkspaceId,
+    item::{Item, ItemEvent},
+};
+use git::Clone as GitClone;
+use gpui::WeakEntity;
+use gpui::{
+    Action, App, Context, Entity, EventEmitter, FocusHandle, Focusable, InteractiveElement,
+    ParentElement, Render, Styled, Task, Window, actions,
+};
+use menu::{SelectNext, SelectPrevious};
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+use ui::{ButtonLike, Divider, DividerColor, KeyBinding, Vector, VectorName, prelude::*};
+use util::ResultExt;
+use zed_actions::{Extensions, OpenOnboarding, OpenSettings, agent, command_palette};
+
+#[derive(PartialEq, Clone, Debug, Deserialize, Serialize, JsonSchema, Action)]
+#[action(namespace = welcome)]
+#[serde(transparent)]
+pub struct OpenRecentProject {
+    pub index: usize,
+}
+
+actions!(
+    zed,
+    [
+        /// Show the Zed welcome screen
+        ShowWelcome
+    ]
+);
+
+#[derive(IntoElement)]
+struct SectionHeader {
+    title: SharedString,
+}
+
+impl SectionHeader {
+    fn new(title: impl Into<SharedString>) -> Self {
+        Self {
+            title: title.into(),
+        }
+    }
+}
+
+impl RenderOnce for SectionHeader {
+    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
+        h_flex()
+            .px_1()
+            .mb_2()
+            .gap_2()
+            .child(
+                Label::new(self.title.to_ascii_uppercase())
+                    .buffer_font(cx)
+                    .color(Color::Muted)
+                    .size(LabelSize::XSmall),
+            )
+            .child(Divider::horizontal().color(DividerColor::BorderVariant))
+    }
+}
+
+#[derive(IntoElement)]
+struct SectionButton {
+    label: SharedString,
+    icon: IconName,
+    action: Box<dyn Action>,
+    tab_index: usize,
+    focus_handle: FocusHandle,
+}
+
+impl SectionButton {
+    fn new(
+        label: impl Into<SharedString>,
+        icon: IconName,
+        action: &dyn Action,
+        tab_index: usize,
+        focus_handle: FocusHandle,
+    ) -> Self {
+        Self {
+            label: label.into(),
+            icon,
+            action: action.boxed_clone(),
+            tab_index,
+            focus_handle,
+        }
+    }
+}
+
+impl RenderOnce for SectionButton {
+    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
+        let id = format!("onb-button-{}", self.label);
+        let action_ref: &dyn Action = &*self.action;
+
+        ButtonLike::new(id)
+            .tab_index(self.tab_index as isize)
+            .full_width()
+            .size(ButtonSize::Medium)
+            .child(
+                h_flex()
+                    .w_full()
+                    .justify_between()
+                    .child(
+                        h_flex()
+                            .gap_2()
+                            .child(
+                                Icon::new(self.icon)
+                                    .color(Color::Muted)
+                                    .size(IconSize::Small),
+                            )
+                            .child(Label::new(self.label)),
+                    )
+                    .child(
+                        KeyBinding::for_action_in(action_ref, &self.focus_handle, cx)
+                            .size(rems_from_px(12.)),
+                    ),
+            )
+            .on_click(move |_, window, cx| window.dispatch_action(self.action.boxed_clone(), cx))
+    }
+}
+
+struct SectionEntry {
+    icon: IconName,
+    title: &'static str,
+    action: &'static dyn Action,
+}
+
+impl SectionEntry {
+    fn render(&self, button_index: usize, focus: &FocusHandle, _cx: &App) -> impl IntoElement {
+        SectionButton::new(
+            self.title,
+            self.icon,
+            self.action,
+            button_index,
+            focus.clone(),
+        )
+    }
+}
+
+const CONTENT: (Section<4>, Section<3>) = (
+    Section {
+        title: "Get Started",
+        entries: [
+            SectionEntry {
+                icon: IconName::Plus,
+                title: "New File",
+                action: &NewFile,
+            },
+            SectionEntry {
+                icon: IconName::FolderOpen,
+                title: "Open Project",
+                action: &Open,
+            },
+            SectionEntry {
+                icon: IconName::CloudDownload,
+                title: "Clone Repository",
+                action: &GitClone,
+            },
+            SectionEntry {
+                icon: IconName::ListCollapse,
+                title: "Open Command Palette",
+                action: &command_palette::Toggle,
+            },
+        ],
+    },
+    Section {
+        title: "Configure",
+        entries: [
+            SectionEntry {
+                icon: IconName::Settings,
+                title: "Open Settings",
+                action: &OpenSettings,
+            },
+            SectionEntry {
+                icon: IconName::ZedAssistant,
+                title: "View AI Settings",
+                action: &agent::OpenSettings,
+            },
+            SectionEntry {
+                icon: IconName::Blocks,
+                title: "Explore Extensions",
+                action: &Extensions {
+                    category_filter: None,
+                    id: None,
+                },
+            },
+        ],
+    },
+);
+
+struct Section<const COLS: usize> {
+    title: &'static str,
+    entries: [SectionEntry; COLS],
+}
+
+impl<const COLS: usize> Section<COLS> {
+    fn render(self, index_offset: usize, focus: &FocusHandle, cx: &App) -> impl IntoElement {
+        v_flex()
+            .min_w_full()
+            .child(SectionHeader::new(self.title))
+            .children(
+                self.entries
+                    .iter()
+                    .enumerate()
+                    .map(|(index, entry)| entry.render(index_offset + index, focus, cx)),
+            )
+    }
+}
+
+pub struct WelcomePage {
+    workspace: WeakEntity<Workspace>,
+    focus_handle: FocusHandle,
+    fallback_to_recent_projects: bool,
+    recent_workspaces: Option<Vec<(WorkspaceId, SerializedWorkspaceLocation, PathList)>>,
+}
+
+impl WelcomePage {
+    pub fn new(
+        workspace: WeakEntity<Workspace>,
+        fallback_to_recent_projects: bool,
+        window: &mut Window,
+        cx: &mut Context<Self>,
+    ) -> Self {
+        let focus_handle = cx.focus_handle();
+        cx.on_focus(&focus_handle, window, |_, _, cx| cx.notify())
+            .detach();
+
+        if fallback_to_recent_projects {
+            cx.spawn_in(window, async move |this: WeakEntity<Self>, cx| {
+                let workspaces = WORKSPACE_DB
+                    .recent_workspaces_on_disk()
+                    .await
+                    .log_err()
+                    .unwrap_or_default();
+
+                this.update(cx, |this, cx| {
+                    this.recent_workspaces = Some(workspaces);
+                    cx.notify();
+                })
+                .ok();
+            })
+            .detach();
+        }
+
+        WelcomePage {
+            workspace,
+            focus_handle,
+            fallback_to_recent_projects,
+            recent_workspaces: None,
+        }
+    }
+
+    fn select_next(&mut self, _: &SelectNext, window: &mut Window, cx: &mut Context<Self>) {
+        window.focus_next(cx);
+        cx.notify();
+    }
+
+    fn select_previous(&mut self, _: &SelectPrevious, window: &mut Window, cx: &mut Context<Self>) {
+        window.focus_prev(cx);
+        cx.notify();
+    }
+
+    fn open_recent_project(
+        &mut self,
+        action: &OpenRecentProject,
+        window: &mut Window,
+        cx: &mut Context<Self>,
+    ) {
+        if let Some(recent_workspaces) = &self.recent_workspaces {
+            if let Some((_workspace_id, location, paths)) = recent_workspaces.get(action.index) {
+                let paths = paths.clone();
+                let location = location.clone();
+                let is_local = matches!(location, SerializedWorkspaceLocation::Local);
+                let workspace = self.workspace.clone();
+
+                if is_local {
+                    let paths = paths.paths().to_vec();
+                    cx.spawn_in(window, async move |_, cx| {
+                        let _ = workspace.update_in(cx, |workspace, window, cx| {
+                            workspace
+                                .open_workspace_for_paths(true, paths, window, cx)
+                                .detach();
+                        });
+                    })
+                    .detach();
+                } else {
+                    use zed_actions::OpenRecent;
+                    window.dispatch_action(OpenRecent::default().boxed_clone(), cx);
+                }
+            }
+        }
+    }
+
+    fn render_recent_project_section(
+        &self,
+        recent_projects: Vec<impl IntoElement>,
+    ) -> impl IntoElement {
+        v_flex()
+            .w_full()
+            .child(SectionHeader::new("Recent Projects"))
+            .children(recent_projects)
+    }
+
+    fn render_recent_project(
+        &self,
+        index: usize,
+        location: &SerializedWorkspaceLocation,
+        paths: &PathList,
+    ) -> impl IntoElement {
+        let (icon, title) = match location {
+            SerializedWorkspaceLocation::Local => {
+                let path = paths.paths().first().map(|p| p.as_path());
+                let name = path
+                    .and_then(|p| p.file_name())
+                    .map(|n| n.to_string_lossy().to_string())
+                    .unwrap_or_else(|| "Untitled".to_string());
+                (IconName::Folder, name)
+            }
+            SerializedWorkspaceLocation::Remote(_) => {
+                (IconName::Server, "Remote Project".to_string())
+            }
+        };
+
+        SectionButton::new(
+            title,
+            icon,
+            &OpenRecentProject { index },
+            10,
+            self.focus_handle.clone(),
+        )
+    }
+}
+
+impl Render for WelcomePage {
+    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
+        let (first_section, second_section) = CONTENT;
+        let first_section_entries = first_section.entries.len();
+        let last_index = first_section_entries + second_section.entries.len();
+
+        let recent_projects = self
+            .recent_workspaces
+            .as_ref()
+            .into_iter()
+            .flatten()
+            .take(5)
+            .enumerate()
+            .map(|(index, (_, loc, paths))| self.render_recent_project(index, loc, paths))
+            .collect::<Vec<_>>();
+
+        let second_section = if self.fallback_to_recent_projects && !recent_projects.is_empty() {
+            self.render_recent_project_section(recent_projects)
+                .into_any_element()
+        } else {
+            second_section
+                .render(first_section_entries, &self.focus_handle, cx)
+                .into_any_element()
+        };
+
+        let welcome_label = if self.fallback_to_recent_projects {
+            "Welcome back to Zed"
+        } else {
+            "Welcome to Zed"
+        };
+
+        h_flex()
+            .key_context("Welcome")
+            .track_focus(&self.focus_handle(cx))
+            .on_action(cx.listener(Self::select_previous))
+            .on_action(cx.listener(Self::select_next))
+            .on_action(cx.listener(Self::open_recent_project))
+            .size_full()
+            .justify_center()
+            .overflow_hidden()
+            .bg(cx.theme().colors().editor_background)
+            .child(
+                h_flex()
+                    .relative()
+                    .size_full()
+                    .px_12()
+                    .py_40()
+                    .max_w(px(1100.))
+                    .child(
+                        v_flex()
+                            .size_full()
+                            .max_w_128()
+                            .mx_auto()
+                            .gap_6()
+                            .overflow_x_hidden()
+                            .child(
+                                h_flex()
+                                    .w_full()
+                                    .justify_center()
+                                    .mb_4()
+                                    .gap_4()
+                                    .child(Vector::square(VectorName::ZedLogo, rems_from_px(45.)))
+                                    .child(
+                                        v_flex().child(Headline::new(welcome_label)).child(
+                                            Label::new("The editor for what's next")
+                                                .size(LabelSize::Small)
+                                                .color(Color::Muted)
+                                                .italic(),
+                                        ),
+                                    ),
+                            )
+                            .child(first_section.render(Default::default(), &self.focus_handle, cx))
+                            .child(second_section)
+                            .when(!self.fallback_to_recent_projects, |this| {
+                                this.child(
+                                    v_flex().gap_1().child(Divider::horizontal()).child(
+                                        Button::new("welcome-exit", "Return to Onboarding")
+                                            .tab_index(last_index as isize)
+                                            .full_width()
+                                            .label_size(LabelSize::XSmall)
+                                            .on_click(|_, window, cx| {
+                                                window.dispatch_action(
+                                                    OpenOnboarding.boxed_clone(),
+                                                    cx,
+                                                );
+                                            }),
+                                    ),
+                                )
+                            }),
+                    ),
+            )
+    }
+}
+
+impl EventEmitter<ItemEvent> for WelcomePage {}
+
+impl Focusable for WelcomePage {
+    fn focus_handle(&self, _: &App) -> gpui::FocusHandle {
+        self.focus_handle.clone()
+    }
+}
+
+impl Item for WelcomePage {
+    type Event = ItemEvent;
+
+    fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
+        "Welcome".into()
+    }
+
+    fn telemetry_event_text(&self) -> Option<&'static str> {
+        Some("New Welcome Page Opened")
+    }
+
+    fn show_toolbar(&self) -> bool {
+        false
+    }
+
+    fn to_item_events(event: &Self::Event, mut f: impl FnMut(crate::item::ItemEvent)) {
+        f(*event)
+    }
+}
+
+impl crate::SerializableItem for WelcomePage {
+    fn serialized_item_kind() -> &'static str {
+        "WelcomePage"
+    }
+
+    fn cleanup(
+        workspace_id: crate::WorkspaceId,
+        alive_items: Vec<crate::ItemId>,
+        _window: &mut Window,
+        cx: &mut App,
+    ) -> Task<gpui::Result<()>> {
+        crate::delete_unloaded_items(
+            alive_items,
+            workspace_id,
+            "welcome_pages",
+            &persistence::WELCOME_PAGES,
+            cx,
+        )
+    }
+
+    fn deserialize(
+        _project: Entity<project::Project>,
+        workspace: gpui::WeakEntity<Workspace>,
+        workspace_id: crate::WorkspaceId,
+        item_id: crate::ItemId,
+        window: &mut Window,
+        cx: &mut App,
+    ) -> Task<gpui::Result<Entity<Self>>> {
+        if persistence::WELCOME_PAGES
+            .get_welcome_page(item_id, workspace_id)
+            .ok()
+            .is_some_and(|is_open| is_open)
+        {
+            Task::ready(Ok(
+                cx.new(|cx| WelcomePage::new(workspace, false, window, cx))
+            ))
+        } else {
+            Task::ready(Err(anyhow::anyhow!("No welcome page to deserialize")))
+        }
+    }
+
+    fn serialize(
+        &mut self,
+        workspace: &mut Workspace,
+        item_id: crate::ItemId,
+        _closing: bool,
+        _window: &mut Window,
+        cx: &mut Context<Self>,
+    ) -> Option<Task<gpui::Result<()>>> {
+        let workspace_id = workspace.database_id()?;
+        Some(cx.background_spawn(async move {
+            persistence::WELCOME_PAGES
+                .save_welcome_page(item_id, workspace_id, true)
+                .await
+        }))
+    }
+
+    fn should_serialize(&self, event: &Self::Event) -> bool {
+        event == &ItemEvent::UpdateTab
+    }
+}
+
+mod persistence {
+    use crate::WorkspaceDb;
+    use db::{
+        query,
+        sqlez::{domain::Domain, thread_safe_connection::ThreadSafeConnection},
+        sqlez_macros::sql,
+    };
+
+    pub struct WelcomePagesDb(ThreadSafeConnection);
+
+    impl Domain for WelcomePagesDb {
+        const NAME: &str = stringify!(WelcomePagesDb);
+
+        const MIGRATIONS: &[&str] = (&[sql!(
+                    CREATE TABLE welcome_pages (
+                        workspace_id INTEGER,
+                        item_id INTEGER UNIQUE,
+                        is_open INTEGER DEFAULT FALSE,
+
+                        PRIMARY KEY(workspace_id, item_id),
+                        FOREIGN KEY(workspace_id) REFERENCES workspaces(workspace_id)
+                        ON DELETE CASCADE
+                    ) STRICT;
+        )]);
+    }
+
+    db::static_connection!(WELCOME_PAGES, WelcomePagesDb, [WorkspaceDb]);
+
+    impl WelcomePagesDb {
+        query! {
+            pub async fn save_welcome_page(
+                item_id: crate::ItemId,
+                workspace_id: crate::WorkspaceId,
+                is_open: bool
+            ) -> Result<()> {
+                INSERT OR REPLACE INTO welcome_pages(item_id, workspace_id, is_open)
+                VALUES (?, ?, ?)
+            }
+        }
+
+        query! {
+            pub fn get_welcome_page(
+                item_id: crate::ItemId,
+                workspace_id: crate::WorkspaceId
+            ) -> Result<bool> {
+                SELECT is_open
+                FROM welcome_pages
+                WHERE item_id = ? AND workspace_id = ?
+            }
+        }
+    }
+}

crates/workspace/src/workspace.rs 🔗

@@ -9,12 +9,15 @@ pub mod pane_group;
 mod path_list;
 mod persistence;
 pub mod searchable;
+mod security_modal;
 pub mod shared_screen;
 mod status_bar;
 pub mod tasks;
 mod theme_preview;
 mod toast_layer;
 mod toolbar;
+pub mod utility_pane;
+pub mod welcome;
 mod workspace_settings;
 
 pub use crate::notifications::NotificationFrame;
@@ -30,6 +33,7 @@ use client::{
 };
 use collections::{HashMap, HashSet, hash_map};
 use dock::{Dock, DockPosition, PanelButtons, PanelHandle, RESIZE_HANDLE_SIZE};
+use feature_flags::{AgentV2FeatureFlag, FeatureFlagAppExt};
 use futures::{
     Future, FutureExt, StreamExt,
     channel::{
@@ -74,7 +78,9 @@ use project::{
     DirectoryLister, Project, ProjectEntryId, ProjectPath, ResolvedPath, Worktree, WorktreeId,
     WorktreeSettings,
     debugger::{breakpoint_store::BreakpointStoreEvent, session::ThreadStatus},
+    project_settings::ProjectSettings,
     toolchain_store::ToolchainStoreEvent,
+    trusted_worktrees::{TrustedWorktrees, TrustedWorktreesEvent},
 };
 use remote::{
     RemoteClientDelegate, RemoteConnection, RemoteConnectionOptions,
@@ -83,7 +89,9 @@ use remote::{
 use schemars::JsonSchema;
 use serde::Deserialize;
 use session::AppSession;
-use settings::{CenteredPaddingSettings, Settings, SettingsLocation, update_settings_file};
+use settings::{
+    CenteredPaddingSettings, Settings, SettingsLocation, SettingsStore, update_settings_file,
+};
 use shared_screen::SharedScreen;
 use sqlez::{
     bindable::{Bind, Column, StaticColumnCount},
@@ -126,11 +134,19 @@ pub use workspace_settings::{
 };
 use zed_actions::{Spawn, feedback::FileBugReport};
 
-use crate::persistence::{
-    SerializedAxis,
-    model::{DockData, DockStructure, SerializedItem, SerializedPane, SerializedPaneGroup},
+use crate::{
+    item::ItemBufferKind,
+    notifications::NotificationId,
+    utility_pane::{UTILITY_PANE_MIN_WIDTH, utility_slot_for_dock_position},
+};
+use crate::{
+    persistence::{
+        SerializedAxis,
+        model::{DockData, DockStructure, SerializedItem, SerializedPane, SerializedPaneGroup},
+    },
+    security_modal::SecurityModal,
+    utility_pane::{DraggedUtilityPane, UtilityPaneFrame, UtilityPaneSlot, UtilityPaneState},
 };
-use crate::{item::ItemBufferKind, notifications::NotificationId};
 
 pub const SERIALIZATION_THROTTLE_TIME: Duration = Duration::from_millis(200);
 
@@ -265,6 +281,16 @@ actions!(
         ToggleRightDock,
         /// Toggles zoom on the active pane.
         ToggleZoom,
+        /// Zooms in on the active pane.
+        ZoomIn,
+        /// Zooms out of the active pane.
+        ZoomOut,
+        /// If any worktrees are in restricted mode, shows a modal with possible actions.
+        /// If the modal is shown already, closes it without trusting any worktree.
+        ToggleWorktreeSecurity,
+        /// Clears all trusted worktrees, placing them in restricted mode on next open.
+        /// Requires restart to take effect on already opened projects.
+        ClearTrustedWorktrees,
         /// Stops following a collaborator.
         Unfollow,
         /// Restores the banner.
@@ -569,44 +595,43 @@ pub fn init(app_state: Arc<AppState>, cx: &mut App) {
     toast_layer::init(cx);
     history_manager::init(cx);
 
-    cx.on_action(|_: &CloseWindow, cx| Workspace::close_global(cx));
-    cx.on_action(|_: &Reload, cx| reload(cx));
-
-    cx.on_action({
-        let app_state = Arc::downgrade(&app_state);
-        move |_: &Open, cx: &mut App| {
-            if let Some(app_state) = app_state.upgrade() {
-                prompt_and_open_paths(
-                    app_state,
-                    PathPromptOptions {
-                        files: true,
-                        directories: true,
-                        multiple: true,
-                        prompt: None,
-                    },
-                    cx,
-                );
+    cx.on_action(|_: &CloseWindow, cx| Workspace::close_global(cx))
+        .on_action(|_: &Reload, cx| reload(cx))
+        .on_action({
+            let app_state = Arc::downgrade(&app_state);
+            move |_: &Open, cx: &mut App| {
+                if let Some(app_state) = app_state.upgrade() {
+                    prompt_and_open_paths(
+                        app_state,
+                        PathPromptOptions {
+                            files: true,
+                            directories: true,
+                            multiple: true,
+                            prompt: None,
+                        },
+                        cx,
+                    );
+                }
             }
-        }
-    });
-    cx.on_action({
-        let app_state = Arc::downgrade(&app_state);
-        move |_: &OpenFiles, cx: &mut App| {
-            let directories = cx.can_select_mixed_files_and_dirs();
-            if let Some(app_state) = app_state.upgrade() {
-                prompt_and_open_paths(
-                    app_state,
-                    PathPromptOptions {
-                        files: true,
-                        directories,
-                        multiple: true,
-                        prompt: None,
-                    },
-                    cx,
-                );
+        })
+        .on_action({
+            let app_state = Arc::downgrade(&app_state);
+            move |_: &OpenFiles, cx: &mut App| {
+                let directories = cx.can_select_mixed_files_and_dirs();
+                if let Some(app_state) = app_state.upgrade() {
+                    prompt_and_open_paths(
+                        app_state,
+                        PathPromptOptions {
+                            files: true,
+                            directories,
+                            multiple: true,
+                            prompt: None,
+                        },
+                        cx,
+                    );
+                }
             }
-        }
-    });
+        });
 }
 
 type BuildProjectItemFn =
@@ -675,6 +700,7 @@ impl ProjectItemRegistry {
                             Ok((project_entry_id, build_workspace_item))
                         }
                         Err(e) => {
+                            log::warn!("Failed to open a project item: {e:#}");
                             if e.error_code() == ErrorCode::Internal {
                                 if let Some(abs_path) =
                                     entry_abs_path.as_deref().filter(|_| is_file)
@@ -962,6 +988,7 @@ impl AppState {
 
     #[cfg(any(test, feature = "test-support"))]
     pub fn test(cx: &mut App) -> Arc<Self> {
+        use fs::Fs;
         use node_runtime::NodeRuntime;
         use session::Session;
         use settings::SettingsStore;
@@ -972,6 +999,7 @@ impl AppState {
         }
 
         let fs = fs::FakeFs::new(cx.background_executor().clone());
+        <dyn Fs>::set_global(fs.clone(), cx);
         let languages = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
         let clock = Arc::new(clock::FakeSystemClock::new());
         let http_client = http_client::FakeHttpClient::with_404_response();
@@ -1160,6 +1188,7 @@ pub struct Workspace {
     _observe_current_user: Task<Result<()>>,
     _schedule_serialize_workspace: Option<Task<()>>,
     _schedule_serialize_ssh_paths: Option<Task<()>>,
+    _schedule_serialize_worktree_trust: Task<()>,
     pane_history_timestamp: Arc<AtomicUsize>,
     bounds: Bounds<Pixels>,
     pub centered_layout: bool,
@@ -1174,6 +1203,8 @@ pub struct Workspace {
     scheduled_tasks: Vec<Task<()>>,
     last_open_dock_positions: Vec<DockPosition>,
     removing: bool,
+    utility_panes: UtilityPaneState,
+    next_modal_placement: Option<ModalPlacement>,
 }
 
 impl EventEmitter<Event> for Workspace {}
@@ -1204,6 +1235,41 @@ impl Workspace {
         window: &mut Window,
         cx: &mut Context<Self>,
     ) -> Self {
+        if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
+            cx.subscribe(&trusted_worktrees, |workspace, worktrees_store, e, cx| {
+                if let TrustedWorktreesEvent::Trusted(..) = e {
+                    // Do not persist auto trusted worktrees
+                    if !ProjectSettings::get_global(cx).session.trust_all_worktrees {
+                        let new_trusted_worktrees =
+                            worktrees_store.update(cx, |worktrees_store, cx| {
+                                worktrees_store.trusted_paths_for_serialization(cx)
+                            });
+                        let timeout = cx.background_executor().timer(SERIALIZATION_THROTTLE_TIME);
+                        workspace._schedule_serialize_worktree_trust =
+                            cx.background_spawn(async move {
+                                timeout.await;
+                                persistence::DB
+                                    .save_trusted_worktrees(new_trusted_worktrees)
+                                    .await
+                                    .log_err();
+                            });
+                    }
+                }
+            })
+            .detach();
+
+            cx.observe_global::<SettingsStore>(|_, cx| {
+                if ProjectSettings::get_global(cx).session.trust_all_worktrees {
+                    if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
+                        trusted_worktrees.update(cx, |trusted_worktrees, cx| {
+                            trusted_worktrees.auto_trust_all(cx);
+                        })
+                    }
+                }
+            })
+            .detach();
+        }
+
         cx.subscribe_in(&project, window, move |this, _, event, window, cx| {
             match event {
                 project::Event::RemoteIdChanged(_) => {
@@ -1214,11 +1280,25 @@ impl Workspace {
                     this.collaborator_left(*peer_id, window, cx);
                 }
 
-                project::Event::WorktreeRemoved(_) | project::Event::WorktreeAdded(_) => {
-                    this.update_window_title(window, cx);
-                    this.serialize_workspace(window, cx);
-                    // This event could be triggered by `AddFolderToProject` or `RemoveFromProject`.
-                    this.update_history(cx);
+                project::Event::WorktreeUpdatedEntries(worktree_id, _) => {
+                    if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
+                        trusted_worktrees.update(cx, |trusted_worktrees, cx| {
+                            trusted_worktrees.can_trust(*worktree_id, cx);
+                        });
+                    }
+                }
+
+                project::Event::WorktreeRemoved(_) => {
+                    this.update_worktree_data(window, cx);
+                }
+
+                project::Event::WorktreeAdded(worktree_id) => {
+                    if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
+                        trusted_worktrees.update(cx, |trusted_worktrees, cx| {
+                            trusted_worktrees.can_trust(*worktree_id, cx);
+                        });
+                    }
+                    this.update_worktree_data(window, cx);
                 }
 
                 project::Event::DisconnectedFromHost => {
@@ -1315,7 +1395,7 @@ impl Workspace {
 
         cx.on_focus_lost(window, |this, window, cx| {
             let focus_handle = this.focus_handle(cx);
-            window.focus(&focus_handle);
+            window.focus(&focus_handle, cx);
         })
         .detach();
 
@@ -1339,7 +1419,7 @@ impl Workspace {
         cx.subscribe_in(&center_pane, window, Self::handle_pane_event)
             .detach();
 
-        window.focus(&center_pane.focus_handle(cx));
+        window.focus(&center_pane.focus_handle(cx), cx);
 
         cx.emit(Event::PaneAdded(center_pane.clone()));
 
@@ -1430,6 +1510,15 @@ impl Workspace {
                             && let Ok(display_uuid) = display.uuid()
                         {
                             let window_bounds = window.inner_window_bounds();
+                            let has_paths = !this.root_paths(cx).is_empty();
+                            if !has_paths {
+                                cx.background_executor()
+                                    .spawn(persistence::write_default_window_bounds(
+                                        window_bounds,
+                                        display_uuid,
+                                    ))
+                                    .detach_and_log_err(cx);
+                            }
                             if let Some(database_id) = workspace_id {
                                 cx.background_executor()
                                     .spawn(DB.set_window_open_status(
@@ -1438,6 +1527,13 @@ impl Workspace {
                                         display_uuid,
                                     ))
                                     .detach_and_log_err(cx);
+                            } else {
+                                cx.background_executor()
+                                    .spawn(persistence::write_default_window_bounds(
+                                        window_bounds,
+                                        display_uuid,
+                                    ))
+                                    .detach_and_log_err(cx);
                             }
                         }
                         this.bounds_save_task_queued.take();
@@ -1461,16 +1557,21 @@ impl Workspace {
             }),
         ];
 
-        cx.defer_in(window, |this, window, cx| {
+        cx.defer_in(window, move |this, window, cx| {
             this.update_window_title(window, cx);
             this.show_initial_notifications(cx);
         });
+
+        let mut center = PaneGroup::new(center_pane.clone());
+        center.set_is_center(true);
+        center.mark_positions(cx);
+
         Workspace {
             weak_self: weak_handle.clone(),
             zoomed: None,
             zoomed_position: None,
             previous_dock_drag_coordinates: None,
-            center: PaneGroup::new(center_pane.clone()),
+            center,
             panes: vec![center_pane.clone()],
             panes_by_item: Default::default(),
             active_pane: center_pane.clone(),
@@ -1499,6 +1600,7 @@ impl Workspace {
             _apply_leader_updates,
             _schedule_serialize_workspace: None,
             _schedule_serialize_ssh_paths: None,
+            _schedule_serialize_worktree_trust: Task::ready(()),
             leader_updates_tx,
             _subscriptions: subscriptions,
             pane_history_timestamp,
@@ -1518,6 +1620,8 @@ impl Workspace {
             scheduled_tasks: Vec::new(),
             last_open_dock_positions: Vec::new(),
             removing: false,
+            utility_panes: UtilityPaneState::default(),
+            next_modal_placement: None,
         }
     }
 
@@ -1526,6 +1630,7 @@ impl Workspace {
         app_state: Arc<AppState>,
         requesting_window: Option<WindowHandle<Workspace>>,
         env: Option<HashMap<String, String>>,
+        init: Option<Box<dyn FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send>>,
         cx: &mut App,
     ) -> Task<
         anyhow::Result<(
@@ -1540,6 +1645,7 @@ impl Workspace {
             app_state.languages.clone(),
             app_state.fs.clone(),
             env,
+            true,
             cx,
         );
 
@@ -1593,8 +1699,22 @@ impl Workspace {
 
             let toolchains = DB.toolchains(workspace_id).await?;
 
-            for (toolchain, worktree_id, path) in toolchains {
+            for (toolchain, worktree_path, path) in toolchains {
                 let toolchain_path = PathBuf::from(toolchain.path.clone().to_string());
+                let Some(worktree_id) = project_handle.read_with(cx, |this, cx| {
+                    this.find_worktree(&worktree_path, cx)
+                        .and_then(|(worktree, rel_path)| {
+                            if rel_path.is_empty() {
+                                Some(worktree.read(cx).id())
+                            } else {
+                                None
+                            }
+                        })
+                })?
+                else {
+                    // We did not find a worktree with a given path, but that's whatever.
+                    continue;
+                };
                 if !app_state.fs.is_file(toolchain_path.as_path()).await {
                     continue;
                 }
@@ -1632,6 +1752,12 @@ impl Workspace {
                         );
 
                         workspace.centered_layout = centered_layout;
+
+                        // Call init callback to add items before window renders
+                        if let Some(init) = init {
+                            init(&mut workspace, window, cx);
+                        }
+
                         workspace
                     });
                 })?;
@@ -1641,20 +1767,18 @@ impl Workspace {
 
                 let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
                     (Some(WindowBounds::Windowed(bounds)), None)
+                } else if let Some(workspace) = serialized_workspace.as_ref()
+                    && let Some(display) = workspace.display
+                    && let Some(bounds) = workspace.window_bounds.as_ref()
+                {
+                    // Reopening an existing workspace - restore its saved bounds
+                    (Some(bounds.0), Some(display))
+                } else if let Some((display, bounds)) = persistence::read_default_window_bounds() {
+                    // New or empty workspace - use the last known window bounds
+                    (Some(bounds), Some(display))
                 } else {
-                    let restorable_bounds = serialized_workspace
-                        .as_ref()
-                        .and_then(|workspace| Some((workspace.display?, workspace.window_bounds?)))
-                        .or_else(|| {
-                            let (display, window_bounds) = DB.last_window().log_err()?;
-                            Some((display?, window_bounds?))
-                        });
-
-                    if let Some((serialized_display, serialized_status)) = restorable_bounds {
-                        (Some(serialized_status.0), Some(serialized_display))
-                    } else {
-                        (None, None)
-                    }
+                    // New window - let GPUI's default_bounds() handle cascading
+                    (None, None)
                 };
 
                 // Use the serialized workspace to construct the new window
@@ -1677,6 +1801,12 @@ impl Workspace {
                                 cx,
                             );
                             workspace.centered_layout = centered_layout;
+
+                            // Call init callback to add items before window renders
+                            if let Some(init) = init {
+                                init(&mut workspace, window, cx);
+                            }
+
                             workspace
                         })
                     }
@@ -1772,10 +1902,18 @@ impl Workspace {
         window: &mut Window,
         cx: &mut Context<Self>,
     ) {
+        let mut found_in_dock = None;
         for dock in [&self.left_dock, &self.bottom_dock, &self.right_dock] {
-            dock.update(cx, |dock, cx| {
-                dock.remove_panel(panel, window, cx);
-            })
+            let found = dock.update(cx, |dock, cx| dock.remove_panel(panel, window, cx));
+
+            if found {
+                found_in_dock = Some(dock.clone());
+            }
+        }
+        if let Some(found_in_dock) = found_in_dock {
+            let position = found_in_dock.read(cx).position();
+            let slot = utility_slot_for_dock_position(position);
+            self.clear_utility_pane_if_provider(slot, Entity::entity_id(panel), cx);
         }
     }
 
@@ -1936,7 +2074,7 @@ impl Workspace {
     ) -> Task<Result<()>> {
         let to_load = if let Some(pane) = pane.upgrade() {
             pane.update(cx, |pane, cx| {
-                window.focus(&pane.focus_handle(cx));
+                window.focus(&pane.focus_handle(cx), cx);
                 loop {
                     // Retrieve the weak item handle from the history.
                     let entry = pane.nav_history_mut().pop(mode, cx)?;
@@ -2242,7 +2380,7 @@ impl Workspace {
             Task::ready(Ok(callback(self, window, cx)))
         } else {
             let env = self.project.read(cx).cli_environment(cx);
-            let task = Self::new_local(Vec::new(), self.app_state.clone(), None, env, cx);
+            let task = Self::new_local(Vec::new(), self.app_state.clone(), None, env, None, cx);
             cx.spawn_in(window, async move |_vh, cx| {
                 let (workspace, _) = task.await?;
                 workspace.update(cx, callback)
@@ -2453,6 +2591,12 @@ impl Workspace {
             .0
             .split(' ')
             .flat_map(|k| Keystroke::parse(k).log_err())
+            .map(|k| {
+                cx.keyboard_mapper()
+                    .map_key_equivalent(k, true)
+                    .inner()
+                    .clone()
+            })
             .collect();
         let _ = self.send_keystrokes_impl(keystrokes, window, cx);
     }
@@ -3049,7 +3193,7 @@ impl Workspace {
                     }
                 } else {
                     let focus_handle = &active_panel.panel_focus_handle(cx);
-                    window.focus(focus_handle);
+                    window.focus(focus_handle, cx);
                     reveal_dock = true;
                 }
             }
@@ -3061,7 +3205,7 @@ impl Workspace {
 
         if focus_center {
             self.active_pane
-                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx)))
+                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
         }
 
         cx.notify();
@@ -3229,7 +3373,7 @@ impl Workspace {
                     if let Some(panel) = panel.as_ref() {
                         if should_focus(&**panel, window, cx) {
                             dock.set_open(true, window, cx);
-                            panel.panel_focus_handle(cx).focus(window);
+                            panel.panel_focus_handle(cx).focus(window, cx);
                         } else {
                             focus_center = true;
                         }
@@ -3239,7 +3383,7 @@ impl Workspace {
 
                 if focus_center {
                     self.active_pane
-                        .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx)))
+                        .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
                 }
 
                 result_panel = panel;
@@ -3313,7 +3457,7 @@ impl Workspace {
 
         if focus_center {
             self.active_pane
-                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx)))
+                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
         }
 
         if self.zoomed_position != dock_to_reveal {
@@ -3344,7 +3488,7 @@ impl Workspace {
             .detach();
         self.panes.push(pane.clone());
 
-        window.focus(&pane.focus_handle(cx));
+        window.focus(&pane.focus_handle(cx), cx);
 
         cx.emit(Event::PaneAdded(pane.clone()));
         pane
@@ -3636,14 +3780,33 @@ impl Workspace {
         project_item: Entity<T::Item>,
         activate_pane: bool,
         focus_item: bool,
+        keep_old_preview: bool,
+        allow_new_preview: bool,
         window: &mut Window,
         cx: &mut Context<Self>,
     ) -> Entity<T>
     where
         T: ProjectItem,
     {
+        let old_item_id = pane.read(cx).active_item().map(|item| item.item_id());
+
         if let Some(item) = self.find_project_item(&pane, &project_item, cx) {
+            if !keep_old_preview
+                && let Some(old_id) = old_item_id
+                && old_id != item.item_id()
+            {
+                // switching to a different item, so unpreview old active item
+                pane.update(cx, |pane, _| {
+                    pane.unpreview_item_if_preview(old_id);
+                });
+            }
+
             self.activate_item(&item, activate_pane, focus_item, window, cx);
+            if !allow_new_preview {
+                pane.update(cx, |pane, _| {
+                    pane.unpreview_item_if_preview(item.item_id());
+                });
+            }
             return item;
         }
 
@@ -3652,16 +3815,14 @@ impl Workspace {
                 T::for_project_item(self.project().clone(), Some(pane), project_item, window, cx)
             })
         });
-        let item_id = item.item_id();
         let mut destination_index = None;
         pane.update(cx, |pane, cx| {
-            if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation
-                && let Some(preview_item_id) = pane.preview_item_id()
-                && preview_item_id != item_id
-            {
-                destination_index = pane.close_current_preview_item(window, cx);
+            if !keep_old_preview && let Some(old_id) = old_item_id {
+                pane.unpreview_item_if_preview(old_id);
+            }
+            if allow_new_preview {
+                destination_index = pane.replace_preview_item_id(item.item_id(), window, cx);
             }
-            pane.set_preview_item_id(Some(item.item_id()), cx)
         });
 
         self.add_item(
@@ -3722,7 +3883,7 @@ impl Workspace {
     ) {
         let panes = self.center.panes();
         if let Some(pane) = panes.get(action.0).map(|p| (*p).clone()) {
-            window.focus(&pane.focus_handle(cx));
+            window.focus(&pane.focus_handle(cx), cx);
         } else {
             self.split_and_clone(self.active_pane.clone(), SplitDirection::Right, window, cx)
                 .detach();
@@ -3749,7 +3910,7 @@ impl Workspace {
                 let new_pane = self.add_pane(window, cx);
                 if self
                     .center
-                    .split(&split_off_pane, &new_pane, direction)
+                    .split(&split_off_pane, &new_pane, direction, cx)
                     .log_err()
                     .is_none()
                 {
@@ -3792,7 +3953,7 @@ impl Workspace {
         if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
             let next_ix = (ix + 1) % panes.len();
             let next_pane = panes[next_ix].clone();
-            window.focus(&next_pane.focus_handle(cx));
+            window.focus(&next_pane.focus_handle(cx), cx);
         }
     }
 
@@ -3801,7 +3962,7 @@ impl Workspace {
         if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
             let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
             let prev_pane = panes[prev_ix].clone();
-            window.focus(&prev_pane.focus_handle(cx));
+            window.focus(&prev_pane.focus_handle(cx), cx);
         }
     }
 
@@ -3897,7 +4058,7 @@ impl Workspace {
             Some(ActivateInDirectionTarget::Pane(pane)) => {
                 let pane = pane.read(cx);
                 if let Some(item) = pane.active_item() {
-                    item.item_focus_handle(cx).focus(window);
+                    item.item_focus_handle(cx).focus(window, cx);
                 } else {
                     log::error!(
                         "Could not find a focus target when in switching focus in {direction} direction for a pane",
@@ -3909,7 +4070,7 @@ impl Workspace {
                 window.defer(cx, move |window, cx| {
                     let dock = dock.read(cx);
                     if let Some(panel) = dock.active_panel() {
-                        panel.panel_focus_handle(cx).focus(window);
+                        panel.panel_focus_handle(cx).focus(window, cx);
                     } else {
                         log::error!("Could not find a focus target when in switching focus in {direction} direction for a {:?} dock", dock.position());
                     }
@@ -3934,7 +4095,7 @@ impl Workspace {
                 let new_pane = self.add_pane(window, cx);
                 if self
                     .center
-                    .split(&self.active_pane, &new_pane, action.direction)
+                    .split(&self.active_pane, &new_pane, action.direction, cx)
                     .log_err()
                     .is_none()
                 {
@@ -3988,7 +4149,7 @@ impl Workspace {
 
     pub fn swap_pane_in_direction(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
         if let Some(to) = self.find_pane_in_direction(direction, cx) {
-            self.center.swap(&self.active_pane, &to);
+            self.center.swap(&self.active_pane, &to, cx);
             cx.notify();
         }
     }
@@ -3996,7 +4157,7 @@ impl Workspace {
     pub fn move_pane_to_border(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
         if self
             .center
-            .move_to_border(&self.active_pane, direction)
+            .move_to_border(&self.active_pane, direction, cx)
             .unwrap()
         {
             cx.notify();
@@ -4026,13 +4187,13 @@ impl Workspace {
             }
         } else {
             self.center
-                .resize(&self.active_pane, axis, amount, &self.bounds);
+                .resize(&self.active_pane, axis, amount, &self.bounds, cx);
         }
         cx.notify();
     }
 
     pub fn reset_pane_sizes(&mut self, cx: &mut Context<Self>) {
-        self.center.reset_pane_sizes();
+        self.center.reset_pane_sizes(cx);
         cx.notify();
     }
 
@@ -4078,7 +4239,7 @@ impl Workspace {
         cx: &mut Context<Self>,
     ) {
         self.active_pane = pane.clone();
-        self.active_item_path_changed(window, cx);
+        self.active_item_path_changed(true, window, cx);
         self.last_active_center_pane = Some(pane.downgrade());
     }
 
@@ -4101,16 +4262,19 @@ impl Workspace {
                     item: item.boxed_clone(),
                 });
             }
-            pane::Event::Split {
-                direction,
-                clone_active_item,
-            } => {
-                if *clone_active_item {
-                    self.split_and_clone(pane.clone(), *direction, window, cx)
-                        .detach();
-                } else {
-                    self.split_and_move(pane.clone(), *direction, window, cx);
-                }
+            pane::Event::Split { direction, mode } => {
+                match mode {
+                    SplitMode::ClonePane => {
+                        self.split_and_clone(pane.clone(), *direction, window, cx)
+                            .detach();
+                    }
+                    SplitMode::EmptyPane => {
+                        self.split_pane(pane.clone(), *direction, window, cx);
+                    }
+                    SplitMode::MovePane => {
+                        self.split_and_move(pane.clone(), *direction, window, cx);
+                    }
+                };
             }
             pane::Event::JoinIntoNext => {
                 self.join_pane_into_next(pane.clone(), window, cx);
@@ -4135,7 +4299,7 @@ impl Workspace {
                 }
                 serialize_workspace = *focus_changed || pane != self.active_pane();
                 if pane == self.active_pane() {
-                    self.active_item_path_changed(window, cx);
+                    self.active_item_path_changed(*focus_changed, window, cx);
                     self.update_active_view_for_followers(window, cx);
                 } else if *local {
                     self.set_active_pane(pane, window, cx);
@@ -4151,7 +4315,7 @@ impl Workspace {
             }
             pane::Event::ChangeItemTitle => {
                 if *pane == self.active_pane {
-                    self.active_item_path_changed(window, cx);
+                    self.active_item_path_changed(false, window, cx);
                 }
                 serialize_workspace = false;
             }
@@ -4218,7 +4382,7 @@ impl Workspace {
     ) -> Entity<Pane> {
         let new_pane = self.add_pane(window, cx);
         self.center
-            .split(&pane_to_split, &new_pane, split_direction)
+            .split(&pane_to_split, &new_pane, split_direction, cx)
             .unwrap();
         cx.notify();
         new_pane
@@ -4238,7 +4402,7 @@ impl Workspace {
         new_pane.update(cx, |pane, cx| {
             pane.add_item(item, true, true, None, window, cx)
         });
-        self.center.split(&pane, &new_pane, direction).unwrap();
+        self.center.split(&pane, &new_pane, direction, cx).unwrap();
         cx.notify();
     }
 
@@ -4263,7 +4427,7 @@ impl Workspace {
                     new_pane.update(cx, |pane, cx| {
                         pane.add_item(clone, true, true, None, window, cx)
                     });
-                    this.center.split(&pane, &new_pane, direction).unwrap();
+                    this.center.split(&pane, &new_pane, direction, cx).unwrap();
                     cx.notify();
                     new_pane
                 })
@@ -4310,7 +4474,7 @@ impl Workspace {
         window: &mut Window,
         cx: &mut Context<Self>,
     ) {
-        if self.center.remove(&pane).unwrap() {
+        if self.center.remove(&pane, cx).unwrap() {
             self.force_remove_pane(&pane, &focus_on, window, cx);
             self.unfollow_in_pane(&pane, window, cx);
             self.last_leaders_by_pane.remove(&pane.downgrade());
@@ -4320,7 +4484,7 @@ impl Workspace {
 
             cx.notify();
         } else {
-            self.active_item_path_changed(window, cx);
+            self.active_item_path_changed(true, window, cx);
         }
         cx.emit(Event::PaneRemoved);
     }
@@ -4529,7 +4693,7 @@ impl Workspace {
 
         // if you're already following, find the right pane and focus it.
         if let Some(follower_state) = self.follower_states.get(&leader_id) {
-            window.focus(&follower_state.pane().focus_handle(cx));
+            window.focus(&follower_state.pane().focus_handle(cx), cx);
 
             return;
         }
@@ -4574,14 +4738,19 @@ impl Workspace {
         self.follower_states.contains_key(&id.into())
     }
 
-    fn active_item_path_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
+    fn active_item_path_changed(
+        &mut self,
+        focus_changed: bool,
+        window: &mut Window,
+        cx: &mut Context<Self>,
+    ) {
         cx.emit(Event::ActiveItemChanged);
         let active_entry = self.active_project_path(cx);
         self.project.update(cx, |project, cx| {
             project.set_active_path(active_entry.clone(), cx)
         });
 
-        if let Some(project_path) = &active_entry {
+        if focus_changed && let Some(project_path) = &active_entry {
             let git_store_entity = self.project.read(cx).git_store().clone();
             git_store_entity.update(cx, |git_store, cx| {
                 git_store.set_active_repo_for_path(project_path, cx);
@@ -5341,12 +5510,12 @@ impl Workspace {
     ) {
         self.panes.retain(|p| p != pane);
         if let Some(focus_on) = focus_on {
-            focus_on.update(cx, |pane, cx| window.focus(&pane.focus_handle(cx)));
+            focus_on.update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
         } else if self.active_pane() == pane {
             self.panes
                 .last()
                 .unwrap()
-                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx)));
+                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
         }
         if self.last_active_center_pane == Some(pane.downgrade()) {
             self.last_active_center_pane = None;
@@ -5520,12 +5689,24 @@ impl Workspace {
                     persistence::DB.save_workspace(serialized_workspace).await;
                 })
             }
-            WorkspaceLocation::DetachFromSession => window.spawn(cx, async move |_| {
-                persistence::DB
-                    .set_session_id(database_id, None)
-                    .await
-                    .log_err();
-            }),
+            WorkspaceLocation::DetachFromSession => {
+                let window_bounds = SerializedWindowBounds(window.window_bounds());
+                let display = window.display(cx).and_then(|d| d.uuid().ok());
+                window.spawn(cx, async move |_| {
+                    persistence::DB
+                        .set_window_open_status(
+                            database_id,
+                            window_bounds,
+                            display.unwrap_or_default(),
+                        )
+                        .await
+                        .log_err();
+                    persistence::DB
+                        .set_session_id(database_id, None)
+                        .await
+                        .log_err();
+                })
+            }
             WorkspaceLocation::None => Task::ready(()),
         }
     }
@@ -5662,6 +5843,9 @@ impl Workspace {
 
                     // Swap workspace center group
                     workspace.center = PaneGroup::with_root(center_group);
+                    workspace.center.set_is_center(true);
+                    workspace.center.mark_positions(cx);
+
                     if let Some(active_pane) = active_pane {
                         workspace.set_active_pane(&active_pane, window, cx);
                         cx.focus_self(window);
@@ -5895,6 +6079,27 @@ impl Workspace {
                     }
                 },
             ))
+            .on_action(cx.listener(
+                |workspace: &mut Workspace, _: &ToggleWorktreeSecurity, window, cx| {
+                    workspace.show_worktree_trust_security_modal(true, window, cx);
+                },
+            ))
+            .on_action(
+                cx.listener(|_: &mut Workspace, _: &ClearTrustedWorktrees, _, cx| {
+                    if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
+                        trusted_worktrees.update(cx, |trusted_worktrees, _| {
+                            trusted_worktrees.clear_trusted_paths()
+                        });
+                        let clear_task = persistence::DB.clear_trusted_worktrees();
+                        cx.spawn(async move |_, cx| {
+                            if clear_task.await.log_err().is_some() {
+                                cx.update(|cx| reload(cx)).ok();
+                            }
+                        })
+                        .detach();
+                    }
+                }),
+            )
             .on_action(cx.listener(
                 |workspace: &mut Workspace, _: &ReopenClosedItem, window, cx| {
                     workspace.reopen_closed_item(window, cx).detach();
@@ -6052,6 +6257,11 @@ impl Workspace {
             .on_action(cx.listener(Workspace::cancel))
     }
 
+    #[cfg(any(test, feature = "test-support"))]
+    pub fn set_random_database_id(&mut self) {
+        self.database_id = Some(WorkspaceId(Uuid::new_v4().as_u64_pair().0 as i64));
+    }
+
     #[cfg(any(test, feature = "test-support"))]
     pub fn test_new(project: Entity<Project>, window: &mut Window, cx: &mut Context<Self>) -> Self {
         use node_runtime::NodeRuntime;
@@ -6075,7 +6285,7 @@ impl Workspace {
         let workspace = Self::new(Default::default(), project, app_state, window, cx);
         workspace
             .active_pane
-            .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx)));
+            .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
         workspace
     }
 
@@ -6121,12 +6331,25 @@ impl Workspace {
         self.modal_layer.read(cx).active_modal()
     }
 
+    pub fn is_modal_open<V: 'static>(&self, cx: &App) -> bool {
+        self.modal_layer.read(cx).active_modal::<V>().is_some()
+    }
+
+    pub fn set_next_modal_placement(&mut self, placement: ModalPlacement) {
+        self.next_modal_placement = Some(placement);
+    }
+
+    fn take_next_modal_placement(&mut self) -> ModalPlacement {
+        self.next_modal_placement.take().unwrap_or_default()
+    }
+
     pub fn toggle_modal<V: ModalView, B>(&mut self, window: &mut Window, cx: &mut App, build: B)
     where
         B: FnOnce(&mut Window, &mut Context<V>) -> V,
     {
+        let placement = self.take_next_modal_placement();
         self.modal_layer.update(cx, |modal_layer, cx| {
-            modal_layer.toggle_modal(window, cx, build)
+            modal_layer.toggle_modal_with_placement(window, cx, placement, build)
         })
     }
 
@@ -6282,6 +6505,7 @@ impl Workspace {
                 left_dock.resize_active_panel(Some(size), window, cx);
             }
         });
+        self.clamp_utility_pane_widths(window, cx);
     }
 
     fn resize_right_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
@@ -6304,6 +6528,7 @@ impl Workspace {
                 right_dock.resize_active_panel(Some(size), window, cx);
             }
         });
+        self.clamp_utility_pane_widths(window, cx);
     }
 
     fn resize_bottom_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {

crates/worktree/Cargo.toml 🔗

@@ -25,8 +25,10 @@ test-support = [
 [dependencies]
 anyhow.workspace = true
 async-lock.workspace = true
+chardetng.workspace = true
 clock.workspace = true
 collections.workspace = true
+encoding_rs.workspace = true
 fs.workspace = true
 futures.workspace = true
 fuzzy.workspace = true

crates/worktree/src/ignore.rs 🔗

@@ -13,6 +13,10 @@ pub enum IgnoreStackEntry {
     Global {
         ignore: Arc<Gitignore>,
     },
+    RepoExclude {
+        ignore: Arc<Gitignore>,
+        parent: Arc<IgnoreStackEntry>,
+    },
     Some {
         abs_base_path: Arc<Path>,
         ignore: Arc<Gitignore>,
@@ -21,6 +25,12 @@ pub enum IgnoreStackEntry {
     All,
 }
 
+#[derive(Debug)]
+pub enum IgnoreKind {
+    Gitignore(Arc<Path>),
+    RepoExclude,
+}
+
 impl IgnoreStack {
     pub fn none() -> Self {
         Self {
@@ -43,13 +53,19 @@ impl IgnoreStack {
         }
     }
 
-    pub fn append(self, abs_base_path: Arc<Path>, ignore: Arc<Gitignore>) -> Self {
+    pub fn append(self, kind: IgnoreKind, ignore: Arc<Gitignore>) -> Self {
         let top = match self.top.as_ref() {
             IgnoreStackEntry::All => self.top.clone(),
-            _ => Arc::new(IgnoreStackEntry::Some {
-                abs_base_path,
-                ignore,
-                parent: self.top.clone(),
+            _ => Arc::new(match kind {
+                IgnoreKind::Gitignore(abs_base_path) => IgnoreStackEntry::Some {
+                    abs_base_path,
+                    ignore,
+                    parent: self.top.clone(),
+                },
+                IgnoreKind::RepoExclude => IgnoreStackEntry::RepoExclude {
+                    ignore,
+                    parent: self.top.clone(),
+                },
             }),
         };
         Self {
@@ -84,6 +100,17 @@ impl IgnoreStack {
                     ignore::Match::Whitelist(_) => false,
                 }
             }
+            IgnoreStackEntry::RepoExclude { ignore, parent } => {
+                match ignore.matched(abs_path, is_dir) {
+                    ignore::Match::None => IgnoreStack {
+                        repo_root: self.repo_root.clone(),
+                        top: parent.clone(),
+                    }
+                    .is_abs_path_ignored(abs_path, is_dir),
+                    ignore::Match::Ignore(_) => true,
+                    ignore::Match::Whitelist(_) => false,
+                }
+            }
             IgnoreStackEntry::Some {
                 abs_base_path,
                 ignore,

crates/worktree/src/worktree.rs 🔗

@@ -5,8 +5,10 @@ mod worktree_tests;
 
 use ::ignore::gitignore::{Gitignore, GitignoreBuilder};
 use anyhow::{Context as _, Result, anyhow};
+use chardetng::EncodingDetector;
 use clock::ReplicaId;
 use collections::{HashMap, HashSet, VecDeque};
+use encoding_rs::Encoding;
 use fs::{Fs, MTime, PathEvent, RemoveOptions, Watcher, copy_recursive, read_dir_items};
 use futures::{
     FutureExt as _, Stream, StreamExt,
@@ -14,15 +16,17 @@ use futures::{
         mpsc::{self, UnboundedSender},
         oneshot,
     },
-    select_biased,
+    select_biased, stream,
     task::Poll,
 };
 use fuzzy::CharBag;
 use git::{
-    COMMIT_MESSAGE, DOT_GIT, FSMONITOR_DAEMON, GITIGNORE, INDEX_LOCK, LFS_DIR, status::GitSummary,
+    COMMIT_MESSAGE, DOT_GIT, FSMONITOR_DAEMON, GITIGNORE, INDEX_LOCK, LFS_DIR, REPO_EXCLUDE,
+    status::GitSummary,
 };
 use gpui::{
-    App, AppContext as _, AsyncApp, BackgroundExecutor, Context, Entity, EventEmitter, Task,
+    App, AppContext as _, AsyncApp, BackgroundExecutor, Context, Entity, EventEmitter, Priority,
+    Task,
 };
 use ignore::IgnoreStack;
 use language::DiskState;
@@ -52,7 +56,7 @@ use std::{
     fmt,
     future::Future,
     mem::{self},
-    ops::{Deref, DerefMut},
+    ops::{Deref, DerefMut, Range},
     path::{Path, PathBuf},
     pin::Pin,
     sync::{
@@ -70,6 +74,8 @@ use util::{
 };
 pub use worktree_settings::WorktreeSettings;
 
+use crate::ignore::IgnoreKind;
+
 pub const FS_WATCH_LATENCY: Duration = Duration::from_millis(100);
 
 /// A set of local or remote files that are being opened as part of a project.
@@ -97,9 +103,12 @@ pub enum CreatedEntry {
     Excluded { abs_path: PathBuf },
 }
 
+#[derive(Debug)]
 pub struct LoadedFile {
     pub file: Arc<File>,
     pub text: String,
+    pub encoding: &'static Encoding,
+    pub has_bom: bool,
 }
 
 pub struct LoadedBinaryFile {
@@ -129,6 +138,7 @@ pub struct LocalWorktree {
     next_entry_id: Arc<AtomicUsize>,
     settings: WorktreeSettings,
     share_private_files: bool,
+    scanning_enabled: bool,
 }
 
 pub struct PathPrefixScanRequest {
@@ -230,6 +240,9 @@ impl Default for WorkDirectory {
 pub struct LocalSnapshot {
     snapshot: Snapshot,
     global_gitignore: Option<Arc<Gitignore>>,
+    /// Exclude files for all git repositories in the worktree, indexed by their absolute path.
+    /// The boolean indicates whether the gitignore needs to be updated.
+    repo_exclude_by_work_dir_abs_path: HashMap<Arc<Path>, (Arc<Gitignore>, bool)>,
     /// All of the gitignore files in the worktree, indexed by their absolute path.
     /// The boolean indicates whether the gitignore needs to be updated.
     ignores_by_parent_abs_path: HashMap<Arc<Path>, (Arc<Gitignore>, bool)>,
@@ -356,6 +369,7 @@ impl Worktree {
         visible: bool,
         fs: Arc<dyn Fs>,
         next_entry_id: Arc<AtomicUsize>,
+        scanning_enabled: bool,
         cx: &mut AsyncApp,
     ) -> Result<Entity<Self>> {
         let abs_path = path.into();
@@ -389,6 +403,7 @@ impl Worktree {
             let mut snapshot = LocalSnapshot {
                 ignores_by_parent_abs_path: Default::default(),
                 global_gitignore: Default::default(),
+                repo_exclude_by_work_dir_abs_path: Default::default(),
                 git_repositories: Default::default(),
                 snapshot: Snapshot::new(
                     cx.entity_id().as_u64(),
@@ -428,7 +443,7 @@ impl Worktree {
                 let mut entry = Entry::new(
                     RelPath::empty().into(),
                     &metadata,
-                    &next_entry_id,
+                    ProjectEntryId::new(&next_entry_id),
                     snapshot.root_char_bag,
                     None,
                 );
@@ -459,6 +474,7 @@ impl Worktree {
                 fs_case_sensitive,
                 visible,
                 settings,
+                scanning_enabled,
             };
             worktree.start_background_scanner(scan_requests_rx, path_prefixes_to_scan_rx, cx);
             Worktree::Local(worktree)
@@ -729,10 +745,14 @@ impl Worktree {
         path: Arc<RelPath>,
         text: Rope,
         line_ending: LineEnding,
+        encoding: &'static Encoding,
+        has_bom: bool,
         cx: &Context<Worktree>,
     ) -> Task<Result<Arc<File>>> {
         match self {
-            Worktree::Local(this) => this.write_file(path, text, line_ending, cx),
+            Worktree::Local(this) => {
+                this.write_file(path, text, line_ending, encoding, has_bom, cx)
+            }
             Worktree::Remote(_) => {
                 Task::ready(Err(anyhow!("remote worktree can't yet write files")))
             }
@@ -1049,13 +1069,18 @@ impl LocalWorktree {
         let share_private_files = self.share_private_files;
         let next_entry_id = self.next_entry_id.clone();
         let fs = self.fs.clone();
+        let scanning_enabled = self.scanning_enabled;
         let settings = self.settings.clone();
         let (scan_states_tx, mut scan_states_rx) = mpsc::unbounded();
         let background_scanner = cx.background_spawn({
             let abs_path = snapshot.abs_path.as_path().to_path_buf();
             let background = cx.background_executor().clone();
             async move {
-                let (events, watcher) = fs.watch(&abs_path, FS_WATCH_LATENCY).await;
+                let (events, watcher) = if scanning_enabled {
+                    fs.watch(&abs_path, FS_WATCH_LATENCY).await
+                } else {
+                    (Box::pin(stream::pending()) as _, Arc::new(NullWatcher) as _)
+                };
                 let fs_case_sensitive = fs.is_case_sensitive().await.unwrap_or_else(|e| {
                     log::error!("Failed to determine whether filesystem is case sensitive: {e:#}");
                     true
@@ -1080,6 +1105,7 @@ impl LocalWorktree {
                     }),
                     phase: BackgroundScannerPhase::InitialScan,
                     share_private_files,
+                    scanning_enabled,
                     settings,
                     watcher,
                 };
@@ -1333,7 +1359,9 @@ impl LocalWorktree {
                     anyhow::bail!("File is too large to load");
                 }
             }
-            let text = fs.load(&abs_path).await?;
+
+            let content = fs.load_bytes(&abs_path).await?;
+            let (text, encoding, has_bom) = decode_byte(content)?;
 
             let worktree = this.upgrade().context("worktree was dropped")?;
             let file = match entry.await? {
@@ -1361,7 +1389,12 @@ impl LocalWorktree {
                 }
             };
 
-            Ok(LoadedFile { file, text })
+            Ok(LoadedFile {
+                file,
+                text,
+                encoding,
+                has_bom,
+            })
         })
     }
 
@@ -1444,6 +1477,8 @@ impl LocalWorktree {
         path: Arc<RelPath>,
         text: Rope,
         line_ending: LineEnding,
+        encoding: &'static Encoding,
+        has_bom: bool,
         cx: &Context<Worktree>,
     ) -> Task<Result<Arc<File>>> {
         let fs = self.fs.clone();
@@ -1453,7 +1488,68 @@ impl LocalWorktree {
         let write = cx.background_spawn({
             let fs = fs.clone();
             let abs_path = abs_path.clone();
-            async move { fs.save(&abs_path, &text, line_ending).await }
+            async move {
+                // For UTF-8, use the optimized `fs.save` which writes Rope chunks directly to disk
+                // without allocating a contiguous string.
+                if encoding == encoding_rs::UTF_8 && !has_bom {
+                    return fs.save(&abs_path, &text, line_ending).await;
+                }
+
+                // For legacy encodings (e.g. Shift-JIS), we fall back to converting the entire Rope
+                // to a String/Bytes in memory before writing.
+                //
+                // Note: This is inefficient for very large files compared to the streaming approach above,
+                // but supporting streaming writes for arbitrary encodings would require a significant
+                // refactor of the `fs` crate to expose a Writer interface.
+                let text_string = text.to_string();
+                let normalized_text = match line_ending {
+                    LineEnding::Unix => text_string,
+                    LineEnding::Windows => text_string.replace('\n', "\r\n"),
+                };
+
+                // Create the byte vector manually for UTF-16 encodings because encoding_rs encodes to UTF-8 by default (per WHATWG standards),
+                //  which is not what we want for saving files.
+                let bytes = if encoding == encoding_rs::UTF_16BE {
+                    let mut data = Vec::with_capacity(normalized_text.len() * 2 + 2);
+                    if has_bom {
+                        data.extend_from_slice(&[0xFE, 0xFF]); // BOM
+                    }
+                    let utf16be_bytes =
+                        normalized_text.encode_utf16().flat_map(|u| u.to_be_bytes());
+                    data.extend(utf16be_bytes);
+                    data.into()
+                } else if encoding == encoding_rs::UTF_16LE {
+                    let mut data = Vec::with_capacity(normalized_text.len() * 2 + 2);
+                    if has_bom {
+                        data.extend_from_slice(&[0xFF, 0xFE]); // BOM
+                    }
+                    let utf16le_bytes =
+                        normalized_text.encode_utf16().flat_map(|u| u.to_le_bytes());
+                    data.extend(utf16le_bytes);
+                    data.into()
+                } else {
+                    // For other encodings (Shift-JIS, UTF-8 with BOM, etc.), delegate to encoding_rs.
+                    let bom_bytes = if has_bom {
+                        if encoding == encoding_rs::UTF_8 {
+                            vec![0xEF, 0xBB, 0xBF]
+                        } else {
+                            vec![]
+                        }
+                    } else {
+                        vec![]
+                    };
+                    let (cow, _, _) = encoding.encode(&normalized_text);
+                    if !bom_bytes.is_empty() {
+                        let mut bytes = bom_bytes;
+                        bytes.extend_from_slice(&cow);
+                        bytes.into()
+                    } else {
+                        cow
+                    }
+                };
+
+                fs.write(&abs_path, &bytes).await
+            }
         });
 
         cx.spawn(async move |this, cx| {
@@ -2554,13 +2650,21 @@ impl LocalSnapshot {
         } else {
             IgnoreStack::none()
         };
+
+        if let Some((repo_exclude, _)) = repo_root
+            .as_ref()
+            .and_then(|abs_path| self.repo_exclude_by_work_dir_abs_path.get(abs_path))
+        {
+            ignore_stack = ignore_stack.append(IgnoreKind::RepoExclude, repo_exclude.clone());
+        }
         ignore_stack.repo_root = repo_root;
         for (parent_abs_path, ignore) in new_ignores.into_iter().rev() {
             if ignore_stack.is_abs_path_ignored(parent_abs_path, true) {
                 ignore_stack = IgnoreStack::all();
                 break;
             } else if let Some(ignore) = ignore {
-                ignore_stack = ignore_stack.append(parent_abs_path.into(), ignore);
+                ignore_stack =
+                    ignore_stack.append(IgnoreKind::Gitignore(parent_abs_path.into()), ignore);
             }
         }
 
@@ -2736,13 +2840,30 @@ impl BackgroundScannerState {
         }
     }
 
-    async fn insert_entry(
+    fn entry_id_for(
         &mut self,
-        mut entry: Entry,
-        fs: &dyn Fs,
-        watcher: &dyn Watcher,
-    ) -> Entry {
-        self.reuse_entry_id(&mut entry);
+        next_entry_id: &AtomicUsize,
+        path: &RelPath,
+        metadata: &fs::Metadata,
+    ) -> ProjectEntryId {
+        // If an entry with the same inode was removed from the worktree during this scan,
+        // then it *might* represent the same file or directory. But the OS might also have
+        // re-used the inode for a completely different file or directory.
+        //
+        // Conditionally reuse the old entry's id:
+        // * if the mtime is the same, the file was probably been renamed.
+        // * if the path is the same, the file may just have been updated
+        if let Some(removed_entry) = self.removed_entries.remove(&metadata.inode) {
+            if removed_entry.mtime == Some(metadata.mtime) || *removed_entry.path == *path {
+                return removed_entry.id;
+            }
+        } else if let Some(existing_entry) = self.snapshot.entry_for_path(path) {
+            return existing_entry.id;
+        }
+        ProjectEntryId::new(next_entry_id)
+    }
+
+    async fn insert_entry(&mut self, entry: Entry, fs: &dyn Fs, watcher: &dyn Watcher) -> Entry {
         let entry = self.snapshot.insert_entry(entry, fs);
         if entry.path.file_name() == Some(&DOT_GIT) {
             self.insert_git_repository(entry.path.clone(), fs, watcher)
@@ -3114,7 +3235,8 @@ impl language::File for File {
             entry_id: self.entry_id.map(|id| id.to_proto()),
             path: self.path.as_ref().to_proto(),
             mtime: self.disk_state.mtime().map(|time| time.into()),
-            is_deleted: self.disk_state == DiskState::Deleted,
+            is_deleted: self.disk_state.is_deleted(),
+            is_historic: matches!(self.disk_state, DiskState::Historic { .. }),
         }
     }
 
@@ -3175,7 +3297,11 @@ impl File {
             "worktree id does not match file"
         );
 
-        let disk_state = if proto.is_deleted {
+        let disk_state = if proto.is_historic {
+            DiskState::Historic {
+                was_deleted: proto.is_deleted,
+            }
+        } else if proto.is_deleted {
             DiskState::Deleted
         } else if let Some(mtime) = proto.mtime.map(&Into::into) {
             DiskState::Present { mtime }
@@ -3389,13 +3515,13 @@ impl Entry {
     fn new(
         path: Arc<RelPath>,
         metadata: &fs::Metadata,
-        next_entry_id: &AtomicUsize,
+        id: ProjectEntryId,
         root_char_bag: CharBag,
         canonical_path: Option<Arc<Path>>,
     ) -> Self {
         let char_bag = char_bag_for_path(root_char_bag, &path);
         Self {
-            id: ProjectEntryId::new(next_entry_id),
+            id,
             kind: if metadata.is_dir {
                 EntryKind::PendingDir
             } else {
@@ -3600,6 +3726,7 @@ struct BackgroundScanner {
     watcher: Arc<dyn Watcher>,
     settings: WorktreeSettings,
     share_private_files: bool,
+    scanning_enabled: bool,
 }
 
 #[derive(Copy, Clone, PartialEq)]
@@ -3615,14 +3742,33 @@ impl BackgroundScanner {
         // the git repository in an ancestor directory. Find any gitignore files
         // in ancestor directories.
         let root_abs_path = self.state.lock().await.snapshot.abs_path.clone();
-        let (ignores, repo) = discover_ancestor_git_repo(self.fs.clone(), &root_abs_path).await;
-        self.state
-            .lock()
-            .await
-            .snapshot
-            .ignores_by_parent_abs_path
-            .extend(ignores);
-        let containing_git_repository = if let Some((ancestor_dot_git, work_directory)) = repo {
+
+        let repo = if self.scanning_enabled {
+            let (ignores, exclude, repo) =
+                discover_ancestor_git_repo(self.fs.clone(), &root_abs_path).await;
+            self.state
+                .lock()
+                .await
+                .snapshot
+                .ignores_by_parent_abs_path
+                .extend(ignores);
+            if let Some(exclude) = exclude {
+                self.state
+                    .lock()
+                    .await
+                    .snapshot
+                    .repo_exclude_by_work_dir_abs_path
+                    .insert(root_abs_path.as_path().into(), (exclude, false));
+            }
+
+            repo
+        } else {
+            None
+        };
+
+        let containing_git_repository = if let Some((ancestor_dot_git, work_directory)) = repo
+            && self.scanning_enabled
+        {
             maybe!(async {
                 self.state
                     .lock()
@@ -3646,6 +3792,7 @@ impl BackgroundScanner {
 
         let mut global_gitignore_events = if let Some(global_gitignore_path) =
             &paths::global_gitignore_path()
+            && self.scanning_enabled
         {
             let is_file = self.fs.is_file(&global_gitignore_path).await;
             self.state.lock().await.snapshot.global_gitignore = if is_file {
@@ -3682,11 +3829,13 @@ impl BackgroundScanner {
                     .await;
                 if ignore_stack.is_abs_path_ignored(root_abs_path.as_path(), true) {
                     root_entry.is_ignored = true;
+                    let mut root_entry = root_entry.clone();
+                    state.reuse_entry_id(&mut root_entry);
                     state
-                        .insert_entry(root_entry.clone(), self.fs.as_ref(), self.watcher.as_ref())
+                        .insert_entry(root_entry, self.fs.as_ref(), self.watcher.as_ref())
                         .await;
                 }
-                if root_entry.is_dir() {
+                if root_entry.is_dir() && self.scanning_enabled {
                     state
                         .enqueue_scan_dir(
                             root_abs_path.as_path().into(),
@@ -3795,7 +3944,7 @@ impl BackgroundScanner {
         let root_canonical_path = match &root_canonical_path {
             Ok(path) => SanitizedPath::new(path),
             Err(err) => {
-                log::error!("failed to canonicalize root path {root_path:?}: {err}");
+                log::error!("failed to canonicalize root path {root_path:?}: {err:#}");
                 return true;
             }
         };
@@ -3873,33 +4022,40 @@ impl BackgroundScanner {
 
         let mut relative_paths = Vec::with_capacity(abs_paths.len());
         let mut dot_git_abs_paths = Vec::new();
+        let mut work_dirs_needing_exclude_update = Vec::new();
         abs_paths.sort_unstable();
         abs_paths.dedup_by(|a, b| a.starts_with(b));
         {
             let snapshot = &self.state.lock().await.snapshot;
-            abs_paths.retain(|abs_path| {
-            let abs_path = &SanitizedPath::new(abs_path);
 
+            let mut ranges_to_drop = SmallVec::<[Range<usize>; 4]>::new();
 
-            {
-                let mut is_git_related = false;
+            fn skip_ix(ranges: &mut SmallVec<[Range<usize>; 4]>, ix: usize) {
+                if let Some(last_range) = ranges.last_mut()
+                    && last_range.end == ix
+                {
+                    last_range.end += 1;
+                } else {
+                    ranges.push(ix..ix + 1);
+                }
+            }
+
+            for (ix, abs_path) in abs_paths.iter().enumerate() {
+                let abs_path = &SanitizedPath::new(&abs_path);
 
-                let dot_git_paths = self.executor.block(maybe!(async  {
-                    let mut path = None;
-                    for ancestor in abs_path.as_path().ancestors() {
+                let mut is_git_related = false;
+                let mut dot_git_paths = None;
 
+                for ancestor in abs_path.as_path().ancestors() {
                     if is_git_dir(ancestor, self.fs.as_ref()).await {
                         let path_in_git_dir = abs_path
                             .as_path()
                             .strip_prefix(ancestor)
                             .expect("stripping off the ancestor");
-                       path = Some((ancestor.to_owned(), path_in_git_dir.to_owned()));
-                       break;
-                    }
+                        dot_git_paths = Some((ancestor.to_owned(), path_in_git_dir.to_owned()));
+                        break;
                     }
-                    path
-
-                }));
+                }
 
                 if let Some((dot_git_abs_path, path_in_git_dir)) = dot_git_paths {
                     if skipped_files_in_dot_git
@@ -3909,8 +4065,11 @@ impl BackgroundScanner {
                             path_in_git_dir.starts_with(skipped_git_subdir)
                         })
                     {
-                        log::debug!("ignoring event {abs_path:?} as it's in the .git directory among skipped files or directories");
-                        return false;
+                        log::debug!(
+                            "ignoring event {abs_path:?} as it's in the .git directory among skipped files or directories"
+                        );
+                        skip_ix(&mut ranges_to_drop, ix);
+                        continue;
                     }
 
                     is_git_related = true;
@@ -3919,8 +4078,7 @@ impl BackgroundScanner {
                     }
                 }
 
-                let relative_path = if let Ok(path) =
-                    abs_path.strip_prefix(&root_canonical_path)
+                let relative_path = if let Ok(path) = abs_path.strip_prefix(&root_canonical_path)
                     && let Ok(path) = RelPath::new(path, PathStyle::local())
                 {
                     path
@@ -3931,12 +4089,25 @@ impl BackgroundScanner {
                         );
                     } else {
                         log::error!(
-                          "ignoring event {abs_path:?} outside of root path {root_canonical_path:?}",
+                            "ignoring event {abs_path:?} outside of root path {root_canonical_path:?}",
                         );
                     }
-                    return false;
+                    skip_ix(&mut ranges_to_drop, ix);
+                    continue;
                 };
 
+                let absolute_path = abs_path.to_path_buf();
+                if absolute_path.ends_with(Path::new(DOT_GIT).join(REPO_EXCLUDE)) {
+                    if let Some(repository) = snapshot
+                        .git_repositories
+                        .values()
+                        .find(|repo| repo.common_dir_abs_path.join(REPO_EXCLUDE) == absolute_path)
+                    {
+                        work_dirs_needing_exclude_update
+                            .push(repository.work_directory_abs_path.clone());
+                    }
+                }
+
                 if abs_path.file_name() == Some(OsStr::new(GITIGNORE)) {
                     for (_, repo) in snapshot
                         .git_repositories
@@ -3958,25 +4129,43 @@ impl BackgroundScanner {
                 });
                 if !parent_dir_is_loaded {
                     log::debug!("ignoring event {relative_path:?} within unloaded directory");
-                    return false;
+                    skip_ix(&mut ranges_to_drop, ix);
+                    continue;
                 }
 
                 if self.settings.is_path_excluded(&relative_path) {
                     if !is_git_related {
                         log::debug!("ignoring FS event for excluded path {relative_path:?}");
                     }
-                    return false;
+                    skip_ix(&mut ranges_to_drop, ix);
+                    continue;
                 }
 
                 relative_paths.push(relative_path.into_arc());
-                true
             }
-        });
+
+            for range_to_drop in ranges_to_drop.into_iter().rev() {
+                abs_paths.drain(range_to_drop);
+            }
         }
+
         if relative_paths.is_empty() && dot_git_abs_paths.is_empty() {
             return;
         }
 
+        if !work_dirs_needing_exclude_update.is_empty() {
+            let mut state = self.state.lock().await;
+            for work_dir_abs_path in work_dirs_needing_exclude_update {
+                if let Some((_, needs_update)) = state
+                    .snapshot
+                    .repo_exclude_by_work_dir_abs_path
+                    .get_mut(&work_dir_abs_path)
+                {
+                    *needs_update = true;
+                }
+            }
+        }
+
         self.state.lock().await.snapshot.scan_id += 1;
 
         let (scan_job_tx, scan_job_rx) = channel::unbounded();
@@ -4090,7 +4279,7 @@ impl BackgroundScanner {
 
         let progress_update_count = AtomicUsize::new(0);
         self.executor
-            .scoped(|scope| {
+            .scoped_priority(Priority::Low, |scope| {
                 for _ in 0..self.executor.num_cpus() {
                     scope.spawn(async {
                         let mut last_progress_update_count = 0;
@@ -4244,7 +4433,8 @@ impl BackgroundScanner {
                 match build_gitignore(&child_abs_path, self.fs.as_ref()).await {
                     Ok(ignore) => {
                         let ignore = Arc::new(ignore);
-                        ignore_stack = ignore_stack.append(job.abs_path.clone(), ignore.clone());
+                        ignore_stack = ignore_stack
+                            .append(IgnoreKind::Gitignore(job.abs_path.clone()), ignore.clone());
                         new_ignore = Some(ignore);
                     }
                     Err(error) => {
@@ -4275,7 +4465,7 @@ impl BackgroundScanner {
             let mut child_entry = Entry::new(
                 child_path.clone(),
                 &child_metadata,
-                &next_entry_id,
+                ProjectEntryId::new(&next_entry_id),
                 root_char_bag,
                 None,
             );
@@ -4462,10 +4652,11 @@ impl BackgroundScanner {
                         .ignore_stack_for_abs_path(&abs_path, metadata.is_dir, self.fs.as_ref())
                         .await;
                     let is_external = !canonical_path.starts_with(&root_canonical_path);
+                    let entry_id = state.entry_id_for(self.next_entry_id.as_ref(), path, &metadata);
                     let mut fs_entry = Entry::new(
                         path.clone(),
                         &metadata,
-                        self.next_entry_id.as_ref(),
+                        entry_id,
                         state.snapshot.root_char_bag,
                         if metadata.is_symlink {
                             Some(canonical_path.as_path().to_path_buf().into())
@@ -4505,11 +4696,24 @@ impl BackgroundScanner {
                         .await;
 
                     if path.is_empty()
-                        && let Some((ignores, repo)) = new_ancestor_repo.take()
+                        && let Some((ignores, exclude, repo)) = new_ancestor_repo.take()
                     {
                         log::trace!("updating ancestor git repository");
                         state.snapshot.ignores_by_parent_abs_path.extend(ignores);
                         if let Some((ancestor_dot_git, work_directory)) = repo {
+                            if let Some(exclude) = exclude {
+                                let work_directory_abs_path = self
+                                    .state
+                                    .lock()
+                                    .await
+                                    .snapshot
+                                    .work_directory_abs_path(&work_directory);
+
+                                state
+                                    .snapshot
+                                    .repo_exclude_by_work_dir_abs_path
+                                    .insert(work_directory_abs_path.into(), (exclude, false));
+                            }
                             state
                                 .insert_git_repository_for_path(
                                     work_directory,
@@ -4607,6 +4811,36 @@ impl BackgroundScanner {
         {
             let snapshot = &mut self.state.lock().await.snapshot;
             let abs_path = snapshot.abs_path.clone();
+
+            snapshot.repo_exclude_by_work_dir_abs_path.retain(
+                |work_dir_abs_path, (exclude, needs_update)| {
+                    if *needs_update {
+                        *needs_update = false;
+                        ignores_to_update.push(work_dir_abs_path.clone());
+
+                        if let Some((_, repository)) = snapshot
+                            .git_repositories
+                            .iter()
+                            .find(|(_, repo)| &repo.work_directory_abs_path == work_dir_abs_path)
+                        {
+                            let exclude_abs_path =
+                                repository.common_dir_abs_path.join(REPO_EXCLUDE);
+                            if let Ok(current_exclude) = self
+                                .executor
+                                .block(build_gitignore(&exclude_abs_path, self.fs.as_ref()))
+                            {
+                                *exclude = Arc::new(current_exclude);
+                            }
+                        }
+                    }
+
+                    snapshot
+                        .git_repositories
+                        .iter()
+                        .any(|(_, repo)| &repo.work_directory_abs_path == work_dir_abs_path)
+                },
+            );
+
             snapshot
                 .ignores_by_parent_abs_path
                 .retain(|parent_abs_path, (_, needs_update)| {
@@ -4661,7 +4895,8 @@ impl BackgroundScanner {
 
         let mut ignore_stack = job.ignore_stack;
         if let Some((ignore, _)) = snapshot.ignores_by_parent_abs_path.get(&job.abs_path) {
-            ignore_stack = ignore_stack.append(job.abs_path.clone(), ignore.clone());
+            ignore_stack =
+                ignore_stack.append(IgnoreKind::Gitignore(job.abs_path.clone()), ignore.clone());
         }
 
         let mut entries_by_id_edits = Vec::new();
@@ -4836,6 +5071,9 @@ impl BackgroundScanner {
                 let preserve = ids_to_preserve.contains(work_directory_id);
                 if !preserve {
                     affected_repo_roots.push(entry.dot_git_abs_path.parent().unwrap().into());
+                    snapshot
+                        .repo_exclude_by_work_dir_abs_path
+                        .remove(&entry.work_directory_abs_path);
                 }
                 preserve
             });
@@ -4875,8 +5113,10 @@ async fn discover_ancestor_git_repo(
     root_abs_path: &SanitizedPath,
 ) -> (
     HashMap<Arc<Path>, (Arc<Gitignore>, bool)>,
+    Option<Arc<Gitignore>>,
     Option<(PathBuf, WorkDirectory)>,
 ) {
+    let mut exclude = None;
     let mut ignores = HashMap::default();
     for (index, ancestor) in root_abs_path.as_path().ancestors().enumerate() {
         if index != 0 {
@@ -4912,6 +5152,7 @@ async fn discover_ancestor_git_repo(
                     // also mark where in the git repo the root folder is located.
                     return (
                         ignores,
+                        exclude,
                         Some((
                             ancestor_dot_git,
                             WorkDirectory::AboveProject {
@@ -4923,12 +5164,17 @@ async fn discover_ancestor_git_repo(
                 };
             }
 
+            let repo_exclude_abs_path = ancestor_dot_git.join(REPO_EXCLUDE);
+            if let Ok(repo_exclude) = build_gitignore(&repo_exclude_abs_path, fs.as_ref()).await {
+                exclude = Some(Arc::new(repo_exclude));
+            }
+
             // Reached root of git repository.
             break;
         }
     }
 
-    (ignores, None)
+    (ignores, exclude, None)
 }
 
 fn build_diff(
@@ -5607,3 +5853,121 @@ async fn discover_git_paths(dot_git_abs_path: &Arc<Path>, fs: &dyn Fs) -> (Arc<P
     };
     (repository_dir_abs_path, common_dir_abs_path)
 }
+
+struct NullWatcher;
+
+impl fs::Watcher for NullWatcher {
+    fn add(&self, _path: &Path) -> Result<()> {
+        Ok(())
+    }
+
+    fn remove(&self, _path: &Path) -> Result<()> {
+        Ok(())
+    }
+}
+
+fn decode_byte(bytes: Vec<u8>) -> anyhow::Result<(String, &'static Encoding, bool)> {
+    // check BOM
+    if let Some((encoding, _bom_len)) = Encoding::for_bom(&bytes) {
+        let (cow, _) = encoding.decode_with_bom_removal(&bytes);
+        return Ok((cow.into_owned(), encoding, true));
+    }
+
+    match analyze_byte_content(&bytes) {
+        ByteContent::Utf16Le => {
+            let encoding = encoding_rs::UTF_16LE;
+            let (cow, _, _) = encoding.decode(&bytes);
+            return Ok((cow.into_owned(), encoding, false));
+        }
+        ByteContent::Utf16Be => {
+            let encoding = encoding_rs::UTF_16BE;
+            let (cow, _, _) = encoding.decode(&bytes);
+            return Ok((cow.into_owned(), encoding, false));
+        }
+        ByteContent::Binary => {
+            anyhow::bail!("Binary files are not supported");
+        }
+        ByteContent::Unknown => {}
+    }
+
+    fn detect_encoding(bytes: Vec<u8>) -> (String, &'static Encoding) {
+        let mut detector = EncodingDetector::new();
+        detector.feed(&bytes, true);
+
+        let encoding = detector.guess(None, true); // Use None for TLD hint to ensure neutral detection logic.
+
+        let (cow, _, _) = encoding.decode(&bytes);
+        (cow.into_owned(), encoding)
+    }
+
+    match String::from_utf8(bytes) {
+        Ok(text) => {
+            // ISO-2022-JP (and other ISO-2022 variants) consists entirely of 7-bit ASCII bytes,
+            // so it is valid UTF-8. However, it contains escape sequences starting with '\x1b'.
+            // If we find an escape character, we double-check the encoding to prevent
+            // displaying raw escape sequences instead of the correct characters.
+            if text.contains('\x1b') {
+                let (s, enc) = detect_encoding(text.into_bytes());
+                Ok((s, enc, false))
+            } else {
+                Ok((text, encoding_rs::UTF_8, false))
+            }
+        }
+        Err(e) => {
+            let (s, enc) = detect_encoding(e.into_bytes());
+            Ok((s, enc, false))
+        }
+    }
+}
+
+#[derive(PartialEq)]
+enum ByteContent {
+    Utf16Le,
+    Utf16Be,
+    Binary,
+    Unknown,
+}
+// Heuristic check using null byte distribution.
+// NOTE: This relies on the presence of ASCII characters (which become `0x00` in UTF-16).
+// Files consisting purely of non-ASCII characters (like Japanese) may not be detected here
+// and will result in `Unknown`.
+fn analyze_byte_content(bytes: &[u8]) -> ByteContent {
+    if bytes.len() < 2 {
+        return ByteContent::Unknown;
+    }
+
+    let check_len = bytes.len().min(1024);
+    let sample = &bytes[..check_len];
+
+    if !sample.contains(&0) {
+        return ByteContent::Unknown;
+    }
+
+    let mut even_nulls = 0;
+    let mut odd_nulls = 0;
+
+    for (i, &byte) in sample.iter().enumerate() {
+        if byte == 0 {
+            if i % 2 == 0 {
+                even_nulls += 1;
+            } else {
+                odd_nulls += 1;
+            }
+        }
+    }
+
+    let total_nulls = even_nulls + odd_nulls;
+    if total_nulls < check_len / 10 {
+        return ByteContent::Unknown;
+    }
+
+    if even_nulls > odd_nulls * 4 {
+        return ByteContent::Utf16Be;
+    }
+
+    if odd_nulls > even_nulls * 4 {
+        return ByteContent::Utf16Le;
+    }
+
+    ByteContent::Binary
+}

crates/worktree/src/worktree_tests.rs 🔗

@@ -1,7 +1,8 @@
 use crate::{Entry, EntryKind, Event, PathChange, Worktree, WorktreeModelHandle};
 use anyhow::Result;
+use encoding_rs;
 use fs::{FakeFs, Fs, RealFs, RemoveOptions};
-use git::GITIGNORE;
+use git::{DOT_GIT, GITIGNORE, REPO_EXCLUDE};
 use gpui::{AppContext as _, BackgroundExecutor, BorrowAppContext, Context, Task, TestAppContext};
 use parking_lot::Mutex;
 use postage::stream::Stream;
@@ -19,6 +20,7 @@ use std::{
 };
 use util::{
     ResultExt, path,
+    paths::PathStyle,
     rel_path::{RelPath, rel_path},
     test::TempTree,
 };
@@ -44,6 +46,7 @@ async fn test_traversal(cx: &mut TestAppContext) {
         true,
         fs,
         Default::default(),
+        true,
         &mut cx.to_async(),
     )
     .await
@@ -108,6 +111,7 @@ async fn test_circular_symlinks(cx: &mut TestAppContext) {
         true,
         fs.clone(),
         Default::default(),
+        true,
         &mut cx.to_async(),
     )
     .await
@@ -207,6 +211,7 @@ async fn test_symlinks_pointing_outside(cx: &mut TestAppContext) {
         true,
         fs.clone(),
         Default::default(),
+        true,
         &mut cx.to_async(),
     )
     .await
@@ -357,6 +362,7 @@ async fn test_renaming_case_only(cx: &mut TestAppContext) {
         true,
         fs.clone(),
         Default::default(),
+        true,
         &mut cx.to_async(),
     )
     .await
@@ -434,6 +440,7 @@ async fn test_open_gitignored_files(cx: &mut TestAppContext) {
         true,
         fs.clone(),
         Default::default(),
+        true,
         &mut cx.to_async(),
     )
     .await
@@ -598,6 +605,7 @@ async fn test_dirs_no_longer_ignored(cx: &mut TestAppContext) {
         true,
         fs.clone(),
         Default::default(),
+        true,
         &mut cx.to_async(),
     )
     .await
@@ -698,6 +706,7 @@ async fn test_write_file(cx: &mut TestAppContext) {
         true,
         Arc::new(RealFs::new(None, cx.executor())),
         Default::default(),
+        true,
         &mut cx.to_async(),
     )
     .await
@@ -716,6 +725,8 @@ async fn test_write_file(cx: &mut TestAppContext) {
                 rel_path("tracked-dir/file.txt").into(),
                 "hello".into(),
                 Default::default(),
+                encoding_rs::UTF_8,
+                false,
                 cx,
             )
         })
@@ -727,6 +738,8 @@ async fn test_write_file(cx: &mut TestAppContext) {
                 rel_path("ignored-dir/file.txt").into(),
                 "world".into(),
                 Default::default(),
+                encoding_rs::UTF_8,
+                false,
                 cx,
             )
         })
@@ -791,6 +804,7 @@ async fn test_file_scan_inclusions(cx: &mut TestAppContext) {
         true,
         Arc::new(RealFs::new(None, cx.executor())),
         Default::default(),
+        true,
         &mut cx.to_async(),
     )
     .await
@@ -856,6 +870,7 @@ async fn test_file_scan_exclusions_overrules_inclusions(cx: &mut TestAppContext)
         true,
         Arc::new(RealFs::new(None, cx.executor())),
         Default::default(),
+        true,
         &mut cx.to_async(),
     )
     .await
@@ -914,6 +929,7 @@ async fn test_file_scan_inclusions_reindexes_on_setting_change(cx: &mut TestAppC
         true,
         Arc::new(RealFs::new(None, cx.executor())),
         Default::default(),
+        true,
         &mut cx.to_async(),
     )
     .await
@@ -999,6 +1015,7 @@ async fn test_file_scan_exclusions(cx: &mut TestAppContext) {
         true,
         Arc::new(RealFs::new(None, cx.executor())),
         Default::default(),
+        true,
         &mut cx.to_async(),
     )
     .await
@@ -1080,6 +1097,7 @@ async fn test_hidden_files(cx: &mut TestAppContext) {
         true,
         Arc::new(RealFs::new(None, cx.executor())),
         Default::default(),
+        true,
         &mut cx.to_async(),
     )
     .await
@@ -1190,6 +1208,7 @@ async fn test_fs_events_in_exclusions(cx: &mut TestAppContext) {
         true,
         Arc::new(RealFs::new(None, cx.executor())),
         Default::default(),
+        true,
         &mut cx.to_async(),
     )
     .await
@@ -1301,6 +1320,7 @@ async fn test_fs_events_in_dot_git_worktree(cx: &mut TestAppContext) {
         true,
         Arc::new(RealFs::new(None, cx.executor())),
         Default::default(),
+        true,
         &mut cx.to_async(),
     )
     .await
@@ -1339,6 +1359,7 @@ async fn test_create_directory_during_initial_scan(cx: &mut TestAppContext) {
         true,
         fs,
         Default::default(),
+        true,
         &mut cx.to_async(),
     )
     .await
@@ -1407,6 +1428,7 @@ async fn test_create_dir_all_on_create_entry(cx: &mut TestAppContext) {
         true,
         fs_fake,
         Default::default(),
+        true,
         &mut cx.to_async(),
     )
     .await
@@ -1448,6 +1470,7 @@ async fn test_create_dir_all_on_create_entry(cx: &mut TestAppContext) {
         true,
         fs_real,
         Default::default(),
+        true,
         &mut cx.to_async(),
     )
     .await
@@ -1533,6 +1556,177 @@ async fn test_create_dir_all_on_create_entry(cx: &mut TestAppContext) {
     });
 }
 
+#[gpui::test]
+async fn test_create_file_in_expanded_gitignored_dir(cx: &mut TestAppContext) {
+    // Tests the behavior of our worktree refresh when a file in a gitignored directory
+    // is created.
+    init_test(cx);
+    let fs = FakeFs::new(cx.background_executor.clone());
+    fs.insert_tree(
+        "/root",
+        json!({
+            ".gitignore": "ignored_dir\n",
+            "ignored_dir": {
+                "existing_file.txt": "existing content",
+                "another_file.txt": "another content",
+            },
+        }),
+    )
+    .await;
+
+    let tree = Worktree::local(
+        Path::new("/root"),
+        true,
+        fs.clone(),
+        Default::default(),
+        true,
+        &mut cx.to_async(),
+    )
+    .await
+    .unwrap();
+
+    cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
+        .await;
+
+    tree.read_with(cx, |tree, _| {
+        let ignored_dir = tree.entry_for_path(rel_path("ignored_dir")).unwrap();
+        assert!(ignored_dir.is_ignored);
+        assert_eq!(ignored_dir.kind, EntryKind::UnloadedDir);
+    });
+
+    tree.update(cx, |tree, cx| {
+        tree.load_file(rel_path("ignored_dir/existing_file.txt"), cx)
+    })
+    .await
+    .unwrap();
+
+    tree.read_with(cx, |tree, _| {
+        let ignored_dir = tree.entry_for_path(rel_path("ignored_dir")).unwrap();
+        assert!(ignored_dir.is_ignored);
+        assert_eq!(ignored_dir.kind, EntryKind::Dir);
+
+        assert!(
+            tree.entry_for_path(rel_path("ignored_dir/existing_file.txt"))
+                .is_some()
+        );
+        assert!(
+            tree.entry_for_path(rel_path("ignored_dir/another_file.txt"))
+                .is_some()
+        );
+    });
+
+    let entry = tree
+        .update(cx, |tree, cx| {
+            tree.create_entry(rel_path("ignored_dir/new_file.txt").into(), false, None, cx)
+        })
+        .await
+        .unwrap();
+    assert!(entry.into_included().is_some());
+
+    cx.executor().run_until_parked();
+
+    tree.read_with(cx, |tree, _| {
+        let ignored_dir = tree.entry_for_path(rel_path("ignored_dir")).unwrap();
+        assert!(ignored_dir.is_ignored);
+        assert_eq!(
+            ignored_dir.kind,
+            EntryKind::Dir,
+            "ignored_dir should still be loaded, not UnloadedDir"
+        );
+
+        assert!(
+            tree.entry_for_path(rel_path("ignored_dir/existing_file.txt"))
+                .is_some(),
+            "existing_file.txt should still be visible"
+        );
+        assert!(
+            tree.entry_for_path(rel_path("ignored_dir/another_file.txt"))
+                .is_some(),
+            "another_file.txt should still be visible"
+        );
+        assert!(
+            tree.entry_for_path(rel_path("ignored_dir/new_file.txt"))
+                .is_some(),
+            "new_file.txt should be visible"
+        );
+    });
+}
+
+#[gpui::test]
+async fn test_fs_event_for_gitignored_dir_does_not_lose_contents(cx: &mut TestAppContext) {
+    // Tests the behavior of our worktree refresh when a directory modification for a gitignored directory
+    // is triggered.
+    init_test(cx);
+    let fs = FakeFs::new(cx.background_executor.clone());
+    fs.insert_tree(
+        "/root",
+        json!({
+            ".gitignore": "ignored_dir\n",
+            "ignored_dir": {
+                "file1.txt": "content1",
+                "file2.txt": "content2",
+            },
+        }),
+    )
+    .await;
+
+    let tree = Worktree::local(
+        Path::new("/root"),
+        true,
+        fs.clone(),
+        Default::default(),
+        true,
+        &mut cx.to_async(),
+    )
+    .await
+    .unwrap();
+
+    cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
+        .await;
+
+    // Load a file to expand the ignored directory
+    tree.update(cx, |tree, cx| {
+        tree.load_file(rel_path("ignored_dir/file1.txt"), cx)
+    })
+    .await
+    .unwrap();
+
+    tree.read_with(cx, |tree, _| {
+        let ignored_dir = tree.entry_for_path(rel_path("ignored_dir")).unwrap();
+        assert_eq!(ignored_dir.kind, EntryKind::Dir);
+        assert!(
+            tree.entry_for_path(rel_path("ignored_dir/file1.txt"))
+                .is_some()
+        );
+        assert!(
+            tree.entry_for_path(rel_path("ignored_dir/file2.txt"))
+                .is_some()
+        );
+    });
+
+    fs.emit_fs_event("/root/ignored_dir", Some(fs::PathEventKind::Changed));
+    tree.flush_fs_events(cx).await;
+
+    tree.read_with(cx, |tree, _| {
+        let ignored_dir = tree.entry_for_path(rel_path("ignored_dir")).unwrap();
+        assert_eq!(
+            ignored_dir.kind,
+            EntryKind::Dir,
+            "ignored_dir should still be loaded (Dir), not UnloadedDir"
+        );
+        assert!(
+            tree.entry_for_path(rel_path("ignored_dir/file1.txt"))
+                .is_some(),
+            "file1.txt should still be visible after directory fs event"
+        );
+        assert!(
+            tree.entry_for_path(rel_path("ignored_dir/file2.txt"))
+                .is_some(),
+            "file2.txt should still be visible after directory fs event"
+        );
+    });
+}
+
 #[gpui::test(iterations = 100)]
 async fn test_random_worktree_operations_during_initial_scan(
     cx: &mut TestAppContext,
@@ -1559,6 +1753,7 @@ async fn test_random_worktree_operations_during_initial_scan(
         true,
         fs.clone(),
         Default::default(),
+        true,
         &mut cx.to_async(),
     )
     .await
@@ -1649,6 +1844,7 @@ async fn test_random_worktree_changes(cx: &mut TestAppContext, mut rng: StdRng)
         true,
         fs.clone(),
         Default::default(),
+        true,
         &mut cx.to_async(),
     )
     .await
@@ -1721,6 +1917,7 @@ async fn test_random_worktree_changes(cx: &mut TestAppContext, mut rng: StdRng)
             true,
             fs.clone(),
             Default::default(),
+            true,
             &mut cx.to_async(),
         )
         .await
@@ -1844,8 +2041,14 @@ fn randomly_mutate_worktree(
                 })
             } else {
                 log::info!("overwriting file {:?} ({})", &entry.path, entry.id.0);
-                let task =
-                    worktree.write_file(entry.path.clone(), "".into(), Default::default(), cx);
+                let task = worktree.write_file(
+                    entry.path.clone(),
+                    "".into(),
+                    Default::default(),
+                    encoding_rs::UTF_8,
+                    false,
+                    cx,
+                );
                 cx.background_spawn(async move {
                     task.await?;
                     Ok(())
@@ -2034,6 +2237,7 @@ async fn test_private_single_file_worktree(cx: &mut TestAppContext) {
         true,
         fs.clone(),
         Default::default(),
+        true,
         &mut cx.to_async(),
     )
     .await
@@ -2066,6 +2270,7 @@ async fn test_repository_above_root(executor: BackgroundExecutor, cx: &mut TestA
         true,
         fs.clone(),
         Arc::default(),
+        true,
         &mut cx.to_async(),
     )
     .await
@@ -2143,6 +2348,7 @@ async fn test_global_gitignore(executor: BackgroundExecutor, cx: &mut TestAppCon
         true,
         fs.clone(),
         Arc::default(),
+        true,
         &mut cx.to_async(),
     )
     .await
@@ -2218,6 +2424,94 @@ async fn test_global_gitignore(executor: BackgroundExecutor, cx: &mut TestAppCon
     });
 }
 
+#[gpui::test]
+async fn test_repo_exclude(executor: BackgroundExecutor, cx: &mut TestAppContext) {
+    init_test(cx);
+
+    let fs = FakeFs::new(executor);
+    let project_dir = Path::new(path!("/project"));
+    fs.insert_tree(
+        project_dir,
+        json!({
+            ".git": {
+                "info": {
+                    "exclude": ".env.*"
+                }
+            },
+            ".env.example": "secret=xxxx",
+            ".env.local": "secret=1234",
+            ".gitignore": "!.env.example",
+            "README.md": "# Repo Exclude",
+            "src": {
+                "main.rs": "fn main() {}",
+            },
+        }),
+    )
+    .await;
+
+    let worktree = Worktree::local(
+        project_dir,
+        true,
+        fs.clone(),
+        Default::default(),
+        true,
+        &mut cx.to_async(),
+    )
+    .await
+    .unwrap();
+    worktree
+        .update(cx, |worktree, _| {
+            worktree.as_local().unwrap().scan_complete()
+        })
+        .await;
+    cx.run_until_parked();
+
+    // .gitignore overrides .git/info/exclude
+    worktree.update(cx, |worktree, _cx| {
+        let expected_excluded_paths = [];
+        let expected_ignored_paths = [".env.local"];
+        let expected_tracked_paths = [".env.example", "README.md", "src/main.rs"];
+        let expected_included_paths = [];
+
+        check_worktree_entries(
+            worktree,
+            &expected_excluded_paths,
+            &expected_ignored_paths,
+            &expected_tracked_paths,
+            &expected_included_paths,
+        );
+    });
+
+    // Ignore statuses are updated when .git/info/exclude file changes
+    fs.write(
+        &project_dir.join(DOT_GIT).join(REPO_EXCLUDE),
+        ".env.example".as_bytes(),
+    )
+    .await
+    .unwrap();
+    worktree
+        .update(cx, |worktree, _| {
+            worktree.as_local().unwrap().scan_complete()
+        })
+        .await;
+    cx.run_until_parked();
+
+    worktree.update(cx, |worktree, _cx| {
+        let expected_excluded_paths = [];
+        let expected_ignored_paths = [];
+        let expected_tracked_paths = [".env.example", ".env.local", "README.md", "src/main.rs"];
+        let expected_included_paths = [];
+
+        check_worktree_entries(
+            worktree,
+            &expected_excluded_paths,
+            &expected_ignored_paths,
+            &expected_tracked_paths,
+            &expected_included_paths,
+        );
+    });
+}
+
 #[track_caller]
 fn check_worktree_entries(
     tree: &Worktree,
@@ -2270,3 +2564,282 @@ fn init_test(cx: &mut gpui::TestAppContext) {
         cx.set_global(settings_store);
     });
 }
+
+#[gpui::test]
+async fn test_load_file_encoding(cx: &mut TestAppContext) {
+    init_test(cx);
+
+    struct TestCase {
+        name: &'static str,
+        bytes: Vec<u8>,
+        expected_text: &'static str,
+    }
+
+    // --- Success Cases ---
+    let success_cases = vec![
+        TestCase {
+            name: "utf8.txt",
+            bytes: "こんにちは".as_bytes().to_vec(),
+            expected_text: "こんにちは",
+        },
+        TestCase {
+            name: "sjis.txt",
+            bytes: vec![0x82, 0xb1, 0x82, 0xf1, 0x82, 0xc9, 0x82, 0xbf, 0x82, 0xcd],
+            expected_text: "こんにちは",
+        },
+        TestCase {
+            name: "eucjp.txt",
+            bytes: vec![0xa4, 0xb3, 0xa4, 0xf3, 0xa4, 0xcb, 0xa4, 0xc1, 0xa4, 0xcf],
+            expected_text: "こんにちは",
+        },
+        TestCase {
+            name: "iso2022jp.txt",
+            bytes: vec![
+                0x1b, 0x24, 0x42, 0x24, 0x33, 0x24, 0x73, 0x24, 0x4b, 0x24, 0x41, 0x24, 0x4f, 0x1b,
+                0x28, 0x42,
+            ],
+            expected_text: "こんにちは",
+        },
+        TestCase {
+            name: "win1252.txt",
+            bytes: vec![0x43, 0x61, 0x66, 0xe9],
+            expected_text: "Café",
+        },
+        TestCase {
+            name: "gbk.txt",
+            bytes: vec![
+                0xbd, 0xf1, 0xcc, 0xec, 0xcc, 0xec, 0xc6, 0xf8, 0xb2, 0xbb, 0xb4, 0xed,
+            ],
+            expected_text: "今天天气不错",
+        },
+        // UTF-16LE with BOM
+        TestCase {
+            name: "utf16le_bom.txt",
+            bytes: vec![
+                0xFF, 0xFE, // BOM
+                0x53, 0x30, 0x93, 0x30, 0x6B, 0x30, 0x61, 0x30, 0x6F, 0x30,
+            ],
+            expected_text: "こんにちは",
+        },
+        // UTF-16BE with BOM
+        TestCase {
+            name: "utf16be_bom.txt",
+            bytes: vec![
+                0xFE, 0xFF, // BOM
+                0x30, 0x53, 0x30, 0x93, 0x30, 0x6B, 0x30, 0x61, 0x30, 0x6F,
+            ],
+            expected_text: "こんにちは",
+        },
+        // UTF-16LE without BOM (ASCII only)
+        // This relies on the "null byte heuristic" we implemented.
+        // "ABC" -> 41 00 42 00 43 00
+        TestCase {
+            name: "utf16le_ascii_no_bom.txt",
+            bytes: vec![0x41, 0x00, 0x42, 0x00, 0x43, 0x00],
+            expected_text: "ABC",
+        },
+    ];
+
+    // --- Failure Cases ---
+    let failure_cases = vec![
+        // Binary File (Should be detected by heuristic and return Error)
+        // Contains random bytes and mixed nulls that don't match UTF-16 patterns
+        TestCase {
+            name: "binary.bin",
+            bytes: vec![0x00, 0xFF, 0x12, 0x00, 0x99, 0x88, 0x77, 0x66, 0x00],
+            expected_text: "", // Not used
+        },
+    ];
+
+    let root_path = if cfg!(windows) {
+        Path::new("C:\\root")
+    } else {
+        Path::new("/root")
+    };
+
+    let fs = FakeFs::new(cx.background_executor.clone());
+    fs.create_dir(root_path).await.unwrap();
+
+    for case in success_cases.iter().chain(failure_cases.iter()) {
+        let path = root_path.join(case.name);
+        fs.write(&path, &case.bytes).await.unwrap();
+    }
+
+    let tree = Worktree::local(
+        root_path,
+        true,
+        fs,
+        Default::default(),
+        true,
+        &mut cx.to_async(),
+    )
+    .await
+    .unwrap();
+
+    cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
+        .await;
+
+    let rel_path = |name: &str| {
+        RelPath::new(&Path::new(name), PathStyle::local())
+            .unwrap()
+            .into_arc()
+    };
+
+    // Run Success Tests
+    for case in success_cases {
+        let loaded = tree
+            .update(cx, |tree, cx| tree.load_file(&rel_path(case.name), cx))
+            .await;
+        if let Err(e) = &loaded {
+            panic!("Failed to load success case '{}': {:?}", case.name, e);
+        }
+        let loaded = loaded.unwrap();
+        assert_eq!(
+            loaded.text, case.expected_text,
+            "Encoding mismatch for file: {}",
+            case.name
+        );
+    }
+
+    // Run Failure Tests
+    for case in failure_cases {
+        let loaded = tree
+            .update(cx, |tree, cx| tree.load_file(&rel_path(case.name), cx))
+            .await;
+        assert!(
+            loaded.is_err(),
+            "Failure case '{}' unexpectedly succeeded! It should have been detected as binary.",
+            case.name
+        );
+        let err_msg = loaded.unwrap_err().to_string();
+        println!("Got expected error for {}: {}", case.name, err_msg);
+    }
+}
+
+#[gpui::test]
+async fn test_write_file_encoding(cx: &mut gpui::TestAppContext) {
+    init_test(cx);
+    let fs = FakeFs::new(cx.executor());
+
+    let root_path = if cfg!(windows) {
+        Path::new("C:\\root")
+    } else {
+        Path::new("/root")
+    };
+    fs.create_dir(root_path).await.unwrap();
+
+    let worktree = Worktree::local(
+        root_path,
+        true,
+        fs.clone(),
+        Default::default(),
+        true,
+        &mut cx.to_async(),
+    )
+    .await
+    .unwrap();
+
+    // Define test case structure
+    struct TestCase {
+        name: &'static str,
+        text: &'static str,
+        encoding: &'static encoding_rs::Encoding,
+        has_bom: bool,
+        expected_bytes: Vec<u8>,
+    }
+
+    let cases = vec![
+        // Shift_JIS with Japanese
+        TestCase {
+            name: "Shift_JIS with Japanese",
+            text: "こんにちは",
+            encoding: encoding_rs::SHIFT_JIS,
+            has_bom: false,
+            expected_bytes: vec![0x82, 0xb1, 0x82, 0xf1, 0x82, 0xc9, 0x82, 0xbf, 0x82, 0xcd],
+        },
+        // UTF-8 No BOM
+        TestCase {
+            name: "UTF-8 No BOM",
+            text: "AB",
+            encoding: encoding_rs::UTF_8,
+            has_bom: false,
+            expected_bytes: vec![0x41, 0x42],
+        },
+        // UTF-8 with BOM
+        TestCase {
+            name: "UTF-8 with BOM",
+            text: "AB",
+            encoding: encoding_rs::UTF_8,
+            has_bom: true,
+            expected_bytes: vec![0xEF, 0xBB, 0xBF, 0x41, 0x42],
+        },
+        // UTF-16LE No BOM with Japanese
+        // NOTE: This passes thanks to the manual encoding fix implemented in `write_file`.
+        TestCase {
+            name: "UTF-16LE No BOM with Japanese",
+            text: "こんにちは",
+            encoding: encoding_rs::UTF_16LE,
+            has_bom: false,
+            expected_bytes: vec![0x53, 0x30, 0x93, 0x30, 0x6b, 0x30, 0x61, 0x30, 0x6f, 0x30],
+        },
+        // UTF-16LE with BOM
+        TestCase {
+            name: "UTF-16LE with BOM",
+            text: "A",
+            encoding: encoding_rs::UTF_16LE,
+            has_bom: true,
+            expected_bytes: vec![0xFF, 0xFE, 0x41, 0x00],
+        },
+        // UTF-16BE No BOM with Japanese
+        // NOTE: This passes thanks to the manual encoding fix.
+        TestCase {
+            name: "UTF-16BE No BOM with Japanese",
+            text: "こんにちは",
+            encoding: encoding_rs::UTF_16BE,
+            has_bom: false,
+            expected_bytes: vec![0x30, 0x53, 0x30, 0x93, 0x30, 0x6b, 0x30, 0x61, 0x30, 0x6f],
+        },
+        // UTF-16BE with BOM
+        TestCase {
+            name: "UTF-16BE with BOM",
+            text: "A",
+            encoding: encoding_rs::UTF_16BE,
+            has_bom: true,
+            expected_bytes: vec![0xFE, 0xFF, 0x00, 0x41],
+        },
+    ];
+
+    for (i, case) in cases.into_iter().enumerate() {
+        let file_name = format!("test_{}.txt", i);
+        let path: Arc<Path> = Path::new(&file_name).into();
+        let file_path = root_path.join(&file_name);
+
+        fs.insert_file(&file_path, "".into()).await;
+
+        let rel_path = RelPath::new(&path, PathStyle::local()).unwrap().into_arc();
+        let text = text::Rope::from(case.text);
+
+        let task = worktree.update(cx, |wt, cx| {
+            wt.write_file(
+                rel_path,
+                text,
+                text::LineEnding::Unix,
+                case.encoding,
+                case.has_bom,
+                cx,
+            )
+        });
+
+        if let Err(e) = task.await {
+            panic!("Unexpected error in case '{}': {:?}", case.name, e);
+        }
+
+        let bytes = fs.load_bytes(&file_path).await.unwrap();
+
+        assert_eq!(
+            bytes, case.expected_bytes,
+            "case '{}' mismatch. Expected {:?}, but got {:?}",
+            case.name, case.expected_bytes, bytes
+        );
+    }
+}

crates/worktree_benchmarks/src/main.rs 🔗

@@ -5,8 +5,7 @@ use std::{
 
 use fs::RealFs;
 use gpui::Application;
-use settings::Settings;
-use worktree::{Worktree, WorktreeSettings};
+use worktree::Worktree;
 
 fn main() {
     let Some(worktree_root_path) = std::env::args().nth(1) else {
@@ -27,6 +26,7 @@ fn main() {
                 true,
                 fs,
                 Arc::new(AtomicUsize::new(0)),
+                true,
                 cx,
             )
             .await

crates/x_ai/src/x_ai.rs 🔗

@@ -30,6 +30,17 @@ pub enum Model {
         alias = "grok-4-fast-non-reasoning-latest"
     )]
     Grok4FastNonReasoning,
+    #[serde(
+        rename = "grok-4-1-fast-non-reasoning",
+        alias = "grok-4-1-fast-non-reasoning-latest"
+    )]
+    Grok41FastNonReasoning,
+    #[serde(
+        rename = "grok-4-1-fast-reasoning",
+        alias = "grok-4-1-fast-reasoning-latest",
+        alias = "grok-4-1-fast"
+    )]
+    Grok41FastReasoning,
     #[serde(rename = "grok-code-fast-1", alias = "grok-code-fast-1-0825")]
     GrokCodeFast1,
     #[serde(rename = "custom")]
@@ -56,6 +67,9 @@ impl Model {
             "grok-4" => Ok(Self::Grok4),
             "grok-4-fast-reasoning" => Ok(Self::Grok4FastReasoning),
             "grok-4-fast-non-reasoning" => Ok(Self::Grok4FastNonReasoning),
+            "grok-4-1-fast-non-reasoning" => Ok(Self::Grok41FastNonReasoning),
+            "grok-4-1-fast-reasoning" => Ok(Self::Grok41FastReasoning),
+            "grok-4-1-fast" => Ok(Self::Grok41FastReasoning),
             "grok-2-vision" => Ok(Self::Grok2Vision),
             "grok-3" => Ok(Self::Grok3),
             "grok-3-mini" => Ok(Self::Grok3Mini),
@@ -76,6 +90,8 @@ impl Model {
             Self::Grok4 => "grok-4",
             Self::Grok4FastReasoning => "grok-4-fast-reasoning",
             Self::Grok4FastNonReasoning => "grok-4-fast-non-reasoning",
+            Self::Grok41FastNonReasoning => "grok-4-1-fast-non-reasoning",
+            Self::Grok41FastReasoning => "grok-4-1-fast-reasoning",
             Self::GrokCodeFast1 => "grok-code-fast-1",
             Self::Custom { name, .. } => name,
         }
@@ -91,6 +107,8 @@ impl Model {
             Self::Grok4 => "Grok 4",
             Self::Grok4FastReasoning => "Grok 4 Fast",
             Self::Grok4FastNonReasoning => "Grok 4 Fast (Non-Reasoning)",
+            Self::Grok41FastNonReasoning => "Grok 4.1 Fast (Non-Reasoning)",
+            Self::Grok41FastReasoning => "Grok 4.1 Fast",
             Self::GrokCodeFast1 => "Grok Code Fast 1",
             Self::Custom {
                 name, display_name, ..
@@ -102,7 +120,10 @@ impl Model {
         match self {
             Self::Grok3 | Self::Grok3Mini | Self::Grok3Fast | Self::Grok3MiniFast => 131_072,
             Self::Grok4 | Self::GrokCodeFast1 => 256_000,
-            Self::Grok4FastReasoning | Self::Grok4FastNonReasoning => 128_000,
+            Self::Grok4FastReasoning
+            | Self::Grok4FastNonReasoning
+            | Self::Grok41FastNonReasoning
+            | Self::Grok41FastReasoning => 2_000_000,
             Self::Grok2Vision => 8_192,
             Self::Custom { max_tokens, .. } => *max_tokens,
         }
@@ -114,6 +135,8 @@ impl Model {
             Self::Grok4
             | Self::Grok4FastReasoning
             | Self::Grok4FastNonReasoning
+            | Self::Grok41FastNonReasoning
+            | Self::Grok41FastReasoning
             | Self::GrokCodeFast1 => Some(64_000),
             Self::Grok2Vision => Some(4_096),
             Self::Custom {
@@ -131,7 +154,9 @@ impl Model {
             | Self::Grok3MiniFast
             | Self::Grok4
             | Self::Grok4FastReasoning
-            | Self::Grok4FastNonReasoning => true,
+            | Self::Grok4FastNonReasoning
+            | Self::Grok41FastNonReasoning
+            | Self::Grok41FastReasoning => true,
             Self::Custom {
                 parallel_tool_calls: Some(support),
                 ..
@@ -154,6 +179,8 @@ impl Model {
             | Self::Grok4
             | Self::Grok4FastReasoning
             | Self::Grok4FastNonReasoning
+            | Self::Grok41FastNonReasoning
+            | Self::Grok41FastReasoning
             | Self::GrokCodeFast1 => true,
             Self::Custom {
                 supports_tools: Some(support),
@@ -165,7 +192,12 @@ impl Model {
 
     pub fn supports_images(&self) -> bool {
         match self {
-            Self::Grok2Vision => true,
+            Self::Grok2Vision
+            | Self::Grok4
+            | Self::Grok4FastReasoning
+            | Self::Grok4FastNonReasoning
+            | Self::Grok41FastNonReasoning
+            | Self::Grok41FastReasoning => true,
             Self::Custom {
                 supports_images: Some(support),
                 ..

crates/zed/Cargo.toml 🔗

@@ -2,7 +2,7 @@
 description = "The fast, collaborative code editor."
 edition.workspace = true
 name = "zed"
-version = "0.216.0"
+version = "0.219.0"
 publish.workspace = true
 license = "GPL-3.0-or-later"
 authors = ["Zed Team <hi@zed.dev>"]
@@ -10,11 +10,10 @@ authors = ["Zed Team <hi@zed.dev>"]
 [lints]
 workspace = true
 
-[[bin]]
-name = "zed"
-path = "src/zed-main.rs"
+[features]
+tracy = ["ztracing/tracy"]
 
-[lib]
+[[bin]]
 name = "zed"
 path = "src/main.rs"
 
@@ -23,6 +22,7 @@ acp_tools.workspace = true
 activity_indicator.workspace = true
 agent_settings.workspace = true
 agent_ui.workspace = true
+agent_ui_v2.workspace = true
 anyhow.workspace = true
 askpass.workspace = true
 assets.workspace = true
@@ -41,6 +41,7 @@ collab_ui.workspace = true
 collections.workspace = true
 command_palette.workspace = true
 component.workspace = true
+component_preview.workspace = true
 copilot.workspace = true
 crashes.workspace = true
 dap_adapters.workspace = true
@@ -50,7 +51,6 @@ debugger_tools.workspace = true
 debugger_ui.workspace = true
 diagnostics.workspace = true
 editor.workspace = true
-zeta2_tools.workspace = true
 env_logger.workspace = true
 extension.workspace = true
 extension_host.workspace = true
@@ -74,7 +74,8 @@ gpui = { workspace = true, features = [
 gpui_tokio.workspace = true
 rayon.workspace = true
 
-edit_prediction_button.workspace = true
+edit_prediction.workspace = true
+edit_prediction_ui.workspace = true
 http_client.workspace = true
 image_viewer.workspace = true
 inspector_ui.workspace = true
@@ -144,9 +145,10 @@ theme_extension.workspace = true
 theme_selector.workspace = true
 time.workspace = true
 title_bar.workspace = true
+ztracing.workspace = true
+tracing.workspace = true
 toolchain_selector.workspace = true
 ui.workspace = true
-ui_input.workspace = true
 ui_prompt.workspace = true
 url.workspace = true
 urlencoding.workspace = true
@@ -157,10 +159,10 @@ vim_mode_setting.workspace = true
 watch.workspace = true
 web_search.workspace = true
 web_search_providers.workspace = true
+which_key.workspace = true
 workspace.workspace = true
 zed_actions.workspace = true
 zed_env_vars.workspace = true
-zeta.workspace = true
 zlog.workspace = true
 zlog_settings.workspace = true
 chrono.workspace = true
@@ -190,6 +192,10 @@ terminal_view = { workspace = true, features = ["test-support"] }
 tree-sitter-md.workspace = true
 tree-sitter-rust.workspace = true
 workspace = { workspace = true, features = ["test-support"] }
+agent_ui = { workspace = true, features = ["test-support"] }
+agent_ui_v2 = { workspace = true, features = ["test-support"] }
+search = { workspace = true, features = ["test-support"] }
+
 
 [package.metadata.bundle-dev]
 icon = ["resources/app-icon-dev@2x.png", "resources/app-icon-dev.png"]
@@ -224,4 +230,4 @@ osx_info_plist_exts = ["resources/info/*"]
 osx_url_schemes = ["zed"]
 
 [package.metadata.cargo-machete]
-ignored = ["profiling", "zstd"]
+ignored = ["profiling", "zstd", "tracing"]

crates/zed/resources/zed.entitlements 🔗

@@ -22,5 +22,9 @@
 	<true/>
 	<key>com.apple.security.personal-information.photos-library</key>
 	<true/>
+	<key>com.apple.security.files.user-selected.read-write</key>
+	<true/>
+	<key>com.apple.security.files.downloads.read-write</key>
+	<true/>
 </dict>
 </plist>

crates/zed/src/main.rs 🔗

@@ -1,9 +1,12 @@
+// Disable command line from opening on release mode
+#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
+
 mod reliability;
 mod zed;
 
 use agent_ui::AgentPanel;
 use anyhow::{Context as _, Error, Result};
-use clap::{Parser, command};
+use clap::Parser;
 use cli::FORCE_CLI_MODE_ENV_VAR_NAME;
 use client::{Client, ProxySettings, UserStore, parse_zed_link};
 use collab_ui::channel_view::ChannelView;
@@ -15,11 +18,13 @@ use extension::ExtensionHostProxy;
 use fs::{Fs, RealFs};
 use futures::{StreamExt, channel::oneshot, future};
 use git::GitHostingProviderRegistry;
+use git_ui::clone::clone_and_open;
 use gpui::{App, AppContext, Application, AsyncApp, Focusable as _, QuitMode, UpdateGlobal as _};
 
 use gpui_tokio::Tokio;
 use language::LanguageRegistry;
 use onboarding::{FIRST_OPEN, show_onboarding_view};
+use project_panel::ProjectPanel;
 use prompt_store::PromptBuilder;
 use remote::RemoteConnectionOptions;
 use reqwest_client::ReqwestClient;
@@ -27,16 +32,18 @@ use reqwest_client::ReqwestClient;
 use assets::Assets;
 use node_runtime::{NodeBinaryOptions, NodeRuntime};
 use parking_lot::Mutex;
-use project::project_settings::ProjectSettings;
+use project::{project_settings::ProjectSettings, trusted_worktrees};
 use recent_projects::{SshSettings, open_remote_project};
 use release_channel::{AppCommitSha, AppVersion, ReleaseChannel};
 use session::{AppSession, Session};
 use settings::{BaseKeymap, Settings, SettingsStore, watch_config_file};
 use std::{
+    cell::RefCell,
     env,
     io::{self, IsTerminal},
     path::{Path, PathBuf},
     process,
+    rc::Rc,
     sync::{Arc, OnceLock},
     time::Instant,
 };
@@ -130,6 +137,7 @@ fn fail_to_open_window(e: anyhow::Error, _cx: &mut App) {
         process::exit(1);
     }
 
+    // Maybe unify this with gpui::platform::linux::platform::ResultExt::notify_err(..)?
     #[cfg(any(target_os = "linux", target_os = "freebsd"))]
     {
         use ashpd::desktop::notification::{Notification, NotificationProxy, Priority};
@@ -162,10 +170,9 @@ fn fail_to_open_window(e: anyhow::Error, _cx: &mut App) {
         .detach();
     }
 }
+static STARTUP_TIME: OnceLock<Instant> = OnceLock::new();
 
-pub static STARTUP_TIME: OnceLock<Instant> = OnceLock::new();
-
-pub fn main() {
+fn main() {
     STARTUP_TIME.get_or_init(|| Instant::now());
 
     #[cfg(unix)]
@@ -240,6 +247,7 @@ pub fn main() {
     }
 
     zlog::init();
+
     if stdout_is_a_pty() {
         zlog::init_output_stdout();
     } else {
@@ -249,6 +257,7 @@ pub fn main() {
             zlog::init_output_stdout();
         };
     }
+    ztracing::init();
 
     let version = option_env!("ZED_BUILD_ID");
     let app_commit_sha =
@@ -404,6 +413,14 @@ pub fn main() {
     });
 
     app.run(move |cx| {
+        let trusted_paths = match workspace::WORKSPACE_DB.fetch_trusted_worktrees(None, None, cx) {
+            Ok(trusted_paths) => trusted_paths,
+            Err(e) => {
+                log::error!("Failed to do initial trusted worktrees fetch: {e:#}");
+                HashMap::default()
+            }
+        };
+        trusted_worktrees::init(trusted_paths, None, None, cx);
         menu::init();
         zed_actions::init();
 
@@ -472,6 +489,7 @@ pub fn main() {
             tx.send(Some(options)).log_err();
         })
         .detach();
+
         let node_runtime = NodeRuntime::new(client.http_client(), Some(shell_env_loaded_rx), rx);
 
         debug_adapter_extension::init(extension_host_proxy.clone(), cx);
@@ -581,7 +599,7 @@ pub fn main() {
         language_model::init(app_state.client.clone(), cx);
         language_models::init(app_state.user_store.clone(), app_state.client.clone(), cx);
         acp_tools::init(cx);
-        zeta2_tools::init(cx);
+        edit_prediction_ui::init(cx);
         web_search::init(cx);
         web_search_providers::init(app_state.client.clone(), cx);
         snippet_provider::init(cx);
@@ -595,6 +613,7 @@ pub fn main() {
             false,
             cx,
         );
+        agent_ui_v2::agents_panel::init(cx);
         repl::init(app_state.fs.clone(), cx);
         recent_projects::init(cx);
 
@@ -640,10 +659,11 @@ pub fn main() {
         settings_ui::init(cx);
         keymap_editor::init(cx);
         extensions_ui::init(cx);
-        zeta::init(cx);
+        edit_prediction::init(cx);
         inspector_ui::init(app_state.clone(), cx);
         json_schema_store::init(cx);
         miniprofiler_ui::init(*STARTUP_TIME.get().unwrap(), cx);
+        which_key::init(cx);
 
         cx.observe_global::<SettingsStore>({
             let http = app_state.client.http_client();
@@ -754,7 +774,7 @@ pub fn main() {
 
         let app_state = app_state.clone();
 
-        crate::zed::component_preview::init(app_state.clone(), cx);
+        component_preview::init(app_state.clone(), cx);
 
         cx.spawn(async move |cx| {
             while let Some(urls) = open_rx.next().await {
@@ -799,7 +819,7 @@ fn handle_open_request(request: OpenRequest, app_state: Arc<AppState>, cx: &mut
                         workspace::get_any_active_workspace(app_state, cx.clone()).await?;
                     workspace.update(cx, |workspace, window, cx| {
                         if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
-                            panel.focus_handle(cx).focus(window);
+                            panel.focus_handle(cx).focus(window, cx);
                         }
                     })
                 })
@@ -813,12 +833,19 @@ fn handle_open_request(request: OpenRequest, app_state: Arc<AppState>, cx: &mut
                     cx.spawn_in(window, async move |workspace, cx| {
                         let res = async move {
                             let json = app_state.languages.language_for_name("JSONC").await.ok();
+                            let lsp_store = workspace.update(cx, |workspace, cx| {
+                                workspace
+                                    .project()
+                                    .update(cx, |project, _| project.lsp_store())
+                            })?;
                             let json_schema_content =
                                 json_schema_store::resolve_schema_request_inner(
                                     &app_state.languages,
+                                    lsp_store,
                                     &schema_path,
                                     cx,
-                                )?;
+                                )
+                                .await?;
                             let json_schema_content =
                                 serde_json::to_string_pretty(&json_schema_content)
                                     .context("Failed to serialize JSON Schema as JSON")?;
@@ -880,6 +907,79 @@ fn handle_open_request(request: OpenRequest, app_state: Arc<AppState>, cx: &mut
                 })
                 .detach_and_log_err(cx);
             }
+            OpenRequestKind::GitClone { repo_url } => {
+                workspace::with_active_or_new_workspace(cx, |_workspace, window, cx| {
+                    if window.is_window_active() {
+                        clone_and_open(
+                            repo_url,
+                            cx.weak_entity(),
+                            window,
+                            cx,
+                            Arc::new(|workspace: &mut workspace::Workspace, window, cx| {
+                                workspace.focus_panel::<ProjectPanel>(window, cx);
+                            }),
+                        );
+                        return;
+                    }
+
+                    let subscription = Rc::new(RefCell::new(None));
+                    subscription.replace(Some(cx.observe_in(&cx.entity(), window, {
+                        let subscription = subscription.clone();
+                        let repo_url = repo_url;
+                        move |_, workspace_entity, window, cx| {
+                            if window.is_window_active() && subscription.take().is_some() {
+                                clone_and_open(
+                                    repo_url.clone(),
+                                    workspace_entity.downgrade(),
+                                    window,
+                                    cx,
+                                    Arc::new(|workspace: &mut workspace::Workspace, window, cx| {
+                                        workspace.focus_panel::<ProjectPanel>(window, cx);
+                                    }),
+                                );
+                            }
+                        }
+                    })));
+                });
+            }
+            OpenRequestKind::GitCommit { sha } => {
+                cx.spawn(async move |cx| {
+                    let paths_with_position =
+                        derive_paths_with_position(app_state.fs.as_ref(), request.open_paths).await;
+                    let (workspace, _results) = open_paths_with_positions(
+                        &paths_with_position,
+                        &[],
+                        app_state,
+                        workspace::OpenOptions::default(),
+                        cx,
+                    )
+                    .await?;
+
+                    workspace
+                        .update(cx, |workspace, window, cx| {
+                            let Some(repo) = workspace.project().read(cx).active_repository(cx)
+                            else {
+                                log::error!("no active repository found for commit view");
+                                return Err(anyhow::anyhow!("no active repository found"));
+                            };
+
+                            git_ui::commit_view::CommitView::open(
+                                sha,
+                                repo.downgrade(),
+                                workspace.weak_handle(),
+                                None,
+                                None,
+                                window,
+                                cx,
+                            );
+                            Ok(())
+                        })
+                        .log_err();
+
+                    anyhow::Ok(())
+                })
+                .detach_and_log_err(cx);
+            }
         }
 
         return;
@@ -1154,7 +1254,13 @@ async fn restore_or_create_workspace(app_state: Arc<AppState>, cx: &mut AsyncApp
                 app_state,
                 cx,
                 |workspace, window, cx| {
-                    Editor::new_file(workspace, &Default::default(), window, cx)
+                    let restore_on_startup = WorkspaceSettings::get_global(cx).restore_on_startup;
+                    match restore_on_startup {
+                        workspace::RestoreOnStartupBehavior::Launchpad => {}
+                        _ => {
+                            Editor::new_file(workspace, &Default::default(), window, cx);
+                        }
+                    }
                 },
             )
         })?
@@ -1244,7 +1350,7 @@ fn init_paths() -> HashMap<io::ErrorKind, Vec<&'static Path>> {
     })
 }
 
-pub fn stdout_is_a_pty() -> bool {
+fn stdout_is_a_pty() -> bool {
     std::env::var(FORCE_CLI_MODE_ENV_VAR_NAME).ok().is_none() && io::stdout().is_terminal()
 }
 
@@ -1490,14 +1596,14 @@ fn dump_all_gpui_actions() {
     struct ActionDef {
         name: &'static str,
         human_name: String,
-        aliases: &'static [&'static str],
+        deprecated_aliases: &'static [&'static str],
         documentation: Option<&'static str>,
     }
     let mut actions = gpui::generate_list_of_all_registered_actions()
         .map(|action| ActionDef {
             name: action.name,
             human_name: command_palette::humanize_action_name(action.name),
-            aliases: action.deprecated_aliases,
+            deprecated_aliases: action.deprecated_aliases,
             documentation: action.documentation,
         })
         .collect::<Vec<ActionDef>>();

crates/zed/src/reliability.rs 🔗

@@ -1,8 +1,8 @@
 use anyhow::{Context as _, Result};
 use client::{Client, telemetry::MINIDUMP_ENDPOINT};
-use futures::AsyncReadExt;
+use futures::{AsyncReadExt, TryStreamExt};
 use gpui::{App, AppContext as _, SerializedThreadTaskTimings};
-use http_client::{self, HttpClient};
+use http_client::{self, AsyncBody, HttpClient, Request};
 use log::info;
 use project::Project;
 use proto::{CrashReport, GetCrashFilesResponse};
@@ -296,11 +296,14 @@ async fn upload_minidump(
 
     // TODO: feature-flag-context, and more of device-context like screen resolution, available ram, device model, etc
 
+    let stream = form
+        .into_stream()
+        .map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))
+        .into_async_read();
+    let body = AsyncBody::from_reader(stream);
+    let req = Request::builder().uri(endpoint).body(body)?;
     let mut response_text = String::new();
-    let mut response = client
-        .http_client()
-        .send_multipart_form(endpoint, form)
-        .await?;
+    let mut response = client.http_client().send(req).await?;
     response
         .body_mut()
         .read_to_string(&mut response_text)

crates/zed/src/zed-main.rs 🔗

@@ -1,8 +0,0 @@
-// Disable command line from opening on release mode
-#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
-
-pub fn main() {
-    // separated out so that the file containing the main function can be imported by other crates,
-    // while having all gpui resources that are registered in main (primarily actions) initialized
-    zed::main();
-}

crates/zed/src/zed.rs 🔗

@@ -1,5 +1,4 @@
 mod app_menus;
-pub mod component_preview;
 pub mod edit_prediction_registry;
 #[cfg(target_os = "macos")]
 pub(crate) mod mac_only_instance;
@@ -10,6 +9,7 @@ mod quick_action_bar;
 pub(crate) mod windows_only_instance;
 
 use agent_ui::{AgentDiffToolbar, AgentPanelDelegate};
+use agent_ui_v2::agents_panel::AgentsPanel;
 use anyhow::Context as _;
 pub use app_menus::*;
 use assets::Assets;
@@ -31,8 +31,8 @@ use git_ui::project_diff::ProjectDiffToolbar;
 use gpui::{
     Action, App, AppContext as _, AsyncWindowContext, Context, DismissEvent, Element, Entity,
     Focusable, KeyBinding, ParentElement, PathPromptOptions, PromptLevel, ReadGlobal, SharedString,
-    Styled, Task, TitlebarOptions, UpdateGlobal, WeakEntity, Window, WindowKind, WindowOptions,
-    actions, image_cache, point, px, retain_all,
+    Task, TitlebarOptions, UpdateGlobal, WeakEntity, Window, WindowKind, WindowOptions, actions,
+    image_cache, point, px, retain_all,
 };
 use image_viewer::ImageInfo;
 use language::Capability;
@@ -81,8 +81,9 @@ use vim_mode_setting::VimModeSetting;
 use workspace::notifications::{
     NotificationId, SuppressEvent, dismiss_app_notification, show_app_notification,
 };
+use workspace::utility_pane::utility_slot_for_dock_position;
 use workspace::{
-    AppState, NewFile, NewWindow, OpenLog, Toast, Workspace, WorkspaceSettings,
+    AppState, NewFile, NewWindow, OpenLog, Panel, Toast, Workspace, WorkspaceSettings,
     create_and_open_local_file, notifications::simple_message_notification::MessageNotification,
     open_new,
 };
@@ -159,15 +160,15 @@ pub fn init(cx: &mut App) {
             || flag.await
         {
             cx.update(|cx| {
-                cx.on_action(|_: &TestPanic, _| panic!("Ran the TestPanic action"));
-                cx.on_action(|_: &TestCrash, _| {
-                    unsafe extern "C" {
-                        fn puts(s: *const i8);
-                    }
-                    unsafe {
-                        puts(0xabad1d3a as *const i8);
-                    }
-                });
+                cx.on_action(|_: &TestPanic, _| panic!("Ran the TestPanic action"))
+                    .on_action(|_: &TestCrash, _| {
+                        unsafe extern "C" {
+                            fn puts(s: *const i8);
+                        }
+                        unsafe {
+                            puts(0xabad1d3a as *const i8);
+                        }
+                    });
             })
             .ok();
         };
@@ -177,11 +178,11 @@ pub fn init(cx: &mut App) {
         with_active_or_new_workspace(cx, |workspace, window, cx| {
             open_log_file(workspace, window, cx);
         });
-    });
-    cx.on_action(|_: &workspace::RevealLogInFileManager, cx| {
+    })
+    .on_action(|_: &workspace::RevealLogInFileManager, cx| {
         cx.reveal_path(paths::log_file().as_path());
-    });
-    cx.on_action(|_: &zed_actions::OpenLicenses, cx| {
+    })
+    .on_action(|_: &zed_actions::OpenLicenses, cx| {
         with_active_or_new_workspace(cx, |workspace, window, cx| {
             open_bundled_file(
                 workspace,
@@ -192,13 +193,13 @@ pub fn init(cx: &mut App) {
                 cx,
             );
         });
-    });
-    cx.on_action(|_: &zed_actions::OpenTelemetryLog, cx| {
+    })
+    .on_action(|_: &zed_actions::OpenTelemetryLog, cx| {
         with_active_or_new_workspace(cx, |workspace, window, cx| {
             open_telemetry_log_file(workspace, window, cx);
         });
-    });
-    cx.on_action(|&zed_actions::OpenKeymapFile, cx| {
+    })
+    .on_action(|&zed_actions::OpenKeymapFile, cx| {
         with_active_or_new_workspace(cx, |_, window, cx| {
             open_settings_file(
                 paths::keymap_file(),
@@ -207,8 +208,8 @@ pub fn init(cx: &mut App) {
                 cx,
             );
         });
-    });
-    cx.on_action(|_: &OpenSettingsFile, cx| {
+    })
+    .on_action(|_: &OpenSettingsFile, cx| {
         with_active_or_new_workspace(cx, |_, window, cx| {
             open_settings_file(
                 paths::settings_file(),
@@ -217,13 +218,13 @@ pub fn init(cx: &mut App) {
                 cx,
             );
         });
-    });
-    cx.on_action(|_: &OpenAccountSettings, cx| {
+    })
+    .on_action(|_: &OpenAccountSettings, cx| {
         with_active_or_new_workspace(cx, |_, _, cx| {
             cx.open_url(&zed_urls::account_url(cx));
         });
-    });
-    cx.on_action(|_: &OpenTasks, cx| {
+    })
+    .on_action(|_: &OpenTasks, cx| {
         with_active_or_new_workspace(cx, |_, window, cx| {
             open_settings_file(
                 paths::tasks_file(),
@@ -232,8 +233,8 @@ pub fn init(cx: &mut App) {
                 cx,
             );
         });
-    });
-    cx.on_action(|_: &OpenDebugTasks, cx| {
+    })
+    .on_action(|_: &OpenDebugTasks, cx| {
         with_active_or_new_workspace(cx, |_, window, cx| {
             open_settings_file(
                 paths::debug_scenarios_file(),
@@ -242,8 +243,8 @@ pub fn init(cx: &mut App) {
                 cx,
             );
         });
-    });
-    cx.on_action(|_: &OpenDefaultSettings, cx| {
+    })
+    .on_action(|_: &OpenDefaultSettings, cx| {
         with_active_or_new_workspace(cx, |workspace, window, cx| {
             open_bundled_file(
                 workspace,
@@ -254,8 +255,8 @@ pub fn init(cx: &mut App) {
                 cx,
             );
         });
-    });
-    cx.on_action(|_: &zed_actions::OpenDefaultKeymap, cx| {
+    })
+    .on_action(|_: &zed_actions::OpenDefaultKeymap, cx| {
         with_active_or_new_workspace(cx, |workspace, window, cx| {
             open_bundled_file(
                 workspace,
@@ -266,8 +267,8 @@ pub fn init(cx: &mut App) {
                 cx,
             );
         });
-    });
-    cx.on_action(|_: &zed_actions::About, cx| {
+    })
+    .on_action(|_: &zed_actions::About, cx| {
         with_active_or_new_workspace(cx, |workspace, window, cx| {
             about(workspace, window, cx);
         });
@@ -351,6 +352,8 @@ pub fn initialize_workspace(
 ) {
     let mut _on_close_subscription = bind_on_window_closed(cx);
     cx.observe_global::<SettingsStore>(move |cx| {
+        // A 1.92 regression causes unused-assignment to trigger on this variable.
+        _ = _on_close_subscription.is_some();
         _on_close_subscription = bind_on_window_closed(cx);
     })
     .detach();
@@ -401,8 +404,8 @@ pub fn initialize_workspace(
         unstable_version_notification(cx);
 
         let edit_prediction_menu_handle = PopoverMenuHandle::default();
-        let edit_prediction_button = cx.new(|cx| {
-            edit_prediction_button::EditPredictionButton::new(
+        let edit_prediction_ui = cx.new(|cx| {
+            edit_prediction_ui::EditPredictionButton::new(
                 app_state.fs.clone(),
                 app_state.user_store.clone(),
                 edit_prediction_menu_handle.clone(),
@@ -411,7 +414,7 @@ pub fn initialize_workspace(
             )
         });
         workspace.register_action({
-            move |_, _: &edit_prediction_button::ToggleMenu, window, cx| {
+            move |_, _: &edit_prediction_ui::ToggleMenu, window, cx| {
                 edit_prediction_menu_handle.toggle(window, cx);
             }
         });
@@ -450,7 +453,7 @@ pub fn initialize_workspace(
             status_bar.add_left_item(lsp_button, window, cx);
             status_bar.add_left_item(diagnostic_summary, window, cx);
             status_bar.add_left_item(activity_indicator, window, cx);
-            status_bar.add_right_item(edit_prediction_button, window, cx);
+            status_bar.add_right_item(edit_prediction_ui, window, cx);
             status_bar.add_right_item(active_buffer_language, window, cx);
             status_bar.add_right_item(active_toolchain_language, window, cx);
             status_bar.add_right_item(line_ending_indicator, window, cx);
@@ -473,7 +476,7 @@ pub fn initialize_workspace(
         initialize_panels(prompt_builder.clone(), window, cx);
         register_actions(app_state.clone(), workspace, window, cx);
 
-        workspace.focus_handle(cx).focus(window);
+        workspace.focus_handle(cx).focus(window, cx);
     })
     .detach();
 }
@@ -679,7 +682,8 @@ fn initialize_panels(
             add_panel_when_ready(channels_panel, workspace_handle.clone(), cx.clone()),
             add_panel_when_ready(notification_panel, workspace_handle.clone(), cx.clone()),
             add_panel_when_ready(debug_panel, workspace_handle.clone(), cx.clone()),
-            initialize_agent_panel(workspace_handle, prompt_builder, cx.clone()).map(|r| r.log_err())
+            initialize_agent_panel(workspace_handle.clone(), prompt_builder, cx.clone()).map(|r| r.log_err()),
+            initialize_agents_panel(workspace_handle, cx.clone()).map(|r| r.log_err())
         );
 
         anyhow::Ok(())
@@ -687,58 +691,64 @@ fn initialize_panels(
     .detach();
 }
 
+fn setup_or_teardown_ai_panel<P: Panel>(
+    workspace: &mut Workspace,
+    window: &mut Window,
+    cx: &mut Context<Workspace>,
+    load_panel: impl FnOnce(
+        WeakEntity<Workspace>,
+        AsyncWindowContext,
+    ) -> Task<anyhow::Result<Entity<P>>>
+    + 'static,
+) -> Task<anyhow::Result<()>> {
+    let disable_ai = SettingsStore::global(cx)
+        .get::<DisableAiSettings>(None)
+        .disable_ai
+        || cfg!(test);
+    let existing_panel = workspace.panel::<P>(cx);
+    match (disable_ai, existing_panel) {
+        (false, None) => cx.spawn_in(window, async move |workspace, cx| {
+            let panel = load_panel(workspace.clone(), cx.clone()).await?;
+            workspace.update_in(cx, |workspace, window, cx| {
+                let disable_ai = SettingsStore::global(cx)
+                    .get::<DisableAiSettings>(None)
+                    .disable_ai;
+                let have_panel = workspace.panel::<P>(cx).is_some();
+                if !disable_ai && !have_panel {
+                    workspace.add_panel(panel, window, cx);
+                }
+            })
+        }),
+        (true, Some(existing_panel)) => {
+            workspace.remove_panel::<P>(&existing_panel, window, cx);
+            Task::ready(Ok(()))
+        }
+        _ => Task::ready(Ok(())),
+    }
+}
+
 async fn initialize_agent_panel(
     workspace_handle: WeakEntity<Workspace>,
     prompt_builder: Arc<PromptBuilder>,
     mut cx: AsyncWindowContext,
 ) -> anyhow::Result<()> {
-    fn setup_or_teardown_agent_panel(
-        workspace: &mut Workspace,
-        prompt_builder: Arc<PromptBuilder>,
-        window: &mut Window,
-        cx: &mut Context<Workspace>,
-    ) -> Task<anyhow::Result<()>> {
-        let disable_ai = SettingsStore::global(cx)
-            .get::<DisableAiSettings>(None)
-            .disable_ai
-            || cfg!(test);
-        let existing_panel = workspace.panel::<agent_ui::AgentPanel>(cx);
-        match (disable_ai, existing_panel) {
-            (false, None) => cx.spawn_in(window, async move |workspace, cx| {
-                let panel =
-                    agent_ui::AgentPanel::load(workspace.clone(), prompt_builder, cx.clone())
-                        .await?;
-                workspace.update_in(cx, |workspace, window, cx| {
-                    let disable_ai = SettingsStore::global(cx)
-                        .get::<DisableAiSettings>(None)
-                        .disable_ai;
-                    let have_panel = workspace.panel::<agent_ui::AgentPanel>(cx).is_some();
-                    if !disable_ai && !have_panel {
-                        workspace.add_panel(panel, window, cx);
-                    }
-                })
-            }),
-            (true, Some(existing_panel)) => {
-                workspace.remove_panel::<agent_ui::AgentPanel>(&existing_panel, window, cx);
-                Task::ready(Ok(()))
-            }
-            _ => Task::ready(Ok(())),
-        }
-    }
-
     workspace_handle
         .update_in(&mut cx, |workspace, window, cx| {
-            setup_or_teardown_agent_panel(workspace, prompt_builder.clone(), window, cx)
+            let prompt_builder = prompt_builder.clone();
+            setup_or_teardown_ai_panel(workspace, window, cx, move |workspace, cx| {
+                agent_ui::AgentPanel::load(workspace, prompt_builder, cx)
+            })
         })?
         .await?;
 
     workspace_handle.update_in(&mut cx, |workspace, window, cx| {
-        cx.observe_global_in::<SettingsStore>(window, {
+        let prompt_builder = prompt_builder.clone();
+        cx.observe_global_in::<SettingsStore>(window, move |workspace, window, cx| {
             let prompt_builder = prompt_builder.clone();
-            move |workspace, window, cx| {
-                setup_or_teardown_agent_panel(workspace, prompt_builder.clone(), window, cx)
-                    .detach_and_log_err(cx);
-            }
+            setup_or_teardown_ai_panel(workspace, window, cx, move |workspace, cx| {
+                agent_ui::AgentPanel::load(workspace, prompt_builder, cx)
+            })
+            .detach_and_log_err(cx);
         })
         .detach();
 
@@ -763,6 +773,31 @@ async fn initialize_agent_panel(
     anyhow::Ok(())
 }
 
+async fn initialize_agents_panel(
+    workspace_handle: WeakEntity<Workspace>,
+    mut cx: AsyncWindowContext,
+) -> anyhow::Result<()> {
+    workspace_handle
+        .update_in(&mut cx, |workspace, window, cx| {
+            setup_or_teardown_ai_panel(workspace, window, cx, |workspace, cx| {
+                AgentsPanel::load(workspace, cx)
+            })
+        })?
+        .await?;
+
+    workspace_handle.update_in(&mut cx, |_workspace, window, cx| {
+        cx.observe_global_in::<SettingsStore>(window, move |workspace, window, cx| {
+            setup_or_teardown_ai_panel(workspace, window, cx, |workspace, cx| {
+                AgentsPanel::load(workspace, cx)
+            })
+            .detach_and_log_err(cx);
+        })
+        .detach();
+    })?;
+
+    anyhow::Ok(())
+}
+
 fn register_actions(
     app_state: Arc<AppState>,
     workspace: &mut Workspace,
@@ -1052,6 +1087,18 @@ fn register_actions(
                 workspace.toggle_panel_focus::<TerminalPanel>(window, cx);
             },
         )
+        .register_action(
+            |workspace: &mut Workspace,
+             _: &zed_actions::agent::ToggleAgentPane,
+             window: &mut Window,
+             cx: &mut Context<Workspace>| {
+                if let Some(panel) = workspace.panel::<AgentsPanel>(cx) {
+                    let position = panel.read(cx).position(window, cx);
+                    let slot = utility_slot_for_dock_position(position);
+                    workspace.toggle_utility_pane(slot, window, cx);
+                }
+            },
+        )
         .register_action({
             let app_state = Arc::downgrade(&app_state);
             move |_, _: &NewWindow, _, cx| {
@@ -1062,7 +1109,21 @@ fn register_actions(
                         cx,
                         |workspace, window, cx| {
                             cx.activate(true);
-                            Editor::new_file(workspace, &Default::default(), window, cx)
+                            // Create buffer synchronously to avoid flicker
+                            let project = workspace.project().clone();
+                            let buffer = project.update(cx, |project, cx| {
+                                project.create_local_buffer("", None, true, cx)
+                            });
+                            let editor = cx.new(|cx| {
+                                Editor::for_buffer(buffer, Some(project), window, cx)
+                            });
+                            workspace.add_item_to_active_pane(
+                                Box::new(editor),
+                                None,
+                                true,
+                                window,
+                                cx,
+                            );
                         },
                     )
                     .detach();
@@ -1643,6 +1704,7 @@ fn show_keymap_file_json_error(
         cx.new(|cx| {
             MessageNotification::new(message.clone(), cx)
                 .primary_message("Open Keymap File")
+                .primary_icon(IconName::Settings)
                 .primary_on_click(|window, cx| {
                     window.dispatch_action(zed_actions::OpenKeymapFile.boxed_clone(), cx);
                     cx.emit(DismissEvent);
@@ -1701,16 +1763,18 @@ fn show_markdown_app_notification<F>(
                 cx.new(move |cx| {
                     MessageNotification::new_from_builder(cx, move |window, cx| {
                         image_cache(retain_all("notification-cache"))
-                            .text_xs()
-                            .child(markdown_preview::markdown_renderer::render_parsed_markdown(
-                                &parsed_markdown.clone(),
-                                Some(workspace_handle.clone()),
-                                window,
-                                cx,
+                            .child(div().text_ui(cx).child(
+                                markdown_preview::markdown_renderer::render_parsed_markdown(
+                                    &parsed_markdown.clone(),
+                                    Some(workspace_handle.clone()),
+                                    window,
+                                    cx,
+                                ),
                             ))
                             .into_any()
                     })
                     .primary_message(primary_button_message)
+                    .primary_icon(IconName::Settings)
                     .primary_on_click_arc(primary_button_on_click)
                 })
             })
@@ -2255,12 +2319,13 @@ mod tests {
         Action, AnyWindowHandle, App, AssetSource, BorrowAppContext, TestAppContext, UpdateGlobal,
         VisualTestContext, WindowHandle, actions,
     };
-    use language::{LanguageMatcher, LanguageRegistry};
+    use language::LanguageRegistry;
+    use languages::{markdown_lang, rust_lang};
     use pretty_assertions::{assert_eq, assert_ne};
     use project::{Project, ProjectPath};
     use semver::Version;
     use serde_json::json;
-    use settings::{SettingsStore, watch_config_file};
+    use settings::{SaturatingBool, SettingsStore, watch_config_file};
     use std::{
         path::{Path, PathBuf},
         time::Duration,
@@ -2895,9 +2960,7 @@ mod tests {
             .await;
 
         let project = Project::test(app_state.fs.clone(), [path!("/root").as_ref()], cx).await;
-        project.update(cx, |project, _cx| {
-            project.languages().add(markdown_language())
-        });
+        project.update(cx, |project, _cx| project.languages().add(markdown_lang()));
         let window = cx.add_window(|window, cx| Workspace::test_new(project, window, cx));
         let workspace = window.root(cx).unwrap();
 
@@ -3327,9 +3390,7 @@ mod tests {
             .await;
 
         let project = Project::test(app_state.fs.clone(), [path!("/root").as_ref()], cx).await;
-        project.update(cx, |project, _cx| {
-            project.languages().add(markdown_language())
-        });
+        project.update(cx, |project, _cx| project.languages().add(markdown_lang()));
         let window = cx.add_window(|window, cx| Workspace::test_new(project, window, cx));
         let workspace = window.root(cx).unwrap();
 
@@ -3421,9 +3482,7 @@ mod tests {
             .await;
 
         let project = Project::test(app_state.fs.clone(), [path!("/root").as_ref()], cx).await;
-        project.update(cx, |project, _cx| {
-            project.languages().add(markdown_language())
-        });
+        project.update(cx, |project, _cx| project.languages().add(markdown_lang()));
         let window = cx.add_window(|window, cx| Workspace::test_new(project, window, cx));
         let workspace = window.root(cx).unwrap();
 
@@ -3494,7 +3553,7 @@ mod tests {
 
         let project = Project::test(app_state.fs.clone(), [path!("/root").as_ref()], cx).await;
         project.update(cx, |project, _| {
-            project.languages().add(markdown_language());
+            project.languages().add(markdown_lang());
             project.languages().add(rust_lang());
         });
         let window = cx.add_window(|window, cx| Workspace::test_new(project, window, cx));
@@ -3647,8 +3706,8 @@ mod tests {
 
         let project = Project::test(app_state.fs.clone(), [], cx).await;
         project.update(cx, |project, _| {
-            project.languages().add(rust_lang());
-            project.languages().add(markdown_language());
+            project.languages().add(language::rust_lang());
+            project.languages().add(language::markdown_lang());
         });
         let window = cx.add_window(|window, cx| Workspace::test_new(project, window, cx));
 
@@ -3727,9 +3786,7 @@ mod tests {
             .await;
 
         let project = Project::test(app_state.fs.clone(), [path!("/root").as_ref()], cx).await;
-        project.update(cx, |project, _cx| {
-            project.languages().add(markdown_language())
-        });
+        project.update(cx, |project, _cx| project.languages().add(markdown_lang()));
         let window = cx.add_window(|window, cx| Workspace::test_new(project, window, cx));
         let workspace = window.root(cx).unwrap();
 
@@ -3760,7 +3817,7 @@ mod tests {
             })
             .unwrap();
 
-        cx.dispatch_action(window.into(), pane::SplitRight);
+        cx.dispatch_action(window.into(), pane::SplitRight::default());
         let editor_2 = cx.update(|cx| {
             let pane_2 = workspace.read(cx).active_pane().clone();
             assert_ne!(pane_1, pane_2);
@@ -3831,9 +3888,7 @@ mod tests {
             .await;
 
         let project = Project::test(app_state.fs.clone(), [path!("/root").as_ref()], cx).await;
-        project.update(cx, |project, _cx| {
-            project.languages().add(markdown_language())
-        });
+        project.update(cx, |project, _cx| project.languages().add(markdown_lang()));
         let workspace =
             cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
         let pane = workspace
@@ -4225,9 +4280,7 @@ mod tests {
             .await;
 
         let project = Project::test(app_state.fs.clone(), [path!("/root").as_ref()], cx).await;
-        project.update(cx, |project, _cx| {
-            project.languages().add(markdown_language())
-        });
+        project.update(cx, |project, _cx| project.languages().add(markdown_lang()));
         let workspace = cx.add_window(|window, cx| Workspace::test_new(project, window, cx));
         let pane = workspace
             .read_with(cx, |workspace, _| workspace.active_pane().clone())
@@ -4725,7 +4778,7 @@ mod tests {
                 "action",
                 "activity_indicator",
                 "agent",
-                #[cfg(not(target_os = "macos"))]
+                "agents",
                 "app_menu",
                 "assistant",
                 "assistant2",
@@ -4756,10 +4809,12 @@ mod tests {
                 "git_panel",
                 "go_to_line",
                 "icon_theme_selector",
+                "inline_assistant",
                 "journal",
                 "keymap_editor",
                 "keystroke_input",
                 "language_selector",
+                "welcome",
                 "line_ending_selector",
                 "lsp_tool",
                 "markdown",
@@ -4914,7 +4969,7 @@ mod tests {
 
             let state = Arc::get_mut(&mut app_state).unwrap();
             state.build_window_options = build_window_options;
-            app_state.languages.add(markdown_language());
+            app_state.languages.add(markdown_lang());
 
             gpui_tokio::init(cx);
             theme::init(theme::LoadThemes::JustBase, cx);
@@ -4951,6 +5006,7 @@ mod tests {
                 false,
                 cx,
             );
+            agent_ui_v2::agents_panel::init(cx);
             repl::init(app_state.fs.clone(), cx);
             repl::notebook::init(cx);
             tasks_ui::init(cx);
@@ -4965,34 +5021,6 @@ mod tests {
         })
     }
 
-    fn rust_lang() -> Arc<language::Language> {
-        Arc::new(language::Language::new(
-            language::LanguageConfig {
-                name: "Rust".into(),
-                matcher: LanguageMatcher {
-                    path_suffixes: vec!["rs".to_string()],
-                    ..Default::default()
-                },
-                ..Default::default()
-            },
-            Some(tree_sitter_rust::LANGUAGE.into()),
-        ))
-    }
-
-    fn markdown_language() -> Arc<language::Language> {
-        Arc::new(language::Language::new(
-            language::LanguageConfig {
-                name: "Markdown".into(),
-                matcher: LanguageMatcher {
-                    path_suffixes: vec!["md".to_string()],
-                    ..Default::default()
-                },
-                ..Default::default()
-            },
-            Some(tree_sitter_md::LANGUAGE.into()),
-        ))
-    }
-
     #[track_caller]
     fn assert_key_bindings_for(
         window: AnyWindowHandle,
@@ -5140,6 +5168,28 @@ mod tests {
         );
     }
 
+    #[gpui::test]
+    async fn test_disable_ai_crash(cx: &mut gpui::TestAppContext) {
+        let app_state = init_test(cx);
+        cx.update(init);
+        let project = Project::test(app_state.fs.clone(), [], cx).await;
+        let _window = cx.add_window(|window, cx| Workspace::test_new(project, window, cx));
+
+        cx.run_until_parked();
+
+        cx.update(|cx| {
+            SettingsStore::update_global(cx, |settings_store, cx| {
+                settings_store.update_user_settings(cx, |settings| {
+                    settings.disable_ai = Some(SaturatingBool(true));
+                });
+            });
+        });
+
+        cx.run_until_parked();
+
+        // If this panics, the test has failed
+    }
+
     #[gpui::test]
     async fn test_prefer_focused_window(cx: &mut gpui::TestAppContext) {
         let app_state = init_test(cx);

crates/zed/src/zed/app_menus.rs 🔗

@@ -32,10 +32,10 @@ pub fn app_menus(cx: &mut App) -> Vec<Menu> {
         MenuItem::submenu(Menu {
             name: "Editor Layout".into(),
             items: vec![
-                MenuItem::action("Split Up", workspace::SplitUp),
-                MenuItem::action("Split Down", workspace::SplitDown),
-                MenuItem::action("Split Left", workspace::SplitLeft),
-                MenuItem::action("Split Right", workspace::SplitRight),
+                MenuItem::action("Split Up", workspace::SplitUp::default()),
+                MenuItem::action("Split Down", workspace::SplitDown::default()),
+                MenuItem::action("Split Left", workspace::SplitLeft::default()),
+                MenuItem::action("Split Right", workspace::SplitRight::default()),
             ],
         }),
         MenuItem::separator(),
@@ -169,7 +169,7 @@ pub fn app_menus(cx: &mut App) -> Vec<Menu> {
                 MenuItem::os_action("Paste", editor::actions::Paste, OsAction::Paste),
                 MenuItem::separator(),
                 MenuItem::action("Find", search::buffer_search::Deploy::find()),
-                MenuItem::action("Find In Project", workspace::DeploySearch::find()),
+                MenuItem::action("Find in Project", workspace::DeploySearch::find()),
                 MenuItem::separator(),
                 MenuItem::action(
                     "Toggle Line Comment",
@@ -247,7 +247,10 @@ pub fn app_menus(cx: &mut App) -> Vec<Menu> {
                 MenuItem::action("Go to Definition", editor::actions::GoToDefinition),
                 MenuItem::action("Go to Declaration", editor::actions::GoToDeclaration),
                 MenuItem::action("Go to Type Definition", editor::actions::GoToTypeDefinition),
-                MenuItem::action("Find All References", editor::actions::FindAllReferences),
+                MenuItem::action(
+                    "Find All References",
+                    editor::actions::FindAllReferences::default(),
+                ),
                 MenuItem::separator(),
                 MenuItem::action("Next Problem", editor::actions::GoToDiagnostic::default()),
                 MenuItem::action(
@@ -277,7 +280,7 @@ pub fn app_menus(cx: &mut App) -> Vec<Menu> {
                 MenuItem::separator(),
                 MenuItem::action("Toggle Breakpoint", editor::actions::ToggleBreakpoint),
                 MenuItem::action("Edit Breakpoint", editor::actions::EditLogBreakpoint),
-                MenuItem::action("Clear all Breakpoints", debugger_ui::ClearAllBreakpoints),
+                MenuItem::action("Clear All Breakpoints", debugger_ui::ClearAllBreakpoints),
             ],
         },
         Menu {

crates/zed/src/zed/edit_prediction_registry.rs 🔗

@@ -1,20 +1,21 @@
 use client::{Client, UserStore};
-use codestral::CodestralCompletionProvider;
+use codestral::CodestralEditPredictionDelegate;
 use collections::HashMap;
-use copilot::{Copilot, CopilotCompletionProvider};
+use copilot::{Copilot, CopilotEditPredictionDelegate};
+use edit_prediction::{SweepFeatureFlag, ZedEditPredictionDelegate, Zeta2FeatureFlag};
 use editor::Editor;
 use feature_flags::FeatureFlagAppExt;
 use gpui::{AnyWindowHandle, App, AppContext as _, Context, Entity, WeakEntity};
 use language::language_settings::{EditPredictionProvider, all_language_settings};
 use language_models::MistralLanguageModelProvider;
 use settings::{
+    EXPERIMENTAL_MERCURY_EDIT_PREDICTION_PROVIDER_NAME,
     EXPERIMENTAL_SWEEP_EDIT_PREDICTION_PROVIDER_NAME,
     EXPERIMENTAL_ZETA2_EDIT_PREDICTION_PROVIDER_NAME, SettingsStore,
 };
 use std::{cell::RefCell, rc::Rc, sync::Arc};
-use supermaven::{Supermaven, SupermavenCompletionProvider};
+use supermaven::{Supermaven, SupermavenEditPredictionDelegate};
 use ui::Window;
-use zeta::{SweepFeatureFlag, Zeta2FeatureFlag, ZetaEditPredictionProvider};
 
 pub fn init(client: Arc<Client>, user_store: Entity<UserStore>, cx: &mut App) {
     let editors: Rc<RefCell<HashMap<WeakEntity<Editor>, AnyWindowHandle>>> = Rc::default();
@@ -59,7 +60,7 @@ pub fn init(client: Arc<Client>, user_store: Entity<UserStore>, cx: &mut App) {
     })
     .detach();
 
-    cx.on_action(clear_zeta_edit_history);
+    cx.on_action(clear_edit_prediction_store_edit_history);
 
     let mut provider = all_language_settings(None, cx).edit_predictions.provider;
     cx.subscribe(&user_store, {
@@ -100,9 +101,9 @@ pub fn init(client: Arc<Client>, user_store: Entity<UserStore>, cx: &mut App) {
     .detach();
 }
 
-fn clear_zeta_edit_history(_: &zeta::ClearHistory, cx: &mut App) {
-    if let Some(zeta) = zeta::Zeta::try_global(cx) {
-        zeta.update(cx, |zeta, _| zeta.clear_history());
+fn clear_edit_prediction_store_edit_history(_: &edit_prediction::ClearHistory, cx: &mut App) {
+    if let Some(ep_store) = edit_prediction::EditPredictionStore::try_global(cx) {
+        ep_store.update(cx, |ep_store, _| ep_store.clear_history());
     }
 }
 
@@ -144,23 +145,6 @@ fn register_backward_compatible_actions(editor: &mut Editor, cx: &mut Context<Ed
             },
         ))
         .detach();
-    editor
-        .register_action(cx.listener(
-            |editor, _: &copilot::NextSuggestion, window: &mut Window, cx: &mut Context<Editor>| {
-                editor.next_edit_prediction(&Default::default(), window, cx);
-            },
-        ))
-        .detach();
-    editor
-        .register_action(cx.listener(
-            |editor,
-             _: &copilot::PreviousSuggestion,
-             window: &mut Window,
-             cx: &mut Context<Editor>| {
-                editor.previous_edit_prediction(&Default::default(), window, cx);
-            },
-        ))
-        .detach();
 }
 
 fn assign_edit_prediction_provider(
@@ -176,7 +160,7 @@ fn assign_edit_prediction_provider(
 
     match provider {
         EditPredictionProvider::None => {
-            editor.set_edit_prediction_provider::<ZetaEditPredictionProvider>(None, window, cx);
+            editor.set_edit_prediction_provider::<ZedEditPredictionDelegate>(None, window, cx);
         }
         EditPredictionProvider::Copilot => {
             if let Some(copilot) = Copilot::global(cx) {
@@ -187,55 +171,65 @@ fn assign_edit_prediction_provider(
                         copilot.register_buffer(&buffer, cx);
                     });
                 }
-                let provider = cx.new(|_| CopilotCompletionProvider::new(copilot));
+                let provider = cx.new(|_| CopilotEditPredictionDelegate::new(copilot));
                 editor.set_edit_prediction_provider(Some(provider), window, cx);
             }
         }
         EditPredictionProvider::Supermaven => {
             if let Some(supermaven) = Supermaven::global(cx) {
-                let provider = cx.new(|_| SupermavenCompletionProvider::new(supermaven));
+                let provider = cx.new(|_| SupermavenEditPredictionDelegate::new(supermaven));
                 editor.set_edit_prediction_provider(Some(provider), window, cx);
             }
         }
         EditPredictionProvider::Codestral => {
             let http_client = client.http_client();
-            let provider = cx.new(|_| CodestralCompletionProvider::new(http_client));
+            let provider = cx.new(|_| CodestralEditPredictionDelegate::new(http_client));
             editor.set_edit_prediction_provider(Some(provider), window, cx);
         }
         value @ (EditPredictionProvider::Experimental(_) | EditPredictionProvider::Zed) => {
-            let zeta = zeta::Zeta::global(client, &user_store, cx);
+            let ep_store = edit_prediction::EditPredictionStore::global(client, &user_store, cx);
 
             if let Some(project) = editor.project()
                 && let Some(buffer) = &singleton_buffer
                 && buffer.read(cx).file().is_some()
             {
-                let has_model = zeta.update(cx, |zeta, cx| {
+                let has_model = ep_store.update(cx, |ep_store, cx| {
                     let model = if let EditPredictionProvider::Experimental(name) = value {
                         if name == EXPERIMENTAL_SWEEP_EDIT_PREDICTION_PROVIDER_NAME
                             && cx.has_flag::<SweepFeatureFlag>()
                         {
-                            zeta::ZetaEditPredictionModel::Sweep
+                            edit_prediction::EditPredictionModel::Sweep
                         } else if name == EXPERIMENTAL_ZETA2_EDIT_PREDICTION_PROVIDER_NAME
                             && cx.has_flag::<Zeta2FeatureFlag>()
                         {
-                            zeta::ZetaEditPredictionModel::Zeta2
+                            edit_prediction::EditPredictionModel::Zeta2
+                        } else if name == EXPERIMENTAL_MERCURY_EDIT_PREDICTION_PROVIDER_NAME
+                            && cx.has_flag::<Zeta2FeatureFlag>()
+                        {
+                            edit_prediction::EditPredictionModel::Mercury
                         } else {
                             return false;
                         }
                     } else if user_store.read(cx).current_user().is_some() {
-                        zeta::ZetaEditPredictionModel::Zeta1
+                        edit_prediction::EditPredictionModel::Zeta1
                     } else {
                         return false;
                     };
 
-                    zeta.set_edit_prediction_model(model);
-                    zeta.register_buffer(buffer, project, cx);
+                    ep_store.set_edit_prediction_model(model);
+                    ep_store.register_buffer(buffer, project, cx);
                     true
                 });
 
                 if has_model {
                     let provider = cx.new(|cx| {
-                        ZetaEditPredictionProvider::new(project.clone(), &client, &user_store, cx)
+                        ZedEditPredictionDelegate::new(
+                            project.clone(),
+                            singleton_buffer,
+                            &client,
+                            &user_store,
+                            cx,
+                        )
                     });
                     editor.set_edit_prediction_provider(Some(provider), window, cx);
                 }

crates/zed/src/zed/open_listener.rs 🔗

@@ -3,13 +3,14 @@ use crate::restorable_workspace_locations;
 use anyhow::{Context as _, Result, anyhow};
 use cli::{CliRequest, CliResponse, ipc::IpcSender};
 use cli::{IpcHandshake, ipc};
-use client::parse_zed_link;
+use client::{ZedLink, parse_zed_link};
 use collections::HashMap;
 use db::kvp::KEY_VALUE_STORE;
 use editor::Editor;
 use fs::Fs;
 use futures::channel::mpsc::{UnboundedReceiver, UnboundedSender};
 use futures::channel::{mpsc, oneshot};
+use futures::future;
 use futures::future::join_all;
 use futures::{FutureExt, SinkExt, StreamExt};
 use git_ui::file_diff_view::FileDiffView;
@@ -24,6 +25,7 @@ use std::path::{Path, PathBuf};
 use std::sync::Arc;
 use std::thread;
 use std::time::Duration;
+use ui::SharedString;
 use util::ResultExt;
 use util::paths::PathWithPosition;
 use workspace::PathList;
@@ -54,9 +56,15 @@ pub enum OpenRequestKind {
         schema_path: String,
     },
     Setting {
-        // None just opens settings without navigating to a specific path
+        /// `None` opens settings without navigating to a specific path.
         setting_path: Option<String>,
     },
+    GitClone {
+        repo_url: SharedString,
+    },
+    GitCommit {
+        sha: String,
+    },
 }
 
 impl OpenRequest {
@@ -109,10 +117,24 @@ impl OpenRequest {
                 this.kind = Some(OpenRequestKind::Setting {
                     setting_path: Some(setting_path.to_string()),
                 });
+            } else if let Some(clone_path) = url.strip_prefix("zed://git/clone") {
+                this.parse_git_clone_url(clone_path)?
+            } else if let Some(commit_path) = url.strip_prefix("zed://git/commit/") {
+                this.parse_git_commit_url(commit_path)?
             } else if url.starts_with("ssh://") {
                 this.parse_ssh_file_path(&url, cx)?
-            } else if let Some(request_path) = parse_zed_link(&url, cx) {
-                this.parse_request_path(request_path).log_err();
+            } else if let Some(zed_link) = parse_zed_link(&url, cx) {
+                match zed_link {
+                    ZedLink::Channel { channel_id } => {
+                        this.join_channel = Some(channel_id);
+                    }
+                    ZedLink::ChannelNotes {
+                        channel_id,
+                        heading,
+                    } => {
+                        this.open_channel_notes.push((channel_id, heading));
+                    }
+                }
             } else {
                 log::error!("unhandled url: {}", url);
             }
@@ -127,6 +149,48 @@ impl OpenRequest {
         }
     }
 
+    fn parse_git_clone_url(&mut self, clone_path: &str) -> Result<()> {
+        // Format: /?repo=<url> or ?repo=<url>
+        let clone_path = clone_path.strip_prefix('/').unwrap_or(clone_path);
+
+        let query = clone_path
+            .strip_prefix('?')
+            .context("invalid git clone url: missing query string")?;
+
+        let repo_url = url::form_urlencoded::parse(query.as_bytes())
+            .find_map(|(key, value)| (key == "repo").then_some(value))
+            .filter(|s| !s.is_empty())
+            .context("invalid git clone url: missing repo query parameter")?
+            .to_string()
+            .into();
+
+        self.kind = Some(OpenRequestKind::GitClone { repo_url });
+
+        Ok(())
+    }
+
+    fn parse_git_commit_url(&mut self, commit_path: &str) -> Result<()> {
+        // Format: <sha>?repo=<path>
+        let (sha, query) = commit_path
+            .split_once('?')
+            .context("invalid git commit url: missing query string")?;
+        anyhow::ensure!(!sha.is_empty(), "invalid git commit url: missing sha");
+
+        let repo = url::form_urlencoded::parse(query.as_bytes())
+            .find_map(|(key, value)| (key == "repo").then_some(value))
+            .filter(|s| !s.is_empty())
+            .context("invalid git commit url: missing repo query parameter")?
+            .to_string();
+
+        self.open_paths.push(repo);
+
+        self.kind = Some(OpenRequestKind::GitCommit {
+            sha: sha.to_string(),
+        });
+
+        Ok(())
+    }
+
     fn parse_ssh_file_path(&mut self, file: &str, cx: &App) -> Result<()> {
         let url = url::Url::parse(file)?;
         let host = url
@@ -156,31 +220,6 @@ impl OpenRequest {
         self.parse_file_path(url.path());
         Ok(())
     }
-
-    fn parse_request_path(&mut self, request_path: &str) -> Result<()> {
-        let mut parts = request_path.split('/');
-        if parts.next() == Some("channel")
-            && let Some(slug) = parts.next()
-            && let Some(id_str) = slug.split('-').next_back()
-            && let Ok(channel_id) = id_str.parse::<u64>()
-        {
-            let Some(next) = parts.next() else {
-                self.join_channel = Some(channel_id);
-                return Ok(());
-            };
-
-            if let Some(heading) = next.strip_prefix("notes#") {
-                self.open_channel_notes
-                    .push((channel_id, Some(heading.to_string())));
-                return Ok(());
-            }
-            if next == "notes" {
-                self.open_channel_notes.push((channel_id, None));
-                return Ok(());
-            }
-        }
-        anyhow::bail!("invalid zed url: {request_path}")
-    }
 }
 
 #[derive(Clone)]
@@ -514,33 +553,27 @@ async fn open_local_workspace(
     app_state: &Arc<AppState>,
     cx: &mut AsyncApp,
 ) -> bool {
-    let mut errored = false;
-
     let paths_with_position =
         derive_paths_with_position(app_state.fs.as_ref(), workspace_paths).await;
 
-    // Handle reuse flag by finding existing window to replace
-    let replace_window = if reuse {
-        cx.update(|cx| workspace::local_workspace_windows(cx).into_iter().next())
-            .ok()
-            .flatten()
-    } else {
-        None
-    };
-
-    // For reuse, force new workspace creation but with replace_window set
-    let effective_open_new_workspace = if reuse {
-        Some(true)
+    // If reuse flag is passed, open a new workspace in an existing window.
+    let (open_new_workspace, replace_window) = if reuse {
+        (
+            Some(true),
+            cx.update(|cx| workspace::local_workspace_windows(cx).into_iter().next())
+                .ok()
+                .flatten(),
+        )
     } else {
-        open_new_workspace
+        (open_new_workspace, None)
     };
 
-    match open_paths_with_positions(
+    let (workspace, items) = match open_paths_with_positions(
         &paths_with_position,
         &diff_paths,
         app_state.clone(),
         workspace::OpenOptions {
-            open_new_workspace: effective_open_new_workspace,
+            open_new_workspace,
             replace_window,
             prefer_focused_window: wait,
             env: env.cloned(),
@@ -550,80 +583,95 @@ async fn open_local_workspace(
     )
     .await
     {
-        Ok((workspace, items)) => {
-            let mut item_release_futures = Vec::new();
+        Ok(result) => result,
+        Err(error) => {
+            responses
+                .send(CliResponse::Stderr {
+                    message: format!("error opening {paths_with_position:?}: {error}"),
+                })
+                .log_err();
+            return true;
+        }
+    };
 
-            for item in items {
-                match item {
-                    Some(Ok(item)) => {
-                        cx.update(|cx| {
-                            let released = oneshot::channel();
-                            item.on_release(
-                                cx,
-                                Box::new(move |_| {
-                                    let _ = released.0.send(());
-                                }),
-                            )
-                            .detach();
-                            item_release_futures.push(released.1);
-                        })
-                        .log_err();
-                    }
-                    Some(Err(err)) => {
-                        responses
-                            .send(CliResponse::Stderr {
-                                message: err.to_string(),
-                            })
-                            .log_err();
-                        errored = true;
-                    }
-                    None => {}
-                }
+    let mut errored = false;
+    let mut item_release_futures = Vec::new();
+    let mut subscriptions = Vec::new();
+
+    // If --wait flag is used with no paths, or a directory, then wait until
+    // the entire workspace is closed.
+    if wait {
+        let mut wait_for_window_close = paths_with_position.is_empty() && diff_paths.is_empty();
+        for path_with_position in &paths_with_position {
+            if app_state.fs.is_dir(&path_with_position.path).await {
+                wait_for_window_close = true;
+                break;
             }
+        }
+
+        if wait_for_window_close {
+            let (release_tx, release_rx) = oneshot::channel();
+            item_release_futures.push(release_rx);
+            subscriptions.push(workspace.update(cx, |_, _, cx| {
+                cx.on_release(move |_, _| {
+                    let _ = release_tx.send(());
+                })
+            }));
+        }
+    }
 
-            if wait {
-                let background = cx.background_executor().clone();
-                let wait = async move {
-                    if paths_with_position.is_empty() && diff_paths.is_empty() {
-                        let (done_tx, done_rx) = oneshot::channel();
-                        let _subscription = workspace.update(cx, |_, _, cx| {
-                            cx.on_release(move |_, _| {
-                                let _ = done_tx.send(());
-                            })
-                        });
-                        let _ = done_rx.await;
-                    } else {
-                        let _ = futures::future::try_join_all(item_release_futures).await;
-                    };
+    for item in items {
+        match item {
+            Some(Ok(item)) => {
+                if wait {
+                    let (release_tx, release_rx) = oneshot::channel();
+                    item_release_futures.push(release_rx);
+                    subscriptions.push(cx.update(|cx| {
+                        item.on_release(
+                            cx,
+                            Box::new(move |_| {
+                                release_tx.send(()).ok();
+                            }),
+                        )
+                    }));
                 }
-                .fuse();
-
-                futures::pin_mut!(wait);
-
-                loop {
-                    // Repeatedly check if CLI is still open to avoid wasting resources
-                    // waiting for files or workspaces to close.
-                    let mut timer = background.timer(Duration::from_secs(1)).fuse();
-                    futures::select_biased! {
-                        _ = wait => break,
-                        _ = timer => {
-                            if responses.send(CliResponse::Ping).is_err() {
-                                break;
-                            }
-                        }
+            }
+            Some(Err(err)) => {
+                responses
+                    .send(CliResponse::Stderr {
+                        message: err.to_string(),
+                    })
+                    .log_err();
+                errored = true;
+            }
+            None => {}
+        }
+    }
+
+    if wait {
+        let wait = async move {
+            let _subscriptions = subscriptions;
+            let _ = future::try_join_all(item_release_futures).await;
+        }
+        .fuse();
+        futures::pin_mut!(wait);
+
+        let background = cx.background_executor().clone();
+        loop {
+            // Repeatedly check if CLI is still open to avoid wasting resources
+            // waiting for files or workspaces to close.
+            let mut timer = background.timer(Duration::from_secs(1)).fuse();
+            futures::select_biased! {
+                _ = wait => break,
+                _ = timer => {
+                    if responses.send(CliResponse::Ping).is_err() {
+                        break;
                     }
                 }
             }
         }
-        Err(error) => {
-            errored = true;
-            responses
-                .send(CliResponse::Stderr {
-                    message: format!("error opening {paths_with_position:?}: {error}"),
-                })
-                .log_err();
-        }
     }
+
     errored
 }
 
@@ -653,12 +701,13 @@ mod tests {
         ipc::{self},
     };
     use editor::Editor;
-    use gpui::TestAppContext;
+    use futures::poll;
+    use gpui::{AppContext as _, TestAppContext};
     use language::LineEnding;
     use remote::SshConnectionOptions;
     use rope::Rope;
     use serde_json::json;
-    use std::sync::Arc;
+    use std::{sync::Arc, task::Poll};
     use util::path;
     use workspace::{AppState, Workspace};
 
@@ -686,11 +735,92 @@ mod tests {
                 port_forwards: None,
                 nickname: None,
                 upload_binary_over_ssh: false,
+                connection_timeout: None,
             })
         );
         assert_eq!(request.open_paths, vec!["/"]);
     }
 
+    #[gpui::test]
+    fn test_parse_git_commit_url(cx: &mut TestAppContext) {
+        let _app_state = init_test(cx);
+
+        // Test basic git commit URL
+        let request = cx.update(|cx| {
+            OpenRequest::parse(
+                RawOpenRequest {
+                    urls: vec!["zed://git/commit/abc123?repo=path/to/repo".into()],
+                    ..Default::default()
+                },
+                cx,
+            )
+            .unwrap()
+        });
+
+        match request.kind.unwrap() {
+            OpenRequestKind::GitCommit { sha } => {
+                assert_eq!(sha, "abc123");
+            }
+            _ => panic!("expected GitCommit variant"),
+        }
+        // Verify path was added to open_paths for workspace routing
+        assert_eq!(request.open_paths, vec!["path/to/repo"]);
+
+        // Test with URL encoded path
+        let request = cx.update(|cx| {
+            OpenRequest::parse(
+                RawOpenRequest {
+                    urls: vec!["zed://git/commit/def456?repo=path%20with%20spaces".into()],
+                    ..Default::default()
+                },
+                cx,
+            )
+            .unwrap()
+        });
+
+        match request.kind.unwrap() {
+            OpenRequestKind::GitCommit { sha } => {
+                assert_eq!(sha, "def456");
+            }
+            _ => panic!("expected GitCommit variant"),
+        }
+        assert_eq!(request.open_paths, vec!["path with spaces"]);
+
+        // Test with empty path
+        cx.update(|cx| {
+            assert!(
+                OpenRequest::parse(
+                    RawOpenRequest {
+                        urls: vec!["zed://git/commit/abc123?repo=".into()],
+                        ..Default::default()
+                    },
+                    cx,
+                )
+                .unwrap_err()
+                .to_string()
+                .contains("missing repo")
+            );
+        });
+
+        // Test error case: missing SHA
+        let result = cx.update(|cx| {
+            OpenRequest::parse(
+                RawOpenRequest {
+                    urls: vec!["zed://git/commit/abc123?foo=bar".into()],
+                    ..Default::default()
+                },
+                cx,
+            )
+        });
+        assert!(result.is_err());
+        assert!(
+            result
+                .unwrap_err()
+                .to_string()
+                .contains("missing repo query parameter")
+        );
+    }
+
     #[gpui::test]
     async fn test_open_workspace_with_directory(cx: &mut TestAppContext) {
         let app_state = init_test(cx);
@@ -753,6 +883,60 @@ mod tests {
             .unwrap();
     }
 
+    #[gpui::test]
+    async fn test_wait_with_directory_waits_for_window_close(cx: &mut TestAppContext) {
+        let app_state = init_test(cx);
+
+        app_state
+            .fs
+            .as_fake()
+            .insert_tree(
+                path!("/root"),
+                json!({
+                    "dir1": {
+                        "file1.txt": "content1",
+                    },
+                }),
+            )
+            .await;
+
+        let (response_tx, _) = ipc::channel::<CliResponse>().unwrap();
+        let workspace_paths = vec![path!("/root/dir1").to_owned()];
+
+        let (done_tx, mut done_rx) = futures::channel::oneshot::channel();
+        cx.spawn({
+            let app_state = app_state.clone();
+            move |mut cx| async move {
+                let errored = open_local_workspace(
+                    workspace_paths,
+                    vec![],
+                    None,
+                    false,
+                    true,
+                    &response_tx,
+                    None,
+                    &app_state,
+                    &mut cx,
+                )
+                .await;
+                let _ = done_tx.send(errored);
+            }
+        })
+        .detach();
+
+        cx.background_executor.run_until_parked();
+        assert_eq!(cx.windows().len(), 1);
+        assert!(matches!(poll!(&mut done_rx), Poll::Pending));
+
+        let window = cx.windows()[0];
+        cx.update_window(window, |_, window, _| window.remove_window())
+            .unwrap();
+        cx.background_executor.run_until_parked();
+
+        let errored = done_rx.await.unwrap();
+        assert!(!errored);
+    }
+
     #[gpui::test]
     async fn test_open_workspace_with_nonexistent_files(cx: &mut TestAppContext) {
         let app_state = init_test(cx);
@@ -929,4 +1113,80 @@ mod tests {
 
         assert!(!errored_reuse);
     }
+
+    #[gpui::test]
+    fn test_parse_git_clone_url(cx: &mut TestAppContext) {
+        let _app_state = init_test(cx);
+
+        let request = cx.update(|cx| {
+            OpenRequest::parse(
+                RawOpenRequest {
+                    urls: vec![
+                        "zed://git/clone/?repo=https://github.com/zed-industries/zed.git".into(),
+                    ],
+                    ..Default::default()
+                },
+                cx,
+            )
+            .unwrap()
+        });
+
+        match request.kind {
+            Some(OpenRequestKind::GitClone { repo_url }) => {
+                assert_eq!(repo_url, "https://github.com/zed-industries/zed.git");
+            }
+            _ => panic!("Expected GitClone kind"),
+        }
+    }
+
+    #[gpui::test]
+    fn test_parse_git_clone_url_without_slash(cx: &mut TestAppContext) {
+        let _app_state = init_test(cx);
+
+        let request = cx.update(|cx| {
+            OpenRequest::parse(
+                RawOpenRequest {
+                    urls: vec![
+                        "zed://git/clone?repo=https://github.com/zed-industries/zed.git".into(),
+                    ],
+                    ..Default::default()
+                },
+                cx,
+            )
+            .unwrap()
+        });
+
+        match request.kind {
+            Some(OpenRequestKind::GitClone { repo_url }) => {
+                assert_eq!(repo_url, "https://github.com/zed-industries/zed.git");
+            }
+            _ => panic!("Expected GitClone kind"),
+        }
+    }
+
+    #[gpui::test]
+    fn test_parse_git_clone_url_with_encoding(cx: &mut TestAppContext) {
+        let _app_state = init_test(cx);
+
+        let request = cx.update(|cx| {
+            OpenRequest::parse(
+                RawOpenRequest {
+                    urls: vec![
+                        "zed://git/clone/?repo=https%3A%2F%2Fgithub.com%2Fzed-industries%2Fzed.git"
+                            .into(),
+                    ],
+                    ..Default::default()
+                },
+                cx,
+            )
+            .unwrap()
+        });
+
+        match request.kind {
+            Some(OpenRequestKind::GitClone { repo_url }) => {
+                assert_eq!(repo_url, "https://github.com/zed-industries/zed.git");
+            }
+            _ => panic!("Expected GitClone kind"),
+        }
+    }
 }

crates/zed/src/zed/quick_action_bar.rs 🔗

@@ -174,17 +174,13 @@ impl Render for QuickActionBar {
                     .as_ref()
                     .is_some_and(|menu| matches!(menu.origin(), ContextMenuOrigin::QuickActionBar))
             };
-            let code_action_element = if is_deployed {
-                editor.update(cx, |editor, cx| {
-                    if let Some(style) = editor.style() {
-                        editor.render_context_menu(style, MAX_CODE_ACTION_MENU_LINES, window, cx)
-                    } else {
-                        None
-                    }
+            let code_action_element = is_deployed
+                .then(|| {
+                    editor.update(cx, |editor, cx| {
+                        editor.render_context_menu(MAX_CODE_ACTION_MENU_LINES, window, cx)
+                    })
                 })
-            } else {
-                None
-            };
+                .flatten();
             v_flex()
                 .child(
                     IconButton::new("toggle_code_actions_icon", IconName::BoltOutlined)

crates/zed_actions/src/lib.rs 🔗

@@ -70,6 +70,8 @@ actions!(
         OpenTelemetryLog,
         /// Opens the performance profiler.
         OpenPerformanceProfiler,
+        /// Opens the onboarding view.
+        OpenOnboarding,
     ]
 );
 
@@ -215,6 +217,10 @@ pub mod git {
             Switch,
             /// Selects a different repository.
             SelectRepo,
+            /// Filter remotes.
+            FilterRemotes,
+            /// Create a git remote.
+            CreateRemote,
             /// Opens the git branch selector.
             #[action(deprecated_aliases = ["branches::OpenRecent"])]
             Branch,
@@ -346,6 +352,10 @@ pub mod agent {
             AddSelectionToThread,
             /// Resets the agent panel zoom levels (agent UI and buffer font sizes).
             ResetAgentZoom,
+            /// Toggles the utility/agent pane open/closed state.
+            ToggleAgentPane,
+            /// Pastes clipboard content without any formatting.
+            PasteRaw,
         ]
     );
 }
@@ -424,6 +434,12 @@ pub struct OpenRemote {
     pub create_new_window: bool,
 }
 
+/// Opens the dev container connection modal.
+#[derive(PartialEq, Clone, Deserialize, Default, JsonSchema, Action)]
+#[action(namespace = projects)]
+#[serde(deny_unknown_fields)]
+pub struct OpenDevContainer;
+
 /// Where to spawn the task in the UI.
 #[derive(Default, Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
 #[serde(rename_all = "snake_case")]

crates/zed_env_vars/src/zed_env_vars.rs 🔗

@@ -5,6 +5,7 @@ use std::sync::LazyLock;
 /// When true, Zed will use in-memory databases instead of persistent storage.
 pub static ZED_STATELESS: LazyLock<bool> = bool_env_var!("ZED_STATELESS");
 
+#[derive(Clone)]
 pub struct EnvVar {
     pub name: SharedString,
     /// Value of the environment variable. Also `None` when set to an empty string.
@@ -30,7 +31,7 @@ impl EnvVar {
 #[macro_export]
 macro_rules! env_var {
     ($name:expr) => {
-        LazyLock::new(|| $crate::EnvVar::new(($name).into()))
+        ::std::sync::LazyLock::new(|| $crate::EnvVar::new(($name).into()))
     };
 }
 
@@ -39,6 +40,6 @@ macro_rules! env_var {
 #[macro_export]
 macro_rules! bool_env_var {
     ($name:expr) => {
-        LazyLock::new(|| $crate::EnvVar::new(($name).into()).value.is_some())
+        ::std::sync::LazyLock::new(|| $crate::EnvVar::new(($name).into()).value.is_some())
     };
 }

crates/zeta/Cargo.toml 🔗

@@ -1,84 +0,0 @@
-[package]
-name = "zeta"
-version = "0.1.0"
-edition.workspace = true
-publish.workspace = true
-license = "GPL-3.0-or-later"
-
-[lints]
-workspace = true
-
-[lib]
-path = "src/zeta.rs"
-
-[features]
-eval-support = []
-
-[dependencies]
-ai_onboarding.workspace = true
-anyhow.workspace = true
-arrayvec.workspace = true
-brotli.workspace = true
-buffer_diff.workspace = true
-client.workspace = true
-cloud_llm_client.workspace = true
-cloud_zeta2_prompt.workspace = true
-collections.workspace = true
-command_palette_hooks.workspace = true
-copilot.workspace = true
-credentials_provider.workspace = true
-db.workspace = true
-edit_prediction.workspace = true
-edit_prediction_context.workspace = true
-editor.workspace = true
-feature_flags.workspace = true
-fs.workspace = true
-futures.workspace = true
-gpui.workspace = true
-indoc.workspace = true
-itertools.workspace = true
-language.workspace = true
-language_model.workspace = true
-log.workspace = true
-lsp.workspace = true
-markdown.workspace = true
-menu.workspace = true
-open_ai.workspace = true
-postage.workspace = true
-pretty_assertions.workspace = true
-project.workspace = true
-rand.workspace = true
-regex.workspace = true
-release_channel.workspace = true
-semver.workspace = true
-serde.workspace = true
-serde_json.workspace = true
-settings.workspace = true
-smol.workspace = true
-strsim.workspace = true
-strum.workspace = true
-telemetry.workspace = true
-telemetry_events.workspace = true
-theme.workspace = true
-thiserror.workspace = true
-ui.workspace = true
-util.workspace = true
-uuid.workspace = true
-workspace.workspace = true
-worktree.workspace = true
-zed_actions.workspace = true
-
-[dev-dependencies]
-clock = { workspace = true, features = ["test-support"] }
-cloud_api_types.workspace = true
-cloud_llm_client = { workspace = true, features = ["test-support"] }
-ctor.workspace = true
-gpui = { workspace = true, features = ["test-support"] }
-indoc.workspace = true
-language = { workspace = true, features = ["test-support"] }
-language_model = { workspace = true, features = ["test-support"] }
-lsp.workspace = true
-parking_lot.workspace = true
-project = { workspace = true, features = ["test-support"] }
-settings = { workspace = true, features = ["test-support"] }
-zlog.workspace = true

crates/zeta/src/assemble_excerpts.rs 🔗

@@ -1,173 +0,0 @@
-use cloud_llm_client::predict_edits_v3::Excerpt;
-use edit_prediction_context::Line;
-use language::{BufferSnapshot, Point};
-use std::ops::Range;
-
-pub fn assemble_excerpts(
-    buffer: &BufferSnapshot,
-    merged_line_ranges: impl IntoIterator<Item = Range<Line>>,
-) -> Vec<Excerpt> {
-    let mut output = Vec::new();
-
-    let outline_items = buffer.outline_items_as_points_containing(0..buffer.len(), false, None);
-    let mut outline_items = outline_items.into_iter().peekable();
-
-    for range in merged_line_ranges {
-        let point_range = Point::new(range.start.0, 0)..Point::new(range.end.0, 0);
-
-        while let Some(outline_item) = outline_items.peek() {
-            if outline_item.range.start >= point_range.start {
-                break;
-            }
-            if outline_item.range.end > point_range.start {
-                let mut point_range = outline_item.source_range_for_text.clone();
-                point_range.start.column = 0;
-                point_range.end.column = buffer.line_len(point_range.end.row);
-
-                output.push(Excerpt {
-                    start_line: Line(point_range.start.row),
-                    text: buffer
-                        .text_for_range(point_range.clone())
-                        .collect::<String>()
-                        .into(),
-                })
-            }
-            outline_items.next();
-        }
-
-        output.push(Excerpt {
-            start_line: Line(point_range.start.row),
-            text: buffer
-                .text_for_range(point_range.clone())
-                .collect::<String>()
-                .into(),
-        })
-    }
-
-    output
-}
-
-#[cfg(test)]
-mod tests {
-    use std::sync::Arc;
-
-    use super::*;
-    use cloud_llm_client::predict_edits_v3;
-    use gpui::{TestAppContext, prelude::*};
-    use indoc::indoc;
-    use language::{Buffer, Language, LanguageConfig, LanguageMatcher, OffsetRangeExt};
-    use pretty_assertions::assert_eq;
-    use util::test::marked_text_ranges;
-
-    #[gpui::test]
-    fn test_rust(cx: &mut TestAppContext) {
-        let table = [
-            (
-                indoc! {r#"
-                    struct User {
-                        first_name: String,
-                    «    last_name: String,
-                        ageˇ: u32,
-                    »    email: String,
-                        create_at: Instant,
-                    }
-
-                    impl User {
-                        pub fn first_name(&self) -> String {
-                            self.first_name.clone()
-                        }
-
-                        pub fn full_name(&self) -> String {
-                    «        format!("{} {}", self.first_name, self.last_name)
-                    »    }
-                    }
-                "#},
-                indoc! {r#"
-                    1|struct User {
-                    …
-                    3|    last_name: String,
-                    4|    age<|cursor|>: u32,
-                    …
-                    9|impl User {
-                    …
-                    14|    pub fn full_name(&self) -> String {
-                    15|        format!("{} {}", self.first_name, self.last_name)
-                    …
-                "#},
-            ),
-            (
-                indoc! {r#"
-                    struct User {
-                        first_name: String,
-                    «    last_name: String,
-                        age: u32,
-                    }
-                    »"#
-                },
-                indoc! {r#"
-                    1|struct User {
-                    …
-                    3|    last_name: String,
-                    4|    age: u32,
-                    5|}
-                "#},
-            ),
-        ];
-
-        for (input, expected_output) in table {
-            let input_without_ranges = input.replace(['«', '»'], "");
-            let input_without_caret = input.replace('ˇ', "");
-            let cursor_offset = input_without_ranges.find('ˇ');
-            let (input, ranges) = marked_text_ranges(&input_without_caret, false);
-            let buffer =
-                cx.new(|cx| Buffer::local(input, cx).with_language(Arc::new(rust_lang()), cx));
-            buffer.read_with(cx, |buffer, _cx| {
-                let insertions = cursor_offset
-                    .map(|offset| {
-                        let point = buffer.offset_to_point(offset);
-                        vec![(
-                            predict_edits_v3::Point {
-                                line: Line(point.row),
-                                column: point.column,
-                            },
-                            "<|cursor|>",
-                        )]
-                    })
-                    .unwrap_or_default();
-                let ranges: Vec<Range<Line>> = ranges
-                    .into_iter()
-                    .map(|range| {
-                        let point_range = range.to_point(&buffer);
-                        Line(point_range.start.row)..Line(point_range.end.row)
-                    })
-                    .collect();
-
-                let mut output = String::new();
-                cloud_zeta2_prompt::write_excerpts(
-                    assemble_excerpts(&buffer.snapshot(), ranges).iter(),
-                    &insertions,
-                    Line(buffer.max_point().row),
-                    true,
-                    &mut output,
-                );
-                assert_eq!(output, expected_output);
-            });
-        }
-    }
-
-    fn rust_lang() -> Language {
-        Language::new(
-            LanguageConfig {
-                name: "Rust".into(),
-                matcher: LanguageMatcher {
-                    path_suffixes: vec!["rs".to_string()],
-                    ..Default::default()
-                },
-                ..Default::default()
-            },
-            Some(language::tree_sitter_rust::LANGUAGE.into()),
-        )
-        .with_outline_query(include_str!("../../languages/src/rust/outline.scm"))
-        .unwrap()
-    }
-}

crates/zeta/src/provider.rs 🔗

@@ -1,217 +0,0 @@
-use std::{cmp, sync::Arc, time::Duration};
-
-use client::{Client, UserStore};
-use cloud_llm_client::EditPredictionRejectReason;
-use edit_prediction::{DataCollectionState, Direction, EditPredictionProvider};
-use gpui::{App, Entity, prelude::*};
-use language::ToPoint as _;
-use project::Project;
-
-use crate::{BufferEditPrediction, Zeta, ZetaEditPredictionModel};
-
-pub struct ZetaEditPredictionProvider {
-    zeta: Entity<Zeta>,
-    project: Entity<Project>,
-}
-
-impl ZetaEditPredictionProvider {
-    pub const THROTTLE_TIMEOUT: Duration = Duration::from_millis(300);
-
-    pub fn new(
-        project: Entity<Project>,
-        client: &Arc<Client>,
-        user_store: &Entity<UserStore>,
-        cx: &mut Context<Self>,
-    ) -> Self {
-        let zeta = Zeta::global(client, user_store, cx);
-        zeta.update(cx, |zeta, cx| {
-            zeta.register_project(&project, cx);
-        });
-
-        cx.observe(&zeta, |_this, _zeta, cx| {
-            cx.notify();
-        })
-        .detach();
-
-        Self {
-            project: project,
-            zeta,
-        }
-    }
-}
-
-impl EditPredictionProvider for ZetaEditPredictionProvider {
-    fn name() -> &'static str {
-        "zed-predict2"
-    }
-
-    fn display_name() -> &'static str {
-        "Zed's Edit Predictions 2"
-    }
-
-    fn show_completions_in_menu() -> bool {
-        true
-    }
-
-    fn show_tab_accept_marker() -> bool {
-        true
-    }
-
-    fn data_collection_state(&self, _cx: &App) -> DataCollectionState {
-        // TODO [zeta2]
-        DataCollectionState::Unsupported
-    }
-
-    fn toggle_data_collection(&mut self, _cx: &mut App) {
-        // TODO [zeta2]
-    }
-
-    fn usage(&self, cx: &App) -> Option<client::EditPredictionUsage> {
-        self.zeta.read(cx).usage(cx)
-    }
-
-    fn is_enabled(
-        &self,
-        _buffer: &Entity<language::Buffer>,
-        _cursor_position: language::Anchor,
-        cx: &App,
-    ) -> bool {
-        let zeta = self.zeta.read(cx);
-        if zeta.edit_prediction_model == ZetaEditPredictionModel::Sweep {
-            zeta.has_sweep_api_token()
-        } else {
-            true
-        }
-    }
-
-    fn is_refreshing(&self, cx: &App) -> bool {
-        self.zeta.read(cx).is_refreshing(&self.project)
-    }
-
-    fn refresh(
-        &mut self,
-        buffer: Entity<language::Buffer>,
-        cursor_position: language::Anchor,
-        _debounce: bool,
-        cx: &mut Context<Self>,
-    ) {
-        let zeta = self.zeta.read(cx);
-
-        if zeta.user_store.read_with(cx, |user_store, _cx| {
-            user_store.account_too_young() || user_store.has_overdue_invoices()
-        }) {
-            return;
-        }
-
-        if let Some(current) = zeta.current_prediction_for_buffer(&buffer, &self.project, cx)
-            && let BufferEditPrediction::Local { prediction } = current
-            && prediction.interpolate(buffer.read(cx)).is_some()
-        {
-            return;
-        }
-
-        self.zeta.update(cx, |zeta, cx| {
-            zeta.refresh_context_if_needed(&self.project, &buffer, cursor_position, cx);
-            zeta.refresh_prediction_from_buffer(self.project.clone(), buffer, cursor_position, cx)
-        });
-    }
-
-    fn cycle(
-        &mut self,
-        _buffer: Entity<language::Buffer>,
-        _cursor_position: language::Anchor,
-        _direction: Direction,
-        _cx: &mut Context<Self>,
-    ) {
-    }
-
-    fn accept(&mut self, cx: &mut Context<Self>) {
-        self.zeta.update(cx, |zeta, cx| {
-            zeta.accept_current_prediction(&self.project, cx);
-        });
-    }
-
-    fn discard(&mut self, cx: &mut Context<Self>) {
-        self.zeta.update(cx, |zeta, _cx| {
-            zeta.reject_current_prediction(EditPredictionRejectReason::Discarded, &self.project);
-        });
-    }
-
-    fn did_show(&mut self, cx: &mut Context<Self>) {
-        self.zeta.update(cx, |zeta, cx| {
-            zeta.did_show_current_prediction(&self.project, cx);
-        });
-    }
-
-    fn suggest(
-        &mut self,
-        buffer: &Entity<language::Buffer>,
-        cursor_position: language::Anchor,
-        cx: &mut Context<Self>,
-    ) -> Option<edit_prediction::EditPrediction> {
-        let prediction =
-            self.zeta
-                .read(cx)
-                .current_prediction_for_buffer(buffer, &self.project, cx)?;
-
-        let prediction = match prediction {
-            BufferEditPrediction::Local { prediction } => prediction,
-            BufferEditPrediction::Jump { prediction } => {
-                return Some(edit_prediction::EditPrediction::Jump {
-                    id: Some(prediction.id.to_string().into()),
-                    snapshot: prediction.snapshot.clone(),
-                    target: prediction.edits.first().unwrap().0.start,
-                });
-            }
-        };
-
-        let buffer = buffer.read(cx);
-        let snapshot = buffer.snapshot();
-
-        let Some(edits) = prediction.interpolate(&snapshot) else {
-            self.zeta.update(cx, |zeta, _cx| {
-                zeta.reject_current_prediction(
-                    EditPredictionRejectReason::InterpolatedEmpty,
-                    &self.project,
-                );
-            });
-            return None;
-        };
-
-        let cursor_row = cursor_position.to_point(&snapshot).row;
-        let (closest_edit_ix, (closest_edit_range, _)) =
-            edits.iter().enumerate().min_by_key(|(_, (range, _))| {
-                let distance_from_start = cursor_row.abs_diff(range.start.to_point(&snapshot).row);
-                let distance_from_end = cursor_row.abs_diff(range.end.to_point(&snapshot).row);
-                cmp::min(distance_from_start, distance_from_end)
-            })?;
-
-        let mut edit_start_ix = closest_edit_ix;
-        for (range, _) in edits[..edit_start_ix].iter().rev() {
-            let distance_from_closest_edit = closest_edit_range.start.to_point(&snapshot).row
-                - range.end.to_point(&snapshot).row;
-            if distance_from_closest_edit <= 1 {
-                edit_start_ix -= 1;
-            } else {
-                break;
-            }
-        }
-
-        let mut edit_end_ix = closest_edit_ix + 1;
-        for (range, _) in &edits[edit_end_ix..] {
-            let distance_from_closest_edit =
-                range.start.to_point(buffer).row - closest_edit_range.end.to_point(&snapshot).row;
-            if distance_from_closest_edit <= 1 {
-                edit_end_ix += 1;
-            } else {
-                break;
-            }
-        }
-
-        Some(edit_prediction::EditPrediction::Local {
-            id: Some(prediction.id.to_string().into()),
-            edits: edits[edit_start_ix..edit_end_ix].to_vec(),
-            edit_preview: Some(prediction.edit_preview.clone()),
-        })
-    }
-}

crates/zeta/src/retrieval_search.rs 🔗

@@ -1,642 +0,0 @@
-use anyhow::Result;
-use cloud_zeta2_prompt::retrieval_prompt::SearchToolQuery;
-use collections::HashMap;
-use futures::{
-    StreamExt,
-    channel::mpsc::{self, UnboundedSender},
-};
-use gpui::{AppContext, AsyncApp, Entity};
-use language::{Anchor, Buffer, BufferSnapshot, OffsetRangeExt, Point, ToOffset, ToPoint};
-use project::{
-    Project, WorktreeSettings,
-    search::{SearchQuery, SearchResult},
-};
-use smol::channel;
-use std::ops::Range;
-use util::{
-    ResultExt as _,
-    paths::{PathMatcher, PathStyle},
-};
-use workspace::item::Settings as _;
-
-#[cfg(feature = "eval-support")]
-type CachedSearchResults = std::collections::BTreeMap<std::path::PathBuf, Vec<Range<usize>>>;
-
-pub async fn run_retrieval_searches(
-    queries: Vec<SearchToolQuery>,
-    project: Entity<Project>,
-    #[cfg(feature = "eval-support")] eval_cache: Option<std::sync::Arc<dyn crate::EvalCache>>,
-    cx: &mut AsyncApp,
-) -> Result<HashMap<Entity<Buffer>, Vec<Range<Anchor>>>> {
-    #[cfg(feature = "eval-support")]
-    let cache = if let Some(eval_cache) = eval_cache {
-        use crate::EvalCacheEntryKind;
-        use anyhow::Context;
-        use collections::FxHasher;
-        use std::hash::{Hash, Hasher};
-
-        let mut hasher = FxHasher::default();
-        project.read_with(cx, |project, cx| {
-            let mut worktrees = project.worktrees(cx);
-            let Some(worktree) = worktrees.next() else {
-                panic!("Expected a single worktree in eval project. Found none.");
-            };
-            assert!(
-                worktrees.next().is_none(),
-                "Expected a single worktree in eval project. Found more than one."
-            );
-            worktree.read(cx).abs_path().hash(&mut hasher);
-        })?;
-
-        queries.hash(&mut hasher);
-        let key = (EvalCacheEntryKind::Search, hasher.finish());
-
-        if let Some(cached_results) = eval_cache.read(key) {
-            let file_results = serde_json::from_str::<CachedSearchResults>(&cached_results)
-                .context("Failed to deserialize cached search results")?;
-            let mut results = HashMap::default();
-
-            for (path, ranges) in file_results {
-                let buffer = project
-                    .update(cx, |project, cx| {
-                        let project_path = project.find_project_path(path, cx).unwrap();
-                        project.open_buffer(project_path, cx)
-                    })?
-                    .await?;
-                let snapshot = buffer.read_with(cx, |buffer, _| buffer.snapshot())?;
-                let mut ranges: Vec<_> = ranges
-                    .into_iter()
-                    .map(|range| {
-                        snapshot.anchor_before(range.start)..snapshot.anchor_after(range.end)
-                    })
-                    .collect();
-                merge_anchor_ranges(&mut ranges, &snapshot);
-                results.insert(buffer, ranges);
-            }
-
-            return Ok(results);
-        }
-
-        Some((eval_cache, serde_json::to_string_pretty(&queries)?, key))
-    } else {
-        None
-    };
-
-    let (exclude_matcher, path_style) = project.update(cx, |project, cx| {
-        let global_settings = WorktreeSettings::get_global(cx);
-        let exclude_patterns = global_settings
-            .file_scan_exclusions
-            .sources()
-            .chain(global_settings.private_files.sources());
-        let path_style = project.path_style(cx);
-        anyhow::Ok((PathMatcher::new(exclude_patterns, path_style)?, path_style))
-    })??;
-
-    let (results_tx, mut results_rx) = mpsc::unbounded();
-
-    for query in queries {
-        let exclude_matcher = exclude_matcher.clone();
-        let results_tx = results_tx.clone();
-        let project = project.clone();
-        cx.spawn(async move |cx| {
-            run_query(
-                query,
-                results_tx.clone(),
-                path_style,
-                exclude_matcher,
-                &project,
-                cx,
-            )
-            .await
-            .log_err();
-        })
-        .detach()
-    }
-    drop(results_tx);
-
-    #[cfg(feature = "eval-support")]
-    let cache = cache.clone();
-    cx.background_spawn(async move {
-        let mut results: HashMap<Entity<Buffer>, Vec<Range<Anchor>>> = HashMap::default();
-        let mut snapshots = HashMap::default();
-
-        let mut total_bytes = 0;
-        'outer: while let Some((buffer, snapshot, excerpts)) = results_rx.next().await {
-            snapshots.insert(buffer.entity_id(), snapshot);
-            let existing = results.entry(buffer).or_default();
-            existing.reserve(excerpts.len());
-
-            for (range, size) in excerpts {
-                // Blunt trimming of the results until we have a proper algorithmic filtering step
-                if (total_bytes + size) > MAX_RESULTS_LEN {
-                    log::trace!("Combined results reached limit of {MAX_RESULTS_LEN}B");
-                    break 'outer;
-                }
-                total_bytes += size;
-                existing.push(range);
-            }
-        }
-
-        #[cfg(feature = "eval-support")]
-        if let Some((cache, queries, key)) = cache {
-            let cached_results: CachedSearchResults = results
-                .iter()
-                .filter_map(|(buffer, ranges)| {
-                    let snapshot = snapshots.get(&buffer.entity_id())?;
-                    let path = snapshot.file().map(|f| f.path());
-                    let mut ranges = ranges
-                        .iter()
-                        .map(|range| range.to_offset(&snapshot))
-                        .collect::<Vec<_>>();
-                    ranges.sort_unstable_by_key(|range| (range.start, range.end));
-
-                    Some((path?.as_std_path().to_path_buf(), ranges))
-                })
-                .collect();
-            cache.write(
-                key,
-                &queries,
-                &serde_json::to_string_pretty(&cached_results)?,
-            );
-        }
-
-        for (buffer, ranges) in results.iter_mut() {
-            if let Some(snapshot) = snapshots.get(&buffer.entity_id()) {
-                merge_anchor_ranges(ranges, snapshot);
-            }
-        }
-
-        Ok(results)
-    })
-    .await
-}
-
-pub(crate) fn merge_anchor_ranges(ranges: &mut Vec<Range<Anchor>>, snapshot: &BufferSnapshot) {
-    ranges.sort_unstable_by(|a, b| {
-        a.start
-            .cmp(&b.start, snapshot)
-            .then(b.end.cmp(&a.end, snapshot))
-    });
-
-    let mut index = 1;
-    while index < ranges.len() {
-        if ranges[index - 1]
-            .end
-            .cmp(&ranges[index].start, snapshot)
-            .is_ge()
-        {
-            let removed = ranges.remove(index);
-            if removed.end.cmp(&ranges[index - 1].end, snapshot).is_gt() {
-                ranges[index - 1].end = removed.end;
-            }
-        } else {
-            index += 1;
-        }
-    }
-}
-
-const MAX_EXCERPT_LEN: usize = 768;
-const MAX_RESULTS_LEN: usize = MAX_EXCERPT_LEN * 5;
-
-struct SearchJob {
-    buffer: Entity<Buffer>,
-    snapshot: BufferSnapshot,
-    ranges: Vec<Range<usize>>,
-    query_ix: usize,
-    jobs_tx: channel::Sender<SearchJob>,
-}
-
-async fn run_query(
-    input_query: SearchToolQuery,
-    results_tx: UnboundedSender<(Entity<Buffer>, BufferSnapshot, Vec<(Range<Anchor>, usize)>)>,
-    path_style: PathStyle,
-    exclude_matcher: PathMatcher,
-    project: &Entity<Project>,
-    cx: &mut AsyncApp,
-) -> Result<()> {
-    let include_matcher = PathMatcher::new(vec![input_query.glob], path_style)?;
-
-    let make_search = |regex: &str| -> Result<SearchQuery> {
-        SearchQuery::regex(
-            regex,
-            false,
-            true,
-            false,
-            true,
-            include_matcher.clone(),
-            exclude_matcher.clone(),
-            true,
-            None,
-        )
-    };
-
-    if let Some(outer_syntax_regex) = input_query.syntax_node.first() {
-        let outer_syntax_query = make_search(outer_syntax_regex)?;
-        let nested_syntax_queries = input_query
-            .syntax_node
-            .into_iter()
-            .skip(1)
-            .map(|query| make_search(&query))
-            .collect::<Result<Vec<_>>>()?;
-        let content_query = input_query
-            .content
-            .map(|regex| make_search(&regex))
-            .transpose()?;
-
-        let (jobs_tx, jobs_rx) = channel::unbounded();
-
-        let outer_search_results_rx =
-            project.update(cx, |project, cx| project.search(outer_syntax_query, cx))?;
-
-        let outer_search_task = cx.spawn(async move |cx| {
-            futures::pin_mut!(outer_search_results_rx);
-            while let Some(SearchResult::Buffer { buffer, ranges }) =
-                outer_search_results_rx.next().await
-            {
-                buffer
-                    .read_with(cx, |buffer, _| buffer.parsing_idle())?
-                    .await;
-                let snapshot = buffer.read_with(cx, |buffer, _cx| buffer.snapshot())?;
-                let expanded_ranges: Vec<_> = ranges
-                    .into_iter()
-                    .filter_map(|range| expand_to_parent_range(&range, &snapshot))
-                    .collect();
-                jobs_tx
-                    .send(SearchJob {
-                        buffer,
-                        snapshot,
-                        ranges: expanded_ranges,
-                        query_ix: 0,
-                        jobs_tx: jobs_tx.clone(),
-                    })
-                    .await?;
-            }
-            anyhow::Ok(())
-        });
-
-        let n_workers = cx.background_executor().num_cpus();
-        let search_job_task = cx.background_executor().scoped(|scope| {
-            for _ in 0..n_workers {
-                scope.spawn(async {
-                    while let Ok(job) = jobs_rx.recv().await {
-                        process_nested_search_job(
-                            &results_tx,
-                            &nested_syntax_queries,
-                            &content_query,
-                            job,
-                        )
-                        .await;
-                    }
-                });
-            }
-        });
-
-        search_job_task.await;
-        outer_search_task.await?;
-    } else if let Some(content_regex) = &input_query.content {
-        let search_query = make_search(&content_regex)?;
-
-        let results_rx = project.update(cx, |project, cx| project.search(search_query, cx))?;
-        futures::pin_mut!(results_rx);
-
-        while let Some(SearchResult::Buffer { buffer, ranges }) = results_rx.next().await {
-            let snapshot = buffer.read_with(cx, |buffer, _cx| buffer.snapshot())?;
-
-            let ranges = ranges
-                .into_iter()
-                .map(|range| {
-                    let range = range.to_offset(&snapshot);
-                    let range = expand_to_entire_lines(range, &snapshot);
-                    let size = range.len();
-                    let range =
-                        snapshot.anchor_before(range.start)..snapshot.anchor_after(range.end);
-                    (range, size)
-                })
-                .collect();
-
-            let send_result = results_tx.unbounded_send((buffer.clone(), snapshot.clone(), ranges));
-
-            if let Err(err) = send_result
-                && !err.is_disconnected()
-            {
-                log::error!("{err}");
-            }
-        }
-    } else {
-        log::warn!("Context gathering model produced a glob-only search");
-    }
-
-    anyhow::Ok(())
-}
-
-async fn process_nested_search_job(
-    results_tx: &UnboundedSender<(Entity<Buffer>, BufferSnapshot, Vec<(Range<Anchor>, usize)>)>,
-    queries: &Vec<SearchQuery>,
-    content_query: &Option<SearchQuery>,
-    job: SearchJob,
-) {
-    if let Some(search_query) = queries.get(job.query_ix) {
-        let mut subranges = Vec::new();
-        for range in job.ranges {
-            let start = range.start;
-            let search_results = search_query.search(&job.snapshot, Some(range)).await;
-            for subrange in search_results {
-                let subrange = start + subrange.start..start + subrange.end;
-                subranges.extend(expand_to_parent_range(&subrange, &job.snapshot));
-            }
-        }
-        job.jobs_tx
-            .send(SearchJob {
-                buffer: job.buffer,
-                snapshot: job.snapshot,
-                ranges: subranges,
-                query_ix: job.query_ix + 1,
-                jobs_tx: job.jobs_tx.clone(),
-            })
-            .await
-            .ok();
-    } else {
-        let ranges = if let Some(content_query) = content_query {
-            let mut subranges = Vec::new();
-            for range in job.ranges {
-                let start = range.start;
-                let search_results = content_query.search(&job.snapshot, Some(range)).await;
-                for subrange in search_results {
-                    let subrange = start + subrange.start..start + subrange.end;
-                    subranges.push(subrange);
-                }
-            }
-            subranges
-        } else {
-            job.ranges
-        };
-
-        let matches = ranges
-            .into_iter()
-            .map(|range| {
-                let snapshot = &job.snapshot;
-                let range = expand_to_entire_lines(range, snapshot);
-                let size = range.len();
-                let range = snapshot.anchor_before(range.start)..snapshot.anchor_after(range.end);
-                (range, size)
-            })
-            .collect();
-
-        let send_result = results_tx.unbounded_send((job.buffer, job.snapshot, matches));
-
-        if let Err(err) = send_result
-            && !err.is_disconnected()
-        {
-            log::error!("{err}");
-        }
-    }
-}
-
-fn expand_to_entire_lines(range: Range<usize>, snapshot: &BufferSnapshot) -> Range<usize> {
-    let mut point_range = range.to_point(snapshot);
-    point_range.start.column = 0;
-    if point_range.end.column > 0 {
-        point_range.end = snapshot.max_point().min(point_range.end + Point::new(1, 0));
-    }
-    point_range.to_offset(snapshot)
-}
-
-fn expand_to_parent_range<T: ToPoint + ToOffset>(
-    range: &Range<T>,
-    snapshot: &BufferSnapshot,
-) -> Option<Range<usize>> {
-    let mut line_range = range.to_point(&snapshot);
-    line_range.start.column = snapshot.indent_size_for_line(line_range.start.row).len;
-    line_range.end.column = snapshot.line_len(line_range.end.row);
-    // TODO skip result if matched line isn't the first node line?
-
-    let node = snapshot.syntax_ancestor(line_range)?;
-    Some(node.byte_range())
-}
-
-#[cfg(test)]
-mod tests {
-    use super::*;
-    use crate::assemble_excerpts::assemble_excerpts;
-    use cloud_zeta2_prompt::write_codeblock;
-    use edit_prediction_context::Line;
-    use gpui::TestAppContext;
-    use indoc::indoc;
-    use language::{Language, LanguageConfig, LanguageMatcher, tree_sitter_rust};
-    use pretty_assertions::assert_eq;
-    use project::FakeFs;
-    use serde_json::json;
-    use settings::SettingsStore;
-    use std::path::Path;
-    use util::path;
-
-    #[gpui::test]
-    async fn test_retrieval(cx: &mut TestAppContext) {
-        init_test(cx);
-        let fs = FakeFs::new(cx.executor());
-        fs.insert_tree(
-            path!("/root"),
-            json!({
-                "user.rs": indoc!{"
-                    pub struct Organization {
-                        owner: Arc<User>,
-                    }
-
-                    pub struct User {
-                        first_name: String,
-                        last_name: String,
-                    }
-
-                    impl Organization {
-                        pub fn owner(&self) -> Arc<User> {
-                            self.owner.clone()
-                        }
-                    }
-
-                    impl User {
-                        pub fn new(first_name: String, last_name: String) -> Self {
-                            Self {
-                                first_name,
-                                last_name
-                            }
-                        }
-
-                        pub fn first_name(&self) -> String {
-                            self.first_name.clone()
-                        }
-
-                        pub fn last_name(&self) -> String {
-                            self.last_name.clone()
-                        }
-                    }
-                "},
-                "main.rs": indoc!{r#"
-                    fn main() {
-                        let user = User::new(FIRST_NAME.clone(), "doe".into());
-                        println!("user {:?}", user);
-                    }
-                "#},
-            }),
-        )
-        .await;
-
-        let project = Project::test(fs, vec![Path::new(path!("/root"))], cx).await;
-        project.update(cx, |project, _cx| {
-            project.languages().add(rust_lang().into())
-        });
-
-        assert_results(
-            &project,
-            SearchToolQuery {
-                glob: "user.rs".into(),
-                syntax_node: vec!["impl\\s+User".into(), "pub\\s+fn\\s+first_name".into()],
-                content: None,
-            },
-            indoc! {r#"
-                `````root/user.rs
-                …
-                impl User {
-                …
-                    pub fn first_name(&self) -> String {
-                        self.first_name.clone()
-                    }
-                …
-                `````
-            "#},
-            cx,
-        )
-        .await;
-
-        assert_results(
-            &project,
-            SearchToolQuery {
-                glob: "user.rs".into(),
-                syntax_node: vec!["impl\\s+User".into()],
-                content: Some("\\.clone".into()),
-            },
-            indoc! {r#"
-                `````root/user.rs
-                …
-                impl User {
-                …
-                    pub fn first_name(&self) -> String {
-                        self.first_name.clone()
-                …
-                    pub fn last_name(&self) -> String {
-                        self.last_name.clone()
-                …
-                `````
-            "#},
-            cx,
-        )
-        .await;
-
-        assert_results(
-            &project,
-            SearchToolQuery {
-                glob: "*.rs".into(),
-                syntax_node: vec![],
-                content: Some("\\.clone".into()),
-            },
-            indoc! {r#"
-                `````root/main.rs
-                fn main() {
-                    let user = User::new(FIRST_NAME.clone(), "doe".into());
-                …
-                `````
-
-                `````root/user.rs
-                …
-                impl Organization {
-                    pub fn owner(&self) -> Arc<User> {
-                        self.owner.clone()
-                …
-                impl User {
-                …
-                    pub fn first_name(&self) -> String {
-                        self.first_name.clone()
-                …
-                    pub fn last_name(&self) -> String {
-                        self.last_name.clone()
-                …
-                `````
-            "#},
-            cx,
-        )
-        .await;
-    }
-
-    async fn assert_results(
-        project: &Entity<Project>,
-        query: SearchToolQuery,
-        expected_output: &str,
-        cx: &mut TestAppContext,
-    ) {
-        let results = run_retrieval_searches(
-            vec![query],
-            project.clone(),
-            #[cfg(feature = "eval-support")]
-            None,
-            &mut cx.to_async(),
-        )
-        .await
-        .unwrap();
-
-        let mut results = results.into_iter().collect::<Vec<_>>();
-        results.sort_by_key(|results| {
-            results
-                .0
-                .read_with(cx, |buffer, _| buffer.file().unwrap().path().clone())
-        });
-
-        let mut output = String::new();
-        for (buffer, ranges) in results {
-            buffer.read_with(cx, |buffer, cx| {
-                let excerpts = ranges.into_iter().map(|range| {
-                    let point_range = range.to_point(buffer);
-                    if point_range.end.column > 0 {
-                        Line(point_range.start.row)..Line(point_range.end.row + 1)
-                    } else {
-                        Line(point_range.start.row)..Line(point_range.end.row)
-                    }
-                });
-
-                write_codeblock(
-                    &buffer.file().unwrap().full_path(cx),
-                    assemble_excerpts(&buffer.snapshot(), excerpts).iter(),
-                    &[],
-                    Line(buffer.max_point().row),
-                    false,
-                    &mut output,
-                );
-            });
-        }
-        output.pop();
-
-        assert_eq!(output, expected_output);
-    }
-
-    fn rust_lang() -> Language {
-        Language::new(
-            LanguageConfig {
-                name: "Rust".into(),
-                matcher: LanguageMatcher {
-                    path_suffixes: vec!["rs".to_string()],
-                    ..Default::default()
-                },
-                ..Default::default()
-            },
-            Some(tree_sitter_rust::LANGUAGE.into()),
-        )
-        .with_outline_query(include_str!("../../languages/src/rust/outline.scm"))
-        .unwrap()
-    }
-
-    fn init_test(cx: &mut TestAppContext) {
-        cx.update(move |cx| {
-            let settings_store = SettingsStore::test(cx);
-            cx.set_global(settings_store);
-            zlog::init_test();
-        });
-    }
-}

crates/zeta/src/xml_edits.rs 🔗

@@ -1,637 +0,0 @@
-use anyhow::{Context as _, Result};
-use language::{Anchor, BufferSnapshot, OffsetRangeExt as _, Point};
-use std::{cmp, ops::Range, path::Path, sync::Arc};
-
-const EDITS_TAG_NAME: &'static str = "edits";
-const OLD_TEXT_TAG_NAME: &'static str = "old_text";
-const NEW_TEXT_TAG_NAME: &'static str = "new_text";
-const XML_TAGS: &[&str] = &[EDITS_TAG_NAME, OLD_TEXT_TAG_NAME, NEW_TEXT_TAG_NAME];
-
-pub async fn parse_xml_edits<'a>(
-    input: &'a str,
-    get_buffer: impl Fn(&Path) -> Option<(&'a BufferSnapshot, &'a [Range<Anchor>])> + Send,
-) -> Result<(&'a BufferSnapshot, Vec<(Range<Anchor>, Arc<str>)>)> {
-    parse_xml_edits_inner(input, get_buffer)
-        .await
-        .with_context(|| format!("Failed to parse XML edits:\n{input}"))
-}
-
-async fn parse_xml_edits_inner<'a>(
-    input: &'a str,
-    get_buffer: impl Fn(&Path) -> Option<(&'a BufferSnapshot, &'a [Range<Anchor>])> + Send,
-) -> Result<(&'a BufferSnapshot, Vec<(Range<Anchor>, Arc<str>)>)> {
-    let xml_edits = extract_xml_replacements(input)?;
-
-    let (buffer, context_ranges) = get_buffer(xml_edits.file_path.as_ref())
-        .with_context(|| format!("no buffer for file {}", xml_edits.file_path))?;
-
-    let mut all_edits = vec![];
-    for (old_text, new_text) in xml_edits.replacements {
-        let match_range = fuzzy_match_in_ranges(old_text, buffer, context_ranges)?;
-        let matched_old_text = buffer
-            .text_for_range(match_range.clone())
-            .collect::<String>();
-        let edits_within_hunk = language::text_diff(&matched_old_text, new_text);
-        all_edits.extend(
-            edits_within_hunk
-                .into_iter()
-                .map(move |(inner_range, inner_text)| {
-                    (
-                        buffer.anchor_after(match_range.start + inner_range.start)
-                            ..buffer.anchor_before(match_range.start + inner_range.end),
-                        inner_text,
-                    )
-                }),
-        );
-    }
-
-    Ok((buffer, all_edits))
-}
-
-fn fuzzy_match_in_ranges(
-    old_text: &str,
-    buffer: &BufferSnapshot,
-    context_ranges: &[Range<Anchor>],
-) -> Result<Range<usize>> {
-    let mut state = FuzzyMatcher::new(buffer, old_text);
-    let mut best_match = None;
-    let mut tie_match_range = None;
-
-    for range in context_ranges {
-        let best_match_cost = best_match.as_ref().map(|(score, _)| *score);
-        match (best_match_cost, state.match_range(range.to_offset(buffer))) {
-            (Some(lowest_cost), Some((new_cost, new_range))) => {
-                if new_cost == lowest_cost {
-                    tie_match_range = Some(new_range);
-                } else if new_cost < lowest_cost {
-                    tie_match_range.take();
-                    best_match = Some((new_cost, new_range));
-                }
-            }
-            (None, Some(new_match)) => {
-                best_match = Some(new_match);
-            }
-            (None, None) | (Some(_), None) => {}
-        };
-    }
-
-    if let Some((_, best_match_range)) = best_match {
-        if let Some(tie_match_range) = tie_match_range {
-            anyhow::bail!(
-                "Multiple ambiguous matches:\n{:?}:\n{}\n\n{:?}:\n{}",
-                best_match_range.clone(),
-                buffer.text_for_range(best_match_range).collect::<String>(),
-                tie_match_range.clone(),
-                buffer.text_for_range(tie_match_range).collect::<String>()
-            );
-        }
-        return Ok(best_match_range);
-    }
-
-    anyhow::bail!(
-        "Failed to fuzzy match `old_text`:\n{}\nin:\n```\n{}\n```",
-        old_text,
-        context_ranges
-            .iter()
-            .map(|range| buffer.text_for_range(range.clone()).collect::<String>())
-            .collect::<Vec<String>>()
-            .join("```\n```")
-    );
-}
-
-#[derive(Debug)]
-struct XmlEdits<'a> {
-    file_path: &'a str,
-    /// Vec of (old_text, new_text) pairs
-    replacements: Vec<(&'a str, &'a str)>,
-}
-
-fn extract_xml_replacements(input: &str) -> Result<XmlEdits<'_>> {
-    let mut cursor = 0;
-
-    let (edits_body_start, edits_attrs) =
-        find_tag_open(input, &mut cursor, EDITS_TAG_NAME)?.context("No edits tag found")?;
-
-    let file_path = edits_attrs
-        .trim_start()
-        .strip_prefix("path")
-        .context("no path attribute on edits tag")?
-        .trim_end()
-        .strip_prefix('=')
-        .context("no value for path attribute")?
-        .trim()
-        .trim_start_matches('"')
-        .trim_end_matches('"');
-
-    cursor = edits_body_start;
-    let mut edits_list = Vec::new();
-
-    while let Some((old_body_start, _)) = find_tag_open(input, &mut cursor, OLD_TEXT_TAG_NAME)? {
-        let old_body_end = find_tag_close(input, &mut cursor)?;
-        let old_text = trim_surrounding_newlines(&input[old_body_start..old_body_end]);
-
-        let (new_body_start, _) = find_tag_open(input, &mut cursor, NEW_TEXT_TAG_NAME)?
-            .context("no new_text tag following old_text")?;
-        let new_body_end = find_tag_close(input, &mut cursor)?;
-        let new_text = trim_surrounding_newlines(&input[new_body_start..new_body_end]);
-
-        edits_list.push((old_text, new_text));
-    }
-
-    Ok(XmlEdits {
-        file_path,
-        replacements: edits_list,
-    })
-}
-
-/// Trims a single leading and trailing newline
-fn trim_surrounding_newlines(input: &str) -> &str {
-    let start = input.strip_prefix('\n').unwrap_or(input);
-    let end = start.strip_suffix('\n').unwrap_or(start);
-    end
-}
-
-fn find_tag_open<'a>(
-    input: &'a str,
-    cursor: &mut usize,
-    expected_tag: &str,
-) -> Result<Option<(usize, &'a str)>> {
-    let mut search_pos = *cursor;
-
-    while search_pos < input.len() {
-        let Some(tag_start) = input[search_pos..].find("<") else {
-            break;
-        };
-        let tag_start = search_pos + tag_start;
-        if !input[tag_start + 1..].starts_with(expected_tag) {
-            search_pos = search_pos + tag_start + 1;
-            continue;
-        };
-
-        let after_tag_name = tag_start + expected_tag.len() + 1;
-        let close_bracket = input[after_tag_name..]
-            .find('>')
-            .with_context(|| format!("missing > after <{}", expected_tag))?;
-        let attrs_end = after_tag_name + close_bracket;
-        let body_start = attrs_end + 1;
-
-        let attributes = input[after_tag_name..attrs_end].trim();
-        *cursor = body_start;
-
-        return Ok(Some((body_start, attributes)));
-    }
-
-    Ok(None)
-}
-
-fn find_tag_close(input: &str, cursor: &mut usize) -> Result<usize> {
-    let mut depth = 1;
-    let mut search_pos = *cursor;
-
-    while search_pos < input.len() && depth > 0 {
-        let Some(bracket_offset) = input[search_pos..].find('<') else {
-            break;
-        };
-        let bracket_pos = search_pos + bracket_offset;
-
-        if input[bracket_pos..].starts_with("</")
-            && let Some(close_end) = input[bracket_pos + 2..].find('>')
-        {
-            let close_start = bracket_pos + 2;
-            let tag_name = input[close_start..close_start + close_end].trim();
-
-            if XML_TAGS.contains(&tag_name) {
-                depth -= 1;
-                if depth == 0 {
-                    *cursor = close_start + close_end + 1;
-                    return Ok(bracket_pos);
-                }
-            }
-            search_pos = close_start + close_end + 1;
-            continue;
-        } else if let Some(close_bracket_offset) = input[bracket_pos..].find('>') {
-            let close_bracket_pos = bracket_pos + close_bracket_offset;
-            let tag_name = &input[bracket_pos + 1..close_bracket_pos].trim();
-            if XML_TAGS.contains(&tag_name) {
-                depth += 1;
-            }
-        }
-
-        search_pos = bracket_pos + 1;
-    }
-
-    anyhow::bail!("no closing tag found")
-}
-
-const REPLACEMENT_COST: u32 = 1;
-const INSERTION_COST: u32 = 3;
-const DELETION_COST: u32 = 10;
-
-/// A fuzzy matcher that can process text chunks incrementally
-/// and return the best match found so far at each step.
-struct FuzzyMatcher<'a> {
-    snapshot: &'a BufferSnapshot,
-    query_lines: Vec<&'a str>,
-    matrix: SearchMatrix,
-}
-
-impl<'a> FuzzyMatcher<'a> {
-    fn new(snapshot: &'a BufferSnapshot, old_text: &'a str) -> Self {
-        let query_lines = old_text.lines().collect();
-        Self {
-            snapshot,
-            query_lines,
-            matrix: SearchMatrix::new(0),
-        }
-    }
-
-    fn match_range(&mut self, range: Range<usize>) -> Option<(u32, Range<usize>)> {
-        let point_range = range.to_point(&self.snapshot);
-        let buffer_line_count = (point_range.end.row - point_range.start.row + 1) as usize;
-
-        self.matrix
-            .reset(self.query_lines.len() + 1, buffer_line_count + 1);
-        let query_line_count = self.query_lines.len();
-
-        for row in 0..query_line_count {
-            let query_line = self.query_lines[row].trim();
-            let leading_deletion_cost = (row + 1) as u32 * DELETION_COST;
-
-            self.matrix.set(
-                row + 1,
-                0,
-                SearchState::new(leading_deletion_cost, SearchDirection::Up),
-            );
-
-            let mut buffer_lines = self.snapshot.text_for_range(range.clone()).lines();
-
-            let mut col = 0;
-            while let Some(buffer_line) = buffer_lines.next() {
-                let buffer_line = buffer_line.trim();
-                let up = SearchState::new(
-                    self.matrix
-                        .get(row, col + 1)
-                        .cost
-                        .saturating_add(DELETION_COST),
-                    SearchDirection::Up,
-                );
-                let left = SearchState::new(
-                    self.matrix
-                        .get(row + 1, col)
-                        .cost
-                        .saturating_add(INSERTION_COST),
-                    SearchDirection::Left,
-                );
-                let diagonal = SearchState::new(
-                    if query_line == buffer_line {
-                        self.matrix.get(row, col).cost
-                    } else if fuzzy_eq(query_line, buffer_line) {
-                        self.matrix.get(row, col).cost + REPLACEMENT_COST
-                    } else {
-                        self.matrix
-                            .get(row, col)
-                            .cost
-                            .saturating_add(DELETION_COST + INSERTION_COST)
-                    },
-                    SearchDirection::Diagonal,
-                );
-                self.matrix
-                    .set(row + 1, col + 1, up.min(left).min(diagonal));
-                col += 1;
-            }
-        }
-
-        // Find all matches with the best cost
-        let mut best_cost = u32::MAX;
-        let mut matches_with_best_cost = Vec::new();
-
-        for col in 1..=buffer_line_count {
-            let cost = self.matrix.get(query_line_count, col).cost;
-            if cost < best_cost {
-                best_cost = cost;
-                matches_with_best_cost.clear();
-                matches_with_best_cost.push(col as u32);
-            } else if cost == best_cost {
-                matches_with_best_cost.push(col as u32);
-            }
-        }
-
-        // Find ranges for the matches
-        for &match_end_col in &matches_with_best_cost {
-            let mut matched_lines = 0;
-            let mut query_row = query_line_count;
-            let mut match_start_col = match_end_col;
-            while query_row > 0 && match_start_col > 0 {
-                let current = self.matrix.get(query_row, match_start_col as usize);
-                match current.direction {
-                    SearchDirection::Diagonal => {
-                        query_row -= 1;
-                        match_start_col -= 1;
-                        matched_lines += 1;
-                    }
-                    SearchDirection::Up => {
-                        query_row -= 1;
-                    }
-                    SearchDirection::Left => {
-                        match_start_col -= 1;
-                    }
-                }
-            }
-
-            let buffer_row_start = match_start_col + point_range.start.row;
-            let buffer_row_end = match_end_col + point_range.start.row;
-
-            let matched_buffer_row_count = buffer_row_end - buffer_row_start;
-            let matched_ratio = matched_lines as f32
-                / (matched_buffer_row_count as f32).max(query_line_count as f32);
-            if matched_ratio >= 0.8 {
-                let buffer_start_ix = self
-                    .snapshot
-                    .point_to_offset(Point::new(buffer_row_start, 0));
-                let buffer_end_ix = self.snapshot.point_to_offset(Point::new(
-                    buffer_row_end - 1,
-                    self.snapshot.line_len(buffer_row_end - 1),
-                ));
-                return Some((best_cost, buffer_start_ix..buffer_end_ix));
-            }
-        }
-
-        None
-    }
-}
-
-fn fuzzy_eq(left: &str, right: &str) -> bool {
-    const THRESHOLD: f64 = 0.8;
-
-    let min_levenshtein = left.len().abs_diff(right.len());
-    let min_normalized_levenshtein =
-        1. - (min_levenshtein as f64 / cmp::max(left.len(), right.len()) as f64);
-    if min_normalized_levenshtein < THRESHOLD {
-        return false;
-    }
-
-    strsim::normalized_levenshtein(left, right) >= THRESHOLD
-}
-
-#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
-enum SearchDirection {
-    Up,
-    Left,
-    Diagonal,
-}
-
-#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
-struct SearchState {
-    cost: u32,
-    direction: SearchDirection,
-}
-
-impl SearchState {
-    fn new(cost: u32, direction: SearchDirection) -> Self {
-        Self { cost, direction }
-    }
-}
-
-struct SearchMatrix {
-    cols: usize,
-    rows: usize,
-    data: Vec<SearchState>,
-}
-
-impl SearchMatrix {
-    fn new(cols: usize) -> Self {
-        SearchMatrix {
-            cols,
-            rows: 0,
-            data: Vec::new(),
-        }
-    }
-
-    fn reset(&mut self, rows: usize, cols: usize) {
-        self.rows = rows;
-        self.cols = cols;
-        self.data
-            .fill(SearchState::new(0, SearchDirection::Diagonal));
-        self.data.resize(
-            self.rows * self.cols,
-            SearchState::new(0, SearchDirection::Diagonal),
-        );
-    }
-
-    fn get(&self, row: usize, col: usize) -> SearchState {
-        debug_assert!(row < self.rows);
-        debug_assert!(col < self.cols);
-        self.data[row * self.cols + col]
-    }
-
-    fn set(&mut self, row: usize, col: usize, state: SearchState) {
-        debug_assert!(row < self.rows && col < self.cols);
-        self.data[row * self.cols + col] = state;
-    }
-}
-
-#[cfg(test)]
-mod tests {
-    use super::*;
-    use gpui::TestAppContext;
-    use indoc::indoc;
-    use language::Point;
-    use project::{FakeFs, Project};
-    use serde_json::json;
-    use settings::SettingsStore;
-    use util::path;
-
-    #[test]
-    fn test_extract_xml_edits() {
-        let input = indoc! {r#"
-            <edits path="test.rs">
-            <old_text>
-            old content
-            </old_text>
-            <new_text>
-            new content
-            </new_text>
-            </edits>
-        "#};
-
-        let result = extract_xml_replacements(input).unwrap();
-        assert_eq!(result.file_path, "test.rs");
-        assert_eq!(result.replacements.len(), 1);
-        assert_eq!(result.replacements[0].0, "old content");
-        assert_eq!(result.replacements[0].1, "new content");
-    }
-
-    #[test]
-    fn test_extract_xml_edits_with_wrong_closing_tags() {
-        let input = indoc! {r#"
-            <edits path="test.rs">
-            <old_text>
-            old content
-            </new_text>
-            <new_text>
-            new content
-            </old_text>
-            </ edits >
-        "#};
-
-        let result = extract_xml_replacements(input).unwrap();
-        assert_eq!(result.file_path, "test.rs");
-        assert_eq!(result.replacements.len(), 1);
-        assert_eq!(result.replacements[0].0, "old content");
-        assert_eq!(result.replacements[0].1, "new content");
-    }
-
-    #[test]
-    fn test_extract_xml_edits_with_xml_like_content() {
-        let input = indoc! {r#"
-            <edits path="component.tsx">
-            <old_text>
-            <foo><bar></bar></foo>
-            </old_text>
-            <new_text>
-            <foo><bar><baz></baz></bar></foo>
-            </new_text>
-            </edits>
-        "#};
-
-        let result = extract_xml_replacements(input).unwrap();
-        assert_eq!(result.file_path, "component.tsx");
-        assert_eq!(result.replacements.len(), 1);
-        assert_eq!(result.replacements[0].0, "<foo><bar></bar></foo>");
-        assert_eq!(
-            result.replacements[0].1,
-            "<foo><bar><baz></baz></bar></foo>"
-        );
-    }
-
-    #[test]
-    fn test_extract_xml_edits_with_conflicting_content() {
-        let input = indoc! {r#"
-            <edits path="component.tsx">
-            <old_text>
-            <new_text></new_text>
-            </old_text>
-            <new_text>
-            <old_text></old_text>
-            </new_text>
-            </edits>
-        "#};
-
-        let result = extract_xml_replacements(input).unwrap();
-        assert_eq!(result.file_path, "component.tsx");
-        assert_eq!(result.replacements.len(), 1);
-        assert_eq!(result.replacements[0].0, "<new_text></new_text>");
-        assert_eq!(result.replacements[0].1, "<old_text></old_text>");
-    }
-
-    #[test]
-    fn test_extract_xml_edits_multiple_pairs() {
-        let input = indoc! {r#"
-            Some reasoning before edits. Lots of thinking going on here
-
-            <edits path="test.rs">
-            <old_text>
-            first old
-            </old_text>
-            <new_text>
-            first new
-            </new_text>
-            <old_text>
-            second old
-            </edits>
-            <new_text>
-            second new
-            </old_text>
-            </edits>
-        "#};
-
-        let result = extract_xml_replacements(input).unwrap();
-        assert_eq!(result.file_path, "test.rs");
-        assert_eq!(result.replacements.len(), 2);
-        assert_eq!(result.replacements[0].0, "first old");
-        assert_eq!(result.replacements[0].1, "first new");
-        assert_eq!(result.replacements[1].0, "second old");
-        assert_eq!(result.replacements[1].1, "second new");
-    }
-
-    #[test]
-    fn test_extract_xml_edits_unexpected_eof() {
-        let input = indoc! {r#"
-            <edits path="test.rs">
-            <old_text>
-            first old
-            </
-        "#};
-
-        extract_xml_replacements(input).expect_err("Unexpected end of file");
-    }
-
-    #[gpui::test]
-    async fn test_parse_xml_edits(cx: &mut TestAppContext) {
-        let fs = init_test(cx);
-
-        let buffer_1_text = indoc! {r#"
-            one two three four
-            five six seven eight
-            nine ten eleven twelve
-            thirteen fourteen fifteen
-            sixteen seventeen eighteen
-        "#};
-
-        fs.insert_tree(
-            path!("/root"),
-            json!({
-                "file1": buffer_1_text,
-            }),
-        )
-        .await;
-
-        let project = Project::test(fs, [path!("/root").as_ref()], cx).await;
-        let buffer = project
-            .update(cx, |project, cx| {
-                project.open_local_buffer(path!("/root/file1"), cx)
-            })
-            .await
-            .unwrap();
-        let buffer_snapshot = buffer.read_with(cx, |buffer, _| buffer.snapshot());
-
-        let edits = indoc! {r#"
-            <edits path="root/file1">
-            <old_text>
-            nine ten eleven twelve
-            </old_text>
-            <new_text>
-            nine TEN eleven twelve!
-            </new_text>
-            </edits>
-        "#};
-
-        let included_ranges = [(buffer_snapshot.anchor_before(Point::new(1, 0))..Anchor::MAX)];
-        let (buffer, edits) = parse_xml_edits(edits, |_path| {
-            Some((&buffer_snapshot, included_ranges.as_slice()))
-        })
-        .await
-        .unwrap();
-
-        let edits = edits
-            .into_iter()
-            .map(|(range, text)| (range.to_point(&buffer), text))
-            .collect::<Vec<_>>();
-        assert_eq!(
-            edits,
-            &[
-                (Point::new(2, 5)..Point::new(2, 8), "TEN".into()),
-                (Point::new(2, 22)..Point::new(2, 22), "!".into())
-            ]
-        );
-    }
-
-    fn init_test(cx: &mut TestAppContext) -> Arc<FakeFs> {
-        cx.update(|cx| {
-            let settings_store = SettingsStore::test(cx);
-            cx.set_global(settings_store);
-        });
-
-        FakeFs::new(cx.background_executor.clone())
-    }
-}

crates/zeta/src/zeta.rs 🔗

@@ -1,4057 +0,0 @@
-use anyhow::{Context as _, Result, anyhow, bail};
-use arrayvec::ArrayVec;
-use client::{Client, EditPredictionUsage, UserStore};
-use cloud_llm_client::predict_edits_v3::{self, Event, PromptFormat, Signature};
-use cloud_llm_client::{
-    AcceptEditPredictionBody, EXPIRED_LLM_TOKEN_HEADER_NAME, EditPredictionRejectReason,
-    EditPredictionRejection, MAX_EDIT_PREDICTION_REJECTIONS_PER_REQUEST,
-    MINIMUM_REQUIRED_VERSION_HEADER_NAME, PredictEditsRequestTrigger, RejectEditPredictionsBodyRef,
-    ZED_VERSION_HEADER_NAME,
-};
-use cloud_zeta2_prompt::retrieval_prompt::{SearchToolInput, SearchToolQuery};
-use cloud_zeta2_prompt::{CURSOR_MARKER, DEFAULT_MAX_PROMPT_BYTES};
-use collections::{HashMap, HashSet};
-use command_palette_hooks::CommandPaletteFilter;
-use db::kvp::{Dismissable, KEY_VALUE_STORE};
-use edit_prediction_context::{
-    DeclarationId, DeclarationStyle, EditPredictionContext, EditPredictionContextOptions,
-    EditPredictionExcerpt, EditPredictionExcerptOptions, EditPredictionScoreOptions, Line,
-    SyntaxIndex, SyntaxIndexState,
-};
-use feature_flags::{FeatureFlag, FeatureFlagAppExt as _, PredictEditsRateCompletionsFeatureFlag};
-use futures::channel::mpsc::UnboundedReceiver;
-use futures::channel::{mpsc, oneshot};
-use futures::{AsyncReadExt as _, FutureExt as _, StreamExt as _, select_biased};
-use gpui::BackgroundExecutor;
-use gpui::{
-    App, AsyncApp, Entity, EntityId, Global, SharedString, Subscription, Task, WeakEntity, actions,
-    http_client::{self, AsyncBody, Method},
-    prelude::*,
-};
-use language::{
-    Anchor, Buffer, DiagnosticSet, File, LanguageServerId, Point, ToOffset as _, ToPoint,
-};
-use language::{BufferSnapshot, OffsetRangeExt};
-use language_model::{LlmApiToken, RefreshLlmTokenListener};
-use open_ai::FunctionDefinition;
-use project::{DisableAiSettings, Project, ProjectPath, WorktreeId};
-use release_channel::AppVersion;
-use semver::Version;
-use serde::de::DeserializeOwned;
-use settings::{EditPredictionProvider, Settings as _, SettingsStore, update_settings_file};
-use std::any::{Any as _, TypeId};
-use std::collections::{VecDeque, hash_map};
-use telemetry_events::EditPredictionRating;
-use workspace::Workspace;
-
-use std::ops::Range;
-use std::path::Path;
-use std::rc::Rc;
-use std::str::FromStr as _;
-use std::sync::{Arc, LazyLock};
-use std::time::{Duration, Instant};
-use std::{env, mem};
-use thiserror::Error;
-use util::rel_path::RelPathBuf;
-use util::{LogErrorFuture, RangeExt as _, ResultExt as _, TryFutureExt};
-use workspace::notifications::{ErrorMessagePrompt, NotificationId, show_app_notification};
-
-pub mod assemble_excerpts;
-mod license_detection;
-mod onboarding_modal;
-mod prediction;
-mod provider;
-mod rate_prediction_modal;
-pub mod retrieval_search;
-pub mod sweep_ai;
-pub mod udiff;
-mod xml_edits;
-pub mod zeta1;
-
-#[cfg(test)]
-mod zeta_tests;
-
-use crate::assemble_excerpts::assemble_excerpts;
-use crate::license_detection::LicenseDetectionWatcher;
-use crate::onboarding_modal::ZedPredictModal;
-pub use crate::prediction::EditPrediction;
-pub use crate::prediction::EditPredictionId;
-pub use crate::prediction::EditPredictionInputs;
-use crate::prediction::EditPredictionResult;
-use crate::rate_prediction_modal::{
-    NextEdit, PreviousEdit, RatePredictionsModal, ThumbsDownActivePrediction,
-    ThumbsUpActivePrediction,
-};
-pub use crate::sweep_ai::SweepAi;
-use crate::zeta1::request_prediction_with_zeta1;
-pub use provider::ZetaEditPredictionProvider;
-
-actions!(
-    edit_prediction,
-    [
-        /// Resets the edit prediction onboarding state.
-        ResetOnboarding,
-        /// Opens the rate completions modal.
-        RateCompletions,
-        /// Clears the edit prediction history.
-        ClearHistory,
-    ]
-);
-
-/// Maximum number of events to track.
-const EVENT_COUNT_MAX: usize = 6;
-const CHANGE_GROUPING_LINE_SPAN: u32 = 8;
-const ZED_PREDICT_DATA_COLLECTION_CHOICE: &str = "zed_predict_data_collection_choice";
-const REJECT_REQUEST_DEBOUNCE: Duration = Duration::from_secs(15);
-
-pub struct SweepFeatureFlag;
-
-impl FeatureFlag for SweepFeatureFlag {
-    const NAME: &str = "sweep-ai";
-}
-pub const DEFAULT_EXCERPT_OPTIONS: EditPredictionExcerptOptions = EditPredictionExcerptOptions {
-    max_bytes: 512,
-    min_bytes: 128,
-    target_before_cursor_over_total_bytes: 0.5,
-};
-
-pub const DEFAULT_CONTEXT_OPTIONS: ContextMode =
-    ContextMode::Agentic(DEFAULT_AGENTIC_CONTEXT_OPTIONS);
-
-pub const DEFAULT_AGENTIC_CONTEXT_OPTIONS: AgenticContextOptions = AgenticContextOptions {
-    excerpt: DEFAULT_EXCERPT_OPTIONS,
-};
-
-pub const DEFAULT_SYNTAX_CONTEXT_OPTIONS: EditPredictionContextOptions =
-    EditPredictionContextOptions {
-        use_imports: true,
-        max_retrieved_declarations: 0,
-        excerpt: DEFAULT_EXCERPT_OPTIONS,
-        score: EditPredictionScoreOptions {
-            omit_excerpt_overlaps: true,
-        },
-    };
-
-pub const DEFAULT_OPTIONS: ZetaOptions = ZetaOptions {
-    context: DEFAULT_CONTEXT_OPTIONS,
-    max_prompt_bytes: DEFAULT_MAX_PROMPT_BYTES,
-    max_diagnostic_bytes: 2048,
-    prompt_format: PromptFormat::DEFAULT,
-    file_indexing_parallelism: 1,
-    buffer_change_grouping_interval: Duration::from_secs(1),
-};
-
-static USE_OLLAMA: LazyLock<bool> =
-    LazyLock::new(|| env::var("ZED_ZETA2_OLLAMA").is_ok_and(|var| !var.is_empty()));
-static CONTEXT_RETRIEVAL_MODEL_ID: LazyLock<String> = LazyLock::new(|| {
-    env::var("ZED_ZETA2_CONTEXT_MODEL").unwrap_or(if *USE_OLLAMA {
-        "qwen3-coder:30b".to_string()
-    } else {
-        "yqvev8r3".to_string()
-    })
-});
-static EDIT_PREDICTIONS_MODEL_ID: LazyLock<String> = LazyLock::new(|| {
-    match env::var("ZED_ZETA2_MODEL").as_deref() {
-        Ok("zeta2-exp") => "4w5n28vw", // Fine-tuned model @ Baseten
-        Ok(model) => model,
-        Err(_) if *USE_OLLAMA => "qwen3-coder:30b",
-        Err(_) => "yqvev8r3", // Vanilla qwen3-coder @ Baseten
-    }
-    .to_string()
-});
-static PREDICT_EDITS_URL: LazyLock<Option<String>> = LazyLock::new(|| {
-    env::var("ZED_PREDICT_EDITS_URL").ok().or_else(|| {
-        if *USE_OLLAMA {
-            Some("http://localhost:11434/v1/chat/completions".into())
-        } else {
-            None
-        }
-    })
-});
-
-pub struct Zeta2FeatureFlag;
-
-impl FeatureFlag for Zeta2FeatureFlag {
-    const NAME: &'static str = "zeta2";
-
-    fn enabled_for_staff() -> bool {
-        true
-    }
-}
-
-#[derive(Clone)]
-struct ZetaGlobal(Entity<Zeta>);
-
-impl Global for ZetaGlobal {}
-
-pub struct Zeta {
-    client: Arc<Client>,
-    user_store: Entity<UserStore>,
-    llm_token: LlmApiToken,
-    _llm_token_subscription: Subscription,
-    projects: HashMap<EntityId, ZetaProject>,
-    options: ZetaOptions,
-    update_required: bool,
-    debug_tx: Option<mpsc::UnboundedSender<ZetaDebugInfo>>,
-    #[cfg(feature = "eval-support")]
-    eval_cache: Option<Arc<dyn EvalCache>>,
-    edit_prediction_model: ZetaEditPredictionModel,
-    pub sweep_ai: SweepAi,
-    data_collection_choice: DataCollectionChoice,
-    reject_predictions_tx: mpsc::UnboundedSender<EditPredictionRejection>,
-    shown_predictions: VecDeque<EditPrediction>,
-    rated_predictions: HashSet<EditPredictionId>,
-}
-
-#[derive(Copy, Clone, Default, PartialEq, Eq)]
-pub enum ZetaEditPredictionModel {
-    #[default]
-    Zeta1,
-    Zeta2,
-    Sweep,
-}
-
-#[derive(Debug, Clone, PartialEq)]
-pub struct ZetaOptions {
-    pub context: ContextMode,
-    pub max_prompt_bytes: usize,
-    pub max_diagnostic_bytes: usize,
-    pub prompt_format: predict_edits_v3::PromptFormat,
-    pub file_indexing_parallelism: usize,
-    pub buffer_change_grouping_interval: Duration,
-}
-
-#[derive(Debug, Clone, PartialEq)]
-pub enum ContextMode {
-    Agentic(AgenticContextOptions),
-    Syntax(EditPredictionContextOptions),
-}
-
-#[derive(Debug, Clone, PartialEq)]
-pub struct AgenticContextOptions {
-    pub excerpt: EditPredictionExcerptOptions,
-}
-
-impl ContextMode {
-    pub fn excerpt(&self) -> &EditPredictionExcerptOptions {
-        match self {
-            ContextMode::Agentic(options) => &options.excerpt,
-            ContextMode::Syntax(options) => &options.excerpt,
-        }
-    }
-}
-
-#[derive(Debug)]
-pub enum ZetaDebugInfo {
-    ContextRetrievalStarted(ZetaContextRetrievalStartedDebugInfo),
-    SearchQueriesGenerated(ZetaSearchQueryDebugInfo),
-    SearchQueriesExecuted(ZetaContextRetrievalDebugInfo),
-    ContextRetrievalFinished(ZetaContextRetrievalDebugInfo),
-    EditPredictionRequested(ZetaEditPredictionDebugInfo),
-}
-
-#[derive(Debug)]
-pub struct ZetaContextRetrievalStartedDebugInfo {
-    pub project: Entity<Project>,
-    pub timestamp: Instant,
-    pub search_prompt: String,
-}
-
-#[derive(Debug)]
-pub struct ZetaContextRetrievalDebugInfo {
-    pub project: Entity<Project>,
-    pub timestamp: Instant,
-}
-
-#[derive(Debug)]
-pub struct ZetaEditPredictionDebugInfo {
-    pub inputs: EditPredictionInputs,
-    pub retrieval_time: Duration,
-    pub buffer: WeakEntity<Buffer>,
-    pub position: language::Anchor,
-    pub local_prompt: Result<String, String>,
-    pub response_rx: oneshot::Receiver<(Result<open_ai::Response, String>, Duration)>,
-}
-
-#[derive(Debug)]
-pub struct ZetaSearchQueryDebugInfo {
-    pub project: Entity<Project>,
-    pub timestamp: Instant,
-    pub search_queries: Vec<SearchToolQuery>,
-}
-
-pub type RequestDebugInfo = predict_edits_v3::DebugInfo;
-
-struct ZetaProject {
-    syntax_index: Option<Entity<SyntaxIndex>>,
-    events: VecDeque<Arc<cloud_llm_client::predict_edits_v3::Event>>,
-    last_event: Option<LastEvent>,
-    recent_paths: VecDeque<ProjectPath>,
-    registered_buffers: HashMap<gpui::EntityId, RegisteredBuffer>,
-    current_prediction: Option<CurrentEditPrediction>,
-    next_pending_prediction_id: usize,
-    pending_predictions: ArrayVec<PendingPrediction, 2>,
-    last_prediction_refresh: Option<(EntityId, Instant)>,
-    cancelled_predictions: HashSet<usize>,
-    context: Option<HashMap<Entity<Buffer>, Vec<Range<Anchor>>>>,
-    refresh_context_task: Option<LogErrorFuture<Task<Result<()>>>>,
-    refresh_context_debounce_task: Option<Task<Option<()>>>,
-    refresh_context_timestamp: Option<Instant>,
-    license_detection_watchers: HashMap<WorktreeId, Rc<LicenseDetectionWatcher>>,
-    _subscription: gpui::Subscription,
-}
-
-impl ZetaProject {
-    pub fn events(&self, cx: &App) -> Vec<Arc<cloud_llm_client::predict_edits_v3::Event>> {
-        self.events
-            .iter()
-            .cloned()
-            .chain(
-                self.last_event
-                    .as_ref()
-                    .and_then(|event| event.finalize(&self.license_detection_watchers, cx)),
-            )
-            .collect()
-    }
-
-    fn cancel_pending_prediction(
-        &mut self,
-        pending_prediction: PendingPrediction,
-        cx: &mut Context<Zeta>,
-    ) {
-        self.cancelled_predictions.insert(pending_prediction.id);
-
-        cx.spawn(async move |this, cx| {
-            let Some(prediction_id) = pending_prediction.task.await else {
-                return;
-            };
-
-            this.update(cx, |this, _cx| {
-                this.reject_prediction(prediction_id, EditPredictionRejectReason::Canceled, false);
-            })
-            .ok();
-        })
-        .detach()
-    }
-}
-
-#[derive(Debug, Clone)]
-struct CurrentEditPrediction {
-    pub requested_by: PredictionRequestedBy,
-    pub prediction: EditPrediction,
-    pub was_shown: bool,
-}
-
-impl CurrentEditPrediction {
-    fn should_replace_prediction(&self, old_prediction: &Self, cx: &App) -> bool {
-        let Some(new_edits) = self
-            .prediction
-            .interpolate(&self.prediction.buffer.read(cx))
-        else {
-            return false;
-        };
-
-        if self.prediction.buffer != old_prediction.prediction.buffer {
-            return true;
-        }
-
-        let Some(old_edits) = old_prediction
-            .prediction
-            .interpolate(&old_prediction.prediction.buffer.read(cx))
-        else {
-            return true;
-        };
-
-        let requested_by_buffer_id = self.requested_by.buffer_id();
-
-        // This reduces the occurrence of UI thrash from replacing edits
-        //
-        // TODO: This is fairly arbitrary - should have a more general heuristic that handles multiple edits.
-        if requested_by_buffer_id == Some(self.prediction.buffer.entity_id())
-            && requested_by_buffer_id == Some(old_prediction.prediction.buffer.entity_id())
-            && old_edits.len() == 1
-            && new_edits.len() == 1
-        {
-            let (old_range, old_text) = &old_edits[0];
-            let (new_range, new_text) = &new_edits[0];
-            new_range == old_range && new_text.starts_with(old_text.as_ref())
-        } else {
-            true
-        }
-    }
-}
-
-#[derive(Debug, Clone)]
-enum PredictionRequestedBy {
-    DiagnosticsUpdate,
-    Buffer(EntityId),
-}
-
-impl PredictionRequestedBy {
-    pub fn buffer_id(&self) -> Option<EntityId> {
-        match self {
-            PredictionRequestedBy::DiagnosticsUpdate => None,
-            PredictionRequestedBy::Buffer(buffer_id) => Some(*buffer_id),
-        }
-    }
-}
-
-#[derive(Debug)]
-struct PendingPrediction {
-    id: usize,
-    task: Task<Option<EditPredictionId>>,
-}
-
-/// A prediction from the perspective of a buffer.
-#[derive(Debug)]
-enum BufferEditPrediction<'a> {
-    Local { prediction: &'a EditPrediction },
-    Jump { prediction: &'a EditPrediction },
-}
-
-#[cfg(test)]
-impl std::ops::Deref for BufferEditPrediction<'_> {
-    type Target = EditPrediction;
-
-    fn deref(&self) -> &Self::Target {
-        match self {
-            BufferEditPrediction::Local { prediction } => prediction,
-            BufferEditPrediction::Jump { prediction } => prediction,
-        }
-    }
-}
-
-struct RegisteredBuffer {
-    snapshot: BufferSnapshot,
-    _subscriptions: [gpui::Subscription; 2],
-}
-
-struct LastEvent {
-    old_snapshot: BufferSnapshot,
-    new_snapshot: BufferSnapshot,
-    end_edit_anchor: Option<Anchor>,
-}
-
-impl LastEvent {
-    pub fn finalize(
-        &self,
-        license_detection_watchers: &HashMap<WorktreeId, Rc<LicenseDetectionWatcher>>,
-        cx: &App,
-    ) -> Option<Arc<predict_edits_v3::Event>> {
-        let path = buffer_path_with_id_fallback(&self.new_snapshot, cx);
-        let old_path = buffer_path_with_id_fallback(&self.old_snapshot, cx);
-
-        let file = self.new_snapshot.file();
-        let old_file = self.old_snapshot.file();
-
-        let in_open_source_repo = [file, old_file].iter().all(|file| {
-            file.is_some_and(|file| {
-                license_detection_watchers
-                    .get(&file.worktree_id(cx))
-                    .is_some_and(|watcher| watcher.is_project_open_source())
-            })
-        });
-
-        let diff = language::unified_diff(&self.old_snapshot.text(), &self.new_snapshot.text());
-
-        if path == old_path && diff.is_empty() {
-            None
-        } else {
-            Some(Arc::new(predict_edits_v3::Event::BufferChange {
-                old_path,
-                path,
-                diff,
-                in_open_source_repo,
-                // TODO: Actually detect if this edit was predicted or not
-                predicted: false,
-            }))
-        }
-    }
-}
-
-fn buffer_path_with_id_fallback(snapshot: &BufferSnapshot, cx: &App) -> Arc<Path> {
-    if let Some(file) = snapshot.file() {
-        file.full_path(cx).into()
-    } else {
-        Path::new(&format!("untitled-{}", snapshot.remote_id())).into()
-    }
-}
-
-impl Zeta {
-    pub fn try_global(cx: &App) -> Option<Entity<Self>> {
-        cx.try_global::<ZetaGlobal>().map(|global| global.0.clone())
-    }
-
-    pub fn global(
-        client: &Arc<Client>,
-        user_store: &Entity<UserStore>,
-        cx: &mut App,
-    ) -> Entity<Self> {
-        cx.try_global::<ZetaGlobal>()
-            .map(|global| global.0.clone())
-            .unwrap_or_else(|| {
-                let zeta = cx.new(|cx| Self::new(client.clone(), user_store.clone(), cx));
-                cx.set_global(ZetaGlobal(zeta.clone()));
-                zeta
-            })
-    }
-
-    pub fn new(client: Arc<Client>, user_store: Entity<UserStore>, cx: &mut Context<Self>) -> Self {
-        let refresh_llm_token_listener = RefreshLlmTokenListener::global(cx);
-        let data_collection_choice = Self::load_data_collection_choice();
-
-        let llm_token = LlmApiToken::default();
-
-        let (reject_tx, reject_rx) = mpsc::unbounded();
-        cx.background_spawn({
-            let client = client.clone();
-            let llm_token = llm_token.clone();
-            let app_version = AppVersion::global(cx);
-            let background_executor = cx.background_executor().clone();
-            async move {
-                Self::handle_rejected_predictions(
-                    reject_rx,
-                    client,
-                    llm_token,
-                    app_version,
-                    background_executor,
-                )
-                .await
-            }
-        })
-        .detach();
-
-        Self {
-            projects: HashMap::default(),
-            client,
-            user_store,
-            options: DEFAULT_OPTIONS,
-            llm_token,
-            _llm_token_subscription: cx.subscribe(
-                &refresh_llm_token_listener,
-                |this, _listener, _event, cx| {
-                    let client = this.client.clone();
-                    let llm_token = this.llm_token.clone();
-                    cx.spawn(async move |_this, _cx| {
-                        llm_token.refresh(&client).await?;
-                        anyhow::Ok(())
-                    })
-                    .detach_and_log_err(cx);
-                },
-            ),
-            update_required: false,
-            debug_tx: None,
-            #[cfg(feature = "eval-support")]
-            eval_cache: None,
-            edit_prediction_model: ZetaEditPredictionModel::Zeta2,
-            sweep_ai: SweepAi::new(cx),
-            data_collection_choice,
-            reject_predictions_tx: reject_tx,
-            rated_predictions: Default::default(),
-            shown_predictions: Default::default(),
-        }
-    }
-
-    pub fn set_edit_prediction_model(&mut self, model: ZetaEditPredictionModel) {
-        self.edit_prediction_model = model;
-    }
-
-    pub fn has_sweep_api_token(&self) -> bool {
-        self.sweep_ai
-            .api_token
-            .clone()
-            .now_or_never()
-            .flatten()
-            .is_some()
-    }
-
-    #[cfg(feature = "eval-support")]
-    pub fn with_eval_cache(&mut self, cache: Arc<dyn EvalCache>) {
-        self.eval_cache = Some(cache);
-    }
-
-    pub fn debug_info(&mut self) -> mpsc::UnboundedReceiver<ZetaDebugInfo> {
-        let (debug_watch_tx, debug_watch_rx) = mpsc::unbounded();
-        self.debug_tx = Some(debug_watch_tx);
-        debug_watch_rx
-    }
-
-    pub fn options(&self) -> &ZetaOptions {
-        &self.options
-    }
-
-    pub fn set_options(&mut self, options: ZetaOptions) {
-        self.options = options;
-    }
-
-    pub fn clear_history(&mut self) {
-        for zeta_project in self.projects.values_mut() {
-            zeta_project.events.clear();
-        }
-    }
-
-    pub fn context_for_project(
-        &self,
-        project: &Entity<Project>,
-    ) -> impl Iterator<Item = (Entity<Buffer>, &[Range<Anchor>])> {
-        self.projects
-            .get(&project.entity_id())
-            .and_then(|project| {
-                Some(
-                    project
-                        .context
-                        .as_ref()?
-                        .iter()
-                        .map(|(buffer, ranges)| (buffer.clone(), ranges.as_slice())),
-                )
-            })
-            .into_iter()
-            .flatten()
-    }
-
-    pub fn usage(&self, cx: &App) -> Option<EditPredictionUsage> {
-        if self.edit_prediction_model == ZetaEditPredictionModel::Zeta2 {
-            self.user_store.read(cx).edit_prediction_usage()
-        } else {
-            None
-        }
-    }
-
-    pub fn register_project(&mut self, project: &Entity<Project>, cx: &mut Context<Self>) {
-        self.get_or_init_zeta_project(project, cx);
-    }
-
-    pub fn register_buffer(
-        &mut self,
-        buffer: &Entity<Buffer>,
-        project: &Entity<Project>,
-        cx: &mut Context<Self>,
-    ) {
-        let zeta_project = self.get_or_init_zeta_project(project, cx);
-        Self::register_buffer_impl(zeta_project, buffer, project, cx);
-    }
-
-    fn get_or_init_zeta_project(
-        &mut self,
-        project: &Entity<Project>,
-        cx: &mut Context<Self>,
-    ) -> &mut ZetaProject {
-        self.projects
-            .entry(project.entity_id())
-            .or_insert_with(|| ZetaProject {
-                syntax_index: if let ContextMode::Syntax(_) = &self.options.context {
-                    Some(cx.new(|cx| {
-                        SyntaxIndex::new(project, self.options.file_indexing_parallelism, cx)
-                    }))
-                } else {
-                    None
-                },
-                events: VecDeque::new(),
-                last_event: None,
-                recent_paths: VecDeque::new(),
-                registered_buffers: HashMap::default(),
-                current_prediction: None,
-                cancelled_predictions: HashSet::default(),
-                pending_predictions: ArrayVec::new(),
-                next_pending_prediction_id: 0,
-                last_prediction_refresh: None,
-                context: None,
-                refresh_context_task: None,
-                refresh_context_debounce_task: None,
-                refresh_context_timestamp: None,
-                license_detection_watchers: HashMap::default(),
-                _subscription: cx.subscribe(&project, Self::handle_project_event),
-            })
-    }
-
-    fn handle_project_event(
-        &mut self,
-        project: Entity<Project>,
-        event: &project::Event,
-        cx: &mut Context<Self>,
-    ) {
-        // TODO [zeta2] init with recent paths
-        match event {
-            project::Event::ActiveEntryChanged(Some(active_entry_id)) => {
-                let Some(zeta_project) = self.projects.get_mut(&project.entity_id()) else {
-                    return;
-                };
-                let path = project.read(cx).path_for_entry(*active_entry_id, cx);
-                if let Some(path) = path {
-                    if let Some(ix) = zeta_project
-                        .recent_paths
-                        .iter()
-                        .position(|probe| probe == &path)
-                    {
-                        zeta_project.recent_paths.remove(ix);
-                    }
-                    zeta_project.recent_paths.push_front(path);
-                }
-            }
-            project::Event::DiagnosticsUpdated { .. } => {
-                if cx.has_flag::<Zeta2FeatureFlag>() {
-                    self.refresh_prediction_from_diagnostics(project, cx);
-                }
-            }
-            _ => (),
-        }
-    }
-
-    fn register_buffer_impl<'a>(
-        zeta_project: &'a mut ZetaProject,
-        buffer: &Entity<Buffer>,
-        project: &Entity<Project>,
-        cx: &mut Context<Self>,
-    ) -> &'a mut RegisteredBuffer {
-        let buffer_id = buffer.entity_id();
-
-        if let Some(file) = buffer.read(cx).file() {
-            let worktree_id = file.worktree_id(cx);
-            if let Some(worktree) = project.read(cx).worktree_for_id(worktree_id, cx) {
-                zeta_project
-                    .license_detection_watchers
-                    .entry(worktree_id)
-                    .or_insert_with(|| {
-                        let project_entity_id = project.entity_id();
-                        cx.observe_release(&worktree, move |this, _worktree, _cx| {
-                            let Some(zeta_project) = this.projects.get_mut(&project_entity_id)
-                            else {
-                                return;
-                            };
-                            zeta_project.license_detection_watchers.remove(&worktree_id);
-                        })
-                        .detach();
-                        Rc::new(LicenseDetectionWatcher::new(&worktree, cx))
-                    });
-            }
-        }
-
-        match zeta_project.registered_buffers.entry(buffer_id) {
-            hash_map::Entry::Occupied(entry) => entry.into_mut(),
-            hash_map::Entry::Vacant(entry) => {
-                let snapshot = buffer.read(cx).snapshot();
-                let project_entity_id = project.entity_id();
-                entry.insert(RegisteredBuffer {
-                    snapshot,
-                    _subscriptions: [
-                        cx.subscribe(buffer, {
-                            let project = project.downgrade();
-                            move |this, buffer, event, cx| {
-                                if let language::BufferEvent::Edited = event
-                                    && let Some(project) = project.upgrade()
-                                {
-                                    this.report_changes_for_buffer(&buffer, &project, cx);
-                                }
-                            }
-                        }),
-                        cx.observe_release(buffer, move |this, _buffer, _cx| {
-                            let Some(zeta_project) = this.projects.get_mut(&project_entity_id)
-                            else {
-                                return;
-                            };
-                            zeta_project.registered_buffers.remove(&buffer_id);
-                        }),
-                    ],
-                })
-            }
-        }
-    }
-
-    fn report_changes_for_buffer(
-        &mut self,
-        buffer: &Entity<Buffer>,
-        project: &Entity<Project>,
-        cx: &mut Context<Self>,
-    ) {
-        let project_state = self.get_or_init_zeta_project(project, cx);
-        let registered_buffer = Self::register_buffer_impl(project_state, buffer, project, cx);
-
-        let new_snapshot = buffer.read(cx).snapshot();
-        if new_snapshot.version == registered_buffer.snapshot.version {
-            return;
-        }
-
-        let old_snapshot = mem::replace(&mut registered_buffer.snapshot, new_snapshot.clone());
-        let end_edit_anchor = new_snapshot
-            .anchored_edits_since::<Point>(&old_snapshot.version)
-            .last()
-            .map(|(_, range)| range.end);
-        let events = &mut project_state.events;
-
-        if let Some(LastEvent {
-            new_snapshot: last_new_snapshot,
-            end_edit_anchor: last_end_edit_anchor,
-            ..
-        }) = project_state.last_event.as_mut()
-        {
-            let is_next_snapshot_of_same_buffer = old_snapshot.remote_id()
-                == last_new_snapshot.remote_id()
-                && old_snapshot.version == last_new_snapshot.version;
-
-            let should_coalesce = is_next_snapshot_of_same_buffer
-                && end_edit_anchor
-                    .as_ref()
-                    .zip(last_end_edit_anchor.as_ref())
-                    .is_some_and(|(a, b)| {
-                        let a = a.to_point(&new_snapshot);
-                        let b = b.to_point(&new_snapshot);
-                        a.row.abs_diff(b.row) <= CHANGE_GROUPING_LINE_SPAN
-                    });
-
-            if should_coalesce {
-                *last_end_edit_anchor = end_edit_anchor;
-                *last_new_snapshot = new_snapshot;
-                return;
-            }
-        }
-
-        if events.len() + 1 >= EVENT_COUNT_MAX {
-            events.pop_front();
-        }
-
-        if let Some(event) = project_state.last_event.take() {
-            events.extend(event.finalize(&project_state.license_detection_watchers, cx));
-        }
-
-        project_state.last_event = Some(LastEvent {
-            old_snapshot,
-            new_snapshot,
-            end_edit_anchor,
-        });
-    }
-
-    fn current_prediction_for_buffer(
-        &self,
-        buffer: &Entity<Buffer>,
-        project: &Entity<Project>,
-        cx: &App,
-    ) -> Option<BufferEditPrediction<'_>> {
-        let project_state = self.projects.get(&project.entity_id())?;
-
-        let CurrentEditPrediction {
-            requested_by,
-            prediction,
-            ..
-        } = project_state.current_prediction.as_ref()?;
-
-        if prediction.targets_buffer(buffer.read(cx)) {
-            Some(BufferEditPrediction::Local { prediction })
-        } else {
-            let show_jump = match requested_by {
-                PredictionRequestedBy::Buffer(requested_by_buffer_id) => {
-                    requested_by_buffer_id == &buffer.entity_id()
-                }
-                PredictionRequestedBy::DiagnosticsUpdate => true,
-            };
-
-            if show_jump {
-                Some(BufferEditPrediction::Jump { prediction })
-            } else {
-                None
-            }
-        }
-    }
-
-    fn accept_current_prediction(&mut self, project: &Entity<Project>, cx: &mut Context<Self>) {
-        match self.edit_prediction_model {
-            ZetaEditPredictionModel::Zeta1 | ZetaEditPredictionModel::Zeta2 => {}
-            ZetaEditPredictionModel::Sweep => return,
-        }
-
-        let Some(project_state) = self.projects.get_mut(&project.entity_id()) else {
-            return;
-        };
-
-        let Some(prediction) = project_state.current_prediction.take() else {
-            return;
-        };
-        let request_id = prediction.prediction.id.to_string();
-        for pending_prediction in mem::take(&mut project_state.pending_predictions) {
-            project_state.cancel_pending_prediction(pending_prediction, cx);
-        }
-
-        let client = self.client.clone();
-        let llm_token = self.llm_token.clone();
-        let app_version = AppVersion::global(cx);
-        cx.spawn(async move |this, cx| {
-            let url = if let Ok(predict_edits_url) = env::var("ZED_ACCEPT_PREDICTION_URL") {
-                http_client::Url::parse(&predict_edits_url)?
-            } else {
-                client
-                    .http_client()
-                    .build_zed_llm_url("/predict_edits/accept", &[])?
-            };
-
-            let response = cx
-                .background_spawn(Self::send_api_request::<()>(
-                    move |builder| {
-                        let req = builder.uri(url.as_ref()).body(
-                            serde_json::to_string(&AcceptEditPredictionBody {
-                                request_id: request_id.clone(),
-                            })?
-                            .into(),
-                        );
-                        Ok(req?)
-                    },
-                    client,
-                    llm_token,
-                    app_version,
-                ))
-                .await;
-
-            Self::handle_api_response(&this, response, cx)?;
-            anyhow::Ok(())
-        })
-        .detach_and_log_err(cx);
-    }
-
-    async fn handle_rejected_predictions(
-        rx: UnboundedReceiver<EditPredictionRejection>,
-        client: Arc<Client>,
-        llm_token: LlmApiToken,
-        app_version: Version,
-        background_executor: BackgroundExecutor,
-    ) {
-        let mut rx = std::pin::pin!(rx.peekable());
-        let mut batched = Vec::new();
-
-        while let Some(rejection) = rx.next().await {
-            batched.push(rejection);
-
-            if batched.len() < MAX_EDIT_PREDICTION_REJECTIONS_PER_REQUEST / 2 {
-                select_biased! {
-                    next = rx.as_mut().peek().fuse() => {
-                        if next.is_some() {
-                            continue;
-                        }
-                    }
-                    () = background_executor.timer(REJECT_REQUEST_DEBOUNCE).fuse() => {},
-                }
-            }
-
-            let url = client
-                .http_client()
-                .build_zed_llm_url("/predict_edits/reject", &[])
-                .unwrap();
-
-            let flush_count = batched
-                .len()
-                // in case items have accumulated after failure
-                .min(MAX_EDIT_PREDICTION_REJECTIONS_PER_REQUEST);
-            let start = batched.len() - flush_count;
-
-            let body = RejectEditPredictionsBodyRef {
-                rejections: &batched[start..],
-            };
-
-            let result = Self::send_api_request::<()>(
-                |builder| {
-                    let req = builder
-                        .uri(url.as_ref())
-                        .body(serde_json::to_string(&body)?.into());
-                    anyhow::Ok(req?)
-                },
-                client.clone(),
-                llm_token.clone(),
-                app_version.clone(),
-            )
-            .await;
-
-            if result.log_err().is_some() {
-                batched.drain(start..);
-            }
-        }
-    }
-
-    fn reject_current_prediction(
-        &mut self,
-        reason: EditPredictionRejectReason,
-        project: &Entity<Project>,
-    ) {
-        if let Some(project_state) = self.projects.get_mut(&project.entity_id()) {
-            project_state.pending_predictions.clear();
-            if let Some(prediction) = project_state.current_prediction.take() {
-                self.reject_prediction(prediction.prediction.id, reason, prediction.was_shown);
-            }
-        };
-    }
-
-    fn did_show_current_prediction(&mut self, project: &Entity<Project>, _cx: &mut Context<Self>) {
-        if let Some(project_state) = self.projects.get_mut(&project.entity_id()) {
-            if let Some(current_prediction) = project_state.current_prediction.as_mut() {
-                if !current_prediction.was_shown {
-                    current_prediction.was_shown = true;
-                    self.shown_predictions
-                        .push_front(current_prediction.prediction.clone());
-                    if self.shown_predictions.len() > 50 {
-                        let completion = self.shown_predictions.pop_back().unwrap();
-                        self.rated_predictions.remove(&completion.id);
-                    }
-                }
-            }
-        }
-    }
-
-    fn reject_prediction(
-        &mut self,
-        prediction_id: EditPredictionId,
-        reason: EditPredictionRejectReason,
-        was_shown: bool,
-    ) {
-        self.reject_predictions_tx
-            .unbounded_send(EditPredictionRejection {
-                request_id: prediction_id.to_string(),
-                reason,
-                was_shown,
-            })
-            .log_err();
-    }
-
-    fn is_refreshing(&self, project: &Entity<Project>) -> bool {
-        self.projects
-            .get(&project.entity_id())
-            .is_some_and(|project_state| !project_state.pending_predictions.is_empty())
-    }
-
-    pub fn refresh_prediction_from_buffer(
-        &mut self,
-        project: Entity<Project>,
-        buffer: Entity<Buffer>,
-        position: language::Anchor,
-        cx: &mut Context<Self>,
-    ) {
-        self.queue_prediction_refresh(project.clone(), buffer.entity_id(), cx, move |this, cx| {
-            let Some(request_task) = this
-                .update(cx, |this, cx| {
-                    this.request_prediction(
-                        &project,
-                        &buffer,
-                        position,
-                        PredictEditsRequestTrigger::Other,
-                        cx,
-                    )
-                })
-                .log_err()
-            else {
-                return Task::ready(anyhow::Ok(None));
-            };
-
-            cx.spawn(async move |_cx| {
-                request_task.await.map(|prediction_result| {
-                    prediction_result.map(|prediction_result| {
-                        (
-                            prediction_result,
-                            PredictionRequestedBy::Buffer(buffer.entity_id()),
-                        )
-                    })
-                })
-            })
-        })
-    }
-
-    pub fn refresh_prediction_from_diagnostics(
-        &mut self,
-        project: Entity<Project>,
-        cx: &mut Context<Self>,
-    ) {
-        let Some(zeta_project) = self.projects.get_mut(&project.entity_id()) else {
-            return;
-        };
-
-        // Prefer predictions from buffer
-        if zeta_project.current_prediction.is_some() {
-            return;
-        };
-
-        self.queue_prediction_refresh(project.clone(), project.entity_id(), cx, move |this, cx| {
-            let Some(open_buffer_task) = project
-                .update(cx, |project, cx| {
-                    project
-                        .active_entry()
-                        .and_then(|entry| project.path_for_entry(entry, cx))
-                        .map(|path| project.open_buffer(path, cx))
-                })
-                .log_err()
-                .flatten()
-            else {
-                return Task::ready(anyhow::Ok(None));
-            };
-
-            cx.spawn(async move |cx| {
-                let active_buffer = open_buffer_task.await?;
-                let snapshot = active_buffer.read_with(cx, |buffer, _cx| buffer.snapshot())?;
-
-                let Some((jump_buffer, jump_position)) = Self::next_diagnostic_location(
-                    active_buffer,
-                    &snapshot,
-                    Default::default(),
-                    Default::default(),
-                    &project,
-                    cx,
-                )
-                .await?
-                else {
-                    return anyhow::Ok(None);
-                };
-
-                let Some(prediction_result) = this
-                    .update(cx, |this, cx| {
-                        this.request_prediction(
-                            &project,
-                            &jump_buffer,
-                            jump_position,
-                            PredictEditsRequestTrigger::Diagnostics,
-                            cx,
-                        )
-                    })?
-                    .await?
-                else {
-                    return anyhow::Ok(None);
-                };
-
-                this.update(cx, |this, cx| {
-                    Some((
-                        if this
-                            .get_or_init_zeta_project(&project, cx)
-                            .current_prediction
-                            .is_none()
-                        {
-                            prediction_result
-                        } else {
-                            EditPredictionResult {
-                                id: prediction_result.id,
-                                prediction: Err(EditPredictionRejectReason::CurrentPreferred),
-                            }
-                        },
-                        PredictionRequestedBy::DiagnosticsUpdate,
-                    ))
-                })
-            })
-        });
-    }
-
-    #[cfg(not(test))]
-    pub const THROTTLE_TIMEOUT: Duration = Duration::from_millis(300);
-    #[cfg(test)]
-    pub const THROTTLE_TIMEOUT: Duration = Duration::ZERO;
-
-    fn queue_prediction_refresh(
-        &mut self,
-        project: Entity<Project>,
-        throttle_entity: EntityId,
-        cx: &mut Context<Self>,
-        do_refresh: impl FnOnce(
-            WeakEntity<Self>,
-            &mut AsyncApp,
-        )
-            -> Task<Result<Option<(EditPredictionResult, PredictionRequestedBy)>>>
-        + 'static,
-    ) {
-        let zeta_project = self.get_or_init_zeta_project(&project, cx);
-        let pending_prediction_id = zeta_project.next_pending_prediction_id;
-        zeta_project.next_pending_prediction_id += 1;
-        let last_request = zeta_project.last_prediction_refresh;
-
-        let task = cx.spawn(async move |this, cx| {
-            if let Some((last_entity, last_timestamp)) = last_request
-                && throttle_entity == last_entity
-                && let Some(timeout) =
-                    (last_timestamp + Self::THROTTLE_TIMEOUT).checked_duration_since(Instant::now())
-            {
-                cx.background_executor().timer(timeout).await;
-            }
-
-            // If this task was cancelled before the throttle timeout expired,
-            // do not perform a request.
-            let mut is_cancelled = true;
-            this.update(cx, |this, cx| {
-                let project_state = this.get_or_init_zeta_project(&project, cx);
-                if !project_state
-                    .cancelled_predictions
-                    .remove(&pending_prediction_id)
-                {
-                    project_state.last_prediction_refresh = Some((throttle_entity, Instant::now()));
-                    is_cancelled = false;
-                }
-            })
-            .ok();
-            if is_cancelled {
-                return None;
-            }
-
-            let new_prediction_result = do_refresh(this.clone(), cx).await.log_err().flatten();
-            let new_prediction_id = new_prediction_result
-                .as_ref()
-                .map(|(prediction, _)| prediction.id.clone());
-
-            // When a prediction completes, remove it from the pending list, and cancel
-            // any pending predictions that were enqueued before it.
-            this.update(cx, |this, cx| {
-                let zeta_project = this.get_or_init_zeta_project(&project, cx);
-
-                let is_cancelled = zeta_project
-                    .cancelled_predictions
-                    .remove(&pending_prediction_id);
-
-                let new_current_prediction = if !is_cancelled
-                    && let Some((prediction_result, requested_by)) = new_prediction_result
-                {
-                    match prediction_result.prediction {
-                        Ok(prediction) => {
-                            let new_prediction = CurrentEditPrediction {
-                                requested_by,
-                                prediction,
-                                was_shown: false,
-                            };
-
-                            if let Some(current_prediction) =
-                                zeta_project.current_prediction.as_ref()
-                            {
-                                if new_prediction.should_replace_prediction(&current_prediction, cx)
-                                {
-                                    this.reject_current_prediction(
-                                        EditPredictionRejectReason::Replaced,
-                                        &project,
-                                    );
-
-                                    Some(new_prediction)
-                                } else {
-                                    this.reject_prediction(
-                                        new_prediction.prediction.id,
-                                        EditPredictionRejectReason::CurrentPreferred,
-                                        false,
-                                    );
-                                    None
-                                }
-                            } else {
-                                Some(new_prediction)
-                            }
-                        }
-                        Err(reject_reason) => {
-                            this.reject_prediction(prediction_result.id, reject_reason, false);
-                            None
-                        }
-                    }
-                } else {
-                    None
-                };
-
-                let zeta_project = this.get_or_init_zeta_project(&project, cx);
-
-                if let Some(new_prediction) = new_current_prediction {
-                    zeta_project.current_prediction = Some(new_prediction);
-                }
-
-                let mut pending_predictions = mem::take(&mut zeta_project.pending_predictions);
-                for (ix, pending_prediction) in pending_predictions.iter().enumerate() {
-                    if pending_prediction.id == pending_prediction_id {
-                        pending_predictions.remove(ix);
-                        for pending_prediction in pending_predictions.drain(0..ix) {
-                            zeta_project.cancel_pending_prediction(pending_prediction, cx)
-                        }
-                        break;
-                    }
-                }
-                this.get_or_init_zeta_project(&project, cx)
-                    .pending_predictions = pending_predictions;
-                cx.notify();
-            })
-            .ok();
-
-            new_prediction_id
-        });
-
-        if zeta_project.pending_predictions.len() <= 1 {
-            zeta_project.pending_predictions.push(PendingPrediction {
-                id: pending_prediction_id,
-                task,
-            });
-        } else if zeta_project.pending_predictions.len() == 2 {
-            let pending_prediction = zeta_project.pending_predictions.pop().unwrap();
-            zeta_project.pending_predictions.push(PendingPrediction {
-                id: pending_prediction_id,
-                task,
-            });
-            zeta_project.cancel_pending_prediction(pending_prediction, cx);
-        }
-    }
-
-    pub fn request_prediction(
-        &mut self,
-        project: &Entity<Project>,
-        active_buffer: &Entity<Buffer>,
-        position: language::Anchor,
-        trigger: PredictEditsRequestTrigger,
-        cx: &mut Context<Self>,
-    ) -> Task<Result<Option<EditPredictionResult>>> {
-        self.request_prediction_internal(
-            project.clone(),
-            active_buffer.clone(),
-            position,
-            trigger,
-            cx.has_flag::<Zeta2FeatureFlag>(),
-            cx,
-        )
-    }
-
-    fn request_prediction_internal(
-        &mut self,
-        project: Entity<Project>,
-        active_buffer: Entity<Buffer>,
-        position: language::Anchor,
-        trigger: PredictEditsRequestTrigger,
-        allow_jump: bool,
-        cx: &mut Context<Self>,
-    ) -> Task<Result<Option<EditPredictionResult>>> {
-        const DIAGNOSTIC_LINES_RANGE: u32 = 20;
-
-        self.get_or_init_zeta_project(&project, cx);
-        let zeta_project = self.projects.get(&project.entity_id()).unwrap();
-        let events = zeta_project.events(cx);
-        let has_events = !events.is_empty();
-
-        let snapshot = active_buffer.read(cx).snapshot();
-        let cursor_point = position.to_point(&snapshot);
-        let diagnostic_search_start = cursor_point.row.saturating_sub(DIAGNOSTIC_LINES_RANGE);
-        let diagnostic_search_end = cursor_point.row + DIAGNOSTIC_LINES_RANGE;
-        let diagnostic_search_range =
-            Point::new(diagnostic_search_start, 0)..Point::new(diagnostic_search_end, 0);
-
-        let task = match self.edit_prediction_model {
-            ZetaEditPredictionModel::Zeta1 => request_prediction_with_zeta1(
-                self,
-                &project,
-                &active_buffer,
-                snapshot.clone(),
-                position,
-                events,
-                trigger,
-                cx,
-            ),
-            ZetaEditPredictionModel::Zeta2 => self.request_prediction_with_zeta2(
-                &project,
-                &active_buffer,
-                snapshot.clone(),
-                position,
-                events,
-                trigger,
-                cx,
-            ),
-            ZetaEditPredictionModel::Sweep => self.sweep_ai.request_prediction_with_sweep(
-                &project,
-                &active_buffer,
-                snapshot.clone(),
-                position,
-                events,
-                &zeta_project.recent_paths,
-                diagnostic_search_range.clone(),
-                cx,
-            ),
-        };
-
-        cx.spawn(async move |this, cx| {
-            let prediction = task.await?;
-
-            if prediction.is_none() && allow_jump {
-                let cursor_point = position.to_point(&snapshot);
-                if has_events
-                    && let Some((jump_buffer, jump_position)) = Self::next_diagnostic_location(
-                        active_buffer.clone(),
-                        &snapshot,
-                        diagnostic_search_range,
-                        cursor_point,
-                        &project,
-                        cx,
-                    )
-                    .await?
-                {
-                    return this
-                        .update(cx, |this, cx| {
-                            this.request_prediction_internal(
-                                project,
-                                jump_buffer,
-                                jump_position,
-                                trigger,
-                                false,
-                                cx,
-                            )
-                        })?
-                        .await;
-                }
-
-                return anyhow::Ok(None);
-            }
-
-            Ok(prediction)
-        })
-    }
-
-    async fn next_diagnostic_location(
-        active_buffer: Entity<Buffer>,
-        active_buffer_snapshot: &BufferSnapshot,
-        active_buffer_diagnostic_search_range: Range<Point>,
-        active_buffer_cursor_point: Point,
-        project: &Entity<Project>,
-        cx: &mut AsyncApp,
-    ) -> Result<Option<(Entity<Buffer>, language::Anchor)>> {
-        // find the closest diagnostic to the cursor that wasn't close enough to be included in the last request
-        let mut jump_location = active_buffer_snapshot
-            .diagnostic_groups(None)
-            .into_iter()
-            .filter_map(|(_, group)| {
-                let range = &group.entries[group.primary_ix]
-                    .range
-                    .to_point(&active_buffer_snapshot);
-                if range.overlaps(&active_buffer_diagnostic_search_range) {
-                    None
-                } else {
-                    Some(range.start)
-                }
-            })
-            .min_by_key(|probe| probe.row.abs_diff(active_buffer_cursor_point.row))
-            .map(|position| {
-                (
-                    active_buffer.clone(),
-                    active_buffer_snapshot.anchor_before(position),
-                )
-            });
-
-        if jump_location.is_none() {
-            let active_buffer_path = active_buffer.read_with(cx, |buffer, cx| {
-                let file = buffer.file()?;
-
-                Some(ProjectPath {
-                    worktree_id: file.worktree_id(cx),
-                    path: file.path().clone(),
-                })
-            })?;
-
-            let buffer_task = project.update(cx, |project, cx| {
-                let (path, _, _) = project
-                    .diagnostic_summaries(false, cx)
-                    .filter(|(path, _, _)| Some(path) != active_buffer_path.as_ref())
-                    .max_by_key(|(path, _, _)| {
-                        // find the buffer with errors that shares most parent directories
-                        path.path
-                            .components()
-                            .zip(
-                                active_buffer_path
-                                    .as_ref()
-                                    .map(|p| p.path.components())
-                                    .unwrap_or_default(),
-                            )
-                            .take_while(|(a, b)| a == b)
-                            .count()
-                    })?;
-
-                Some(project.open_buffer(path, cx))
-            })?;
-
-            if let Some(buffer_task) = buffer_task {
-                let closest_buffer = buffer_task.await?;
-
-                jump_location = closest_buffer
-                    .read_with(cx, |buffer, _cx| {
-                        buffer
-                            .buffer_diagnostics(None)
-                            .into_iter()
-                            .min_by_key(|entry| entry.diagnostic.severity)
-                            .map(|entry| entry.range.start)
-                    })?
-                    .map(|position| (closest_buffer, position));
-            }
-        }
-
-        anyhow::Ok(jump_location)
-    }
-
-    fn request_prediction_with_zeta2(
-        &mut self,
-        project: &Entity<Project>,
-        active_buffer: &Entity<Buffer>,
-        active_snapshot: BufferSnapshot,
-        position: language::Anchor,
-        events: Vec<Arc<Event>>,
-        trigger: PredictEditsRequestTrigger,
-        cx: &mut Context<Self>,
-    ) -> Task<Result<Option<EditPredictionResult>>> {
-        let project_state = self.projects.get(&project.entity_id());
-
-        let index_state = project_state.and_then(|state| {
-            state
-                .syntax_index
-                .as_ref()
-                .map(|syntax_index| syntax_index.read_with(cx, |index, _cx| index.state().clone()))
-        });
-        let options = self.options.clone();
-        let buffer_snapshotted_at = Instant::now();
-        let Some(excerpt_path) = active_snapshot
-            .file()
-            .map(|path| -> Arc<Path> { path.full_path(cx).into() })
-        else {
-            return Task::ready(Err(anyhow!("No file path for excerpt")));
-        };
-        let client = self.client.clone();
-        let llm_token = self.llm_token.clone();
-        let app_version = AppVersion::global(cx);
-        let worktree_snapshots = project
-            .read(cx)
-            .worktrees(cx)
-            .map(|worktree| worktree.read(cx).snapshot())
-            .collect::<Vec<_>>();
-        let debug_tx = self.debug_tx.clone();
-
-        let diagnostics = active_snapshot.diagnostic_sets().clone();
-
-        let file = active_buffer.read(cx).file();
-        let parent_abs_path = project::File::from_dyn(file).and_then(|f| {
-            let mut path = f.worktree.read(cx).absolutize(&f.path);
-            if path.pop() { Some(path) } else { None }
-        });
-
-        // TODO data collection
-        let can_collect_data = file
-            .as_ref()
-            .map_or(false, |file| self.can_collect_file(project, file, cx));
-
-        let empty_context_files = HashMap::default();
-        let context_files = project_state
-            .and_then(|project_state| project_state.context.as_ref())
-            .unwrap_or(&empty_context_files);
-
-        #[cfg(feature = "eval-support")]
-        let parsed_fut = futures::future::join_all(
-            context_files
-                .keys()
-                .map(|buffer| buffer.read(cx).parsing_idle()),
-        );
-
-        let mut included_files = context_files
-            .iter()
-            .filter_map(|(buffer_entity, ranges)| {
-                let buffer = buffer_entity.read(cx);
-                Some((
-                    buffer_entity.clone(),
-                    buffer.snapshot(),
-                    buffer.file()?.full_path(cx).into(),
-                    ranges.clone(),
-                ))
-            })
-            .collect::<Vec<_>>();
-
-        included_files.sort_by(|(_, _, path_a, ranges_a), (_, _, path_b, ranges_b)| {
-            (path_a, ranges_a.len()).cmp(&(path_b, ranges_b.len()))
-        });
-
-        #[cfg(feature = "eval-support")]
-        let eval_cache = self.eval_cache.clone();
-
-        let request_task = cx.background_spawn({
-            let active_buffer = active_buffer.clone();
-            async move {
-                #[cfg(feature = "eval-support")]
-                parsed_fut.await;
-
-                let index_state = if let Some(index_state) = index_state {
-                    Some(index_state.lock_owned().await)
-                } else {
-                    None
-                };
-
-                let cursor_offset = position.to_offset(&active_snapshot);
-                let cursor_point = cursor_offset.to_point(&active_snapshot);
-
-                let before_retrieval = Instant::now();
-
-                let (diagnostic_groups, diagnostic_groups_truncated) =
-                    Self::gather_nearby_diagnostics(
-                        cursor_offset,
-                        &diagnostics,
-                        &active_snapshot,
-                        options.max_diagnostic_bytes,
-                    );
-
-                let cloud_request = match options.context {
-                    ContextMode::Agentic(context_options) => {
-                        let Some(excerpt) = EditPredictionExcerpt::select_from_buffer(
-                            cursor_point,
-                            &active_snapshot,
-                            &context_options.excerpt,
-                            index_state.as_deref(),
-                        ) else {
-                            return Ok((None, None));
-                        };
-
-                        let excerpt_anchor_range = active_snapshot.anchor_after(excerpt.range.start)
-                            ..active_snapshot.anchor_before(excerpt.range.end);
-
-                        if let Some(buffer_ix) =
-                            included_files.iter().position(|(_, snapshot, _, _)| {
-                                snapshot.remote_id() == active_snapshot.remote_id()
-                            })
-                        {
-                            let (_, buffer, _, ranges) = &mut included_files[buffer_ix];
-                            ranges.push(excerpt_anchor_range);
-                            retrieval_search::merge_anchor_ranges(ranges, buffer);
-                            let last_ix = included_files.len() - 1;
-                            included_files.swap(buffer_ix, last_ix);
-                        } else {
-                            included_files.push((
-                                active_buffer.clone(),
-                                active_snapshot.clone(),
-                                excerpt_path.clone(),
-                                vec![excerpt_anchor_range],
-                            ));
-                        }
-
-                        let included_files = included_files
-                            .iter()
-                            .map(|(_, snapshot, path, ranges)| {
-                                let ranges = ranges
-                                    .iter()
-                                    .map(|range| {
-                                        let point_range = range.to_point(&snapshot);
-                                        Line(point_range.start.row)..Line(point_range.end.row)
-                                    })
-                                    .collect::<Vec<_>>();
-                                let excerpts = assemble_excerpts(&snapshot, ranges);
-                                predict_edits_v3::IncludedFile {
-                                    path: path.clone(),
-                                    max_row: Line(snapshot.max_point().row),
-                                    excerpts,
-                                }
-                            })
-                            .collect::<Vec<_>>();
-
-                        predict_edits_v3::PredictEditsRequest {
-                            excerpt_path,
-                            excerpt: String::new(),
-                            excerpt_line_range: Line(0)..Line(0),
-                            excerpt_range: 0..0,
-                            cursor_point: predict_edits_v3::Point {
-                                line: predict_edits_v3::Line(cursor_point.row),
-                                column: cursor_point.column,
-                            },
-                            included_files,
-                            referenced_declarations: vec![],
-                            events,
-                            can_collect_data,
-                            diagnostic_groups,
-                            diagnostic_groups_truncated,
-                            debug_info: debug_tx.is_some(),
-                            prompt_max_bytes: Some(options.max_prompt_bytes),
-                            prompt_format: options.prompt_format,
-                            // TODO [zeta2]
-                            signatures: vec![],
-                            excerpt_parent: None,
-                            git_info: None,
-                            trigger,
-                        }
-                    }
-                    ContextMode::Syntax(context_options) => {
-                        let Some(context) = EditPredictionContext::gather_context(
-                            cursor_point,
-                            &active_snapshot,
-                            parent_abs_path.as_deref(),
-                            &context_options,
-                            index_state.as_deref(),
-                        ) else {
-                            return Ok((None, None));
-                        };
-
-                        make_syntax_context_cloud_request(
-                            excerpt_path,
-                            context,
-                            events,
-                            can_collect_data,
-                            diagnostic_groups,
-                            diagnostic_groups_truncated,
-                            None,
-                            debug_tx.is_some(),
-                            &worktree_snapshots,
-                            index_state.as_deref(),
-                            Some(options.max_prompt_bytes),
-                            options.prompt_format,
-                            trigger,
-                        )
-                    }
-                };
-
-                let prompt_result = cloud_zeta2_prompt::build_prompt(&cloud_request);
-
-                let inputs = EditPredictionInputs {
-                    included_files: cloud_request.included_files,
-                    events: cloud_request.events,
-                    cursor_point: cloud_request.cursor_point,
-                    cursor_path: cloud_request.excerpt_path,
-                };
-
-                let retrieval_time = Instant::now() - before_retrieval;
-
-                let debug_response_tx = if let Some(debug_tx) = &debug_tx {
-                    let (response_tx, response_rx) = oneshot::channel();
-
-                    debug_tx
-                        .unbounded_send(ZetaDebugInfo::EditPredictionRequested(
-                            ZetaEditPredictionDebugInfo {
-                                inputs: inputs.clone(),
-                                retrieval_time,
-                                buffer: active_buffer.downgrade(),
-                                local_prompt: match prompt_result.as_ref() {
-                                    Ok((prompt, _)) => Ok(prompt.clone()),
-                                    Err(err) => Err(err.to_string()),
-                                },
-                                position,
-                                response_rx,
-                            },
-                        ))
-                        .ok();
-                    Some(response_tx)
-                } else {
-                    None
-                };
-
-                if cfg!(debug_assertions) && env::var("ZED_ZETA2_SKIP_REQUEST").is_ok() {
-                    if let Some(debug_response_tx) = debug_response_tx {
-                        debug_response_tx
-                            .send((Err("Request skipped".to_string()), Duration::ZERO))
-                            .ok();
-                    }
-                    anyhow::bail!("Skipping request because ZED_ZETA2_SKIP_REQUEST is set")
-                }
-
-                let (prompt, _) = prompt_result?;
-                let generation_params =
-                    cloud_zeta2_prompt::generation_params(cloud_request.prompt_format);
-                let request = open_ai::Request {
-                    model: EDIT_PREDICTIONS_MODEL_ID.clone(),
-                    messages: vec![open_ai::RequestMessage::User {
-                        content: open_ai::MessageContent::Plain(prompt),
-                    }],
-                    stream: false,
-                    max_completion_tokens: None,
-                    stop: generation_params.stop.unwrap_or_default(),
-                    temperature: generation_params.temperature.unwrap_or(0.7),
-                    tool_choice: None,
-                    parallel_tool_calls: None,
-                    tools: vec![],
-                    prompt_cache_key: None,
-                    reasoning_effort: None,
-                };
-
-                log::trace!("Sending edit prediction request");
-
-                let before_request = Instant::now();
-                let response = Self::send_raw_llm_request(
-                    request,
-                    client,
-                    llm_token,
-                    app_version,
-                    #[cfg(feature = "eval-support")]
-                    eval_cache,
-                    #[cfg(feature = "eval-support")]
-                    EvalCacheEntryKind::Prediction,
-                )
-                .await;
-                let received_response_at = Instant::now();
-                let request_time = received_response_at - before_request;
-
-                log::trace!("Got edit prediction response");
-
-                if let Some(debug_response_tx) = debug_response_tx {
-                    debug_response_tx
-                        .send((
-                            response
-                                .as_ref()
-                                .map_err(|err| err.to_string())
-                                .map(|response| response.0.clone()),
-                            request_time,
-                        ))
-                        .ok();
-                }
-
-                let (res, usage) = response?;
-                let request_id = EditPredictionId(res.id.clone().into());
-                let Some(mut output_text) = text_from_response(res) else {
-                    return Ok((Some((request_id, None)), usage));
-                };
-
-                if output_text.contains(CURSOR_MARKER) {
-                    log::trace!("Stripping out {CURSOR_MARKER} from response");
-                    output_text = output_text.replace(CURSOR_MARKER, "");
-                }
-
-                let get_buffer_from_context = |path: &Path| {
-                    included_files
-                        .iter()
-                        .find_map(|(_, buffer, probe_path, ranges)| {
-                            if probe_path.as_ref() == path {
-                                Some((buffer, ranges.as_slice()))
-                            } else {
-                                None
-                            }
-                        })
-                };
-
-                let (edited_buffer_snapshot, edits) = match options.prompt_format {
-                    PromptFormat::NumLinesUniDiff => {
-                        // TODO: Implement parsing of multi-file diffs
-                        crate::udiff::parse_diff(&output_text, get_buffer_from_context).await?
-                    }
-                    PromptFormat::Minimal
-                    | PromptFormat::MinimalQwen
-                    | PromptFormat::SeedCoder1120 => {
-                        if output_text.contains("--- a/\n+++ b/\nNo edits") {
-                            let edits = vec![];
-                            (&active_snapshot, edits)
-                        } else {
-                            crate::udiff::parse_diff(&output_text, get_buffer_from_context).await?
-                        }
-                    }
-                    PromptFormat::OldTextNewText => {
-                        crate::xml_edits::parse_xml_edits(&output_text, get_buffer_from_context)
-                            .await?
-                    }
-                    _ => {
-                        bail!("unsupported prompt format {}", options.prompt_format)
-                    }
-                };
-
-                let edited_buffer = included_files
-                    .iter()
-                    .find_map(|(buffer, snapshot, _, _)| {
-                        if snapshot.remote_id() == edited_buffer_snapshot.remote_id() {
-                            Some(buffer.clone())
-                        } else {
-                            None
-                        }
-                    })
-                    .context("Failed to find buffer in included_buffers")?;
-
-                anyhow::Ok((
-                    Some((
-                        request_id,
-                        Some((
-                            inputs,
-                            edited_buffer,
-                            edited_buffer_snapshot.clone(),
-                            edits,
-                            received_response_at,
-                        )),
-                    )),
-                    usage,
-                ))
-            }
-        });
-
-        cx.spawn({
-            async move |this, cx| {
-                let Some((id, prediction)) =
-                    Self::handle_api_response(&this, request_task.await, cx)?
-                else {
-                    return Ok(None);
-                };
-
-                let Some((
-                    inputs,
-                    edited_buffer,
-                    edited_buffer_snapshot,
-                    edits,
-                    received_response_at,
-                )) = prediction
-                else {
-                    return Ok(Some(EditPredictionResult {
-                        id,
-                        prediction: Err(EditPredictionRejectReason::Empty),
-                    }));
-                };
-
-                // TODO telemetry: duration, etc
-                Ok(Some(
-                    EditPredictionResult::new(
-                        id,
-                        &edited_buffer,
-                        &edited_buffer_snapshot,
-                        edits.into(),
-                        buffer_snapshotted_at,
-                        received_response_at,
-                        inputs,
-                        cx,
-                    )
-                    .await,
-                ))
-            }
-        })
-    }
-
-    async fn send_raw_llm_request(
-        request: open_ai::Request,
-        client: Arc<Client>,
-        llm_token: LlmApiToken,
-        app_version: Version,
-        #[cfg(feature = "eval-support")] eval_cache: Option<Arc<dyn EvalCache>>,
-        #[cfg(feature = "eval-support")] eval_cache_kind: EvalCacheEntryKind,
-    ) -> Result<(open_ai::Response, Option<EditPredictionUsage>)> {
-        let url = if let Some(predict_edits_url) = PREDICT_EDITS_URL.as_ref() {
-            http_client::Url::parse(&predict_edits_url)?
-        } else {
-            client
-                .http_client()
-                .build_zed_llm_url("/predict_edits/raw", &[])?
-        };
-
-        #[cfg(feature = "eval-support")]
-        let cache_key = if let Some(cache) = eval_cache {
-            use collections::FxHasher;
-            use std::hash::{Hash, Hasher};
-
-            let mut hasher = FxHasher::default();
-            url.hash(&mut hasher);
-            let request_str = serde_json::to_string_pretty(&request)?;
-            request_str.hash(&mut hasher);
-            let hash = hasher.finish();
-
-            let key = (eval_cache_kind, hash);
-            if let Some(response_str) = cache.read(key) {
-                return Ok((serde_json::from_str(&response_str)?, None));
-            }
-
-            Some((cache, request_str, key))
-        } else {
-            None
-        };
-
-        let (response, usage) = Self::send_api_request(
-            |builder| {
-                let req = builder
-                    .uri(url.as_ref())
-                    .body(serde_json::to_string(&request)?.into());
-                Ok(req?)
-            },
-            client,
-            llm_token,
-            app_version,
-        )
-        .await?;
-
-        #[cfg(feature = "eval-support")]
-        if let Some((cache, request, key)) = cache_key {
-            cache.write(key, &request, &serde_json::to_string_pretty(&response)?);
-        }
-
-        Ok((response, usage))
-    }
-
-    fn handle_api_response<T>(
-        this: &WeakEntity<Self>,
-        response: Result<(T, Option<EditPredictionUsage>)>,
-        cx: &mut gpui::AsyncApp,
-    ) -> Result<T> {
-        match response {
-            Ok((data, usage)) => {
-                if let Some(usage) = usage {
-                    this.update(cx, |this, cx| {
-                        this.user_store.update(cx, |user_store, cx| {
-                            user_store.update_edit_prediction_usage(usage, cx);
-                        });
-                    })
-                    .ok();
-                }
-                Ok(data)
-            }
-            Err(err) => {
-                if err.is::<ZedUpdateRequiredError>() {
-                    cx.update(|cx| {
-                        this.update(cx, |this, _cx| {
-                            this.update_required = true;
-                        })
-                        .ok();
-
-                        let error_message: SharedString = err.to_string().into();
-                        show_app_notification(
-                            NotificationId::unique::<ZedUpdateRequiredError>(),
-                            cx,
-                            move |cx| {
-                                cx.new(|cx| {
-                                    ErrorMessagePrompt::new(error_message.clone(), cx)
-                                        .with_link_button("Update Zed", "https://zed.dev/releases")
-                                })
-                            },
-                        );
-                    })
-                    .ok();
-                }
-                Err(err)
-            }
-        }
-    }
-
-    async fn send_api_request<Res>(
-        build: impl Fn(http_client::http::request::Builder) -> Result<http_client::Request<AsyncBody>>,
-        client: Arc<Client>,
-        llm_token: LlmApiToken,
-        app_version: Version,
-    ) -> Result<(Res, Option<EditPredictionUsage>)>
-    where
-        Res: DeserializeOwned,
-    {
-        let http_client = client.http_client();
-        let mut token = llm_token.acquire(&client).await?;
-        let mut did_retry = false;
-
-        loop {
-            let request_builder = http_client::Request::builder().method(Method::POST);
-
-            let request = build(
-                request_builder
-                    .header("Content-Type", "application/json")
-                    .header("Authorization", format!("Bearer {}", token))
-                    .header(ZED_VERSION_HEADER_NAME, app_version.to_string()),
-            )?;
-
-            let mut response = http_client.send(request).await?;
-
-            if let Some(minimum_required_version) = response
-                .headers()
-                .get(MINIMUM_REQUIRED_VERSION_HEADER_NAME)
-                .and_then(|version| Version::from_str(version.to_str().ok()?).ok())
-            {
-                anyhow::ensure!(
-                    app_version >= minimum_required_version,
-                    ZedUpdateRequiredError {
-                        minimum_version: minimum_required_version
-                    }
-                );
-            }
-
-            if response.status().is_success() {
-                let usage = EditPredictionUsage::from_headers(response.headers()).ok();
-
-                let mut body = Vec::new();
-                response.body_mut().read_to_end(&mut body).await?;
-                return Ok((serde_json::from_slice(&body)?, usage));
-            } else if !did_retry
-                && response
-                    .headers()
-                    .get(EXPIRED_LLM_TOKEN_HEADER_NAME)
-                    .is_some()
-            {
-                did_retry = true;
-                token = llm_token.refresh(&client).await?;
-            } else {
-                let mut body = String::new();
-                response.body_mut().read_to_string(&mut body).await?;
-                anyhow::bail!(
-                    "Request failed with status: {:?}\nBody: {}",
-                    response.status(),
-                    body
-                );
-            }
-        }
-    }
-
-    pub const CONTEXT_RETRIEVAL_IDLE_DURATION: Duration = Duration::from_secs(10);
-    pub const CONTEXT_RETRIEVAL_DEBOUNCE_DURATION: Duration = Duration::from_secs(3);
-
-    // Refresh the related excerpts when the user just beguns editing after
-    // an idle period, and after they pause editing.
-    fn refresh_context_if_needed(
-        &mut self,
-        project: &Entity<Project>,
-        buffer: &Entity<language::Buffer>,
-        cursor_position: language::Anchor,
-        cx: &mut Context<Self>,
-    ) {
-        if !matches!(self.edit_prediction_model, ZetaEditPredictionModel::Zeta2) {
-            return;
-        }
-
-        if !matches!(&self.options().context, ContextMode::Agentic { .. }) {
-            return;
-        }
-
-        let Some(zeta_project) = self.projects.get_mut(&project.entity_id()) else {
-            return;
-        };
-
-        let now = Instant::now();
-        let was_idle = zeta_project
-            .refresh_context_timestamp
-            .map_or(true, |timestamp| {
-                now - timestamp > Self::CONTEXT_RETRIEVAL_IDLE_DURATION
-            });
-        zeta_project.refresh_context_timestamp = Some(now);
-        zeta_project.refresh_context_debounce_task = Some(cx.spawn({
-            let buffer = buffer.clone();
-            let project = project.clone();
-            async move |this, cx| {
-                if was_idle {
-                    log::debug!("refetching edit prediction context after idle");
-                } else {
-                    cx.background_executor()
-                        .timer(Self::CONTEXT_RETRIEVAL_DEBOUNCE_DURATION)
-                        .await;
-                    log::debug!("refetching edit prediction context after pause");
-                }
-                this.update(cx, |this, cx| {
-                    let task = this.refresh_context(project.clone(), buffer, cursor_position, cx);
-
-                    if let Some(zeta_project) = this.projects.get_mut(&project.entity_id()) {
-                        zeta_project.refresh_context_task = Some(task.log_err());
-                    };
-                })
-                .ok()
-            }
-        }));
-    }
-
-    // Refresh the related excerpts asynchronously. Ensure the task runs to completion,
-    // and avoid spawning more than one concurrent task.
-    pub fn refresh_context(
-        &mut self,
-        project: Entity<Project>,
-        buffer: Entity<language::Buffer>,
-        cursor_position: language::Anchor,
-        cx: &mut Context<Self>,
-    ) -> Task<Result<()>> {
-        let Some(zeta_project) = self.projects.get(&project.entity_id()) else {
-            return Task::ready(anyhow::Ok(()));
-        };
-
-        let ContextMode::Agentic(options) = &self.options().context else {
-            return Task::ready(anyhow::Ok(()));
-        };
-
-        let snapshot = buffer.read(cx).snapshot();
-        let cursor_point = cursor_position.to_point(&snapshot);
-        let Some(cursor_excerpt) = EditPredictionExcerpt::select_from_buffer(
-            cursor_point,
-            &snapshot,
-            &options.excerpt,
-            None,
-        ) else {
-            return Task::ready(Ok(()));
-        };
-
-        let app_version = AppVersion::global(cx);
-        let client = self.client.clone();
-        let llm_token = self.llm_token.clone();
-        let debug_tx = self.debug_tx.clone();
-        let current_file_path: Arc<Path> = snapshot
-            .file()
-            .map(|f| f.full_path(cx).into())
-            .unwrap_or_else(|| Path::new("untitled").into());
-
-        let prompt = match cloud_zeta2_prompt::retrieval_prompt::build_prompt(
-            predict_edits_v3::PlanContextRetrievalRequest {
-                excerpt: cursor_excerpt.text(&snapshot).body,
-                excerpt_path: current_file_path,
-                excerpt_line_range: cursor_excerpt.line_range,
-                cursor_file_max_row: Line(snapshot.max_point().row),
-                events: zeta_project.events(cx),
-            },
-        ) {
-            Ok(prompt) => prompt,
-            Err(err) => {
-                return Task::ready(Err(err));
-            }
-        };
-
-        if let Some(debug_tx) = &debug_tx {
-            debug_tx
-                .unbounded_send(ZetaDebugInfo::ContextRetrievalStarted(
-                    ZetaContextRetrievalStartedDebugInfo {
-                        project: project.clone(),
-                        timestamp: Instant::now(),
-                        search_prompt: prompt.clone(),
-                    },
-                ))
-                .ok();
-        }
-
-        pub static TOOL_SCHEMA: LazyLock<(serde_json::Value, String)> = LazyLock::new(|| {
-            let schema = language_model::tool_schema::root_schema_for::<SearchToolInput>(
-                language_model::LanguageModelToolSchemaFormat::JsonSchemaSubset,
-            );
-
-            let description = schema
-                .get("description")
-                .and_then(|description| description.as_str())
-                .unwrap()
-                .to_string();
-
-            (schema.into(), description)
-        });
-
-        let (tool_schema, tool_description) = TOOL_SCHEMA.clone();
-
-        let request = open_ai::Request {
-            model: CONTEXT_RETRIEVAL_MODEL_ID.clone(),
-            messages: vec![open_ai::RequestMessage::User {
-                content: open_ai::MessageContent::Plain(prompt),
-            }],
-            stream: false,
-            max_completion_tokens: None,
-            stop: Default::default(),
-            temperature: 0.7,
-            tool_choice: None,
-            parallel_tool_calls: None,
-            tools: vec![open_ai::ToolDefinition::Function {
-                function: FunctionDefinition {
-                    name: cloud_zeta2_prompt::retrieval_prompt::TOOL_NAME.to_string(),
-                    description: Some(tool_description),
-                    parameters: Some(tool_schema),
-                },
-            }],
-            prompt_cache_key: None,
-            reasoning_effort: None,
-        };
-
-        #[cfg(feature = "eval-support")]
-        let eval_cache = self.eval_cache.clone();
-
-        cx.spawn(async move |this, cx| {
-            log::trace!("Sending search planning request");
-            let response = Self::send_raw_llm_request(
-                request,
-                client,
-                llm_token,
-                app_version,
-                #[cfg(feature = "eval-support")]
-                eval_cache.clone(),
-                #[cfg(feature = "eval-support")]
-                EvalCacheEntryKind::Context,
-            )
-            .await;
-            let mut response = Self::handle_api_response(&this, response, cx)?;
-            log::trace!("Got search planning response");
-
-            let choice = response
-                .choices
-                .pop()
-                .context("No choices in retrieval response")?;
-            let open_ai::RequestMessage::Assistant {
-                content: _,
-                tool_calls,
-            } = choice.message
-            else {
-                anyhow::bail!("Retrieval response didn't include an assistant message");
-            };
-
-            let mut queries: Vec<SearchToolQuery> = Vec::new();
-            for tool_call in tool_calls {
-                let open_ai::ToolCallContent::Function { function } = tool_call.content;
-                if function.name != cloud_zeta2_prompt::retrieval_prompt::TOOL_NAME {
-                    log::warn!(
-                        "Context retrieval response tried to call an unknown tool: {}",
-                        function.name
-                    );
-
-                    continue;
-                }
-
-                let input: SearchToolInput = serde_json::from_str(&function.arguments)
-                    .with_context(|| format!("invalid search json {}", &function.arguments))?;
-                queries.extend(input.queries);
-            }
-
-            if let Some(debug_tx) = &debug_tx {
-                debug_tx
-                    .unbounded_send(ZetaDebugInfo::SearchQueriesGenerated(
-                        ZetaSearchQueryDebugInfo {
-                            project: project.clone(),
-                            timestamp: Instant::now(),
-                            search_queries: queries.clone(),
-                        },
-                    ))
-                    .ok();
-            }
-
-            log::trace!("Running retrieval search: {queries:#?}");
-
-            let related_excerpts_result = retrieval_search::run_retrieval_searches(
-                queries,
-                project.clone(),
-                #[cfg(feature = "eval-support")]
-                eval_cache,
-                cx,
-            )
-            .await;
-
-            log::trace!("Search queries executed");
-
-            if let Some(debug_tx) = &debug_tx {
-                debug_tx
-                    .unbounded_send(ZetaDebugInfo::SearchQueriesExecuted(
-                        ZetaContextRetrievalDebugInfo {
-                            project: project.clone(),
-                            timestamp: Instant::now(),
-                        },
-                    ))
-                    .ok();
-            }
-
-            this.update(cx, |this, _cx| {
-                let Some(zeta_project) = this.projects.get_mut(&project.entity_id()) else {
-                    return Ok(());
-                };
-                zeta_project.refresh_context_task.take();
-                if let Some(debug_tx) = &this.debug_tx {
-                    debug_tx
-                        .unbounded_send(ZetaDebugInfo::ContextRetrievalFinished(
-                            ZetaContextRetrievalDebugInfo {
-                                project,
-                                timestamp: Instant::now(),
-                            },
-                        ))
-                        .ok();
-                }
-                match related_excerpts_result {
-                    Ok(excerpts) => {
-                        zeta_project.context = Some(excerpts);
-                        Ok(())
-                    }
-                    Err(error) => Err(error),
-                }
-            })?
-        })
-    }
-
-    pub fn set_context(
-        &mut self,
-        project: Entity<Project>,
-        context: HashMap<Entity<Buffer>, Vec<Range<Anchor>>>,
-    ) {
-        if let Some(zeta_project) = self.projects.get_mut(&project.entity_id()) {
-            zeta_project.context = Some(context);
-        }
-    }
-
-    fn gather_nearby_diagnostics(
-        cursor_offset: usize,
-        diagnostic_sets: &[(LanguageServerId, DiagnosticSet)],
-        snapshot: &BufferSnapshot,
-        max_diagnostics_bytes: usize,
-    ) -> (Vec<predict_edits_v3::DiagnosticGroup>, bool) {
-        // TODO: Could make this more efficient
-        let mut diagnostic_groups = Vec::new();
-        for (language_server_id, diagnostics) in diagnostic_sets {
-            let mut groups = Vec::new();
-            diagnostics.groups(*language_server_id, &mut groups, &snapshot);
-            diagnostic_groups.extend(
-                groups
-                    .into_iter()
-                    .map(|(_, group)| group.resolve::<usize>(&snapshot)),
-            );
-        }
-
-        // sort by proximity to cursor
-        diagnostic_groups.sort_by_key(|group| {
-            let range = &group.entries[group.primary_ix].range;
-            if range.start >= cursor_offset {
-                range.start - cursor_offset
-            } else if cursor_offset >= range.end {
-                cursor_offset - range.end
-            } else {
-                (cursor_offset - range.start).min(range.end - cursor_offset)
-            }
-        });
-
-        let mut results = Vec::new();
-        let mut diagnostic_groups_truncated = false;
-        let mut diagnostics_byte_count = 0;
-        for group in diagnostic_groups {
-            let raw_value = serde_json::value::to_raw_value(&group).unwrap();
-            diagnostics_byte_count += raw_value.get().len();
-            if diagnostics_byte_count > max_diagnostics_bytes {
-                diagnostic_groups_truncated = true;
-                break;
-            }
-            results.push(predict_edits_v3::DiagnosticGroup(raw_value));
-        }
-
-        (results, diagnostic_groups_truncated)
-    }
-
-    // TODO: Dedupe with similar code in request_prediction?
-    pub fn cloud_request_for_zeta_cli(
-        &mut self,
-        project: &Entity<Project>,
-        buffer: &Entity<Buffer>,
-        position: language::Anchor,
-        cx: &mut Context<Self>,
-    ) -> Task<Result<predict_edits_v3::PredictEditsRequest>> {
-        let project_state = self.projects.get(&project.entity_id());
-
-        let index_state = project_state.and_then(|state| {
-            state
-                .syntax_index
-                .as_ref()
-                .map(|index| index.read_with(cx, |index, _cx| index.state().clone()))
-        });
-        let options = self.options.clone();
-        let snapshot = buffer.read(cx).snapshot();
-        let Some(excerpt_path) = snapshot.file().map(|path| path.full_path(cx)) else {
-            return Task::ready(Err(anyhow!("No file path for excerpt")));
-        };
-        let worktree_snapshots = project
-            .read(cx)
-            .worktrees(cx)
-            .map(|worktree| worktree.read(cx).snapshot())
-            .collect::<Vec<_>>();
-
-        let parent_abs_path = project::File::from_dyn(buffer.read(cx).file()).and_then(|f| {
-            let mut path = f.worktree.read(cx).absolutize(&f.path);
-            if path.pop() { Some(path) } else { None }
-        });
-
-        cx.background_spawn(async move {
-            let index_state = if let Some(index_state) = index_state {
-                Some(index_state.lock_owned().await)
-            } else {
-                None
-            };
-
-            let cursor_point = position.to_point(&snapshot);
-
-            let debug_info = true;
-            EditPredictionContext::gather_context(
-                cursor_point,
-                &snapshot,
-                parent_abs_path.as_deref(),
-                match &options.context {
-                    ContextMode::Agentic(_) => {
-                        // TODO
-                        panic!("Llm mode not supported in zeta cli yet");
-                    }
-                    ContextMode::Syntax(edit_prediction_context_options) => {
-                        edit_prediction_context_options
-                    }
-                },
-                index_state.as_deref(),
-            )
-            .context("Failed to select excerpt")
-            .map(|context| {
-                make_syntax_context_cloud_request(
-                    excerpt_path.into(),
-                    context,
-                    // TODO pass everything
-                    Vec::new(),
-                    false,
-                    Vec::new(),
-                    false,
-                    None,
-                    debug_info,
-                    &worktree_snapshots,
-                    index_state.as_deref(),
-                    Some(options.max_prompt_bytes),
-                    options.prompt_format,
-                    PredictEditsRequestTrigger::Other,
-                )
-            })
-        })
-    }
-
-    pub fn wait_for_initial_indexing(
-        &mut self,
-        project: &Entity<Project>,
-        cx: &mut Context<Self>,
-    ) -> Task<Result<()>> {
-        let zeta_project = self.get_or_init_zeta_project(project, cx);
-        if let Some(syntax_index) = &zeta_project.syntax_index {
-            syntax_index.read(cx).wait_for_initial_file_indexing(cx)
-        } else {
-            Task::ready(Ok(()))
-        }
-    }
-
-    fn is_file_open_source(
-        &self,
-        project: &Entity<Project>,
-        file: &Arc<dyn File>,
-        cx: &App,
-    ) -> bool {
-        if !file.is_local() || file.is_private() {
-            return false;
-        }
-        let Some(zeta_project) = self.projects.get(&project.entity_id()) else {
-            return false;
-        };
-        zeta_project
-            .license_detection_watchers
-            .get(&file.worktree_id(cx))
-            .as_ref()
-            .is_some_and(|watcher| watcher.is_project_open_source())
-    }
-
-    fn can_collect_file(&self, project: &Entity<Project>, file: &Arc<dyn File>, cx: &App) -> bool {
-        self.data_collection_choice.is_enabled() && self.is_file_open_source(project, file, cx)
-    }
-
-    fn can_collect_events(&self, events: &[Arc<Event>]) -> bool {
-        if !self.data_collection_choice.is_enabled() {
-            return false;
-        }
-        events.iter().all(|event| {
-            matches!(
-                event.as_ref(),
-                Event::BufferChange {
-                    in_open_source_repo: true,
-                    ..
-                }
-            )
-        })
-    }
-
-    fn load_data_collection_choice() -> DataCollectionChoice {
-        let choice = KEY_VALUE_STORE
-            .read_kvp(ZED_PREDICT_DATA_COLLECTION_CHOICE)
-            .log_err()
-            .flatten();
-
-        match choice.as_deref() {
-            Some("true") => DataCollectionChoice::Enabled,
-            Some("false") => DataCollectionChoice::Disabled,
-            Some(_) => {
-                log::error!("unknown value in '{ZED_PREDICT_DATA_COLLECTION_CHOICE}'");
-                DataCollectionChoice::NotAnswered
-            }
-            None => DataCollectionChoice::NotAnswered,
-        }
-    }
-
-    pub fn shown_predictions(&self) -> impl DoubleEndedIterator<Item = &EditPrediction> {
-        self.shown_predictions.iter()
-    }
-
-    pub fn shown_completions_len(&self) -> usize {
-        self.shown_predictions.len()
-    }
-
-    pub fn is_prediction_rated(&self, id: &EditPredictionId) -> bool {
-        self.rated_predictions.contains(id)
-    }
-
-    pub fn rate_prediction(
-        &mut self,
-        prediction: &EditPrediction,
-        rating: EditPredictionRating,
-        feedback: String,
-        cx: &mut Context<Self>,
-    ) {
-        self.rated_predictions.insert(prediction.id.clone());
-        telemetry::event!(
-            "Edit Prediction Rated",
-            rating,
-            inputs = prediction.inputs,
-            output = prediction.edit_preview.as_unified_diff(&prediction.edits),
-            feedback
-        );
-        self.client.telemetry().flush_events().detach();
-        cx.notify();
-    }
-}
-
-pub fn text_from_response(mut res: open_ai::Response) -> Option<String> {
-    let choice = res.choices.pop()?;
-    let output_text = match choice.message {
-        open_ai::RequestMessage::Assistant {
-            content: Some(open_ai::MessageContent::Plain(content)),
-            ..
-        } => content,
-        open_ai::RequestMessage::Assistant {
-            content: Some(open_ai::MessageContent::Multipart(mut content)),
-            ..
-        } => {
-            if content.is_empty() {
-                log::error!("No output from Baseten completion response");
-                return None;
-            }
-
-            match content.remove(0) {
-                open_ai::MessagePart::Text { text } => text,
-                open_ai::MessagePart::Image { .. } => {
-                    log::error!("Expected text, got an image");
-                    return None;
-                }
-            }
-        }
-        _ => {
-            log::error!("Invalid response message: {:?}", choice.message);
-            return None;
-        }
-    };
-    Some(output_text)
-}
-
-#[derive(Error, Debug)]
-#[error(
-    "You must update to Zed version {minimum_version} or higher to continue using edit predictions."
-)]
-pub struct ZedUpdateRequiredError {
-    minimum_version: Version,
-}
-
-fn make_syntax_context_cloud_request(
-    excerpt_path: Arc<Path>,
-    context: EditPredictionContext,
-    events: Vec<Arc<predict_edits_v3::Event>>,
-    can_collect_data: bool,
-    diagnostic_groups: Vec<predict_edits_v3::DiagnosticGroup>,
-    diagnostic_groups_truncated: bool,
-    git_info: Option<cloud_llm_client::PredictEditsGitInfo>,
-    debug_info: bool,
-    worktrees: &Vec<worktree::Snapshot>,
-    index_state: Option<&SyntaxIndexState>,
-    prompt_max_bytes: Option<usize>,
-    prompt_format: PromptFormat,
-    trigger: PredictEditsRequestTrigger,
-) -> predict_edits_v3::PredictEditsRequest {
-    let mut signatures = Vec::new();
-    let mut declaration_to_signature_index = HashMap::default();
-    let mut referenced_declarations = Vec::new();
-
-    for snippet in context.declarations {
-        let project_entry_id = snippet.declaration.project_entry_id();
-        let Some(path) = worktrees.iter().find_map(|worktree| {
-            worktree.entry_for_id(project_entry_id).map(|entry| {
-                let mut full_path = RelPathBuf::new();
-                full_path.push(worktree.root_name());
-                full_path.push(&entry.path);
-                full_path
-            })
-        }) else {
-            continue;
-        };
-
-        let parent_index = index_state.and_then(|index_state| {
-            snippet.declaration.parent().and_then(|parent| {
-                add_signature(
-                    parent,
-                    &mut declaration_to_signature_index,
-                    &mut signatures,
-                    index_state,
-                )
-            })
-        });
-
-        let (text, text_is_truncated) = snippet.declaration.item_text();
-        referenced_declarations.push(predict_edits_v3::ReferencedDeclaration {
-            path: path.as_std_path().into(),
-            text: text.into(),
-            range: snippet.declaration.item_line_range(),
-            text_is_truncated,
-            signature_range: snippet.declaration.signature_range_in_item_text(),
-            parent_index,
-            signature_score: snippet.score(DeclarationStyle::Signature),
-            declaration_score: snippet.score(DeclarationStyle::Declaration),
-            score_components: snippet.components,
-        });
-    }
-
-    let excerpt_parent = index_state.and_then(|index_state| {
-        context
-            .excerpt
-            .parent_declarations
-            .last()
-            .and_then(|(parent, _)| {
-                add_signature(
-                    *parent,
-                    &mut declaration_to_signature_index,
-                    &mut signatures,
-                    index_state,
-                )
-            })
-    });
-
-    predict_edits_v3::PredictEditsRequest {
-        excerpt_path,
-        excerpt: context.excerpt_text.body,
-        excerpt_line_range: context.excerpt.line_range,
-        excerpt_range: context.excerpt.range,
-        cursor_point: predict_edits_v3::Point {
-            line: predict_edits_v3::Line(context.cursor_point.row),
-            column: context.cursor_point.column,
-        },
-        referenced_declarations,
-        included_files: vec![],
-        signatures,
-        excerpt_parent,
-        events,
-        can_collect_data,
-        diagnostic_groups,
-        diagnostic_groups_truncated,
-        git_info,
-        debug_info,
-        prompt_max_bytes,
-        prompt_format,
-        trigger,
-    }
-}
-
-fn add_signature(
-    declaration_id: DeclarationId,
-    declaration_to_signature_index: &mut HashMap<DeclarationId, usize>,
-    signatures: &mut Vec<Signature>,
-    index: &SyntaxIndexState,
-) -> Option<usize> {
-    if let Some(signature_index) = declaration_to_signature_index.get(&declaration_id) {
-        return Some(*signature_index);
-    }
-    let Some(parent_declaration) = index.declaration(declaration_id) else {
-        log::error!("bug: missing parent declaration");
-        return None;
-    };
-    let parent_index = parent_declaration.parent().and_then(|parent| {
-        add_signature(parent, declaration_to_signature_index, signatures, index)
-    });
-    let (text, text_is_truncated) = parent_declaration.signature_text();
-    let signature_index = signatures.len();
-    signatures.push(Signature {
-        text: text.into(),
-        text_is_truncated,
-        parent_index,
-        range: parent_declaration.signature_line_range(),
-    });
-    declaration_to_signature_index.insert(declaration_id, signature_index);
-    Some(signature_index)
-}
-
-#[cfg(feature = "eval-support")]
-pub type EvalCacheKey = (EvalCacheEntryKind, u64);
-
-#[cfg(feature = "eval-support")]
-#[derive(Debug, Clone, Copy, PartialEq)]
-pub enum EvalCacheEntryKind {
-    Context,
-    Search,
-    Prediction,
-}
-
-#[cfg(feature = "eval-support")]
-impl std::fmt::Display for EvalCacheEntryKind {
-    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
-        match self {
-            EvalCacheEntryKind::Search => write!(f, "search"),
-            EvalCacheEntryKind::Context => write!(f, "context"),
-            EvalCacheEntryKind::Prediction => write!(f, "prediction"),
-        }
-    }
-}
-
-#[cfg(feature = "eval-support")]
-pub trait EvalCache: Send + Sync {
-    fn read(&self, key: EvalCacheKey) -> Option<String>;
-    fn write(&self, key: EvalCacheKey, input: &str, value: &str);
-}
-
-#[derive(Debug, Clone, Copy)]
-pub enum DataCollectionChoice {
-    NotAnswered,
-    Enabled,
-    Disabled,
-}
-
-impl DataCollectionChoice {
-    pub fn is_enabled(self) -> bool {
-        match self {
-            Self::Enabled => true,
-            Self::NotAnswered | Self::Disabled => false,
-        }
-    }
-
-    pub fn is_answered(self) -> bool {
-        match self {
-            Self::Enabled | Self::Disabled => true,
-            Self::NotAnswered => false,
-        }
-    }
-
-    #[must_use]
-    pub fn toggle(&self) -> DataCollectionChoice {
-        match self {
-            Self::Enabled => Self::Disabled,
-            Self::Disabled => Self::Enabled,
-            Self::NotAnswered => Self::Enabled,
-        }
-    }
-}
-
-impl From<bool> for DataCollectionChoice {
-    fn from(value: bool) -> Self {
-        match value {
-            true => DataCollectionChoice::Enabled,
-            false => DataCollectionChoice::Disabled,
-        }
-    }
-}
-
-struct ZedPredictUpsell;
-
-impl Dismissable for ZedPredictUpsell {
-    const KEY: &'static str = "dismissed-edit-predict-upsell";
-
-    fn dismissed() -> bool {
-        // To make this backwards compatible with older versions of Zed, we
-        // check if the user has seen the previous Edit Prediction Onboarding
-        // before, by checking the data collection choice which was written to
-        // the database once the user clicked on "Accept and Enable"
-        if KEY_VALUE_STORE
-            .read_kvp(ZED_PREDICT_DATA_COLLECTION_CHOICE)
-            .log_err()
-            .is_some_and(|s| s.is_some())
-        {
-            return true;
-        }
-
-        KEY_VALUE_STORE
-            .read_kvp(Self::KEY)
-            .log_err()
-            .is_some_and(|s| s.is_some())
-    }
-}
-
-pub fn should_show_upsell_modal() -> bool {
-    !ZedPredictUpsell::dismissed()
-}
-
-pub fn init(cx: &mut App) {
-    feature_gate_predict_edits_actions(cx);
-
-    cx.observe_new(move |workspace: &mut Workspace, _, _cx| {
-        workspace.register_action(|workspace, _: &RateCompletions, window, cx| {
-            if cx.has_flag::<PredictEditsRateCompletionsFeatureFlag>() {
-                RatePredictionsModal::toggle(workspace, window, cx);
-            }
-        });
-
-        workspace.register_action(
-            move |workspace, _: &zed_actions::OpenZedPredictOnboarding, window, cx| {
-                ZedPredictModal::toggle(
-                    workspace,
-                    workspace.user_store().clone(),
-                    workspace.client().clone(),
-                    window,
-                    cx,
-                )
-            },
-        );
-
-        workspace.register_action(|workspace, _: &ResetOnboarding, _window, cx| {
-            update_settings_file(workspace.app_state().fs.clone(), cx, move |settings, _| {
-                settings
-                    .project
-                    .all_languages
-                    .features
-                    .get_or_insert_default()
-                    .edit_prediction_provider = Some(EditPredictionProvider::None)
-            });
-        });
-    })
-    .detach();
-}
-
-fn feature_gate_predict_edits_actions(cx: &mut App) {
-    let rate_completion_action_types = [TypeId::of::<RateCompletions>()];
-    let reset_onboarding_action_types = [TypeId::of::<ResetOnboarding>()];
-    let zeta_all_action_types = [
-        TypeId::of::<RateCompletions>(),
-        TypeId::of::<ResetOnboarding>(),
-        zed_actions::OpenZedPredictOnboarding.type_id(),
-        TypeId::of::<ClearHistory>(),
-        TypeId::of::<ThumbsUpActivePrediction>(),
-        TypeId::of::<ThumbsDownActivePrediction>(),
-        TypeId::of::<NextEdit>(),
-        TypeId::of::<PreviousEdit>(),
-    ];
-
-    CommandPaletteFilter::update_global(cx, |filter, _cx| {
-        filter.hide_action_types(&rate_completion_action_types);
-        filter.hide_action_types(&reset_onboarding_action_types);
-        filter.hide_action_types(&[zed_actions::OpenZedPredictOnboarding.type_id()]);
-    });
-
-    cx.observe_global::<SettingsStore>(move |cx| {
-        let is_ai_disabled = DisableAiSettings::get_global(cx).disable_ai;
-        let has_feature_flag = cx.has_flag::<PredictEditsRateCompletionsFeatureFlag>();
-
-        CommandPaletteFilter::update_global(cx, |filter, _cx| {
-            if is_ai_disabled {
-                filter.hide_action_types(&zeta_all_action_types);
-            } else if has_feature_flag {
-                filter.show_action_types(&rate_completion_action_types);
-            } else {
-                filter.hide_action_types(&rate_completion_action_types);
-            }
-        });
-    })
-    .detach();
-
-    cx.observe_flag::<PredictEditsRateCompletionsFeatureFlag, _>(move |is_enabled, cx| {
-        if !DisableAiSettings::get_global(cx).disable_ai {
-            if is_enabled {
-                CommandPaletteFilter::update_global(cx, |filter, _cx| {
-                    filter.show_action_types(&rate_completion_action_types);
-                });
-            } else {
-                CommandPaletteFilter::update_global(cx, |filter, _cx| {
-                    filter.hide_action_types(&rate_completion_action_types);
-                });
-            }
-        }
-    })
-    .detach();
-}
-
-#[cfg(test)]
-mod tests {
-    use std::{path::Path, sync::Arc, time::Duration};
-
-    use client::UserStore;
-    use clock::FakeSystemClock;
-    use cloud_llm_client::{
-        EditPredictionRejectReason, EditPredictionRejection, RejectEditPredictionsBody,
-    };
-    use cloud_zeta2_prompt::retrieval_prompt::{SearchToolInput, SearchToolQuery};
-    use futures::{
-        AsyncReadExt, StreamExt,
-        channel::{mpsc, oneshot},
-    };
-    use gpui::{
-        Entity, TestAppContext,
-        http_client::{FakeHttpClient, Response},
-        prelude::*,
-    };
-    use indoc::indoc;
-    use language::OffsetRangeExt as _;
-    use open_ai::Usage;
-    use pretty_assertions::{assert_eq, assert_matches};
-    use project::{FakeFs, Project};
-    use serde_json::json;
-    use settings::SettingsStore;
-    use util::path;
-    use uuid::Uuid;
-
-    use crate::{BufferEditPrediction, EditPredictionId, REJECT_REQUEST_DEBOUNCE, Zeta};
-
-    #[gpui::test]
-    async fn test_current_state(cx: &mut TestAppContext) {
-        let (zeta, mut requests) = init_test(cx);
-        let fs = FakeFs::new(cx.executor());
-        fs.insert_tree(
-            "/root",
-            json!({
-                "1.txt": "Hello!\nHow\nBye\n",
-                "2.txt": "Hola!\nComo\nAdios\n"
-            }),
-        )
-        .await;
-        let project = Project::test(fs, vec![path!("/root").as_ref()], cx).await;
-
-        zeta.update(cx, |zeta, cx| {
-            zeta.register_project(&project, cx);
-        });
-
-        let buffer1 = project
-            .update(cx, |project, cx| {
-                let path = project.find_project_path(path!("root/1.txt"), cx).unwrap();
-                project.open_buffer(path, cx)
-            })
-            .await
-            .unwrap();
-        let snapshot1 = buffer1.read_with(cx, |buffer, _cx| buffer.snapshot());
-        let position = snapshot1.anchor_before(language::Point::new(1, 3));
-
-        // Prediction for current file
-
-        zeta.update(cx, |zeta, cx| {
-            zeta.refresh_prediction_from_buffer(project.clone(), buffer1.clone(), position, cx)
-        });
-        let (_request, respond_tx) = requests.predict.next().await.unwrap();
-
-        respond_tx
-            .send(model_response(indoc! {r"
-                --- a/root/1.txt
-                +++ b/root/1.txt
-                @@ ... @@
-                 Hello!
-                -How
-                +How are you?
-                 Bye
-            "}))
-            .unwrap();
-
-        cx.run_until_parked();
-
-        zeta.read_with(cx, |zeta, cx| {
-            let prediction = zeta
-                .current_prediction_for_buffer(&buffer1, &project, cx)
-                .unwrap();
-            assert_matches!(prediction, BufferEditPrediction::Local { .. });
-        });
-
-        // Context refresh
-        let refresh_task = zeta.update(cx, |zeta, cx| {
-            zeta.refresh_context(project.clone(), buffer1.clone(), position, cx)
-        });
-        let (_request, respond_tx) = requests.predict.next().await.unwrap();
-        respond_tx
-            .send(open_ai::Response {
-                id: Uuid::new_v4().to_string(),
-                object: "response".into(),
-                created: 0,
-                model: "model".into(),
-                choices: vec![open_ai::Choice {
-                    index: 0,
-                    message: open_ai::RequestMessage::Assistant {
-                        content: None,
-                        tool_calls: vec![open_ai::ToolCall {
-                            id: "search".into(),
-                            content: open_ai::ToolCallContent::Function {
-                                function: open_ai::FunctionContent {
-                                    name: cloud_zeta2_prompt::retrieval_prompt::TOOL_NAME
-                                        .to_string(),
-                                    arguments: serde_json::to_string(&SearchToolInput {
-                                        queries: Box::new([SearchToolQuery {
-                                            glob: "root/2.txt".to_string(),
-                                            syntax_node: vec![],
-                                            content: Some(".".into()),
-                                        }]),
-                                    })
-                                    .unwrap(),
-                                },
-                            },
-                        }],
-                    },
-                    finish_reason: None,
-                }],
-                usage: Usage {
-                    prompt_tokens: 0,
-                    completion_tokens: 0,
-                    total_tokens: 0,
-                },
-            })
-            .unwrap();
-        refresh_task.await.unwrap();
-
-        zeta.update(cx, |zeta, _cx| {
-            zeta.reject_current_prediction(EditPredictionRejectReason::Discarded, &project);
-        });
-
-        // Prediction for another file
-        zeta.update(cx, |zeta, cx| {
-            zeta.refresh_prediction_from_buffer(project.clone(), buffer1.clone(), position, cx)
-        });
-        let (_request, respond_tx) = requests.predict.next().await.unwrap();
-        respond_tx
-            .send(model_response(indoc! {r#"
-                --- a/root/2.txt
-                +++ b/root/2.txt
-                 Hola!
-                -Como
-                +Como estas?
-                 Adios
-            "#}))
-            .unwrap();
-        cx.run_until_parked();
-
-        zeta.read_with(cx, |zeta, cx| {
-            let prediction = zeta
-                .current_prediction_for_buffer(&buffer1, &project, cx)
-                .unwrap();
-            assert_matches!(
-                prediction,
-                BufferEditPrediction::Jump { prediction } if prediction.snapshot.file().unwrap().full_path(cx) == Path::new(path!("root/2.txt"))
-            );
-        });
-
-        let buffer2 = project
-            .update(cx, |project, cx| {
-                let path = project.find_project_path(path!("root/2.txt"), cx).unwrap();
-                project.open_buffer(path, cx)
-            })
-            .await
-            .unwrap();
-
-        zeta.read_with(cx, |zeta, cx| {
-            let prediction = zeta
-                .current_prediction_for_buffer(&buffer2, &project, cx)
-                .unwrap();
-            assert_matches!(prediction, BufferEditPrediction::Local { .. });
-        });
-    }
-
-    #[gpui::test]
-    async fn test_simple_request(cx: &mut TestAppContext) {
-        let (zeta, mut requests) = init_test(cx);
-        let fs = FakeFs::new(cx.executor());
-        fs.insert_tree(
-            "/root",
-            json!({
-                "foo.md":  "Hello!\nHow\nBye\n"
-            }),
-        )
-        .await;
-        let project = Project::test(fs, vec![path!("/root").as_ref()], cx).await;
-
-        let buffer = project
-            .update(cx, |project, cx| {
-                let path = project.find_project_path(path!("root/foo.md"), cx).unwrap();
-                project.open_buffer(path, cx)
-            })
-            .await
-            .unwrap();
-        let snapshot = buffer.read_with(cx, |buffer, _cx| buffer.snapshot());
-        let position = snapshot.anchor_before(language::Point::new(1, 3));
-
-        let prediction_task = zeta.update(cx, |zeta, cx| {
-            zeta.request_prediction(&project, &buffer, position, Default::default(), cx)
-        });
-
-        let (_, respond_tx) = requests.predict.next().await.unwrap();
-
-        // TODO Put back when we have a structured request again
-        // assert_eq!(
-        //     request.excerpt_path.as_ref(),
-        //     Path::new(path!("root/foo.md"))
-        // );
-        // assert_eq!(
-        //     request.cursor_point,
-        //     Point {
-        //         line: Line(1),
-        //         column: 3
-        //     }
-        // );
-
-        respond_tx
-            .send(model_response(indoc! { r"
-                --- a/root/foo.md
-                +++ b/root/foo.md
-                @@ ... @@
-                 Hello!
-                -How
-                +How are you?
-                 Bye
-            "}))
-            .unwrap();
-
-        let prediction = prediction_task.await.unwrap().unwrap().prediction.unwrap();
-
-        assert_eq!(prediction.edits.len(), 1);
-        assert_eq!(
-            prediction.edits[0].0.to_point(&snapshot).start,
-            language::Point::new(1, 3)
-        );
-        assert_eq!(prediction.edits[0].1.as_ref(), " are you?");
-    }
-
-    #[gpui::test]
-    async fn test_request_events(cx: &mut TestAppContext) {
-        let (zeta, mut requests) = init_test(cx);
-        let fs = FakeFs::new(cx.executor());
-        fs.insert_tree(
-            "/root",
-            json!({
-                "foo.md": "Hello!\n\nBye\n"
-            }),
-        )
-        .await;
-        let project = Project::test(fs, vec![path!("/root").as_ref()], cx).await;
-
-        let buffer = project
-            .update(cx, |project, cx| {
-                let path = project.find_project_path(path!("root/foo.md"), cx).unwrap();
-                project.open_buffer(path, cx)
-            })
-            .await
-            .unwrap();
-
-        zeta.update(cx, |zeta, cx| {
-            zeta.register_buffer(&buffer, &project, cx);
-        });
-
-        buffer.update(cx, |buffer, cx| {
-            buffer.edit(vec![(7..7, "How")], None, cx);
-        });
-
-        let snapshot = buffer.read_with(cx, |buffer, _cx| buffer.snapshot());
-        let position = snapshot.anchor_before(language::Point::new(1, 3));
-
-        let prediction_task = zeta.update(cx, |zeta, cx| {
-            zeta.request_prediction(&project, &buffer, position, Default::default(), cx)
-        });
-
-        let (request, respond_tx) = requests.predict.next().await.unwrap();
-
-        let prompt = prompt_from_request(&request);
-        assert!(
-            prompt.contains(indoc! {"
-            --- a/root/foo.md
-            +++ b/root/foo.md
-            @@ -1,3 +1,3 @@
-             Hello!
-            -
-            +How
-             Bye
-        "}),
-            "{prompt}"
-        );
-
-        respond_tx
-            .send(model_response(indoc! {r#"
-                --- a/root/foo.md
-                +++ b/root/foo.md
-                @@ ... @@
-                 Hello!
-                -How
-                +How are you?
-                 Bye
-            "#}))
-            .unwrap();
-
-        let prediction = prediction_task.await.unwrap().unwrap().prediction.unwrap();
-
-        assert_eq!(prediction.edits.len(), 1);
-        assert_eq!(
-            prediction.edits[0].0.to_point(&snapshot).start,
-            language::Point::new(1, 3)
-        );
-        assert_eq!(prediction.edits[0].1.as_ref(), " are you?");
-    }
-
-    #[gpui::test]
-    async fn test_empty_prediction(cx: &mut TestAppContext) {
-        let (zeta, mut requests) = init_test(cx);
-        let fs = FakeFs::new(cx.executor());
-        fs.insert_tree(
-            "/root",
-            json!({
-                "foo.md":  "Hello!\nHow\nBye\n"
-            }),
-        )
-        .await;
-        let project = Project::test(fs, vec![path!("/root").as_ref()], cx).await;
-
-        let buffer = project
-            .update(cx, |project, cx| {
-                let path = project.find_project_path(path!("root/foo.md"), cx).unwrap();
-                project.open_buffer(path, cx)
-            })
-            .await
-            .unwrap();
-        let snapshot = buffer.read_with(cx, |buffer, _cx| buffer.snapshot());
-        let position = snapshot.anchor_before(language::Point::new(1, 3));
-
-        zeta.update(cx, |zeta, cx| {
-            zeta.refresh_prediction_from_buffer(project.clone(), buffer.clone(), position, cx);
-        });
-
-        const NO_OP_DIFF: &str = indoc! { r"
-            --- a/root/foo.md
-            +++ b/root/foo.md
-            @@ ... @@
-             Hello!
-            -How
-            +How
-             Bye
-        "};
-
-        let (_, respond_tx) = requests.predict.next().await.unwrap();
-        let response = model_response(NO_OP_DIFF);
-        let id = response.id.clone();
-        respond_tx.send(response).unwrap();
-
-        cx.run_until_parked();
-
-        zeta.read_with(cx, |zeta, cx| {
-            assert!(
-                zeta.current_prediction_for_buffer(&buffer, &project, cx)
-                    .is_none()
-            );
-        });
-
-        // prediction is reported as rejected
-        let (reject_request, _) = requests.reject.next().await.unwrap();
-
-        assert_eq!(
-            &reject_request.rejections,
-            &[EditPredictionRejection {
-                request_id: id,
-                reason: EditPredictionRejectReason::Empty,
-                was_shown: false
-            }]
-        );
-    }
-
-    #[gpui::test]
-    async fn test_interpolated_empty(cx: &mut TestAppContext) {
-        let (zeta, mut requests) = init_test(cx);
-        let fs = FakeFs::new(cx.executor());
-        fs.insert_tree(
-            "/root",
-            json!({
-                "foo.md":  "Hello!\nHow\nBye\n"
-            }),
-        )
-        .await;
-        let project = Project::test(fs, vec![path!("/root").as_ref()], cx).await;
-
-        let buffer = project
-            .update(cx, |project, cx| {
-                let path = project.find_project_path(path!("root/foo.md"), cx).unwrap();
-                project.open_buffer(path, cx)
-            })
-            .await
-            .unwrap();
-        let snapshot = buffer.read_with(cx, |buffer, _cx| buffer.snapshot());
-        let position = snapshot.anchor_before(language::Point::new(1, 3));
-
-        zeta.update(cx, |zeta, cx| {
-            zeta.refresh_prediction_from_buffer(project.clone(), buffer.clone(), position, cx);
-        });
-
-        let (_, respond_tx) = requests.predict.next().await.unwrap();
-
-        buffer.update(cx, |buffer, cx| {
-            buffer.set_text("Hello!\nHow are you?\nBye", cx);
-        });
-
-        let response = model_response(SIMPLE_DIFF);
-        let id = response.id.clone();
-        respond_tx.send(response).unwrap();
-
-        cx.run_until_parked();
-
-        zeta.read_with(cx, |zeta, cx| {
-            assert!(
-                zeta.current_prediction_for_buffer(&buffer, &project, cx)
-                    .is_none()
-            );
-        });
-
-        // prediction is reported as rejected
-        let (reject_request, _) = requests.reject.next().await.unwrap();
-
-        assert_eq!(
-            &reject_request.rejections,
-            &[EditPredictionRejection {
-                request_id: id,
-                reason: EditPredictionRejectReason::InterpolatedEmpty,
-                was_shown: false
-            }]
-        );
-    }
-
-    const SIMPLE_DIFF: &str = indoc! { r"
-        --- a/root/foo.md
-        +++ b/root/foo.md
-        @@ ... @@
-         Hello!
-        -How
-        +How are you?
-         Bye
-    "};
-
-    #[gpui::test]
-    async fn test_replace_current(cx: &mut TestAppContext) {
-        let (zeta, mut requests) = init_test(cx);
-        let fs = FakeFs::new(cx.executor());
-        fs.insert_tree(
-            "/root",
-            json!({
-                "foo.md":  "Hello!\nHow\nBye\n"
-            }),
-        )
-        .await;
-        let project = Project::test(fs, vec![path!("/root").as_ref()], cx).await;
-
-        let buffer = project
-            .update(cx, |project, cx| {
-                let path = project.find_project_path(path!("root/foo.md"), cx).unwrap();
-                project.open_buffer(path, cx)
-            })
-            .await
-            .unwrap();
-        let snapshot = buffer.read_with(cx, |buffer, _cx| buffer.snapshot());
-        let position = snapshot.anchor_before(language::Point::new(1, 3));
-
-        zeta.update(cx, |zeta, cx| {
-            zeta.refresh_prediction_from_buffer(project.clone(), buffer.clone(), position, cx);
-        });
-
-        let (_, respond_tx) = requests.predict.next().await.unwrap();
-        let first_response = model_response(SIMPLE_DIFF);
-        let first_id = first_response.id.clone();
-        respond_tx.send(first_response).unwrap();
-
-        cx.run_until_parked();
-
-        zeta.read_with(cx, |zeta, cx| {
-            assert_eq!(
-                zeta.current_prediction_for_buffer(&buffer, &project, cx)
-                    .unwrap()
-                    .id
-                    .0,
-                first_id
-            );
-        });
-
-        // a second request is triggered
-        zeta.update(cx, |zeta, cx| {
-            zeta.refresh_prediction_from_buffer(project.clone(), buffer.clone(), position, cx);
-        });
-
-        let (_, respond_tx) = requests.predict.next().await.unwrap();
-        let second_response = model_response(SIMPLE_DIFF);
-        let second_id = second_response.id.clone();
-        respond_tx.send(second_response).unwrap();
-
-        cx.run_until_parked();
-
-        zeta.read_with(cx, |zeta, cx| {
-            // second replaces first
-            assert_eq!(
-                zeta.current_prediction_for_buffer(&buffer, &project, cx)
-                    .unwrap()
-                    .id
-                    .0,
-                second_id
-            );
-        });
-
-        // first is reported as replaced
-        let (reject_request, _) = requests.reject.next().await.unwrap();
-
-        assert_eq!(
-            &reject_request.rejections,
-            &[EditPredictionRejection {
-                request_id: first_id,
-                reason: EditPredictionRejectReason::Replaced,
-                was_shown: false
-            }]
-        );
-    }
-
-    #[gpui::test]
-    async fn test_current_preferred(cx: &mut TestAppContext) {
-        let (zeta, mut requests) = init_test(cx);
-        let fs = FakeFs::new(cx.executor());
-        fs.insert_tree(
-            "/root",
-            json!({
-                "foo.md":  "Hello!\nHow\nBye\n"
-            }),
-        )
-        .await;
-        let project = Project::test(fs, vec![path!("/root").as_ref()], cx).await;
-
-        let buffer = project
-            .update(cx, |project, cx| {
-                let path = project.find_project_path(path!("root/foo.md"), cx).unwrap();
-                project.open_buffer(path, cx)
-            })
-            .await
-            .unwrap();
-        let snapshot = buffer.read_with(cx, |buffer, _cx| buffer.snapshot());
-        let position = snapshot.anchor_before(language::Point::new(1, 3));
-
-        zeta.update(cx, |zeta, cx| {
-            zeta.refresh_prediction_from_buffer(project.clone(), buffer.clone(), position, cx);
-        });
-
-        let (_, respond_tx) = requests.predict.next().await.unwrap();
-        let first_response = model_response(SIMPLE_DIFF);
-        let first_id = first_response.id.clone();
-        respond_tx.send(first_response).unwrap();
-
-        cx.run_until_parked();
-
-        zeta.read_with(cx, |zeta, cx| {
-            assert_eq!(
-                zeta.current_prediction_for_buffer(&buffer, &project, cx)
-                    .unwrap()
-                    .id
-                    .0,
-                first_id
-            );
-        });
-
-        // a second request is triggered
-        zeta.update(cx, |zeta, cx| {
-            zeta.refresh_prediction_from_buffer(project.clone(), buffer.clone(), position, cx);
-        });
-
-        let (_, respond_tx) = requests.predict.next().await.unwrap();
-        // worse than current prediction
-        let second_response = model_response(indoc! { r"
-            --- a/root/foo.md
-            +++ b/root/foo.md
-            @@ ... @@
-             Hello!
-            -How
-            +How are
-             Bye
-        "});
-        let second_id = second_response.id.clone();
-        respond_tx.send(second_response).unwrap();
-
-        cx.run_until_parked();
-
-        zeta.read_with(cx, |zeta, cx| {
-            // first is preferred over second
-            assert_eq!(
-                zeta.current_prediction_for_buffer(&buffer, &project, cx)
-                    .unwrap()
-                    .id
-                    .0,
-                first_id
-            );
-        });
-
-        // second is reported as rejected
-        let (reject_request, _) = requests.reject.next().await.unwrap();
-
-        assert_eq!(
-            &reject_request.rejections,
-            &[EditPredictionRejection {
-                request_id: second_id,
-                reason: EditPredictionRejectReason::CurrentPreferred,
-                was_shown: false
-            }]
-        );
-    }
-
-    #[gpui::test]
-    async fn test_cancel_earlier_pending_requests(cx: &mut TestAppContext) {
-        let (zeta, mut requests) = init_test(cx);
-        let fs = FakeFs::new(cx.executor());
-        fs.insert_tree(
-            "/root",
-            json!({
-                "foo.md":  "Hello!\nHow\nBye\n"
-            }),
-        )
-        .await;
-        let project = Project::test(fs, vec![path!("/root").as_ref()], cx).await;
-
-        let buffer = project
-            .update(cx, |project, cx| {
-                let path = project.find_project_path(path!("root/foo.md"), cx).unwrap();
-                project.open_buffer(path, cx)
-            })
-            .await
-            .unwrap();
-        let snapshot = buffer.read_with(cx, |buffer, _cx| buffer.snapshot());
-        let position = snapshot.anchor_before(language::Point::new(1, 3));
-
-        // start two refresh tasks
-        zeta.update(cx, |zeta, cx| {
-            zeta.refresh_prediction_from_buffer(project.clone(), buffer.clone(), position, cx);
-        });
-
-        let (_, respond_first) = requests.predict.next().await.unwrap();
-
-        zeta.update(cx, |zeta, cx| {
-            zeta.refresh_prediction_from_buffer(project.clone(), buffer.clone(), position, cx);
-        });
-
-        let (_, respond_second) = requests.predict.next().await.unwrap();
-
-        // wait for throttle
-        cx.run_until_parked();
-
-        // second responds first
-        let second_response = model_response(SIMPLE_DIFF);
-        let second_id = second_response.id.clone();
-        respond_second.send(second_response).unwrap();
-
-        cx.run_until_parked();
-
-        zeta.read_with(cx, |zeta, cx| {
-            // current prediction is second
-            assert_eq!(
-                zeta.current_prediction_for_buffer(&buffer, &project, cx)
-                    .unwrap()
-                    .id
-                    .0,
-                second_id
-            );
-        });
-
-        let first_response = model_response(SIMPLE_DIFF);
-        let first_id = first_response.id.clone();
-        respond_first.send(first_response).unwrap();
-
-        cx.run_until_parked();
-
-        zeta.read_with(cx, |zeta, cx| {
-            // current prediction is still second, since first was cancelled
-            assert_eq!(
-                zeta.current_prediction_for_buffer(&buffer, &project, cx)
-                    .unwrap()
-                    .id
-                    .0,
-                second_id
-            );
-        });
-
-        // first is reported as rejected
-        let (reject_request, _) = requests.reject.next().await.unwrap();
-
-        cx.run_until_parked();
-
-        assert_eq!(
-            &reject_request.rejections,
-            &[EditPredictionRejection {
-                request_id: first_id,
-                reason: EditPredictionRejectReason::Canceled,
-                was_shown: false
-            }]
-        );
-    }
-
-    #[gpui::test]
-    async fn test_cancel_second_on_third_request(cx: &mut TestAppContext) {
-        let (zeta, mut requests) = init_test(cx);
-        let fs = FakeFs::new(cx.executor());
-        fs.insert_tree(
-            "/root",
-            json!({
-                "foo.md":  "Hello!\nHow\nBye\n"
-            }),
-        )
-        .await;
-        let project = Project::test(fs, vec![path!("/root").as_ref()], cx).await;
-
-        let buffer = project
-            .update(cx, |project, cx| {
-                let path = project.find_project_path(path!("root/foo.md"), cx).unwrap();
-                project.open_buffer(path, cx)
-            })
-            .await
-            .unwrap();
-        let snapshot = buffer.read_with(cx, |buffer, _cx| buffer.snapshot());
-        let position = snapshot.anchor_before(language::Point::new(1, 3));
-
-        // start two refresh tasks
-        zeta.update(cx, |zeta, cx| {
-            zeta.refresh_prediction_from_buffer(project.clone(), buffer.clone(), position, cx);
-        });
-
-        let (_, respond_first) = requests.predict.next().await.unwrap();
-
-        zeta.update(cx, |zeta, cx| {
-            zeta.refresh_prediction_from_buffer(project.clone(), buffer.clone(), position, cx);
-        });
-
-        let (_, respond_second) = requests.predict.next().await.unwrap();
-
-        // wait for throttle, so requests are sent
-        cx.run_until_parked();
-
-        zeta.update(cx, |zeta, cx| {
-            // start a third request
-            zeta.refresh_prediction_from_buffer(project.clone(), buffer.clone(), position, cx);
-
-            // 2 are pending, so 2nd is cancelled
-            assert_eq!(
-                zeta.get_or_init_zeta_project(&project, cx)
-                    .cancelled_predictions
-                    .iter()
-                    .copied()
-                    .collect::<Vec<_>>(),
-                [1]
-            );
-        });
-
-        // wait for throttle
-        cx.run_until_parked();
-
-        let (_, respond_third) = requests.predict.next().await.unwrap();
-
-        let first_response = model_response(SIMPLE_DIFF);
-        let first_id = first_response.id.clone();
-        respond_first.send(first_response).unwrap();
-
-        cx.run_until_parked();
-
-        zeta.read_with(cx, |zeta, cx| {
-            // current prediction is first
-            assert_eq!(
-                zeta.current_prediction_for_buffer(&buffer, &project, cx)
-                    .unwrap()
-                    .id
-                    .0,
-                first_id
-            );
-        });
-
-        let cancelled_response = model_response(SIMPLE_DIFF);
-        let cancelled_id = cancelled_response.id.clone();
-        respond_second.send(cancelled_response).unwrap();
-
-        cx.run_until_parked();
-
-        zeta.read_with(cx, |zeta, cx| {
-            // current prediction is still first, since second was cancelled
-            assert_eq!(
-                zeta.current_prediction_for_buffer(&buffer, &project, cx)
-                    .unwrap()
-                    .id
-                    .0,
-                first_id
-            );
-        });
-
-        let third_response = model_response(SIMPLE_DIFF);
-        let third_response_id = third_response.id.clone();
-        respond_third.send(third_response).unwrap();
-
-        cx.run_until_parked();
-
-        zeta.read_with(cx, |zeta, cx| {
-            // third completes and replaces first
-            assert_eq!(
-                zeta.current_prediction_for_buffer(&buffer, &project, cx)
-                    .unwrap()
-                    .id
-                    .0,
-                third_response_id
-            );
-        });
-
-        // second is reported as rejected
-        let (reject_request, _) = requests.reject.next().await.unwrap();
-
-        cx.run_until_parked();
-
-        assert_eq!(
-            &reject_request.rejections,
-            &[
-                EditPredictionRejection {
-                    request_id: cancelled_id,
-                    reason: EditPredictionRejectReason::Canceled,
-                    was_shown: false
-                },
-                EditPredictionRejection {
-                    request_id: first_id,
-                    reason: EditPredictionRejectReason::Replaced,
-                    was_shown: false
-                }
-            ]
-        );
-    }
-
-    #[gpui::test]
-    async fn test_rejections_flushing(cx: &mut TestAppContext) {
-        let (zeta, mut requests) = init_test(cx);
-
-        zeta.update(cx, |zeta, _cx| {
-            zeta.reject_prediction(
-                EditPredictionId("test-1".into()),
-                EditPredictionRejectReason::Discarded,
-                false,
-            );
-            zeta.reject_prediction(
-                EditPredictionId("test-2".into()),
-                EditPredictionRejectReason::Canceled,
-                true,
-            );
-        });
-
-        cx.executor().advance_clock(REJECT_REQUEST_DEBOUNCE);
-        cx.run_until_parked();
-
-        let (reject_request, respond_tx) = requests.reject.next().await.unwrap();
-        respond_tx.send(()).unwrap();
-
-        // batched
-        assert_eq!(reject_request.rejections.len(), 2);
-        assert_eq!(
-            reject_request.rejections[0],
-            EditPredictionRejection {
-                request_id: "test-1".to_string(),
-                reason: EditPredictionRejectReason::Discarded,
-                was_shown: false
-            }
-        );
-        assert_eq!(
-            reject_request.rejections[1],
-            EditPredictionRejection {
-                request_id: "test-2".to_string(),
-                reason: EditPredictionRejectReason::Canceled,
-                was_shown: true
-            }
-        );
-
-        // Reaching batch size limit sends without debounce
-        zeta.update(cx, |zeta, _cx| {
-            for i in 0..70 {
-                zeta.reject_prediction(
-                    EditPredictionId(format!("batch-{}", i).into()),
-                    EditPredictionRejectReason::Discarded,
-                    false,
-                );
-            }
-        });
-
-        // First MAX/2 items are sent immediately
-        cx.run_until_parked();
-        let (reject_request, respond_tx) = requests.reject.next().await.unwrap();
-        respond_tx.send(()).unwrap();
-
-        assert_eq!(reject_request.rejections.len(), 50);
-        assert_eq!(reject_request.rejections[0].request_id, "batch-0");
-        assert_eq!(reject_request.rejections[49].request_id, "batch-49");
-
-        // Remaining items are debounced with the next batch
-        cx.executor().advance_clock(Duration::from_secs(15));
-        cx.run_until_parked();
-
-        let (reject_request, respond_tx) = requests.reject.next().await.unwrap();
-        respond_tx.send(()).unwrap();
-
-        assert_eq!(reject_request.rejections.len(), 20);
-        assert_eq!(reject_request.rejections[0].request_id, "batch-50");
-        assert_eq!(reject_request.rejections[19].request_id, "batch-69");
-
-        // Request failure
-        zeta.update(cx, |zeta, _cx| {
-            zeta.reject_prediction(
-                EditPredictionId("retry-1".into()),
-                EditPredictionRejectReason::Discarded,
-                false,
-            );
-        });
-
-        cx.executor().advance_clock(REJECT_REQUEST_DEBOUNCE);
-        cx.run_until_parked();
-
-        let (reject_request, _respond_tx) = requests.reject.next().await.unwrap();
-        assert_eq!(reject_request.rejections.len(), 1);
-        assert_eq!(reject_request.rejections[0].request_id, "retry-1");
-        // Simulate failure
-        drop(_respond_tx);
-
-        // Add another rejection
-        zeta.update(cx, |zeta, _cx| {
-            zeta.reject_prediction(
-                EditPredictionId("retry-2".into()),
-                EditPredictionRejectReason::Discarded,
-                false,
-            );
-        });
-
-        cx.executor().advance_clock(REJECT_REQUEST_DEBOUNCE);
-        cx.run_until_parked();
-
-        // Retry should include both the failed item and the new one
-        let (reject_request, respond_tx) = requests.reject.next().await.unwrap();
-        respond_tx.send(()).unwrap();
-
-        assert_eq!(reject_request.rejections.len(), 2);
-        assert_eq!(reject_request.rejections[0].request_id, "retry-1");
-        assert_eq!(reject_request.rejections[1].request_id, "retry-2");
-    }
-
-    // Skipped until we start including diagnostics in prompt
-    // #[gpui::test]
-    // async fn test_request_diagnostics(cx: &mut TestAppContext) {
-    //     let (zeta, mut req_rx) = init_test(cx);
-    //     let fs = FakeFs::new(cx.executor());
-    //     fs.insert_tree(
-    //         "/root",
-    //         json!({
-    //             "foo.md": "Hello!\nBye"
-    //         }),
-    //     )
-    //     .await;
-    //     let project = Project::test(fs, vec![path!("/root").as_ref()], cx).await;
-
-    //     let path_to_buffer_uri = lsp::Uri::from_file_path(path!("/root/foo.md")).unwrap();
-    //     let diagnostic = lsp::Diagnostic {
-    //         range: lsp::Range::new(lsp::Position::new(1, 1), lsp::Position::new(1, 5)),
-    //         severity: Some(lsp::DiagnosticSeverity::ERROR),
-    //         message: "\"Hello\" deprecated. Use \"Hi\" instead".to_string(),
-    //         ..Default::default()
-    //     };
-
-    //     project.update(cx, |project, cx| {
-    //         project.lsp_store().update(cx, |lsp_store, cx| {
-    //             // Create some diagnostics
-    //             lsp_store
-    //                 .update_diagnostics(
-    //                     LanguageServerId(0),
-    //                     lsp::PublishDiagnosticsParams {
-    //                         uri: path_to_buffer_uri.clone(),
-    //                         diagnostics: vec![diagnostic],
-    //                         version: None,
-    //                     },
-    //                     None,
-    //                     language::DiagnosticSourceKind::Pushed,
-    //                     &[],
-    //                     cx,
-    //                 )
-    //                 .unwrap();
-    //         });
-    //     });
-
-    //     let buffer = project
-    //         .update(cx, |project, cx| {
-    //             let path = project.find_project_path(path!("root/foo.md"), cx).unwrap();
-    //             project.open_buffer(path, cx)
-    //         })
-    //         .await
-    //         .unwrap();
-
-    //     let snapshot = buffer.read_with(cx, |buffer, _cx| buffer.snapshot());
-    //     let position = snapshot.anchor_before(language::Point::new(0, 0));
-
-    //     let _prediction_task = zeta.update(cx, |zeta, cx| {
-    //         zeta.request_prediction(&project, &buffer, position, cx)
-    //     });
-
-    //     let (request, _respond_tx) = req_rx.next().await.unwrap();
-
-    //     assert_eq!(request.diagnostic_groups.len(), 1);
-    //     let value = serde_json::from_str::<serde_json::Value>(request.diagnostic_groups[0].0.get())
-    //         .unwrap();
-    //     // We probably don't need all of this. TODO define a specific diagnostic type in predict_edits_v3
-    //     assert_eq!(
-    //         value,
-    //         json!({
-    //             "entries": [{
-    //                 "range": {
-    //                     "start": 8,
-    //                     "end": 10
-    //                 },
-    //                 "diagnostic": {
-    //                     "source": null,
-    //                     "code": null,
-    //                     "code_description": null,
-    //                     "severity": 1,
-    //                     "message": "\"Hello\" deprecated. Use \"Hi\" instead",
-    //                     "markdown": null,
-    //                     "group_id": 0,
-    //                     "is_primary": true,
-    //                     "is_disk_based": false,
-    //                     "is_unnecessary": false,
-    //                     "source_kind": "Pushed",
-    //                     "data": null,
-    //                     "underline": true
-    //                 }
-    //             }],
-    //             "primary_ix": 0
-    //         })
-    //     );
-    // }
-
-    fn model_response(text: &str) -> open_ai::Response {
-        open_ai::Response {
-            id: Uuid::new_v4().to_string(),
-            object: "response".into(),
-            created: 0,
-            model: "model".into(),
-            choices: vec![open_ai::Choice {
-                index: 0,
-                message: open_ai::RequestMessage::Assistant {
-                    content: Some(open_ai::MessageContent::Plain(text.to_string())),
-                    tool_calls: vec![],
-                },
-                finish_reason: None,
-            }],
-            usage: Usage {
-                prompt_tokens: 0,
-                completion_tokens: 0,
-                total_tokens: 0,
-            },
-        }
-    }
-
-    fn prompt_from_request(request: &open_ai::Request) -> &str {
-        assert_eq!(request.messages.len(), 1);
-        let open_ai::RequestMessage::User {
-            content: open_ai::MessageContent::Plain(content),
-            ..
-        } = &request.messages[0]
-        else {
-            panic!(
-                "Request does not have single user message of type Plain. {:#?}",
-                request
-            );
-        };
-        content
-    }
-
-    struct RequestChannels {
-        predict: mpsc::UnboundedReceiver<(open_ai::Request, oneshot::Sender<open_ai::Response>)>,
-        reject: mpsc::UnboundedReceiver<(RejectEditPredictionsBody, oneshot::Sender<()>)>,
-    }
-
-    fn init_test(cx: &mut TestAppContext) -> (Entity<Zeta>, RequestChannels) {
-        cx.update(move |cx| {
-            let settings_store = SettingsStore::test(cx);
-            cx.set_global(settings_store);
-            zlog::init_test();
-
-            let (predict_req_tx, predict_req_rx) = mpsc::unbounded();
-            let (reject_req_tx, reject_req_rx) = mpsc::unbounded();
-
-            let http_client = FakeHttpClient::create({
-                move |req| {
-                    let uri = req.uri().path().to_string();
-                    let mut body = req.into_body();
-                    let predict_req_tx = predict_req_tx.clone();
-                    let reject_req_tx = reject_req_tx.clone();
-                    async move {
-                        let resp = match uri.as_str() {
-                            "/client/llm_tokens" => serde_json::to_string(&json!({
-                                "token": "test"
-                            }))
-                            .unwrap(),
-                            "/predict_edits/raw" => {
-                                let mut buf = Vec::new();
-                                body.read_to_end(&mut buf).await.ok();
-                                let req = serde_json::from_slice(&buf).unwrap();
-
-                                let (res_tx, res_rx) = oneshot::channel();
-                                predict_req_tx.unbounded_send((req, res_tx)).unwrap();
-                                serde_json::to_string(&res_rx.await?).unwrap()
-                            }
-                            "/predict_edits/reject" => {
-                                let mut buf = Vec::new();
-                                body.read_to_end(&mut buf).await.ok();
-                                let req = serde_json::from_slice(&buf).unwrap();
-
-                                let (res_tx, res_rx) = oneshot::channel();
-                                reject_req_tx.unbounded_send((req, res_tx)).unwrap();
-                                serde_json::to_string(&res_rx.await?).unwrap()
-                            }
-                            _ => {
-                                panic!("Unexpected path: {}", uri)
-                            }
-                        };
-
-                        Ok(Response::builder().body(resp.into()).unwrap())
-                    }
-                }
-            });
-
-            let client = client::Client::new(Arc::new(FakeSystemClock::new()), http_client, cx);
-            client.cloud_client().set_credentials(1, "test".into());
-
-            language_model::init(client.clone(), cx);
-
-            let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
-            let zeta = Zeta::global(&client, &user_store, cx);
-
-            (
-                zeta,
-                RequestChannels {
-                    predict: predict_req_rx,
-                    reject: reject_req_rx,
-                },
-            )
-        })
-    }
-}

crates/zeta/src/zeta1/input_excerpt.rs 🔗

@@ -1,231 +0,0 @@
-use super::{
-    CURSOR_MARKER, EDITABLE_REGION_END_MARKER, EDITABLE_REGION_START_MARKER, START_OF_FILE_MARKER,
-    guess_token_count,
-};
-use language::{BufferSnapshot, Point};
-use std::{fmt::Write, ops::Range};
-
-#[derive(Debug)]
-pub struct InputExcerpt {
-    pub context_range: Range<Point>,
-    pub editable_range: Range<Point>,
-    pub prompt: String,
-}
-
-pub fn excerpt_for_cursor_position(
-    position: Point,
-    path: &str,
-    snapshot: &BufferSnapshot,
-    editable_region_token_limit: usize,
-    context_token_limit: usize,
-) -> InputExcerpt {
-    let mut scope_range = position..position;
-    let mut remaining_edit_tokens = editable_region_token_limit;
-
-    while let Some(parent) = snapshot.syntax_ancestor(scope_range.clone()) {
-        let parent_tokens = guess_token_count(parent.byte_range().len());
-        let parent_point_range = Point::new(
-            parent.start_position().row as u32,
-            parent.start_position().column as u32,
-        )
-            ..Point::new(
-                parent.end_position().row as u32,
-                parent.end_position().column as u32,
-            );
-        if parent_point_range == scope_range {
-            break;
-        } else if parent_tokens <= editable_region_token_limit {
-            scope_range = parent_point_range;
-            remaining_edit_tokens = editable_region_token_limit - parent_tokens;
-        } else {
-            break;
-        }
-    }
-
-    let editable_range = expand_range(snapshot, scope_range, remaining_edit_tokens);
-    let context_range = expand_range(snapshot, editable_range.clone(), context_token_limit);
-
-    let mut prompt = String::new();
-
-    writeln!(&mut prompt, "```{path}").unwrap();
-    if context_range.start == Point::zero() {
-        writeln!(&mut prompt, "{START_OF_FILE_MARKER}").unwrap();
-    }
-
-    for chunk in snapshot.chunks(context_range.start..editable_range.start, false) {
-        prompt.push_str(chunk.text);
-    }
-
-    push_editable_range(position, snapshot, editable_range.clone(), &mut prompt);
-
-    for chunk in snapshot.chunks(editable_range.end..context_range.end, false) {
-        prompt.push_str(chunk.text);
-    }
-    write!(prompt, "\n```").unwrap();
-
-    InputExcerpt {
-        context_range,
-        editable_range,
-        prompt,
-    }
-}
-
-fn push_editable_range(
-    cursor_position: Point,
-    snapshot: &BufferSnapshot,
-    editable_range: Range<Point>,
-    prompt: &mut String,
-) {
-    writeln!(prompt, "{EDITABLE_REGION_START_MARKER}").unwrap();
-    for chunk in snapshot.chunks(editable_range.start..cursor_position, false) {
-        prompt.push_str(chunk.text);
-    }
-    prompt.push_str(CURSOR_MARKER);
-    for chunk in snapshot.chunks(cursor_position..editable_range.end, false) {
-        prompt.push_str(chunk.text);
-    }
-    write!(prompt, "\n{EDITABLE_REGION_END_MARKER}").unwrap();
-}
-
-fn expand_range(
-    snapshot: &BufferSnapshot,
-    range: Range<Point>,
-    mut remaining_tokens: usize,
-) -> Range<Point> {
-    let mut expanded_range = range;
-    expanded_range.start.column = 0;
-    expanded_range.end.column = snapshot.line_len(expanded_range.end.row);
-    loop {
-        let mut expanded = false;
-
-        if remaining_tokens > 0 && expanded_range.start.row > 0 {
-            expanded_range.start.row -= 1;
-            let line_tokens =
-                guess_token_count(snapshot.line_len(expanded_range.start.row) as usize);
-            remaining_tokens = remaining_tokens.saturating_sub(line_tokens);
-            expanded = true;
-        }
-
-        if remaining_tokens > 0 && expanded_range.end.row < snapshot.max_point().row {
-            expanded_range.end.row += 1;
-            expanded_range.end.column = snapshot.line_len(expanded_range.end.row);
-            let line_tokens = guess_token_count(expanded_range.end.column as usize);
-            remaining_tokens = remaining_tokens.saturating_sub(line_tokens);
-            expanded = true;
-        }
-
-        if !expanded {
-            break;
-        }
-    }
-    expanded_range
-}
-
-#[cfg(test)]
-mod tests {
-    use super::*;
-    use gpui::{App, AppContext};
-    use indoc::indoc;
-    use language::{Buffer, Language, LanguageConfig, LanguageMatcher, tree_sitter_rust};
-    use std::sync::Arc;
-
-    #[gpui::test]
-    fn test_excerpt_for_cursor_position(cx: &mut App) {
-        let text = indoc! {r#"
-            fn foo() {
-                let x = 42;
-                println!("Hello, world!");
-            }
-
-            fn bar() {
-                let x = 42;
-                let mut sum = 0;
-                for i in 0..x {
-                    sum += i;
-                }
-                println!("Sum: {}", sum);
-                return sum;
-            }
-
-            fn generate_random_numbers() -> Vec<i32> {
-                let mut rng = rand::thread_rng();
-                let mut numbers = Vec::new();
-                for _ in 0..5 {
-                    numbers.push(rng.random_range(1..101));
-                }
-                numbers
-            }
-        "#};
-        let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(Arc::new(rust_lang()), cx));
-        let snapshot = buffer.read(cx).snapshot();
-
-        // Ensure we try to fit the largest possible syntax scope, resorting to line-based expansion
-        // when a larger scope doesn't fit the editable region.
-        let excerpt = excerpt_for_cursor_position(Point::new(12, 5), "main.rs", &snapshot, 50, 32);
-        assert_eq!(
-            excerpt.prompt,
-            indoc! {r#"
-            ```main.rs
-                let x = 42;
-                println!("Hello, world!");
-            <|editable_region_start|>
-            }
-
-            fn bar() {
-                let x = 42;
-                let mut sum = 0;
-                for i in 0..x {
-                    sum += i;
-                }
-                println!("Sum: {}", sum);
-                r<|user_cursor_is_here|>eturn sum;
-            }
-
-            fn generate_random_numbers() -> Vec<i32> {
-            <|editable_region_end|>
-                let mut rng = rand::thread_rng();
-                let mut numbers = Vec::new();
-            ```"#}
-        );
-
-        // The `bar` function won't fit within the editable region, so we resort to line-based expansion.
-        let excerpt = excerpt_for_cursor_position(Point::new(12, 5), "main.rs", &snapshot, 40, 32);
-        assert_eq!(
-            excerpt.prompt,
-            indoc! {r#"
-            ```main.rs
-            fn bar() {
-                let x = 42;
-                let mut sum = 0;
-            <|editable_region_start|>
-                for i in 0..x {
-                    sum += i;
-                }
-                println!("Sum: {}", sum);
-                r<|user_cursor_is_here|>eturn sum;
-            }
-
-            fn generate_random_numbers() -> Vec<i32> {
-                let mut rng = rand::thread_rng();
-            <|editable_region_end|>
-                let mut numbers = Vec::new();
-                for _ in 0..5 {
-                    numbers.push(rng.random_range(1..101));
-            ```"#}
-        );
-    }
-
-    fn rust_lang() -> Language {
-        Language::new(
-            LanguageConfig {
-                name: "Rust".into(),
-                matcher: LanguageMatcher {
-                    path_suffixes: vec!["rs".to_string()],
-                    ..Default::default()
-                },
-                ..Default::default()
-            },
-            Some(tree_sitter_rust::LANGUAGE.into()),
-        )
-    }
-}

crates/zeta/src/zeta_tests.rs 🔗

@@ -1,671 +0,0 @@
-use client::test::FakeServer;
-use clock::{FakeSystemClock, ReplicaId};
-use cloud_api_types::{CreateLlmTokenResponse, LlmToken};
-use cloud_llm_client::{PredictEditsBody, PredictEditsResponse};
-use gpui::TestAppContext;
-use http_client::FakeHttpClient;
-use indoc::indoc;
-use language::Point;
-use parking_lot::Mutex;
-use serde_json::json;
-use settings::SettingsStore;
-use util::{path, rel_path::rel_path};
-
-use crate::zeta1::MAX_EVENT_TOKENS;
-
-use super::*;
-
-const BSD_0_TXT: &str = include_str!("../license_examples/0bsd.txt");
-
-#[gpui::test]
-async fn test_edit_prediction_basic_interpolation(cx: &mut TestAppContext) {
-    let buffer = cx.new(|cx| Buffer::local("Lorem ipsum dolor", cx));
-    let edits: Arc<[(Range<Anchor>, Arc<str>)]> = cx.update(|cx| {
-        to_completion_edits([(2..5, "REM".into()), (9..11, "".into())], &buffer, cx).into()
-    });
-
-    let edit_preview = cx
-        .read(|cx| buffer.read(cx).preview_edits(edits.clone(), cx))
-        .await;
-
-    let completion = EditPrediction {
-        edits,
-        edit_preview,
-        buffer: buffer.clone(),
-        snapshot: cx.read(|cx| buffer.read(cx).snapshot()),
-        id: EditPredictionId("the-id".into()),
-        inputs: EditPredictionInputs {
-            events: Default::default(),
-            included_files: Default::default(),
-            cursor_point: cloud_llm_client::predict_edits_v3::Point {
-                line: Line(0),
-                column: 0,
-            },
-            cursor_path: Path::new("").into(),
-        },
-        buffer_snapshotted_at: Instant::now(),
-        response_received_at: Instant::now(),
-    };
-
-    cx.update(|cx| {
-        assert_eq!(
-            from_completion_edits(
-                &completion.interpolate(&buffer.read(cx).snapshot()).unwrap(),
-                &buffer,
-                cx
-            ),
-            vec![(2..5, "REM".into()), (9..11, "".into())]
-        );
-
-        buffer.update(cx, |buffer, cx| buffer.edit([(2..5, "")], None, cx));
-        assert_eq!(
-            from_completion_edits(
-                &completion.interpolate(&buffer.read(cx).snapshot()).unwrap(),
-                &buffer,
-                cx
-            ),
-            vec![(2..2, "REM".into()), (6..8, "".into())]
-        );
-
-        buffer.update(cx, |buffer, cx| buffer.undo(cx));
-        assert_eq!(
-            from_completion_edits(
-                &completion.interpolate(&buffer.read(cx).snapshot()).unwrap(),
-                &buffer,
-                cx
-            ),
-            vec![(2..5, "REM".into()), (9..11, "".into())]
-        );
-
-        buffer.update(cx, |buffer, cx| buffer.edit([(2..5, "R")], None, cx));
-        assert_eq!(
-            from_completion_edits(
-                &completion.interpolate(&buffer.read(cx).snapshot()).unwrap(),
-                &buffer,
-                cx
-            ),
-            vec![(3..3, "EM".into()), (7..9, "".into())]
-        );
-
-        buffer.update(cx, |buffer, cx| buffer.edit([(3..3, "E")], None, cx));
-        assert_eq!(
-            from_completion_edits(
-                &completion.interpolate(&buffer.read(cx).snapshot()).unwrap(),
-                &buffer,
-                cx
-            ),
-            vec![(4..4, "M".into()), (8..10, "".into())]
-        );
-
-        buffer.update(cx, |buffer, cx| buffer.edit([(4..4, "M")], None, cx));
-        assert_eq!(
-            from_completion_edits(
-                &completion.interpolate(&buffer.read(cx).snapshot()).unwrap(),
-                &buffer,
-                cx
-            ),
-            vec![(9..11, "".into())]
-        );
-
-        buffer.update(cx, |buffer, cx| buffer.edit([(4..5, "")], None, cx));
-        assert_eq!(
-            from_completion_edits(
-                &completion.interpolate(&buffer.read(cx).snapshot()).unwrap(),
-                &buffer,
-                cx
-            ),
-            vec![(4..4, "M".into()), (8..10, "".into())]
-        );
-
-        buffer.update(cx, |buffer, cx| buffer.edit([(8..10, "")], None, cx));
-        assert_eq!(
-            from_completion_edits(
-                &completion.interpolate(&buffer.read(cx).snapshot()).unwrap(),
-                &buffer,
-                cx
-            ),
-            vec![(4..4, "M".into())]
-        );
-
-        buffer.update(cx, |buffer, cx| buffer.edit([(4..6, "")], None, cx));
-        assert_eq!(completion.interpolate(&buffer.read(cx).snapshot()), None);
-    })
-}
-
-#[gpui::test]
-async fn test_clean_up_diff(cx: &mut TestAppContext) {
-    init_test(cx);
-
-    assert_eq!(
-        apply_edit_prediction(
-            indoc! {"
-                    fn main() {
-                        let word_1 = \"lorem\";
-                        let range = word.len()..word.len();
-                    }
-                "},
-            indoc! {"
-                    <|editable_region_start|>
-                    fn main() {
-                        let word_1 = \"lorem\";
-                        let range = word_1.len()..word_1.len();
-                    }
-
-                    <|editable_region_end|>
-                "},
-            cx,
-        )
-        .await,
-        indoc! {"
-                fn main() {
-                    let word_1 = \"lorem\";
-                    let range = word_1.len()..word_1.len();
-                }
-            "},
-    );
-
-    assert_eq!(
-        apply_edit_prediction(
-            indoc! {"
-                    fn main() {
-                        let story = \"the quick\"
-                    }
-                "},
-            indoc! {"
-                    <|editable_region_start|>
-                    fn main() {
-                        let story = \"the quick brown fox jumps over the lazy dog\";
-                    }
-
-                    <|editable_region_end|>
-                "},
-            cx,
-        )
-        .await,
-        indoc! {"
-                fn main() {
-                    let story = \"the quick brown fox jumps over the lazy dog\";
-                }
-            "},
-    );
-}
-
-#[gpui::test]
-async fn test_edit_prediction_end_of_buffer(cx: &mut TestAppContext) {
-    init_test(cx);
-
-    let buffer_content = "lorem\n";
-    let completion_response = indoc! {"
-            ```animals.js
-            <|start_of_file|>
-            <|editable_region_start|>
-            lorem
-            ipsum
-            <|editable_region_end|>
-            ```"};
-
-    assert_eq!(
-        apply_edit_prediction(buffer_content, completion_response, cx).await,
-        "lorem\nipsum"
-    );
-}
-
-#[gpui::test]
-async fn test_can_collect_data(cx: &mut TestAppContext) {
-    init_test(cx);
-
-    let fs = project::FakeFs::new(cx.executor());
-    fs.insert_tree(path!("/project"), json!({ "LICENSE": BSD_0_TXT }))
-        .await;
-
-    let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
-    let buffer = project
-        .update(cx, |project, cx| {
-            project.open_local_buffer(path!("/project/src/main.rs"), cx)
-        })
-        .await
-        .unwrap();
-
-    let (zeta, captured_request, _) = make_test_zeta(&project, cx).await;
-    zeta.update(cx, |zeta, _cx| {
-        zeta.data_collection_choice = DataCollectionChoice::Enabled
-    });
-
-    run_edit_prediction(&buffer, &project, &zeta, cx).await;
-    assert_eq!(
-        captured_request.lock().clone().unwrap().can_collect_data,
-        true
-    );
-
-    zeta.update(cx, |zeta, _cx| {
-        zeta.data_collection_choice = DataCollectionChoice::Disabled
-    });
-
-    run_edit_prediction(&buffer, &project, &zeta, cx).await;
-    assert_eq!(
-        captured_request.lock().clone().unwrap().can_collect_data,
-        false
-    );
-}
-
-#[gpui::test]
-async fn test_no_data_collection_for_remote_file(cx: &mut TestAppContext) {
-    init_test(cx);
-
-    let fs = project::FakeFs::new(cx.executor());
-    let project = Project::test(fs.clone(), [], cx).await;
-
-    let buffer = cx.new(|_cx| {
-        Buffer::remote(
-            language::BufferId::new(1).unwrap(),
-            ReplicaId::new(1),
-            language::Capability::ReadWrite,
-            "fn main() {\n    println!(\"Hello\");\n}",
-        )
-    });
-
-    let (zeta, captured_request, _) = make_test_zeta(&project, cx).await;
-    zeta.update(cx, |zeta, _cx| {
-        zeta.data_collection_choice = DataCollectionChoice::Enabled
-    });
-
-    run_edit_prediction(&buffer, &project, &zeta, cx).await;
-    assert_eq!(
-        captured_request.lock().clone().unwrap().can_collect_data,
-        false
-    );
-}
-
-#[gpui::test]
-async fn test_no_data_collection_for_private_file(cx: &mut TestAppContext) {
-    init_test(cx);
-
-    let fs = project::FakeFs::new(cx.executor());
-    fs.insert_tree(
-        path!("/project"),
-        json!({
-            "LICENSE": BSD_0_TXT,
-            ".env": "SECRET_KEY=secret"
-        }),
-    )
-    .await;
-
-    let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
-    let buffer = project
-        .update(cx, |project, cx| {
-            project.open_local_buffer("/project/.env", cx)
-        })
-        .await
-        .unwrap();
-
-    let (zeta, captured_request, _) = make_test_zeta(&project, cx).await;
-    zeta.update(cx, |zeta, _cx| {
-        zeta.data_collection_choice = DataCollectionChoice::Enabled
-    });
-
-    run_edit_prediction(&buffer, &project, &zeta, cx).await;
-    assert_eq!(
-        captured_request.lock().clone().unwrap().can_collect_data,
-        false
-    );
-}
-
-#[gpui::test]
-async fn test_no_data_collection_for_untitled_buffer(cx: &mut TestAppContext) {
-    init_test(cx);
-
-    let fs = project::FakeFs::new(cx.executor());
-    let project = Project::test(fs.clone(), [], cx).await;
-    let buffer = cx.new(|cx| Buffer::local("", cx));
-
-    let (zeta, captured_request, _) = make_test_zeta(&project, cx).await;
-    zeta.update(cx, |zeta, _cx| {
-        zeta.data_collection_choice = DataCollectionChoice::Enabled
-    });
-
-    run_edit_prediction(&buffer, &project, &zeta, cx).await;
-    assert_eq!(
-        captured_request.lock().clone().unwrap().can_collect_data,
-        false
-    );
-}
-
-#[gpui::test]
-async fn test_no_data_collection_when_closed_source(cx: &mut TestAppContext) {
-    init_test(cx);
-
-    let fs = project::FakeFs::new(cx.executor());
-    fs.insert_tree(path!("/project"), json!({ "main.rs": "fn main() {}" }))
-        .await;
-
-    let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
-    let buffer = project
-        .update(cx, |project, cx| {
-            project.open_local_buffer("/project/main.rs", cx)
-        })
-        .await
-        .unwrap();
-
-    let (zeta, captured_request, _) = make_test_zeta(&project, cx).await;
-    zeta.update(cx, |zeta, _cx| {
-        zeta.data_collection_choice = DataCollectionChoice::Enabled
-    });
-
-    run_edit_prediction(&buffer, &project, &zeta, cx).await;
-    assert_eq!(
-        captured_request.lock().clone().unwrap().can_collect_data,
-        false
-    );
-}
-
-#[gpui::test]
-async fn test_data_collection_status_changes_on_move(cx: &mut TestAppContext) {
-    init_test(cx);
-
-    let fs = project::FakeFs::new(cx.executor());
-    fs.insert_tree(
-        path!("/open_source_worktree"),
-        json!({ "LICENSE": BSD_0_TXT, "main.rs": "" }),
-    )
-    .await;
-    fs.insert_tree(path!("/closed_source_worktree"), json!({ "main.rs": "" }))
-        .await;
-
-    let project = Project::test(
-        fs.clone(),
-        [
-            path!("/open_source_worktree").as_ref(),
-            path!("/closed_source_worktree").as_ref(),
-        ],
-        cx,
-    )
-    .await;
-    let buffer = project
-        .update(cx, |project, cx| {
-            project.open_local_buffer(path!("/open_source_worktree/main.rs"), cx)
-        })
-        .await
-        .unwrap();
-
-    let (zeta, captured_request, _) = make_test_zeta(&project, cx).await;
-    zeta.update(cx, |zeta, _cx| {
-        zeta.data_collection_choice = DataCollectionChoice::Enabled
-    });
-
-    run_edit_prediction(&buffer, &project, &zeta, cx).await;
-    assert_eq!(
-        captured_request.lock().clone().unwrap().can_collect_data,
-        true
-    );
-
-    let closed_source_file = project
-        .update(cx, |project, cx| {
-            let worktree2 = project
-                .worktree_for_root_name("closed_source_worktree", cx)
-                .unwrap();
-            worktree2.update(cx, |worktree2, cx| {
-                worktree2.load_file(rel_path("main.rs"), cx)
-            })
-        })
-        .await
-        .unwrap()
-        .file;
-
-    buffer.update(cx, |buffer, cx| {
-        buffer.file_updated(closed_source_file, cx);
-    });
-
-    run_edit_prediction(&buffer, &project, &zeta, cx).await;
-    assert_eq!(
-        captured_request.lock().clone().unwrap().can_collect_data,
-        false
-    );
-}
-
-#[gpui::test]
-async fn test_no_data_collection_for_events_in_uncollectable_buffers(cx: &mut TestAppContext) {
-    init_test(cx);
-
-    let fs = project::FakeFs::new(cx.executor());
-    fs.insert_tree(
-        path!("/worktree1"),
-        json!({ "LICENSE": BSD_0_TXT, "main.rs": "", "other.rs": "" }),
-    )
-    .await;
-    fs.insert_tree(path!("/worktree2"), json!({ "private.rs": "" }))
-        .await;
-
-    let project = Project::test(
-        fs.clone(),
-        [path!("/worktree1").as_ref(), path!("/worktree2").as_ref()],
-        cx,
-    )
-    .await;
-    let buffer = project
-        .update(cx, |project, cx| {
-            project.open_local_buffer(path!("/worktree1/main.rs"), cx)
-        })
-        .await
-        .unwrap();
-    let private_buffer = project
-        .update(cx, |project, cx| {
-            project.open_local_buffer(path!("/worktree2/file.rs"), cx)
-        })
-        .await
-        .unwrap();
-
-    let (zeta, captured_request, _) = make_test_zeta(&project, cx).await;
-    zeta.update(cx, |zeta, _cx| {
-        zeta.data_collection_choice = DataCollectionChoice::Enabled
-    });
-
-    run_edit_prediction(&buffer, &project, &zeta, cx).await;
-    assert_eq!(
-        captured_request.lock().clone().unwrap().can_collect_data,
-        true
-    );
-
-    // this has a side effect of registering the buffer to watch for edits
-    run_edit_prediction(&private_buffer, &project, &zeta, cx).await;
-    assert_eq!(
-        captured_request.lock().clone().unwrap().can_collect_data,
-        false
-    );
-
-    private_buffer.update(cx, |private_buffer, cx| {
-        private_buffer.edit([(0..0, "An edit for the history!")], None, cx);
-    });
-
-    run_edit_prediction(&buffer, &project, &zeta, cx).await;
-    assert_eq!(
-        captured_request.lock().clone().unwrap().can_collect_data,
-        false
-    );
-
-    // make an edit that uses too many bytes, causing private_buffer edit to not be able to be
-    // included
-    buffer.update(cx, |buffer, cx| {
-        buffer.edit(
-            [(
-                0..0,
-                " ".repeat(MAX_EVENT_TOKENS * zeta1::BYTES_PER_TOKEN_GUESS),
-            )],
-            None,
-            cx,
-        );
-    });
-
-    run_edit_prediction(&buffer, &project, &zeta, cx).await;
-    assert_eq!(
-        captured_request.lock().clone().unwrap().can_collect_data,
-        true
-    );
-}
-
-fn init_test(cx: &mut TestAppContext) {
-    cx.update(|cx| {
-        let settings_store = SettingsStore::test(cx);
-        cx.set_global(settings_store);
-    });
-}
-
-async fn apply_edit_prediction(
-    buffer_content: &str,
-    completion_response: &str,
-    cx: &mut TestAppContext,
-) -> String {
-    let fs = project::FakeFs::new(cx.executor());
-    let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
-    let buffer = cx.new(|cx| Buffer::local(buffer_content, cx));
-    let (zeta, _, response) = make_test_zeta(&project, cx).await;
-    *response.lock() = completion_response.to_string();
-    let edit_prediction = run_edit_prediction(&buffer, &project, &zeta, cx).await;
-    buffer.update(cx, |buffer, cx| {
-        buffer.edit(edit_prediction.edits.iter().cloned(), None, cx)
-    });
-    buffer.read_with(cx, |buffer, _| buffer.text())
-}
-
-async fn run_edit_prediction(
-    buffer: &Entity<Buffer>,
-    project: &Entity<Project>,
-    zeta: &Entity<Zeta>,
-    cx: &mut TestAppContext,
-) -> EditPrediction {
-    let cursor = buffer.read_with(cx, |buffer, _| buffer.anchor_before(Point::new(1, 0)));
-    zeta.update(cx, |zeta, cx| zeta.register_buffer(buffer, &project, cx));
-    cx.background_executor.run_until_parked();
-    let prediction_task = zeta.update(cx, |zeta, cx| {
-        zeta.request_prediction(&project, buffer, cursor, Default::default(), cx)
-    });
-    prediction_task.await.unwrap().unwrap().prediction.unwrap()
-}
-
-async fn make_test_zeta(
-    project: &Entity<Project>,
-    cx: &mut TestAppContext,
-) -> (
-    Entity<Zeta>,
-    Arc<Mutex<Option<PredictEditsBody>>>,
-    Arc<Mutex<String>>,
-) {
-    let default_response = indoc! {"
-            ```main.rs
-            <|start_of_file|>
-            <|editable_region_start|>
-            hello world
-            <|editable_region_end|>
-            ```"
-    };
-    let captured_request: Arc<Mutex<Option<PredictEditsBody>>> = Arc::new(Mutex::new(None));
-    let completion_response: Arc<Mutex<String>> =
-        Arc::new(Mutex::new(default_response.to_string()));
-    let http_client = FakeHttpClient::create({
-        let captured_request = captured_request.clone();
-        let completion_response = completion_response.clone();
-        let mut next_request_id = 0;
-        move |req| {
-            let captured_request = captured_request.clone();
-            let completion_response = completion_response.clone();
-            async move {
-                match (req.method(), req.uri().path()) {
-                    (&Method::POST, "/client/llm_tokens") => Ok(http_client::Response::builder()
-                        .status(200)
-                        .body(
-                            serde_json::to_string(&CreateLlmTokenResponse {
-                                token: LlmToken("the-llm-token".to_string()),
-                            })
-                            .unwrap()
-                            .into(),
-                        )
-                        .unwrap()),
-                    (&Method::POST, "/predict_edits/v2") => {
-                        let mut request_body = String::new();
-                        req.into_body().read_to_string(&mut request_body).await?;
-                        *captured_request.lock() =
-                            Some(serde_json::from_str(&request_body).unwrap());
-                        next_request_id += 1;
-                        Ok(http_client::Response::builder()
-                            .status(200)
-                            .body(
-                                serde_json::to_string(&PredictEditsResponse {
-                                    request_id: format!("request-{next_request_id}"),
-                                    output_excerpt: completion_response.lock().clone(),
-                                })
-                                .unwrap()
-                                .into(),
-                            )
-                            .unwrap())
-                    }
-                    _ => Ok(http_client::Response::builder()
-                        .status(404)
-                        .body("Not Found".into())
-                        .unwrap()),
-                }
-            }
-        }
-    });
-
-    let client = cx.update(|cx| Client::new(Arc::new(FakeSystemClock::new()), http_client, cx));
-    cx.update(|cx| {
-        RefreshLlmTokenListener::register(client.clone(), cx);
-    });
-    let _server = FakeServer::for_client(42, &client, cx).await;
-
-    let zeta = cx.new(|cx| {
-        let mut zeta = Zeta::new(client, project.read(cx).user_store(), cx);
-        zeta.set_edit_prediction_model(ZetaEditPredictionModel::Zeta1);
-
-        let worktrees = project.read(cx).worktrees(cx).collect::<Vec<_>>();
-        for worktree in worktrees {
-            let worktree_id = worktree.read(cx).id();
-            zeta.get_or_init_zeta_project(project, cx)
-                .license_detection_watchers
-                .entry(worktree_id)
-                .or_insert_with(|| Rc::new(LicenseDetectionWatcher::new(&worktree, cx)));
-        }
-
-        zeta
-    });
-
-    (zeta, captured_request, completion_response)
-}
-
-fn to_completion_edits(
-    iterator: impl IntoIterator<Item = (Range<usize>, Arc<str>)>,
-    buffer: &Entity<Buffer>,
-    cx: &App,
-) -> Vec<(Range<Anchor>, Arc<str>)> {
-    let buffer = buffer.read(cx);
-    iterator
-        .into_iter()
-        .map(|(range, text)| {
-            (
-                buffer.anchor_after(range.start)..buffer.anchor_before(range.end),
-                text,
-            )
-        })
-        .collect()
-}
-
-fn from_completion_edits(
-    editor_edits: &[(Range<Anchor>, Arc<str>)],
-    buffer: &Entity<Buffer>,
-    cx: &App,
-) -> Vec<(Range<usize>, Arc<str>)> {
-    let buffer = buffer.read(cx);
-    editor_edits
-        .iter()
-        .map(|(range, text)| {
-            (
-                range.start.to_offset(buffer)..range.end.to_offset(buffer),
-                text.clone(),
-            )
-        })
-        .collect()
-}
-
-#[ctor::ctor]
-fn init_logger() {
-    zlog::init_test();
-}

crates/zeta2_tools/Cargo.toml 🔗

@@ -1,49 +0,0 @@
-[package]
-name = "zeta2_tools"
-version = "0.1.0"
-edition.workspace = true
-publish.workspace = true
-license = "GPL-3.0-or-later"
-
-[lints]
-workspace = true
-
-[lib]
-path = "src/zeta2_tools.rs"
-
-[dependencies]
-anyhow.workspace = true
-client.workspace = true
-cloud_llm_client.workspace = true
-cloud_zeta2_prompt.workspace = true
-collections.workspace = true
-edit_prediction_context.workspace = true
-editor.workspace = true
-feature_flags.workspace = true
-futures.workspace = true
-gpui.workspace = true
-language.workspace = true
-multi_buffer.workspace = true
-project.workspace = true
-serde.workspace = true
-serde_json.workspace = true
-telemetry.workspace = true
-text.workspace = true
-ui.workspace = true
-ui_input.workspace = true
-util.workspace = true
-workspace.workspace = true
-zeta.workspace = true
-
-[dev-dependencies]
-clap.workspace = true
-gpui = { workspace = true, features = ["test-support"] }
-indoc.workspace = true
-language = { workspace = true, features = ["test-support"] }
-pretty_assertions.workspace = true
-project = { workspace = true, features = ["test-support"] }
-serde_json.workspace = true
-settings = { workspace = true, features = ["test-support"] }
-text = { workspace = true, features = ["test-support"] }
-util = { workspace = true, features = ["test-support"] }
-zlog.workspace = true

crates/zeta2_tools/src/zeta2_context_view.rs 🔗

@@ -1,438 +0,0 @@
-use std::{
-    any::TypeId,
-    collections::VecDeque,
-    ops::Add,
-    sync::Arc,
-    time::{Duration, Instant},
-};
-
-use anyhow::Result;
-use client::{Client, UserStore};
-use cloud_zeta2_prompt::retrieval_prompt::SearchToolQuery;
-use editor::{Editor, PathKey};
-use futures::StreamExt as _;
-use gpui::{
-    Animation, AnimationExt, App, AppContext as _, Context, Entity, EventEmitter, FocusHandle,
-    Focusable, ParentElement as _, SharedString, Styled as _, Task, TextAlign, Window, actions,
-    pulsating_between,
-};
-use multi_buffer::MultiBuffer;
-use project::Project;
-use text::OffsetRangeExt;
-use ui::{
-    ButtonCommon, Clickable, Color, Disableable, FluentBuilder as _, Icon, IconButton, IconName,
-    IconSize, InteractiveElement, IntoElement, ListHeader, ListItem, StyledTypography, div, h_flex,
-    v_flex,
-};
-use workspace::Item;
-use zeta::{
-    Zeta, ZetaContextRetrievalDebugInfo, ZetaContextRetrievalStartedDebugInfo, ZetaDebugInfo,
-    ZetaSearchQueryDebugInfo,
-};
-
-pub struct Zeta2ContextView {
-    empty_focus_handle: FocusHandle,
-    project: Entity<Project>,
-    zeta: Entity<Zeta>,
-    runs: VecDeque<RetrievalRun>,
-    current_ix: usize,
-    _update_task: Task<Result<()>>,
-}
-
-#[derive(Debug)]
-struct RetrievalRun {
-    editor: Entity<Editor>,
-    search_queries: Vec<SearchToolQuery>,
-    started_at: Instant,
-    search_results_generated_at: Option<Instant>,
-    search_results_executed_at: Option<Instant>,
-    finished_at: Option<Instant>,
-}
-
-actions!(
-    dev,
-    [
-        /// Go to the previous context retrieval run
-        Zeta2ContextGoBack,
-        /// Go to the next context retrieval run
-        Zeta2ContextGoForward
-    ]
-);
-
-impl Zeta2ContextView {
-    pub fn new(
-        project: Entity<Project>,
-        client: &Arc<Client>,
-        user_store: &Entity<UserStore>,
-        window: &mut gpui::Window,
-        cx: &mut Context<Self>,
-    ) -> Self {
-        let zeta = Zeta::global(client, user_store, cx);
-
-        let mut debug_rx = zeta.update(cx, |zeta, _| zeta.debug_info());
-        let _update_task = cx.spawn_in(window, async move |this, cx| {
-            while let Some(event) = debug_rx.next().await {
-                this.update_in(cx, |this, window, cx| {
-                    this.handle_zeta_event(event, window, cx)
-                })?;
-            }
-            Ok(())
-        });
-
-        Self {
-            empty_focus_handle: cx.focus_handle(),
-            project,
-            runs: VecDeque::new(),
-            current_ix: 0,
-            zeta,
-            _update_task,
-        }
-    }
-
-    fn handle_zeta_event(
-        &mut self,
-        event: ZetaDebugInfo,
-        window: &mut gpui::Window,
-        cx: &mut Context<Self>,
-    ) {
-        match event {
-            ZetaDebugInfo::ContextRetrievalStarted(info) => {
-                if info.project == self.project {
-                    self.handle_context_retrieval_started(info, window, cx);
-                }
-            }
-            ZetaDebugInfo::SearchQueriesGenerated(info) => {
-                if info.project == self.project {
-                    self.handle_search_queries_generated(info, window, cx);
-                }
-            }
-            ZetaDebugInfo::SearchQueriesExecuted(info) => {
-                if info.project == self.project {
-                    self.handle_search_queries_executed(info, window, cx);
-                }
-            }
-            ZetaDebugInfo::ContextRetrievalFinished(info) => {
-                if info.project == self.project {
-                    self.handle_context_retrieval_finished(info, window, cx);
-                }
-            }
-            ZetaDebugInfo::EditPredictionRequested(_) => {}
-        }
-    }
-
-    fn handle_context_retrieval_started(
-        &mut self,
-        info: ZetaContextRetrievalStartedDebugInfo,
-        window: &mut Window,
-        cx: &mut Context<Self>,
-    ) {
-        if self
-            .runs
-            .back()
-            .is_some_and(|run| run.search_results_executed_at.is_none())
-        {
-            self.runs.pop_back();
-        }
-
-        let multibuffer = cx.new(|_| MultiBuffer::new(language::Capability::ReadOnly));
-        let editor = cx
-            .new(|cx| Editor::for_multibuffer(multibuffer, Some(self.project.clone()), window, cx));
-
-        if self.runs.len() == 32 {
-            self.runs.pop_front();
-        }
-
-        self.runs.push_back(RetrievalRun {
-            editor,
-            search_queries: Vec::new(),
-            started_at: info.timestamp,
-            search_results_generated_at: None,
-            search_results_executed_at: None,
-            finished_at: None,
-        });
-
-        cx.notify();
-    }
-
-    fn handle_context_retrieval_finished(
-        &mut self,
-        info: ZetaContextRetrievalDebugInfo,
-        window: &mut Window,
-        cx: &mut Context<Self>,
-    ) {
-        let Some(run) = self.runs.back_mut() else {
-            return;
-        };
-
-        run.finished_at = Some(info.timestamp);
-
-        let multibuffer = run.editor.read(cx).buffer().clone();
-        multibuffer.update(cx, |multibuffer, cx| {
-            multibuffer.clear(cx);
-
-            let context = self.zeta.read(cx).context_for_project(&self.project);
-            let mut paths = Vec::new();
-            for (buffer, ranges) in context {
-                let path = PathKey::for_buffer(&buffer, cx);
-                let snapshot = buffer.read(cx).snapshot();
-                let ranges = ranges
-                    .iter()
-                    .map(|range| range.to_point(&snapshot))
-                    .collect::<Vec<_>>();
-                paths.push((path, buffer, ranges));
-            }
-
-            for (path, buffer, ranges) in paths {
-                multibuffer.set_excerpts_for_path(path, buffer, ranges, 0, cx);
-            }
-        });
-
-        run.editor.update(cx, |editor, cx| {
-            editor.move_to_beginning(&Default::default(), window, cx);
-        });
-
-        cx.notify();
-    }
-
-    fn handle_search_queries_generated(
-        &mut self,
-        info: ZetaSearchQueryDebugInfo,
-        _window: &mut Window,
-        cx: &mut Context<Self>,
-    ) {
-        let Some(run) = self.runs.back_mut() else {
-            return;
-        };
-
-        run.search_results_generated_at = Some(info.timestamp);
-        run.search_queries = info.search_queries;
-        cx.notify();
-    }
-
-    fn handle_search_queries_executed(
-        &mut self,
-        info: ZetaContextRetrievalDebugInfo,
-        _window: &mut Window,
-        cx: &mut Context<Self>,
-    ) {
-        if self.current_ix + 2 == self.runs.len() {
-            // Switch to latest when the queries are executed
-            self.current_ix += 1;
-        }
-
-        let Some(run) = self.runs.back_mut() else {
-            return;
-        };
-
-        run.search_results_executed_at = Some(info.timestamp);
-        cx.notify();
-    }
-
-    fn handle_go_back(
-        &mut self,
-        _: &Zeta2ContextGoBack,
-        window: &mut Window,
-        cx: &mut Context<Self>,
-    ) {
-        self.current_ix = self.current_ix.saturating_sub(1);
-        cx.focus_self(window);
-        cx.notify();
-    }
-
-    fn handle_go_forward(
-        &mut self,
-        _: &Zeta2ContextGoForward,
-        window: &mut Window,
-        cx: &mut Context<Self>,
-    ) {
-        self.current_ix = self
-            .current_ix
-            .add(1)
-            .min(self.runs.len().saturating_sub(1));
-        cx.focus_self(window);
-        cx.notify();
-    }
-
-    fn render_informational_footer(&self, cx: &mut Context<'_, Zeta2ContextView>) -> ui::Div {
-        let is_latest = self.runs.len() == self.current_ix + 1;
-        let run = &self.runs[self.current_ix];
-
-        h_flex()
-            .p_2()
-            .w_full()
-            .font_buffer(cx)
-            .text_xs()
-            .border_t_1()
-            .gap_2()
-            .child(
-                v_flex().h_full().flex_1().children(
-                    run.search_queries
-                        .iter()
-                        .enumerate()
-                        .flat_map(|(ix, query)| {
-                            std::iter::once(ListHeader::new(query.glob.clone()).into_any_element())
-                                .chain(query.syntax_node.iter().enumerate().map(
-                                    move |(regex_ix, regex)| {
-                                        ListItem::new(ix * 100 + regex_ix)
-                                            .start_slot(
-                                                Icon::new(IconName::MagnifyingGlass)
-                                                    .color(Color::Muted)
-                                                    .size(IconSize::Small),
-                                            )
-                                            .child(regex.clone())
-                                            .into_any_element()
-                                    },
-                                ))
-                                .chain(query.content.as_ref().map(move |regex| {
-                                    ListItem::new(ix * 100 + query.syntax_node.len())
-                                        .start_slot(
-                                            Icon::new(IconName::MagnifyingGlass)
-                                                .color(Color::Muted)
-                                                .size(IconSize::Small),
-                                        )
-                                        .child(regex.clone())
-                                        .into_any_element()
-                                }))
-                        }),
-                ),
-            )
-            .child(
-                v_flex()
-                    .h_full()
-                    .text_align(TextAlign::Right)
-                    .child(
-                        h_flex()
-                            .justify_end()
-                            .child(
-                                IconButton::new("go-back", IconName::ChevronLeft)
-                                    .disabled(self.current_ix == 0 || self.runs.len() < 2)
-                                    .tooltip(ui::Tooltip::for_action_title(
-                                        "Go to previous run",
-                                        &Zeta2ContextGoBack,
-                                    ))
-                                    .on_click(cx.listener(|this, _, window, cx| {
-                                        this.handle_go_back(&Zeta2ContextGoBack, window, cx);
-                                    })),
-                            )
-                            .child(
-                                div()
-                                    .child(format!("{}/{}", self.current_ix + 1, self.runs.len()))
-                                    .map(|this| {
-                                        if self.runs.back().is_some_and(|back| {
-                                            back.search_results_executed_at.is_none()
-                                        }) {
-                                            this.with_animation(
-                                                "pulsating-count",
-                                                Animation::new(Duration::from_secs(2))
-                                                    .repeat()
-                                                    .with_easing(pulsating_between(0.4, 0.8)),
-                                                |label, delta| label.opacity(delta),
-                                            )
-                                            .into_any_element()
-                                        } else {
-                                            this.into_any_element()
-                                        }
-                                    }),
-                            )
-                            .child(
-                                IconButton::new("go-forward", IconName::ChevronRight)
-                                    .disabled(self.current_ix + 1 == self.runs.len())
-                                    .tooltip(ui::Tooltip::for_action_title(
-                                        "Go to next run",
-                                        &Zeta2ContextGoBack,
-                                    ))
-                                    .on_click(cx.listener(|this, _, window, cx| {
-                                        this.handle_go_forward(&Zeta2ContextGoForward, window, cx);
-                                    })),
-                            ),
-                    )
-                    .map(|mut div| {
-                        let pending_message = |div: ui::Div, msg: &'static str| {
-                            if is_latest {
-                                return div.child(msg);
-                            } else {
-                                return div.child("Canceled");
-                            }
-                        };
-
-                        let t0 = run.started_at;
-                        let Some(t1) = run.search_results_generated_at else {
-                            return pending_message(div, "Planning search...");
-                        };
-                        div = div.child(format!("Planned search: {:>5} ms", (t1 - t0).as_millis()));
-
-                        let Some(t2) = run.search_results_executed_at else {
-                            return pending_message(div, "Running search...");
-                        };
-                        div = div.child(format!("Ran search: {:>5} ms", (t2 - t1).as_millis()));
-
-                        div.child(format!(
-                            "Total: {:>5} ms",
-                            (run.finished_at.unwrap_or(t0) - t0).as_millis()
-                        ))
-                    }),
-            )
-    }
-}
-
-impl Focusable for Zeta2ContextView {
-    fn focus_handle(&self, cx: &App) -> FocusHandle {
-        self.runs
-            .get(self.current_ix)
-            .map(|run| run.editor.read(cx).focus_handle(cx))
-            .unwrap_or_else(|| self.empty_focus_handle.clone())
-    }
-}
-
-impl EventEmitter<()> for Zeta2ContextView {}
-
-impl Item for Zeta2ContextView {
-    type Event = ();
-
-    fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
-        "Edit Prediction Context".into()
-    }
-
-    fn buffer_kind(&self, _cx: &App) -> workspace::item::ItemBufferKind {
-        workspace::item::ItemBufferKind::Multibuffer
-    }
-
-    fn act_as_type<'a>(
-        &'a self,
-        type_id: TypeId,
-        self_handle: &'a Entity<Self>,
-        _: &'a App,
-    ) -> Option<gpui::AnyEntity> {
-        if type_id == TypeId::of::<Self>() {
-            Some(self_handle.clone().into())
-        } else if type_id == TypeId::of::<Editor>() {
-            Some(self.runs.get(self.current_ix)?.editor.clone().into())
-        } else {
-            None
-        }
-    }
-}
-
-impl gpui::Render for Zeta2ContextView {
-    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl ui::IntoElement {
-        v_flex()
-            .key_context("Zeta2Context")
-            .on_action(cx.listener(Self::handle_go_back))
-            .on_action(cx.listener(Self::handle_go_forward))
-            .size_full()
-            .map(|this| {
-                if self.runs.is_empty() {
-                    this.child(
-                        v_flex()
-                            .size_full()
-                            .justify_center()
-                            .items_center()
-                            .child("No retrieval runs yet"),
-                    )
-                } else {
-                    this.child(self.runs[self.current_ix].editor.clone())
-                        .child(self.render_informational_footer(cx))
-                }
-            })
-    }
-}

crates/zeta2_tools/src/zeta2_tools.rs 🔗

@@ -1,1023 +0,0 @@
-mod zeta2_context_view;
-
-use std::{str::FromStr, sync::Arc, time::Duration};
-
-use client::{Client, UserStore};
-use cloud_llm_client::predict_edits_v3::PromptFormat;
-use collections::HashMap;
-use editor::{Editor, EditorEvent, EditorMode, MultiBuffer};
-use feature_flags::FeatureFlagAppExt as _;
-use futures::{FutureExt, StreamExt as _, channel::oneshot, future::Shared};
-use gpui::{
-    Empty, Entity, EventEmitter, FocusHandle, Focusable, Subscription, Task, WeakEntity, actions,
-    prelude::*,
-};
-use language::Buffer;
-use project::{Project, telemetry_snapshot::TelemetrySnapshot};
-use ui::{ButtonLike, ContextMenu, ContextMenuEntry, DropdownMenu, KeyBinding, prelude::*};
-use ui_input::InputField;
-use util::ResultExt;
-use workspace::{Item, SplitDirection, Workspace};
-use zeta::{
-    AgenticContextOptions, ContextMode, DEFAULT_SYNTAX_CONTEXT_OPTIONS, EditPredictionInputs, Zeta,
-    Zeta2FeatureFlag, ZetaDebugInfo, ZetaEditPredictionDebugInfo, ZetaOptions,
-};
-
-use edit_prediction_context::{EditPredictionContextOptions, EditPredictionExcerptOptions};
-use zeta2_context_view::Zeta2ContextView;
-
-actions!(
-    dev,
-    [
-        /// Opens the edit prediction context view.
-        OpenZeta2ContextView,
-        /// Opens the edit prediction inspector.
-        OpenZeta2Inspector,
-        /// Rate prediction as positive.
-        Zeta2RatePredictionPositive,
-        /// Rate prediction as negative.
-        Zeta2RatePredictionNegative,
-    ]
-);
-
-pub fn init(cx: &mut App) {
-    cx.observe_new(move |workspace: &mut Workspace, _, _cx| {
-        workspace.register_action_renderer(|div, _, _, cx| {
-            let has_flag = cx.has_flag::<Zeta2FeatureFlag>();
-            div.when(has_flag, |div| {
-                div.on_action(
-                    cx.listener(move |workspace, _: &OpenZeta2Inspector, window, cx| {
-                        let project = workspace.project();
-                        workspace.split_item(
-                            SplitDirection::Right,
-                            Box::new(cx.new(|cx| {
-                                Zeta2Inspector::new(
-                                    &project,
-                                    workspace.client(),
-                                    workspace.user_store(),
-                                    window,
-                                    cx,
-                                )
-                            })),
-                            window,
-                            cx,
-                        )
-                    }),
-                )
-                .on_action(cx.listener(
-                    move |workspace, _: &OpenZeta2ContextView, window, cx| {
-                        let project = workspace.project();
-                        workspace.split_item(
-                            SplitDirection::Right,
-                            Box::new(cx.new(|cx| {
-                                Zeta2ContextView::new(
-                                    project.clone(),
-                                    workspace.client(),
-                                    workspace.user_store(),
-                                    window,
-                                    cx,
-                                )
-                            })),
-                            window,
-                            cx,
-                        );
-                    },
-                ))
-            })
-        });
-    })
-    .detach();
-}
-
-// TODO show included diagnostics, and events
-
-pub struct Zeta2Inspector {
-    focus_handle: FocusHandle,
-    project: Entity<Project>,
-    last_prediction: Option<LastPrediction>,
-    max_excerpt_bytes_input: Entity<InputField>,
-    min_excerpt_bytes_input: Entity<InputField>,
-    cursor_context_ratio_input: Entity<InputField>,
-    max_prompt_bytes_input: Entity<InputField>,
-    context_mode: ContextModeState,
-    zeta: Entity<Zeta>,
-    _active_editor_subscription: Option<Subscription>,
-    _update_state_task: Task<()>,
-    _receive_task: Task<()>,
-}
-
-pub enum ContextModeState {
-    Llm,
-    Syntax {
-        max_retrieved_declarations: Entity<InputField>,
-    },
-}
-
-struct LastPrediction {
-    prompt_editor: Entity<Editor>,
-    retrieval_time: Duration,
-    request_time: Option<Duration>,
-    buffer: WeakEntity<Buffer>,
-    position: language::Anchor,
-    state: LastPredictionState,
-    inputs: EditPredictionInputs,
-    project_snapshot: Shared<Task<Arc<TelemetrySnapshot>>>,
-    _task: Option<Task<()>>,
-}
-
-#[derive(Clone, Copy, PartialEq)]
-enum Feedback {
-    Positive,
-    Negative,
-}
-
-enum LastPredictionState {
-    Requested,
-    Success {
-        model_response_editor: Entity<Editor>,
-        feedback_editor: Entity<Editor>,
-        feedback: Option<Feedback>,
-        request_id: String,
-    },
-    Failed {
-        message: String,
-    },
-}
-
-impl Zeta2Inspector {
-    pub fn new(
-        project: &Entity<Project>,
-        client: &Arc<Client>,
-        user_store: &Entity<UserStore>,
-        window: &mut Window,
-        cx: &mut Context<Self>,
-    ) -> Self {
-        let zeta = Zeta::global(client, user_store, cx);
-        let mut request_rx = zeta.update(cx, |zeta, _cx| zeta.debug_info());
-
-        let receive_task = cx.spawn_in(window, async move |this, cx| {
-            while let Some(prediction) = request_rx.next().await {
-                this.update_in(cx, |this, window, cx| {
-                    this.update_last_prediction(prediction, window, cx)
-                })
-                .ok();
-            }
-        });
-
-        let mut this = Self {
-            focus_handle: cx.focus_handle(),
-            project: project.clone(),
-            last_prediction: None,
-            max_excerpt_bytes_input: Self::number_input("Max Excerpt Bytes", window, cx),
-            min_excerpt_bytes_input: Self::number_input("Min Excerpt Bytes", window, cx),
-            cursor_context_ratio_input: Self::number_input("Cursor Context Ratio", window, cx),
-            max_prompt_bytes_input: Self::number_input("Max Prompt Bytes", window, cx),
-            context_mode: ContextModeState::Llm,
-            zeta: zeta.clone(),
-            _active_editor_subscription: None,
-            _update_state_task: Task::ready(()),
-            _receive_task: receive_task,
-        };
-        this.set_options_state(&zeta.read(cx).options().clone(), window, cx);
-        this
-    }
-
-    fn set_options_state(
-        &mut self,
-        options: &ZetaOptions,
-        window: &mut Window,
-        cx: &mut Context<Self>,
-    ) {
-        let excerpt_options = options.context.excerpt();
-        self.max_excerpt_bytes_input.update(cx, |input, cx| {
-            input.set_text(excerpt_options.max_bytes.to_string(), window, cx);
-        });
-        self.min_excerpt_bytes_input.update(cx, |input, cx| {
-            input.set_text(excerpt_options.min_bytes.to_string(), window, cx);
-        });
-        self.cursor_context_ratio_input.update(cx, |input, cx| {
-            input.set_text(
-                format!(
-                    "{:.2}",
-                    excerpt_options.target_before_cursor_over_total_bytes
-                ),
-                window,
-                cx,
-            );
-        });
-        self.max_prompt_bytes_input.update(cx, |input, cx| {
-            input.set_text(options.max_prompt_bytes.to_string(), window, cx);
-        });
-
-        match &options.context {
-            ContextMode::Agentic(_) => {
-                self.context_mode = ContextModeState::Llm;
-            }
-            ContextMode::Syntax(_) => {
-                self.context_mode = ContextModeState::Syntax {
-                    max_retrieved_declarations: Self::number_input(
-                        "Max Retrieved Definitions",
-                        window,
-                        cx,
-                    ),
-                };
-            }
-        }
-        cx.notify();
-    }
-
-    fn set_zeta_options(&mut self, options: ZetaOptions, cx: &mut Context<Self>) {
-        self.zeta.update(cx, |this, _cx| this.set_options(options));
-
-        if let Some(prediction) = self.last_prediction.as_mut() {
-            if let Some(buffer) = prediction.buffer.upgrade() {
-                let position = prediction.position;
-                let project = self.project.clone();
-                self.zeta.update(cx, |zeta, cx| {
-                    zeta.refresh_prediction_from_buffer(project, buffer, position, cx)
-                });
-                prediction.state = LastPredictionState::Requested;
-            } else {
-                self.last_prediction.take();
-            }
-        }
-
-        cx.notify();
-    }
-
-    fn number_input(
-        label: &'static str,
-        window: &mut Window,
-        cx: &mut Context<Self>,
-    ) -> Entity<InputField> {
-        let input = cx.new(|cx| {
-            InputField::new(window, cx, "")
-                .label(label)
-                .label_min_width(px(64.))
-        });
-
-        cx.subscribe_in(
-            &input.read(cx).editor().clone(),
-            window,
-            |this, _, event, _window, cx| {
-                let EditorEvent::BufferEdited = event else {
-                    return;
-                };
-
-                fn number_input_value<T: FromStr + Default>(
-                    input: &Entity<InputField>,
-                    cx: &App,
-                ) -> T {
-                    input
-                        .read(cx)
-                        .editor()
-                        .read(cx)
-                        .text(cx)
-                        .parse::<T>()
-                        .unwrap_or_default()
-                }
-
-                let zeta_options = this.zeta.read(cx).options().clone();
-
-                let excerpt_options = EditPredictionExcerptOptions {
-                    max_bytes: number_input_value(&this.max_excerpt_bytes_input, cx),
-                    min_bytes: number_input_value(&this.min_excerpt_bytes_input, cx),
-                    target_before_cursor_over_total_bytes: number_input_value(
-                        &this.cursor_context_ratio_input,
-                        cx,
-                    ),
-                };
-
-                let context = match zeta_options.context {
-                    ContextMode::Agentic(_context_options) => {
-                        ContextMode::Agentic(AgenticContextOptions {
-                            excerpt: excerpt_options,
-                        })
-                    }
-                    ContextMode::Syntax(context_options) => {
-                        let max_retrieved_declarations = match &this.context_mode {
-                            ContextModeState::Llm => {
-                                zeta::DEFAULT_SYNTAX_CONTEXT_OPTIONS.max_retrieved_declarations
-                            }
-                            ContextModeState::Syntax {
-                                max_retrieved_declarations,
-                            } => number_input_value(max_retrieved_declarations, cx),
-                        };
-
-                        ContextMode::Syntax(EditPredictionContextOptions {
-                            excerpt: excerpt_options,
-                            max_retrieved_declarations,
-                            ..context_options
-                        })
-                    }
-                };
-
-                this.set_zeta_options(
-                    ZetaOptions {
-                        context,
-                        max_prompt_bytes: number_input_value(&this.max_prompt_bytes_input, cx),
-                        max_diagnostic_bytes: zeta_options.max_diagnostic_bytes,
-                        prompt_format: zeta_options.prompt_format,
-                        file_indexing_parallelism: zeta_options.file_indexing_parallelism,
-                        buffer_change_grouping_interval: zeta_options
-                            .buffer_change_grouping_interval,
-                    },
-                    cx,
-                );
-            },
-        )
-        .detach();
-        input
-    }
-
-    fn update_last_prediction(
-        &mut self,
-        prediction: zeta::ZetaDebugInfo,
-        window: &mut Window,
-        cx: &mut Context<Self>,
-    ) {
-        self._update_state_task = cx.spawn_in(window, {
-            let language_registry = self.project.read(cx).languages().clone();
-            async move |this, cx| {
-                let mut languages = HashMap::default();
-                let ZetaDebugInfo::EditPredictionRequested(prediction) = prediction else {
-                    return;
-                };
-                for ext in prediction
-                    .inputs
-                    .included_files
-                    .iter()
-                    .filter_map(|file| file.path.extension())
-                {
-                    if !languages.contains_key(ext) {
-                        // Most snippets are gonna be the same language,
-                        // so we think it's fine to do this sequentially for now
-                        languages.insert(
-                            ext.to_owned(),
-                            language_registry
-                                .language_for_name_or_extension(&ext.to_string_lossy())
-                                .await
-                                .ok(),
-                        );
-                    }
-                }
-
-                let markdown_language = language_registry
-                    .language_for_name("Markdown")
-                    .await
-                    .log_err();
-
-                let json_language = language_registry.language_for_name("Json").await.log_err();
-
-                this.update_in(cx, |this, window, cx| {
-                    let ZetaEditPredictionDebugInfo {
-                        response_rx,
-                        position,
-                        buffer,
-                        retrieval_time,
-                        local_prompt,
-                        ..
-                    } = prediction;
-
-                    let task = cx.spawn_in(window, {
-                        let markdown_language = markdown_language.clone();
-                        let json_language = json_language.clone();
-                        async move |this, cx| {
-                            let response = response_rx.await;
-
-                            this.update_in(cx, |this, window, cx| {
-                                if let Some(prediction) = this.last_prediction.as_mut() {
-                                    prediction.state = match response {
-                                        Ok((Ok(response), request_time)) => {
-                                            prediction.request_time = Some(request_time);
-
-                                            let feedback_editor = cx.new(|cx| {
-                                                let buffer = cx.new(|cx| {
-                                                    let mut buffer = Buffer::local("", cx);
-                                                    buffer.set_language(
-                                                        markdown_language.clone(),
-                                                        cx,
-                                                    );
-                                                    buffer
-                                                });
-                                                let buffer =
-                                                    cx.new(|cx| MultiBuffer::singleton(buffer, cx));
-                                                let mut editor = Editor::new(
-                                                    EditorMode::AutoHeight {
-                                                        min_lines: 3,
-                                                        max_lines: None,
-                                                    },
-                                                    buffer,
-                                                    None,
-                                                    window,
-                                                    cx,
-                                                );
-                                                editor.set_placeholder_text(
-                                                    "Write feedback here",
-                                                    window,
-                                                    cx,
-                                                );
-                                                editor.set_show_line_numbers(false, cx);
-                                                editor.set_show_gutter(false, cx);
-                                                editor.set_show_scrollbars(false, cx);
-                                                editor
-                                            });
-
-                                            cx.subscribe_in(
-                                                &feedback_editor,
-                                                window,
-                                                |this, editor, ev, window, cx| match ev {
-                                                    EditorEvent::BufferEdited => {
-                                                        if let Some(last_prediction) =
-                                                            this.last_prediction.as_mut()
-                                                            && let LastPredictionState::Success {
-                                                                feedback: feedback_state,
-                                                                ..
-                                                            } = &mut last_prediction.state
-                                                        {
-                                                            if feedback_state.take().is_some() {
-                                                                editor.update(cx, |editor, cx| {
-                                                                    editor.set_placeholder_text(
-                                                                        "Write feedback here",
-                                                                        window,
-                                                                        cx,
-                                                                    );
-                                                                });
-                                                                cx.notify();
-                                                            }
-                                                        }
-                                                    }
-                                                    _ => {}
-                                                },
-                                            )
-                                            .detach();
-
-                                            LastPredictionState::Success {
-                                                model_response_editor: cx.new(|cx| {
-                                                    let buffer = cx.new(|cx| {
-                                                        let mut buffer = Buffer::local(
-                                                            serde_json::to_string_pretty(&response)
-                                                                .unwrap_or_default(),
-                                                            cx,
-                                                        );
-                                                        buffer.set_language(json_language, cx);
-                                                        buffer
-                                                    });
-                                                    let buffer = cx.new(|cx| {
-                                                        MultiBuffer::singleton(buffer, cx)
-                                                    });
-                                                    let mut editor = Editor::new(
-                                                        EditorMode::full(),
-                                                        buffer,
-                                                        None,
-                                                        window,
-                                                        cx,
-                                                    );
-                                                    editor.set_read_only(true);
-                                                    editor.set_show_line_numbers(false, cx);
-                                                    editor.set_show_gutter(false, cx);
-                                                    editor.set_show_scrollbars(false, cx);
-                                                    editor
-                                                }),
-                                                feedback_editor,
-                                                feedback: None,
-                                                request_id: response.id.clone(),
-                                            }
-                                        }
-                                        Ok((Err(err), request_time)) => {
-                                            prediction.request_time = Some(request_time);
-                                            LastPredictionState::Failed { message: err }
-                                        }
-                                        Err(oneshot::Canceled) => LastPredictionState::Failed {
-                                            message: "Canceled".to_string(),
-                                        },
-                                    };
-                                }
-                            })
-                            .ok();
-                        }
-                    });
-
-                    let project_snapshot_task = TelemetrySnapshot::new(&this.project, cx);
-
-                    this.last_prediction = Some(LastPrediction {
-                        prompt_editor: cx.new(|cx| {
-                            let buffer = cx.new(|cx| {
-                                let mut buffer =
-                                    Buffer::local(local_prompt.unwrap_or_else(|err| err), cx);
-                                buffer.set_language(markdown_language.clone(), cx);
-                                buffer
-                            });
-                            let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
-                            let mut editor =
-                                Editor::new(EditorMode::full(), buffer, None, window, cx);
-                            editor.set_read_only(true);
-                            editor.set_show_line_numbers(false, cx);
-                            editor.set_show_gutter(false, cx);
-                            editor.set_show_scrollbars(false, cx);
-                            editor
-                        }),
-                        retrieval_time,
-                        request_time: None,
-                        buffer,
-                        position,
-                        state: LastPredictionState::Requested,
-                        project_snapshot: cx
-                            .foreground_executor()
-                            .spawn(async move { Arc::new(project_snapshot_task.await) })
-                            .shared(),
-                        inputs: prediction.inputs,
-                        _task: Some(task),
-                    });
-                    cx.notify();
-                })
-                .ok();
-            }
-        });
-    }
-
-    fn handle_rate_positive(
-        &mut self,
-        _action: &Zeta2RatePredictionPositive,
-        window: &mut Window,
-        cx: &mut Context<Self>,
-    ) {
-        self.handle_rate(Feedback::Positive, window, cx);
-    }
-
-    fn handle_rate_negative(
-        &mut self,
-        _action: &Zeta2RatePredictionNegative,
-        window: &mut Window,
-        cx: &mut Context<Self>,
-    ) {
-        self.handle_rate(Feedback::Negative, window, cx);
-    }
-
-    fn handle_rate(&mut self, kind: Feedback, window: &mut Window, cx: &mut Context<Self>) {
-        let Some(last_prediction) = self.last_prediction.as_mut() else {
-            return;
-        };
-
-        let project_snapshot_task = last_prediction.project_snapshot.clone();
-
-        cx.spawn_in(window, async move |this, cx| {
-            let project_snapshot = project_snapshot_task.await;
-            this.update_in(cx, |this, window, cx| {
-                let Some(last_prediction) = this.last_prediction.as_mut() else {
-                    return;
-                };
-
-                let LastPredictionState::Success {
-                    feedback: feedback_state,
-                    feedback_editor,
-                    model_response_editor,
-                    request_id,
-                    ..
-                } = &mut last_prediction.state
-                else {
-                    return;
-                };
-
-                *feedback_state = Some(kind);
-                let text = feedback_editor.update(cx, |feedback_editor, cx| {
-                    feedback_editor.set_placeholder_text(
-                        "Submitted. Edit or submit again to change.",
-                        window,
-                        cx,
-                    );
-                    feedback_editor.text(cx)
-                });
-                cx.notify();
-
-                cx.defer_in(window, {
-                    let model_response_editor = model_response_editor.downgrade();
-                    move |_, window, cx| {
-                        if let Some(model_response_editor) = model_response_editor.upgrade() {
-                            model_response_editor.focus_handle(cx).focus(window);
-                        }
-                    }
-                });
-
-                let kind = match kind {
-                    Feedback::Positive => "positive",
-                    Feedback::Negative => "negative",
-                };
-
-                telemetry::event!(
-                    "Zeta2 Prediction Rated",
-                    id = request_id,
-                    kind = kind,
-                    text = text,
-                    request = last_prediction.inputs,
-                    project_snapshot = project_snapshot,
-                );
-            })
-            .log_err();
-        })
-        .detach();
-    }
-
-    fn render_options(&self, window: &mut Window, cx: &mut Context<Self>) -> Div {
-        v_flex()
-            .gap_2()
-            .child(
-                h_flex()
-                    .child(Headline::new("Options").size(HeadlineSize::Small))
-                    .justify_between()
-                    .child(
-                        ui::Button::new("reset-options", "Reset")
-                            .disabled(self.zeta.read(cx).options() == &zeta::DEFAULT_OPTIONS)
-                            .style(ButtonStyle::Outlined)
-                            .size(ButtonSize::Large)
-                            .on_click(cx.listener(|this, _, window, cx| {
-                                this.set_options_state(&zeta::DEFAULT_OPTIONS, window, cx);
-                            })),
-                    ),
-            )
-            .child(
-                v_flex()
-                    .gap_2()
-                    .child(
-                        h_flex()
-                            .gap_2()
-                            .items_end()
-                            .child(self.max_excerpt_bytes_input.clone())
-                            .child(self.min_excerpt_bytes_input.clone())
-                            .child(self.cursor_context_ratio_input.clone())
-                            .child(self.render_context_mode_dropdown(window, cx)),
-                    )
-                    .child(
-                        h_flex()
-                            .gap_2()
-                            .items_end()
-                            .children(match &self.context_mode {
-                                ContextModeState::Llm => None,
-                                ContextModeState::Syntax {
-                                    max_retrieved_declarations,
-                                } => Some(max_retrieved_declarations.clone()),
-                            })
-                            .child(self.max_prompt_bytes_input.clone())
-                            .child(self.render_prompt_format_dropdown(window, cx)),
-                    ),
-            )
-    }
-
-    fn render_context_mode_dropdown(&self, window: &mut Window, cx: &mut Context<Self>) -> Div {
-        let this = cx.weak_entity();
-
-        v_flex()
-            .gap_1p5()
-            .child(
-                Label::new("Context Mode")
-                    .size(LabelSize::Small)
-                    .color(Color::Muted),
-            )
-            .child(
-                DropdownMenu::new(
-                    "ep-ctx-mode",
-                    match &self.context_mode {
-                        ContextModeState::Llm => "LLM-based",
-                        ContextModeState::Syntax { .. } => "Syntax",
-                    },
-                    ContextMenu::build(window, cx, move |menu, _window, _cx| {
-                        menu.item(
-                            ContextMenuEntry::new("LLM-based")
-                                .toggleable(
-                                    IconPosition::End,
-                                    matches!(self.context_mode, ContextModeState::Llm),
-                                )
-                                .handler({
-                                    let this = this.clone();
-                                    move |window, cx| {
-                                        this.update(cx, |this, cx| {
-                                            let current_options =
-                                                this.zeta.read(cx).options().clone();
-                                            match current_options.context.clone() {
-                                                ContextMode::Agentic(_) => {}
-                                                ContextMode::Syntax(context_options) => {
-                                                    let options = ZetaOptions {
-                                                        context: ContextMode::Agentic(
-                                                            AgenticContextOptions {
-                                                                excerpt: context_options.excerpt,
-                                                            },
-                                                        ),
-                                                        ..current_options
-                                                    };
-                                                    this.set_options_state(&options, window, cx);
-                                                    this.set_zeta_options(options, cx);
-                                                }
-                                            }
-                                        })
-                                        .ok();
-                                    }
-                                }),
-                        )
-                        .item(
-                            ContextMenuEntry::new("Syntax")
-                                .toggleable(
-                                    IconPosition::End,
-                                    matches!(self.context_mode, ContextModeState::Syntax { .. }),
-                                )
-                                .handler({
-                                    move |window, cx| {
-                                        this.update(cx, |this, cx| {
-                                            let current_options =
-                                                this.zeta.read(cx).options().clone();
-                                            match current_options.context.clone() {
-                                                ContextMode::Agentic(context_options) => {
-                                                    let options = ZetaOptions {
-                                                        context: ContextMode::Syntax(
-                                                            EditPredictionContextOptions {
-                                                                excerpt: context_options.excerpt,
-                                                                ..DEFAULT_SYNTAX_CONTEXT_OPTIONS
-                                                            },
-                                                        ),
-                                                        ..current_options
-                                                    };
-                                                    this.set_options_state(&options, window, cx);
-                                                    this.set_zeta_options(options, cx);
-                                                }
-                                                ContextMode::Syntax(_) => {}
-                                            }
-                                        })
-                                        .ok();
-                                    }
-                                }),
-                        )
-                    }),
-                )
-                .style(ui::DropdownStyle::Outlined),
-            )
-    }
-
-    fn render_prompt_format_dropdown(&self, window: &mut Window, cx: &mut Context<Self>) -> Div {
-        let active_format = self.zeta.read(cx).options().prompt_format;
-        let this = cx.weak_entity();
-
-        v_flex()
-            .gap_1p5()
-            .child(
-                Label::new("Prompt Format")
-                    .size(LabelSize::Small)
-                    .color(Color::Muted),
-            )
-            .child(
-                DropdownMenu::new(
-                    "ep-prompt-format",
-                    active_format.to_string(),
-                    ContextMenu::build(window, cx, move |mut menu, _window, _cx| {
-                        for prompt_format in PromptFormat::iter() {
-                            menu = menu.item(
-                                ContextMenuEntry::new(prompt_format.to_string())
-                                    .toggleable(IconPosition::End, active_format == prompt_format)
-                                    .handler({
-                                        let this = this.clone();
-                                        move |_window, cx| {
-                                            this.update(cx, |this, cx| {
-                                                let current_options =
-                                                    this.zeta.read(cx).options().clone();
-                                                let options = ZetaOptions {
-                                                    prompt_format,
-                                                    ..current_options
-                                                };
-                                                this.set_zeta_options(options, cx);
-                                            })
-                                            .ok();
-                                        }
-                                    }),
-                            )
-                        }
-                        menu
-                    }),
-                )
-                .style(ui::DropdownStyle::Outlined),
-            )
-    }
-
-    fn render_stats(&self) -> Option<Div> {
-        let Some(prediction) = self.last_prediction.as_ref() else {
-            return None;
-        };
-
-        Some(
-            v_flex()
-                .p_4()
-                .gap_2()
-                .min_w(px(160.))
-                .child(Headline::new("Stats").size(HeadlineSize::Small))
-                .child(Self::render_duration(
-                    "Context retrieval",
-                    Some(prediction.retrieval_time),
-                ))
-                .child(Self::render_duration("Request", prediction.request_time)),
-        )
-    }
-
-    fn render_duration(name: &'static str, time: Option<Duration>) -> Div {
-        h_flex()
-            .gap_1()
-            .child(Label::new(name).color(Color::Muted).size(LabelSize::Small))
-            .child(match time {
-                Some(time) => Label::new(if time.as_micros() >= 1000 {
-                    format!("{} ms", time.as_millis())
-                } else {
-                    format!("{} µs", time.as_micros())
-                })
-                .size(LabelSize::Small),
-                None => Label::new("...").size(LabelSize::Small),
-            })
-    }
-
-    fn render_content(&self, _: &mut Window, cx: &mut Context<Self>) -> AnyElement {
-        if !cx.has_flag::<Zeta2FeatureFlag>() {
-            return Self::render_message("`zeta2` feature flag is not enabled");
-        }
-
-        match self.last_prediction.as_ref() {
-            None => Self::render_message("No prediction"),
-            Some(prediction) => self.render_last_prediction(prediction, cx).into_any(),
-        }
-    }
-
-    fn render_message(message: impl Into<SharedString>) -> AnyElement {
-        v_flex()
-            .size_full()
-            .justify_center()
-            .items_center()
-            .child(Label::new(message).size(LabelSize::Large))
-            .into_any()
-    }
-
-    fn render_last_prediction(&self, prediction: &LastPrediction, cx: &mut Context<Self>) -> Div {
-        h_flex()
-            .items_start()
-            .w_full()
-            .flex_1()
-            .border_t_1()
-            .border_color(cx.theme().colors().border)
-            .bg(cx.theme().colors().editor_background)
-            .child(
-                v_flex()
-                    .flex_1()
-                    .gap_2()
-                    .p_4()
-                    .h_full()
-                    .child(
-                        h_flex()
-                            .justify_between()
-                            .child(ui::Headline::new("Prompt").size(ui::HeadlineSize::XSmall))
-                            .child(match prediction.state {
-                                LastPredictionState::Requested
-                                | LastPredictionState::Failed { .. } => ui::Chip::new("Local")
-                                    .bg_color(cx.theme().status().warning_background)
-                                    .label_color(Color::Success),
-                                LastPredictionState::Success { .. } => ui::Chip::new("Cloud")
-                                    .bg_color(cx.theme().status().success_background)
-                                    .label_color(Color::Success),
-                            }),
-                    )
-                    .child(prediction.prompt_editor.clone()),
-            )
-            .child(ui::vertical_divider())
-            .child(
-                v_flex()
-                    .flex_1()
-                    .gap_2()
-                    .h_full()
-                    .child(
-                        v_flex()
-                            .flex_1()
-                            .gap_2()
-                            .p_4()
-                            .child(
-                                ui::Headline::new("Model Response").size(ui::HeadlineSize::XSmall),
-                            )
-                            .child(match &prediction.state {
-                                LastPredictionState::Success {
-                                    model_response_editor,
-                                    ..
-                                } => model_response_editor.clone().into_any_element(),
-                                LastPredictionState::Requested => v_flex()
-                                    .gap_2()
-                                    .child(Label::new("Loading...").buffer_font(cx))
-                                    .into_any_element(),
-                                LastPredictionState::Failed { message } => v_flex()
-                                    .gap_2()
-                                    .max_w_96()
-                                    .child(Label::new(message.clone()).buffer_font(cx))
-                                    .into_any_element(),
-                            }),
-                    )
-                    .child(ui::divider())
-                    .child(
-                        if let LastPredictionState::Success {
-                            feedback_editor,
-                            feedback: feedback_state,
-                            ..
-                        } = &prediction.state
-                        {
-                            v_flex()
-                                .key_context("Zeta2Feedback")
-                                .on_action(cx.listener(Self::handle_rate_positive))
-                                .on_action(cx.listener(Self::handle_rate_negative))
-                                .gap_2()
-                                .p_2()
-                                .child(feedback_editor.clone())
-                                .child(
-                                    h_flex()
-                                        .justify_end()
-                                        .w_full()
-                                        .child(
-                                            ButtonLike::new("rate-positive")
-                                                .when(
-                                                    *feedback_state == Some(Feedback::Positive),
-                                                    |this| this.style(ButtonStyle::Filled),
-                                                )
-                                                .child(
-                                                    KeyBinding::for_action(
-                                                        &Zeta2RatePredictionPositive,
-                                                        cx,
-                                                    )
-                                                    .size(TextSize::Small.rems(cx)),
-                                                )
-                                                .child(ui::Icon::new(ui::IconName::ThumbsUp))
-                                                .on_click(cx.listener(|this, _, window, cx| {
-                                                    this.handle_rate_positive(
-                                                        &Zeta2RatePredictionPositive,
-                                                        window,
-                                                        cx,
-                                                    );
-                                                })),
-                                        )
-                                        .child(
-                                            ButtonLike::new("rate-negative")
-                                                .when(
-                                                    *feedback_state == Some(Feedback::Negative),
-                                                    |this| this.style(ButtonStyle::Filled),
-                                                )
-                                                .child(
-                                                    KeyBinding::for_action(
-                                                        &Zeta2RatePredictionNegative,
-                                                        cx,
-                                                    )
-                                                    .size(TextSize::Small.rems(cx)),
-                                                )
-                                                .child(ui::Icon::new(ui::IconName::ThumbsDown))
-                                                .on_click(cx.listener(|this, _, window, cx| {
-                                                    this.handle_rate_negative(
-                                                        &Zeta2RatePredictionNegative,
-                                                        window,
-                                                        cx,
-                                                    );
-                                                })),
-                                        ),
-                                )
-                                .into_any()
-                        } else {
-                            Empty.into_any_element()
-                        },
-                    ),
-            )
-    }
-}
-
-impl Focusable for Zeta2Inspector {
-    fn focus_handle(&self, _cx: &App) -> FocusHandle {
-        self.focus_handle.clone()
-    }
-}
-
-impl Item for Zeta2Inspector {
-    type Event = ();
-
-    fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
-        "Zeta2 Inspector".into()
-    }
-}
-
-impl EventEmitter<()> for Zeta2Inspector {}
-
-impl Render for Zeta2Inspector {
-    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
-        v_flex()
-            .size_full()
-            .bg(cx.theme().colors().editor_background)
-            .child(
-                h_flex()
-                    .w_full()
-                    .child(
-                        v_flex()
-                            .flex_1()
-                            .p_4()
-                            .h_full()
-                            .justify_between()
-                            .child(self.render_options(window, cx))
-                            .gap_4(),
-                    )
-                    .child(ui::vertical_divider())
-                    .children(self.render_stats()),
-            )
-            .child(self.render_content(window, cx))
-    }
-}

crates/zeta_cli/src/evaluate.rs 🔗

@@ -1,641 +0,0 @@
-use crate::metrics::{self, Scores};
-use std::{
-    collections::HashMap,
-    io::{IsTerminal, Write},
-    sync::Arc,
-};
-
-use anyhow::Result;
-use gpui::{AsyncApp, Entity};
-use project::Project;
-use util::ResultExt as _;
-use zeta::{Zeta, udiff::DiffLine};
-
-use crate::{
-    EvaluateArguments, PredictionOptions,
-    example::{Example, NamedExample},
-    headless::ZetaCliAppState,
-    paths::print_run_data_dir,
-    predict::{PredictionDetails, perform_predict, setup_zeta},
-};
-
-#[derive(Debug)]
-pub(crate) struct ExecutionData {
-    execution_id: String,
-    diff: String,
-    reasoning: String,
-}
-
-pub async fn run_evaluate(
-    args: EvaluateArguments,
-    app_state: &Arc<ZetaCliAppState>,
-    cx: &mut AsyncApp,
-) {
-    if args.example_paths.is_empty() {
-        eprintln!("No examples provided");
-        return;
-    }
-
-    let all_tasks = args.example_paths.into_iter().map(|path| {
-        let options = args.options.clone();
-        let app_state = app_state.clone();
-        let example = NamedExample::load(&path).expect("Failed to load example");
-
-        cx.spawn(async move |cx| {
-            let project = example.setup_project(&app_state, cx).await.unwrap();
-
-            let providers = (0..args.repetitions)
-                .map(|_| setup_zeta(args.options.provider, &project, &app_state, cx).unwrap())
-                .collect::<Vec<_>>();
-
-            let _edited_buffers = example.apply_edit_history(&project, cx).await.unwrap();
-
-            let tasks = providers
-                .into_iter()
-                .enumerate()
-                .map(move |(repetition_ix, zeta)| {
-                    let repetition_ix = (args.repetitions > 1).then(|| repetition_ix as u16);
-                    let example = example.clone();
-                    let project = project.clone();
-                    let options = options.clone();
-
-                    cx.spawn(async move |cx| {
-                        let name = example.name.clone();
-                        run_evaluate_one(
-                            example,
-                            repetition_ix,
-                            project,
-                            zeta,
-                            options,
-                            !args.skip_prediction,
-                            cx,
-                        )
-                        .await
-                        .map_err(|err| (err, name, repetition_ix))
-                    })
-                });
-            futures::future::join_all(tasks).await
-        })
-    });
-    let all_results = futures::future::join_all(all_tasks).await;
-
-    write_aggregated_scores(&mut std::io::stdout(), &all_results).unwrap();
-    if let Some(mut output_file) =
-        std::fs::File::create(crate::paths::RUN_DIR.join("aggregated_results.md")).log_err()
-    {
-        write_aggregated_scores(&mut output_file, &all_results).log_err();
-    };
-
-    if args.repetitions > 1 {
-        if let Err(e) = write_bucketed_analysis(&all_results) {
-            eprintln!("Failed to write bucketed analysis: {:?}", e);
-        }
-    }
-
-    print_run_data_dir(args.repetitions == 1, std::io::stdout().is_terminal());
-}
-
-fn write_aggregated_scores(
-    w: &mut impl std::io::Write,
-    all_results: &Vec<
-        Vec<Result<(EvaluationResult, ExecutionData), (anyhow::Error, String, Option<u16>)>>,
-    >,
-) -> Result<()> {
-    let mut successful = Vec::new();
-    let mut failed_count = 0;
-
-    for result in all_results.iter().flatten() {
-        match result {
-            Ok((eval_result, _execution_data)) => successful.push(eval_result),
-            Err((err, name, repetition_ix)) => {
-                if failed_count == 0 {
-                    writeln!(w, "## Errors\n")?;
-                }
-
-                failed_count += 1;
-                writeln!(w, "{}", fmt_evaluation_error(err, name, repetition_ix))?;
-            }
-        }
-    }
-
-    if successful.len() > 1 {
-        let edit_scores = successful
-            .iter()
-            .filter_map(|r| r.edit_scores.clone())
-            .collect::<Vec<_>>();
-        let has_edit_predictions = edit_scores.len() > 0;
-        let aggregated_result = EvaluationResult {
-            context_scores: Scores::aggregate(successful.iter().map(|r| &r.context_scores)),
-            edit_scores: has_edit_predictions.then(|| EditScores::aggregate(&edit_scores)),
-            prompt_len: successful.iter().map(|r| r.prompt_len).sum::<usize>() / successful.len(),
-            generated_len: successful.iter().map(|r| r.generated_len).sum::<usize>()
-                / successful.len(),
-        };
-
-        writeln!(w, "\n{}", "-".repeat(80))?;
-        writeln!(w, "\n## TOTAL SCORES")?;
-        writeln!(w, "{:#}", aggregated_result)?;
-    }
-
-    if successful.len() + failed_count > 1 {
-        writeln!(
-            w,
-            "\nCongratulations! {}/{} ({:.2}%) of runs weren't outright failures 🎉",
-            successful.len(),
-            successful.len() + failed_count,
-            (successful.len() as f64 / (successful.len() + failed_count) as f64) * 100.0
-        )?;
-    }
-
-    Ok(())
-}
-
-pub async fn run_evaluate_one(
-    example: NamedExample,
-    repetition_ix: Option<u16>,
-    project: Entity<Project>,
-    zeta: Entity<Zeta>,
-    prediction_options: PredictionOptions,
-    predict: bool,
-    cx: &mut AsyncApp,
-) -> Result<(EvaluationResult, ExecutionData)> {
-    let predict_result = perform_predict(
-        example.clone(),
-        project,
-        zeta,
-        repetition_ix,
-        prediction_options,
-        cx,
-    )
-    .await?;
-
-    let evaluation_result = evaluate(&example.example, &predict_result, predict);
-
-    if repetition_ix.is_none() {
-        write_eval_result(
-            &example,
-            &predict_result,
-            &evaluation_result,
-            &mut std::io::stdout(),
-            std::io::stdout().is_terminal(),
-            predict,
-        )?;
-    }
-
-    if let Some(mut results_file) =
-        std::fs::File::create(predict_result.run_example_dir.join("results.md")).log_err()
-    {
-        write_eval_result(
-            &example,
-            &predict_result,
-            &evaluation_result,
-            &mut results_file,
-            false,
-            predict,
-        )
-        .log_err();
-    }
-
-    let execution_data = ExecutionData {
-        execution_id: if let Some(rep_ix) = repetition_ix {
-            format!("{:03}", rep_ix)
-        } else {
-            example.name.clone()
-        },
-        diff: predict_result.diff.clone(),
-        reasoning: std::fs::read_to_string(
-            predict_result
-                .run_example_dir
-                .join("prediction_response.md"),
-        )
-        .unwrap_or_default(),
-    };
-
-    anyhow::Ok((evaluation_result, execution_data))
-}
-
-fn write_eval_result(
-    example: &NamedExample,
-    predictions: &PredictionDetails,
-    evaluation_result: &EvaluationResult,
-    out: &mut impl Write,
-    use_color: bool,
-    predict: bool,
-) -> Result<()> {
-    if predict {
-        writeln!(
-            out,
-            "## Expected edit prediction:\n\n```diff\n{}\n```\n",
-            compare_diffs(
-                &example.example.expected_patch,
-                &predictions.diff,
-                use_color
-            )
-        )?;
-        writeln!(
-            out,
-            "## Actual edit prediction:\n\n```diff\n{}\n```\n",
-            compare_diffs(
-                &predictions.diff,
-                &example.example.expected_patch,
-                use_color
-            )
-        )?;
-    }
-
-    writeln!(out, "{:#}", evaluation_result)?;
-
-    anyhow::Ok(())
-}
-
-#[derive(Debug, Default, Clone)]
-pub struct EditScores {
-    pub line_match: Scores,
-    pub chr_f: f64,
-}
-
-impl EditScores {
-    pub fn aggregate(scores: &[EditScores]) -> EditScores {
-        let line_match = Scores::aggregate(scores.iter().map(|s| &s.line_match));
-        let chr_f = scores.iter().map(|s| s.chr_f).sum::<f64>() / scores.len() as f64;
-
-        EditScores { line_match, chr_f }
-    }
-}
-
-#[derive(Debug, Default)]
-pub struct EvaluationResult {
-    pub edit_scores: Option<EditScores>,
-    pub context_scores: Scores,
-    pub prompt_len: usize,
-    pub generated_len: usize,
-}
-
-impl std::fmt::Display for EvaluationResult {
-    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
-        if f.alternate() {
-            self.fmt_table(f)
-        } else {
-            self.fmt_markdown(f)
-        }
-    }
-}
-
-impl EvaluationResult {
-    fn fmt_markdown(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
-        write!(
-            f,
-            r#"
-### Context Scores
-{}
-"#,
-            self.context_scores.to_markdown(),
-        )?;
-        if let Some(scores) = &self.edit_scores {
-            write!(
-                f,
-                r#"
-                ### Edit Prediction Scores
-                {}"#,
-                scores.line_match.to_markdown()
-            )?;
-        }
-        Ok(())
-    }
-
-    fn fmt_table(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
-        writeln!(f, "#### Prompt Statistics")?;
-        writeln!(f, "─────────────────────────")?;
-        writeln!(f, "Prompt_len  Generated_len")?;
-        writeln!(f, "─────────────────────────")?;
-        writeln!(f, "{:<11} {:<14}", self.prompt_len, self.generated_len,)?;
-        writeln!(f)?;
-        writeln!(f)?;
-        writeln!(f, "#### Performance Scores")?;
-        writeln!(
-            f,
-            "──────────────────────────────────────────────────────────────────"
-        )?;
-        writeln!(
-            f,
-            "                   TP     FP     FN     Precision   Recall     F1"
-        )?;
-        writeln!(
-            f,
-            "──────────────────────────────────────────────────────────────────"
-        )?;
-        writeln!(
-            f,
-            "Context Retrieval  {:<6} {:<6} {:<6} {:>8.2}  {:>7.2}  {:>6.2}",
-            self.context_scores.true_positives,
-            self.context_scores.false_positives,
-            self.context_scores.false_negatives,
-            self.context_scores.precision() * 100.0,
-            self.context_scores.recall() * 100.0,
-            self.context_scores.f1_score() * 100.0
-        )?;
-        if let Some(edit_scores) = &self.edit_scores {
-            let line_match = &edit_scores.line_match;
-            writeln!(f, "Edit Prediction")?;
-            writeln!(
-                f,
-                "  ├─ exact lines   {:<6} {:<6} {:<6} {:>8.2}  {:>7.2}  {:>6.2}",
-                line_match.true_positives,
-                line_match.false_positives,
-                line_match.false_negatives,
-                line_match.precision() * 100.0,
-                line_match.recall() * 100.0,
-                line_match.f1_score() * 100.0
-            )?;
-            writeln!(
-                f,
-                "  └─ diff chrF     {:<6} {:<6} {:<6} {:>8} {:>8}  {:>6.2}",
-                "-", "-", "-", "-", "-", edit_scores.chr_f
-            )?;
-        }
-        Ok(())
-    }
-}
-
-fn evaluate(example: &Example, preds: &PredictionDetails, predict: bool) -> EvaluationResult {
-    let mut eval_result = EvaluationResult {
-        prompt_len: preds.prompt_len,
-        generated_len: preds.generated_len,
-        ..Default::default()
-    };
-
-    if predict {
-        // todo: alternatives for patches
-        let expected_patch = example
-            .expected_patch
-            .lines()
-            .map(DiffLine::parse)
-            .collect::<Vec<_>>();
-        let actual_patch = preds.diff.lines().map(DiffLine::parse).collect::<Vec<_>>();
-
-        let line_match = metrics::line_match_score(&expected_patch, &actual_patch);
-        let chr_f = metrics::delta_chr_f(&expected_patch, &actual_patch);
-
-        eval_result.edit_scores = Some(EditScores { line_match, chr_f });
-    }
-
-    eval_result
-}
-
-/// Return annotated `patch_a` so that:
-/// Additions and deletions that are not present in `patch_b` will be highlighted in red.
-/// Additions and deletions that are present in `patch_b` will be highlighted in green.
-pub fn compare_diffs(patch_a: &str, patch_b: &str, use_color: bool) -> String {
-    let green = if use_color { "\x1b[32m✓ " } else { "" };
-    let red = if use_color { "\x1b[31m✗ " } else { "" };
-    let neutral = if use_color { "  " } else { "" };
-    let reset = if use_color { "\x1b[0m" } else { "" };
-    let lines_a = patch_a.lines().map(DiffLine::parse);
-    let lines_b: Vec<_> = patch_b.lines().map(DiffLine::parse).collect();
-
-    let annotated = lines_a
-        .map(|line| match line {
-            DiffLine::Addition(_) | DiffLine::Deletion(_) => {
-                if lines_b.contains(&line) {
-                    format!("{green}{line}{reset}")
-                } else {
-                    format!("{red}{line}{reset}")
-                }
-            }
-            _ => format!("{neutral}{line}{reset}"),
-        })
-        .collect::<Vec<String>>();
-
-    annotated.join("\n")
-}
-
-fn write_bucketed_analysis(
-    all_results: &Vec<
-        Vec<Result<(EvaluationResult, ExecutionData), (anyhow::Error, String, Option<u16>)>>,
-    >,
-) -> Result<()> {
-    #[derive(Debug)]
-    struct EditBucket {
-        diff: String,
-        is_correct: bool,
-        execution_indices: Vec<String>,
-        reasoning_samples: Vec<String>,
-    }
-
-    let mut total_executions = 0;
-    let mut empty_predictions = Vec::new();
-    let mut errors = Vec::new();
-
-    let mut buckets: HashMap<String, EditBucket> = HashMap::new();
-
-    for result in all_results.iter().flatten() {
-        total_executions += 1;
-
-        let (evaluation_result, execution_data) = match result {
-            Ok((eval_result, execution_data)) => {
-                if execution_data.diff.is_empty() {
-                    empty_predictions.push(execution_data);
-                    continue;
-                }
-                (eval_result, execution_data)
-            }
-            Err(err) => {
-                errors.push(err);
-                continue;
-            }
-        };
-
-        buckets
-            .entry(execution_data.diff.clone())
-            .and_modify(|bucket| {
-                bucket
-                    .execution_indices
-                    .push(execution_data.execution_id.clone());
-                bucket
-                    .reasoning_samples
-                    .push(execution_data.reasoning.clone());
-            })
-            .or_insert_with(|| EditBucket {
-                diff: execution_data.diff.clone(),
-                is_correct: {
-                    evaluation_result
-                        .edit_scores
-                        .as_ref()
-                        .map_or(false, |edit_scores| {
-                            edit_scores.line_match.false_positives == 0
-                                && edit_scores.line_match.false_negatives == 0
-                                && edit_scores.line_match.true_positives > 0
-                        })
-                },
-                execution_indices: vec![execution_data.execution_id.clone()],
-                reasoning_samples: vec![execution_data.reasoning.clone()],
-            });
-    }
-
-    let mut sorted_buckets = buckets.into_values().collect::<Vec<_>>();
-    sorted_buckets.sort_by(|a, b| match (a.is_correct, b.is_correct) {
-        (true, false) => std::cmp::Ordering::Less,
-        (false, true) => std::cmp::Ordering::Greater,
-        _ => b.execution_indices.len().cmp(&a.execution_indices.len()),
-    });
-
-    let output_path = crate::paths::RUN_DIR.join("bucketed_analysis.md");
-    let mut output = std::fs::File::create(&output_path)?;
-
-    writeln!(output, "# Bucketed Edit Analysis\n")?;
-
-    writeln!(output, "## Summary\n")?;
-    writeln!(output, "- **Total executions**: {}", total_executions)?;
-
-    let correct_count: usize = sorted_buckets
-        .iter()
-        .filter(|b| b.is_correct)
-        .map(|b| b.execution_indices.len())
-        .sum();
-
-    let incorrect_count: usize = sorted_buckets
-        .iter()
-        .filter(|b| !b.is_correct)
-        .map(|b| b.execution_indices.len())
-        .sum();
-
-    writeln!(
-        output,
-        "- **Correct predictions**: {} ({:.1}%)",
-        correct_count,
-        (correct_count as f64 / total_executions as f64) * 100.0
-    )?;
-
-    writeln!(
-        output,
-        "- **Incorrect predictions**: {} ({:.1}%)",
-        incorrect_count,
-        (incorrect_count as f64 / total_executions as f64) * 100.0
-    )?;
-
-    writeln!(
-        output,
-        "- **No Predictions**: {} ({:.1}%)",
-        empty_predictions.len(),
-        (empty_predictions.len() as f64 / total_executions as f64) * 100.0
-    )?;
-
-    let unique_incorrect = sorted_buckets.iter().filter(|b| !b.is_correct).count();
-    writeln!(
-        output,
-        "- **Unique incorrect edit patterns**: {}\n",
-        unique_incorrect
-    )?;
-
-    writeln!(output, "---\n")?;
-
-    for (idx, bucket) in sorted_buckets.iter().filter(|b| b.is_correct).enumerate() {
-        if idx == 0 {
-            writeln!(
-                output,
-                "## Correct Predictions ({} occurrences)\n",
-                bucket.execution_indices.len()
-            )?;
-        }
-
-        writeln!(output, "**Predicted Edit:**\n")?;
-        writeln!(output, "```diff")?;
-        writeln!(output, "{}", bucket.diff)?;
-        writeln!(output, "```\n")?;
-
-        writeln!(
-            output,
-            "**Executions:** {}\n",
-            bucket.execution_indices.join(", ")
-        )?;
-        writeln!(output, "---\n")?;
-    }
-
-    for (idx, bucket) in sorted_buckets.iter().filter(|b| !b.is_correct).enumerate() {
-        writeln!(
-            output,
-            "## Incorrect Prediction #{} ({} occurrences)\n",
-            idx + 1,
-            bucket.execution_indices.len()
-        )?;
-
-        writeln!(output, "**Predicted Edit:**\n")?;
-        writeln!(output, "```diff")?;
-        writeln!(output, "{}", bucket.diff)?;
-        writeln!(output, "```\n")?;
-
-        writeln!(
-            output,
-            "**Executions:** {}\n",
-            bucket.execution_indices.join(", ")
-        )?;
-
-        for (exec_id, reasoning) in bucket
-            .execution_indices
-            .iter()
-            .zip(bucket.reasoning_samples.iter())
-        {
-            writeln!(output, "{}", fmt_execution(exec_id, reasoning))?;
-        }
-
-        writeln!(output, "\n---\n")?;
-    }
-
-    if !empty_predictions.is_empty() {
-        writeln!(
-            output,
-            "## No Predictions ({} occurrences)\n",
-            empty_predictions.len()
-        )?;
-
-        for execution_data in &empty_predictions {
-            writeln!(
-                output,
-                "{}",
-                fmt_execution(&execution_data.execution_id, &execution_data.reasoning)
-            )?;
-        }
-        writeln!(output, "\n---\n")?;
-    }
-
-    if !errors.is_empty() {
-        writeln!(output, "## Errors ({} occurrences)\n", errors.len())?;
-
-        for (err, name, repetition_ix) in &errors {
-            writeln!(output, "{}", fmt_evaluation_error(err, name, repetition_ix))?;
-        }
-        writeln!(output, "\n---\n")?;
-    }
-
-    fn fmt_execution(exec_id: &str, reasoning: &str) -> String {
-        let exec_content = format!(
-            "\n### Execution {} `{}/{}/prediction_response.md`{}",
-            exec_id,
-            crate::paths::RUN_DIR.display(),
-            exec_id,
-            indent_text(&format!("\n\n```\n{}\n```\n", reasoning,), 2)
-        );
-        indent_text(&exec_content, 2)
-    }
-
-    fn indent_text(text: &str, spaces: usize) -> String {
-        let indent = " ".repeat(spaces);
-        text.lines()
-            .collect::<Vec<_>>()
-            .join(&format!("\n{}", indent))
-    }
-
-    Ok(())
-}
-
-fn fmt_evaluation_error(err: &anyhow::Error, name: &str, repetition_ix: &Option<u16>) -> String {
-    let err = format!("{err:?}")
-        .replace("<edits", "```xml\n<edits")
-        .replace("</edits>", "</edits>\n```");
-    format!(
-        "### ERROR {name}{}\n\n{err}\n",
-        repetition_ix
-            .map(|ix| format!(" [RUN {ix:03}]"))
-            .unwrap_or_default()
-    )
-}

crates/zeta_cli/src/example.rs 🔗

@@ -1,561 +0,0 @@
-use std::{
-    borrow::Cow,
-    cell::RefCell,
-    fmt::{self, Display},
-    fs,
-    io::Write,
-    mem,
-    path::{Path, PathBuf},
-    sync::{Arc, OnceLock},
-};
-
-use crate::headless::ZetaCliAppState;
-use anyhow::{Context as _, Result, anyhow};
-use clap::ValueEnum;
-use cloud_zeta2_prompt::CURSOR_MARKER;
-use collections::HashMap;
-use futures::{
-    AsyncWriteExt as _,
-    lock::{Mutex, OwnedMutexGuard},
-};
-use futures::{FutureExt as _, future::Shared};
-use gpui::{AsyncApp, Entity, Task, http_client::Url};
-use language::{Anchor, Buffer};
-use project::{Project, ProjectPath};
-use pulldown_cmark::CowStr;
-use serde::{Deserialize, Serialize};
-use util::{paths::PathStyle, rel_path::RelPath};
-use zeta::udiff::OpenedBuffers;
-
-use crate::paths::{REPOS_DIR, WORKTREES_DIR};
-
-const UNCOMMITTED_DIFF_HEADING: &str = "Uncommitted Diff";
-const EDIT_HISTORY_HEADING: &str = "Edit History";
-const CURSOR_POSITION_HEADING: &str = "Cursor Position";
-const EXPECTED_PATCH_HEADING: &str = "Expected Patch";
-const EXPECTED_CONTEXT_HEADING: &str = "Expected Context";
-const REPOSITORY_URL_FIELD: &str = "repository_url";
-const REVISION_FIELD: &str = "revision";
-
-#[derive(Debug, Clone)]
-pub struct NamedExample {
-    pub name: String,
-    pub example: Example,
-}
-
-#[derive(Clone, Debug, Serialize, Deserialize)]
-pub struct Example {
-    pub repository_url: String,
-    pub revision: String,
-    pub uncommitted_diff: String,
-    pub cursor_path: PathBuf,
-    pub cursor_position: String,
-    pub edit_history: String,
-    pub expected_patch: String,
-}
-
-pub type ActualExcerpt = Excerpt;
-
-#[derive(Clone, Debug, Serialize, Deserialize)]
-pub struct Excerpt {
-    pub path: PathBuf,
-    pub text: String,
-}
-
-#[derive(ValueEnum, Debug, Clone)]
-pub enum ExampleFormat {
-    Json,
-    Toml,
-    Md,
-}
-
-impl NamedExample {
-    pub fn load(path: impl AsRef<Path>) -> Result<Self> {
-        let path = path.as_ref();
-        let content = std::fs::read_to_string(path)?;
-        let ext = path.extension();
-
-        match ext.and_then(|s| s.to_str()) {
-            Some("json") => Ok(Self {
-                name: path.file_stem().unwrap_or_default().display().to_string(),
-                example: serde_json::from_str(&content)?,
-            }),
-            Some("toml") => Ok(Self {
-                name: path.file_stem().unwrap_or_default().display().to_string(),
-                example: toml::from_str(&content)?,
-            }),
-            Some("md") => Self::parse_md(&content),
-            Some(_) => {
-                anyhow::bail!("Unrecognized example extension: {}", ext.unwrap().display());
-            }
-            None => {
-                anyhow::bail!(
-                    "Failed to determine example type since the file does not have an extension."
-                );
-            }
-        }
-    }
-
-    pub fn parse_md(input: &str) -> Result<Self> {
-        use pulldown_cmark::{CodeBlockKind, Event, HeadingLevel, Parser, Tag, TagEnd};
-
-        let parser = Parser::new(input);
-
-        let mut named = NamedExample {
-            name: String::new(),
-            example: Example {
-                repository_url: String::new(),
-                revision: String::new(),
-                uncommitted_diff: String::new(),
-                cursor_path: PathBuf::new(),
-                cursor_position: String::new(),
-                edit_history: String::new(),
-                expected_patch: String::new(),
-            },
-        };
-
-        let mut text = String::new();
-        let mut block_info: CowStr = "".into();
-
-        #[derive(PartialEq)]
-        enum Section {
-            UncommittedDiff,
-            EditHistory,
-            CursorPosition,
-            ExpectedExcerpts,
-            ExpectedPatch,
-            Other,
-        }
-
-        let mut current_section = Section::Other;
-
-        for event in parser {
-            match event {
-                Event::Text(line) => {
-                    text.push_str(&line);
-
-                    if !named.name.is_empty()
-                        && current_section == Section::Other
-                        // in h1 section
-                        && let Some((field, value)) = line.split_once('=')
-                    {
-                        match field.trim() {
-                            REPOSITORY_URL_FIELD => {
-                                named.example.repository_url = value.trim().to_string();
-                            }
-                            REVISION_FIELD => {
-                                named.example.revision = value.trim().to_string();
-                            }
-                            _ => {}
-                        }
-                    }
-                }
-                Event::End(TagEnd::Heading(HeadingLevel::H1)) => {
-                    if !named.name.is_empty() {
-                        anyhow::bail!(
-                            "Found multiple H1 headings. There should only be one with the name of the example."
-                        );
-                    }
-                    named.name = mem::take(&mut text);
-                }
-                Event::End(TagEnd::Heading(HeadingLevel::H2)) => {
-                    let title = mem::take(&mut text);
-                    current_section = if title.eq_ignore_ascii_case(UNCOMMITTED_DIFF_HEADING) {
-                        Section::UncommittedDiff
-                    } else if title.eq_ignore_ascii_case(EDIT_HISTORY_HEADING) {
-                        Section::EditHistory
-                    } else if title.eq_ignore_ascii_case(CURSOR_POSITION_HEADING) {
-                        Section::CursorPosition
-                    } else if title.eq_ignore_ascii_case(EXPECTED_PATCH_HEADING) {
-                        Section::ExpectedPatch
-                    } else if title.eq_ignore_ascii_case(EXPECTED_CONTEXT_HEADING) {
-                        Section::ExpectedExcerpts
-                    } else {
-                        Section::Other
-                    };
-                }
-                Event::End(TagEnd::Heading(HeadingLevel::H3)) => {
-                    mem::take(&mut text);
-                }
-                Event::End(TagEnd::Heading(HeadingLevel::H4)) => {
-                    mem::take(&mut text);
-                }
-                Event::End(TagEnd::Heading(level)) => {
-                    anyhow::bail!("Unexpected heading level: {level}");
-                }
-                Event::Start(Tag::CodeBlock(kind)) => {
-                    match kind {
-                        CodeBlockKind::Fenced(info) => {
-                            block_info = info;
-                        }
-                        CodeBlockKind::Indented => {
-                            anyhow::bail!("Unexpected indented codeblock");
-                        }
-                    };
-                }
-                Event::Start(_) => {
-                    text.clear();
-                    block_info = "".into();
-                }
-                Event::End(TagEnd::CodeBlock) => {
-                    let block_info = block_info.trim();
-                    match current_section {
-                        Section::UncommittedDiff => {
-                            named.example.uncommitted_diff = mem::take(&mut text);
-                        }
-                        Section::EditHistory => {
-                            named.example.edit_history.push_str(&mem::take(&mut text));
-                        }
-                        Section::CursorPosition => {
-                            named.example.cursor_path = block_info.into();
-                            named.example.cursor_position = mem::take(&mut text);
-                        }
-                        Section::ExpectedExcerpts => {
-                            mem::take(&mut text);
-                        }
-                        Section::ExpectedPatch => {
-                            named.example.expected_patch = mem::take(&mut text);
-                        }
-                        Section::Other => {}
-                    }
-                }
-                _ => {}
-            }
-        }
-
-        if named.example.cursor_path.as_path() == Path::new("")
-            || named.example.cursor_position.is_empty()
-        {
-            anyhow::bail!("Missing cursor position codeblock");
-        }
-
-        Ok(named)
-    }
-
-    pub fn write(&self, format: ExampleFormat, mut out: impl Write) -> Result<()> {
-        match format {
-            ExampleFormat::Json => Ok(serde_json::to_writer(out, &self.example)?),
-            ExampleFormat::Toml => {
-                Ok(out.write_all(toml::to_string_pretty(&self.example)?.as_bytes())?)
-            }
-            ExampleFormat::Md => Ok(write!(out, "{}", self)?),
-        }
-    }
-
-    pub async fn setup_project(
-        &self,
-        app_state: &Arc<ZetaCliAppState>,
-        cx: &mut AsyncApp,
-    ) -> Result<Entity<Project>> {
-        let worktree_path = self.setup_worktree().await?;
-
-        static AUTHENTICATED: OnceLock<Shared<Task<()>>> = OnceLock::new();
-
-        AUTHENTICATED
-            .get_or_init(|| {
-                let client = app_state.client.clone();
-                cx.spawn(async move |cx| {
-                    client
-                        .sign_in_with_optional_connect(true, cx)
-                        .await
-                        .unwrap();
-                })
-                .shared()
-            })
-            .clone()
-            .await;
-
-        let project = cx.update(|cx| {
-            Project::local(
-                app_state.client.clone(),
-                app_state.node_runtime.clone(),
-                app_state.user_store.clone(),
-                app_state.languages.clone(),
-                app_state.fs.clone(),
-                None,
-                cx,
-            )
-        })?;
-
-        let worktree = project
-            .update(cx, |project, cx| {
-                project.create_worktree(&worktree_path, true, cx)
-            })?
-            .await?;
-        worktree
-            .read_with(cx, |worktree, _cx| {
-                worktree.as_local().unwrap().scan_complete()
-            })?
-            .await;
-
-        anyhow::Ok(project)
-    }
-
-    pub async fn setup_worktree(&self) -> Result<PathBuf> {
-        let (repo_owner, repo_name) = self.repo_name()?;
-        let file_name = self.file_name();
-
-        let repo_dir = REPOS_DIR.join(repo_owner.as_ref()).join(repo_name.as_ref());
-        let repo_lock = lock_repo(&repo_dir).await;
-
-        if !repo_dir.is_dir() {
-            fs::create_dir_all(&repo_dir)?;
-            run_git(&repo_dir, &["init"]).await?;
-            run_git(
-                &repo_dir,
-                &["remote", "add", "origin", &self.example.repository_url],
-            )
-            .await?;
-        }
-
-        // Resolve the example to a revision, fetching it if needed.
-        let revision = run_git(
-            &repo_dir,
-            &[
-                "rev-parse",
-                &format!("{}^{{commit}}", self.example.revision),
-            ],
-        )
-        .await;
-        let revision = if let Ok(revision) = revision {
-            revision
-        } else {
-            run_git(
-                &repo_dir,
-                &["fetch", "--depth", "1", "origin", &self.example.revision],
-            )
-            .await?;
-            let revision = run_git(&repo_dir, &["rev-parse", "FETCH_HEAD"]).await?;
-            if revision != self.example.revision {
-                run_git(&repo_dir, &["tag", &self.example.revision, &revision]).await?;
-            }
-            revision
-        };
-
-        // Create the worktree for this example if needed.
-        let worktree_path = WORKTREES_DIR.join(&file_name).join(repo_name.as_ref());
-        if worktree_path.is_dir() {
-            run_git(&worktree_path, &["clean", "--force", "-d"]).await?;
-            run_git(&worktree_path, &["reset", "--hard", "HEAD"]).await?;
-            run_git(&worktree_path, &["checkout", revision.as_str()]).await?;
-        } else {
-            let worktree_path_string = worktree_path.to_string_lossy();
-            run_git(&repo_dir, &["branch", "-f", &file_name, revision.as_str()]).await?;
-            run_git(
-                &repo_dir,
-                &["worktree", "add", "-f", &worktree_path_string, &file_name],
-            )
-            .await?;
-        }
-        drop(repo_lock);
-
-        // Apply the uncommitted diff for this example.
-        if !self.example.uncommitted_diff.is_empty() {
-            let mut apply_process = smol::process::Command::new("git")
-                .current_dir(&worktree_path)
-                .args(&["apply", "-"])
-                .stdin(std::process::Stdio::piped())
-                .spawn()?;
-
-            let mut stdin = apply_process.stdin.take().unwrap();
-            stdin
-                .write_all(self.example.uncommitted_diff.as_bytes())
-                .await?;
-            stdin.close().await?;
-            drop(stdin);
-
-            let apply_result = apply_process.output().await?;
-            if !apply_result.status.success() {
-                anyhow::bail!(
-                    "Failed to apply uncommitted diff patch with status: {}\nstderr:\n{}\nstdout:\n{}",
-                    apply_result.status,
-                    String::from_utf8_lossy(&apply_result.stderr),
-                    String::from_utf8_lossy(&apply_result.stdout),
-                );
-            }
-        }
-
-        Ok(worktree_path)
-    }
-
-    pub fn file_name(&self) -> String {
-        self.name
-            .chars()
-            .map(|c| {
-                if c.is_whitespace() {
-                    '-'
-                } else {
-                    c.to_ascii_lowercase()
-                }
-            })
-            .collect()
-    }
-
-    fn repo_name(&self) -> Result<(Cow<'_, str>, Cow<'_, str>)> {
-        // git@github.com:owner/repo.git
-        if self.example.repository_url.contains('@') {
-            let (owner, repo) = self
-                .example
-                .repository_url
-                .split_once(':')
-                .context("expected : in git url")?
-                .1
-                .split_once('/')
-                .context("expected / in git url")?;
-            Ok((
-                Cow::Borrowed(owner),
-                Cow::Borrowed(repo.trim_end_matches(".git")),
-            ))
-        // http://github.com/owner/repo.git
-        } else {
-            let url = Url::parse(&self.example.repository_url)?;
-            let mut segments = url.path_segments().context("empty http url")?;
-            let owner = segments
-                .next()
-                .context("expected owner path segment")?
-                .to_string();
-            let repo = segments
-                .next()
-                .context("expected repo path segment")?
-                .trim_end_matches(".git")
-                .to_string();
-            assert!(segments.next().is_none());
-
-            Ok((owner.into(), repo.into()))
-        }
-    }
-
-    pub async fn cursor_position(
-        &self,
-        project: &Entity<Project>,
-        cx: &mut AsyncApp,
-    ) -> Result<(Entity<Buffer>, Anchor)> {
-        let worktree = project.read_with(cx, |project, cx| {
-            project.visible_worktrees(cx).next().unwrap()
-        })?;
-        let cursor_path = RelPath::new(&self.example.cursor_path, PathStyle::Posix)?.into_arc();
-        let cursor_buffer = project
-            .update(cx, |project, cx| {
-                project.open_buffer(
-                    ProjectPath {
-                        worktree_id: worktree.read(cx).id(),
-                        path: cursor_path,
-                    },
-                    cx,
-                )
-            })?
-            .await?;
-        let cursor_offset_within_excerpt = self
-            .example
-            .cursor_position
-            .find(CURSOR_MARKER)
-            .ok_or_else(|| anyhow!("missing cursor marker"))?;
-        let mut cursor_excerpt = self.example.cursor_position.clone();
-        cursor_excerpt.replace_range(
-            cursor_offset_within_excerpt..(cursor_offset_within_excerpt + CURSOR_MARKER.len()),
-            "",
-        );
-        let excerpt_offset = cursor_buffer.read_with(cx, |buffer, _cx| {
-            let text = buffer.text();
-
-            let mut matches = text.match_indices(&cursor_excerpt);
-            let Some((excerpt_offset, _)) = matches.next() else {
-                anyhow::bail!(
-                    "\nExcerpt:\n\n{cursor_excerpt}\nBuffer text:\n{text}\n.Cursor excerpt did not exist in buffer."
-                );
-            };
-            assert!(matches.next().is_none());
-
-            Ok(excerpt_offset)
-        })??;
-
-        let cursor_offset = excerpt_offset + cursor_offset_within_excerpt;
-        let cursor_anchor =
-            cursor_buffer.read_with(cx, |buffer, _| buffer.anchor_after(cursor_offset))?;
-        Ok((cursor_buffer, cursor_anchor))
-    }
-
-    #[must_use]
-    pub async fn apply_edit_history(
-        &self,
-        project: &Entity<Project>,
-        cx: &mut AsyncApp,
-    ) -> Result<OpenedBuffers<'_>> {
-        zeta::udiff::apply_diff(&self.example.edit_history, project, cx).await
-    }
-}
-
-async fn run_git(repo_path: &Path, args: &[&str]) -> Result<String> {
-    let output = smol::process::Command::new("git")
-        .current_dir(repo_path)
-        .args(args)
-        .output()
-        .await?;
-
-    anyhow::ensure!(
-        output.status.success(),
-        "`git {}` within `{}` failed with status: {}\nstderr:\n{}\nstdout:\n{}",
-        args.join(" "),
-        repo_path.display(),
-        output.status,
-        String::from_utf8_lossy(&output.stderr),
-        String::from_utf8_lossy(&output.stdout),
-    );
-    Ok(String::from_utf8(output.stdout)?.trim().to_string())
-}
-
-impl Display for NamedExample {
-    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
-        write!(f, "# {}\n\n", self.name)?;
-        write!(
-            f,
-            "{REPOSITORY_URL_FIELD} = {}\n",
-            self.example.repository_url
-        )?;
-        write!(f, "{REVISION_FIELD} = {}\n\n", self.example.revision)?;
-
-        write!(f, "## {UNCOMMITTED_DIFF_HEADING}\n\n")?;
-        write!(f, "`````diff\n")?;
-        write!(f, "{}", self.example.uncommitted_diff)?;
-        write!(f, "`````\n")?;
-
-        if !self.example.edit_history.is_empty() {
-            write!(f, "`````diff\n{}`````\n", self.example.edit_history)?;
-        }
-
-        write!(
-            f,
-            "## {CURSOR_POSITION_HEADING}\n\n`````{}\n{}`````\n",
-            self.example.cursor_path.display(),
-            self.example.cursor_position
-        )?;
-        write!(f, "## {EDIT_HISTORY_HEADING}\n\n")?;
-
-        if !self.example.expected_patch.is_empty() {
-            write!(
-                f,
-                "\n## {EXPECTED_PATCH_HEADING}\n\n`````diff\n{}`````\n",
-                self.example.expected_patch
-            )?;
-        }
-
-        Ok(())
-    }
-}
-
-thread_local! {
-    static REPO_LOCKS: RefCell<HashMap<PathBuf, Arc<Mutex<()>>>> = RefCell::new(HashMap::default());
-}
-
-#[must_use]
-pub async fn lock_repo(path: impl AsRef<Path>) -> OwnedMutexGuard<()> {
-    REPO_LOCKS
-        .with(|cell| {
-            cell.borrow_mut()
-                .entry(path.as_ref().to_path_buf())
-                .or_default()
-                .clone()
-        })
-        .lock_owned()
-        .await
-}

crates/zeta_cli/src/main.rs 🔗

@@ -1,560 +0,0 @@
-mod evaluate;
-mod example;
-mod headless;
-mod metrics;
-mod paths;
-mod predict;
-mod source_location;
-mod syntax_retrieval_stats;
-mod util;
-
-use crate::{
-    evaluate::run_evaluate,
-    example::{ExampleFormat, NamedExample},
-    headless::ZetaCliAppState,
-    predict::run_predict,
-    source_location::SourceLocation,
-    syntax_retrieval_stats::retrieval_stats,
-    util::{open_buffer, open_buffer_with_language_server},
-};
-use ::util::paths::PathStyle;
-use anyhow::{Result, anyhow};
-use clap::{Args, Parser, Subcommand, ValueEnum};
-use cloud_llm_client::predict_edits_v3;
-use edit_prediction_context::{
-    EditPredictionContextOptions, EditPredictionExcerptOptions, EditPredictionScoreOptions,
-};
-use gpui::{Application, AsyncApp, Entity, prelude::*};
-use language::{Bias, Buffer, BufferSnapshot, Point};
-use metrics::delta_chr_f;
-use project::{Project, Worktree};
-use reqwest_client::ReqwestClient;
-use serde_json::json;
-use std::io::{self};
-use std::time::Duration;
-use std::{collections::HashSet, path::PathBuf, str::FromStr, sync::Arc};
-use zeta::ContextMode;
-use zeta::udiff::DiffLine;
-
-#[derive(Parser, Debug)]
-#[command(name = "zeta")]
-struct ZetaCliArgs {
-    #[arg(long, default_value_t = false)]
-    printenv: bool,
-    #[command(subcommand)]
-    command: Option<Command>,
-}
-
-#[derive(Subcommand, Debug)]
-enum Command {
-    Context(ContextArgs),
-    ContextStats(ContextStatsArgs),
-    Predict(PredictArguments),
-    Eval(EvaluateArguments),
-    ConvertExample {
-        path: PathBuf,
-        #[arg(long, value_enum, default_value_t = ExampleFormat::Md)]
-        output_format: ExampleFormat,
-    },
-    Score {
-        golden_patch: PathBuf,
-        actual_patch: PathBuf,
-    },
-    Clean,
-}
-
-#[derive(Debug, Args)]
-struct ContextStatsArgs {
-    #[arg(long)]
-    worktree: PathBuf,
-    #[arg(long)]
-    extension: Option<String>,
-    #[arg(long)]
-    limit: Option<usize>,
-    #[arg(long)]
-    skip: Option<usize>,
-    #[clap(flatten)]
-    zeta2_args: Zeta2Args,
-}
-
-#[derive(Debug, Args)]
-struct ContextArgs {
-    #[arg(long)]
-    provider: ContextProvider,
-    #[arg(long)]
-    worktree: PathBuf,
-    #[arg(long)]
-    cursor: SourceLocation,
-    #[arg(long)]
-    use_language_server: bool,
-    #[arg(long)]
-    edit_history: Option<FileOrStdin>,
-    #[clap(flatten)]
-    zeta2_args: Zeta2Args,
-}
-
-#[derive(clap::ValueEnum, Default, Debug, Clone, Copy)]
-enum ContextProvider {
-    Zeta1,
-    #[default]
-    Syntax,
-}
-
-#[derive(Clone, Debug, Args)]
-struct Zeta2Args {
-    #[arg(long, default_value_t = 8192)]
-    max_prompt_bytes: usize,
-    #[arg(long, default_value_t = 2048)]
-    max_excerpt_bytes: usize,
-    #[arg(long, default_value_t = 1024)]
-    min_excerpt_bytes: usize,
-    #[arg(long, default_value_t = 0.66)]
-    target_before_cursor_over_total_bytes: f32,
-    #[arg(long, default_value_t = 1024)]
-    max_diagnostic_bytes: usize,
-    #[arg(long, value_enum, default_value_t = PromptFormat::default())]
-    prompt_format: PromptFormat,
-    #[arg(long, value_enum, default_value_t = Default::default())]
-    output_format: OutputFormat,
-    #[arg(long, default_value_t = 42)]
-    file_indexing_parallelism: usize,
-    #[arg(long, default_value_t = false)]
-    disable_imports_gathering: bool,
-    #[arg(long, default_value_t = u8::MAX)]
-    max_retrieved_definitions: u8,
-}
-
-#[derive(Debug, Args)]
-pub struct PredictArguments {
-    #[clap(long, short, value_enum, default_value_t = PredictionsOutputFormat::Md)]
-    format: PredictionsOutputFormat,
-    example_path: PathBuf,
-    #[clap(flatten)]
-    options: PredictionOptions,
-}
-
-#[derive(Clone, Debug, Args)]
-pub struct PredictionOptions {
-    #[clap(flatten)]
-    zeta2: Zeta2Args,
-    #[clap(long)]
-    provider: PredictionProvider,
-    #[clap(long, value_enum, default_value_t = CacheMode::default())]
-    cache: CacheMode,
-}
-
-#[derive(Debug, ValueEnum, Default, Clone, Copy, PartialEq)]
-pub enum CacheMode {
-    /// Use cached LLM requests and responses, except when multiple repetitions are requested
-    #[default]
-    Auto,
-    /// Use cached LLM requests and responses, based on the hash of the prompt and the endpoint.
-    #[value(alias = "request")]
-    Requests,
-    /// Ignore existing cache entries for both LLM and search.
-    Skip,
-    /// Use cached LLM responses AND search results for full determinism. Fails if they haven't been cached yet.
-    /// Useful for reproducing results and fixing bugs outside of search queries
-    Force,
-}
-
-impl CacheMode {
-    fn use_cached_llm_responses(&self) -> bool {
-        self.assert_not_auto();
-        matches!(self, CacheMode::Requests | CacheMode::Force)
-    }
-
-    fn use_cached_search_results(&self) -> bool {
-        self.assert_not_auto();
-        matches!(self, CacheMode::Force)
-    }
-
-    fn assert_not_auto(&self) {
-        assert_ne!(
-            *self,
-            CacheMode::Auto,
-            "Cache mode should not be auto at this point!"
-        );
-    }
-}
-
-#[derive(clap::ValueEnum, Debug, Clone)]
-pub enum PredictionsOutputFormat {
-    Json,
-    Md,
-    Diff,
-}
-
-#[derive(Debug, Args)]
-pub struct EvaluateArguments {
-    example_paths: Vec<PathBuf>,
-    #[clap(flatten)]
-    options: PredictionOptions,
-    #[clap(short, long, default_value_t = 1, alias = "repeat")]
-    repetitions: u16,
-    #[arg(long)]
-    skip_prediction: bool,
-}
-
-#[derive(clap::ValueEnum, Default, Debug, Clone, Copy, PartialEq)]
-enum PredictionProvider {
-    Zeta1,
-    #[default]
-    Zeta2,
-    Sweep,
-}
-
-fn zeta2_args_to_options(args: &Zeta2Args, omit_excerpt_overlaps: bool) -> zeta::ZetaOptions {
-    zeta::ZetaOptions {
-        context: ContextMode::Syntax(EditPredictionContextOptions {
-            max_retrieved_declarations: args.max_retrieved_definitions,
-            use_imports: !args.disable_imports_gathering,
-            excerpt: EditPredictionExcerptOptions {
-                max_bytes: args.max_excerpt_bytes,
-                min_bytes: args.min_excerpt_bytes,
-                target_before_cursor_over_total_bytes: args.target_before_cursor_over_total_bytes,
-            },
-            score: EditPredictionScoreOptions {
-                omit_excerpt_overlaps,
-            },
-        }),
-        max_diagnostic_bytes: args.max_diagnostic_bytes,
-        max_prompt_bytes: args.max_prompt_bytes,
-        prompt_format: args.prompt_format.into(),
-        file_indexing_parallelism: args.file_indexing_parallelism,
-        buffer_change_grouping_interval: Duration::ZERO,
-    }
-}
-
-#[derive(clap::ValueEnum, Default, Debug, Clone, Copy)]
-enum PromptFormat {
-    MarkedExcerpt,
-    LabeledSections,
-    OnlySnippets,
-    #[default]
-    NumberedLines,
-    OldTextNewText,
-    Minimal,
-    MinimalQwen,
-    SeedCoder1120,
-}
-
-impl Into<predict_edits_v3::PromptFormat> for PromptFormat {
-    fn into(self) -> predict_edits_v3::PromptFormat {
-        match self {
-            Self::MarkedExcerpt => predict_edits_v3::PromptFormat::MarkedExcerpt,
-            Self::LabeledSections => predict_edits_v3::PromptFormat::LabeledSections,
-            Self::OnlySnippets => predict_edits_v3::PromptFormat::OnlySnippets,
-            Self::NumberedLines => predict_edits_v3::PromptFormat::NumLinesUniDiff,
-            Self::OldTextNewText => predict_edits_v3::PromptFormat::OldTextNewText,
-            Self::Minimal => predict_edits_v3::PromptFormat::Minimal,
-            Self::MinimalQwen => predict_edits_v3::PromptFormat::MinimalQwen,
-            Self::SeedCoder1120 => predict_edits_v3::PromptFormat::SeedCoder1120,
-        }
-    }
-}
-
-#[derive(clap::ValueEnum, Default, Debug, Clone)]
-enum OutputFormat {
-    #[default]
-    Prompt,
-    Request,
-    Full,
-}
-
-#[derive(Debug, Clone)]
-enum FileOrStdin {
-    File(PathBuf),
-    Stdin,
-}
-
-impl FileOrStdin {
-    async fn read_to_string(&self) -> Result<String, std::io::Error> {
-        match self {
-            FileOrStdin::File(path) => smol::fs::read_to_string(path).await,
-            FileOrStdin::Stdin => smol::unblock(|| std::io::read_to_string(std::io::stdin())).await,
-        }
-    }
-}
-
-impl FromStr for FileOrStdin {
-    type Err = <PathBuf as FromStr>::Err;
-
-    fn from_str(s: &str) -> Result<Self, Self::Err> {
-        match s {
-            "-" => Ok(Self::Stdin),
-            _ => Ok(Self::File(PathBuf::from_str(s)?)),
-        }
-    }
-}
-
-struct LoadedContext {
-    full_path_str: String,
-    snapshot: BufferSnapshot,
-    clipped_cursor: Point,
-    worktree: Entity<Worktree>,
-    project: Entity<Project>,
-    buffer: Entity<Buffer>,
-}
-
-async fn load_context(
-    args: &ContextArgs,
-    app_state: &Arc<ZetaCliAppState>,
-    cx: &mut AsyncApp,
-) -> Result<LoadedContext> {
-    let ContextArgs {
-        worktree: worktree_path,
-        cursor,
-        use_language_server,
-        ..
-    } = args;
-
-    let worktree_path = worktree_path.canonicalize()?;
-
-    let project = cx.update(|cx| {
-        Project::local(
-            app_state.client.clone(),
-            app_state.node_runtime.clone(),
-            app_state.user_store.clone(),
-            app_state.languages.clone(),
-            app_state.fs.clone(),
-            None,
-            cx,
-        )
-    })?;
-
-    let worktree = project
-        .update(cx, |project, cx| {
-            project.create_worktree(&worktree_path, true, cx)
-        })?
-        .await?;
-
-    let mut ready_languages = HashSet::default();
-    let (_lsp_open_handle, buffer) = if *use_language_server {
-        let (lsp_open_handle, _, buffer) = open_buffer_with_language_server(
-            project.clone(),
-            worktree.clone(),
-            cursor.path.clone(),
-            &mut ready_languages,
-            cx,
-        )
-        .await?;
-        (Some(lsp_open_handle), buffer)
-    } else {
-        let buffer =
-            open_buffer(project.clone(), worktree.clone(), cursor.path.clone(), cx).await?;
-        (None, buffer)
-    };
-
-    let full_path_str = worktree
-        .read_with(cx, |worktree, _| worktree.root_name().join(&cursor.path))?
-        .display(PathStyle::local())
-        .to_string();
-
-    let snapshot = cx.update(|cx| buffer.read(cx).snapshot())?;
-    let clipped_cursor = snapshot.clip_point(cursor.point, Bias::Left);
-    if clipped_cursor != cursor.point {
-        let max_row = snapshot.max_point().row;
-        if cursor.point.row < max_row {
-            return Err(anyhow!(
-                "Cursor position {:?} is out of bounds (line length is {})",
-                cursor.point,
-                snapshot.line_len(cursor.point.row)
-            ));
-        } else {
-            return Err(anyhow!(
-                "Cursor position {:?} is out of bounds (max row is {})",
-                cursor.point,
-                max_row
-            ));
-        }
-    }
-
-    Ok(LoadedContext {
-        full_path_str,
-        snapshot,
-        clipped_cursor,
-        worktree,
-        project,
-        buffer,
-    })
-}
-
-async fn zeta2_syntax_context(
-    args: ContextArgs,
-    app_state: &Arc<ZetaCliAppState>,
-    cx: &mut AsyncApp,
-) -> Result<String> {
-    let LoadedContext {
-        worktree,
-        project,
-        buffer,
-        clipped_cursor,
-        ..
-    } = load_context(&args, app_state, cx).await?;
-
-    // wait for worktree scan before starting zeta2 so that wait_for_initial_indexing waits for
-    // the whole worktree.
-    worktree
-        .read_with(cx, |worktree, _cx| {
-            worktree.as_local().unwrap().scan_complete()
-        })?
-        .await;
-    let output = cx
-        .update(|cx| {
-            let zeta = cx.new(|cx| {
-                zeta::Zeta::new(app_state.client.clone(), app_state.user_store.clone(), cx)
-            });
-            let indexing_done_task = zeta.update(cx, |zeta, cx| {
-                zeta.set_options(zeta2_args_to_options(&args.zeta2_args, true));
-                zeta.register_buffer(&buffer, &project, cx);
-                zeta.wait_for_initial_indexing(&project, cx)
-            });
-            cx.spawn(async move |cx| {
-                indexing_done_task.await?;
-                let request = zeta
-                    .update(cx, |zeta, cx| {
-                        let cursor = buffer.read(cx).snapshot().anchor_before(clipped_cursor);
-                        zeta.cloud_request_for_zeta_cli(&project, &buffer, cursor, cx)
-                    })?
-                    .await?;
-
-                let (prompt_string, section_labels) = cloud_zeta2_prompt::build_prompt(&request)?;
-
-                match args.zeta2_args.output_format {
-                    OutputFormat::Prompt => anyhow::Ok(prompt_string),
-                    OutputFormat::Request => anyhow::Ok(serde_json::to_string_pretty(&request)?),
-                    OutputFormat::Full => anyhow::Ok(serde_json::to_string_pretty(&json!({
-                        "request": request,
-                        "prompt": prompt_string,
-                        "section_labels": section_labels,
-                    }))?),
-                }
-            })
-        })?
-        .await?;
-
-    Ok(output)
-}
-
-async fn zeta1_context(
-    args: ContextArgs,
-    app_state: &Arc<ZetaCliAppState>,
-    cx: &mut AsyncApp,
-) -> Result<zeta::zeta1::GatherContextOutput> {
-    let LoadedContext {
-        full_path_str,
-        snapshot,
-        clipped_cursor,
-        ..
-    } = load_context(&args, app_state, cx).await?;
-
-    let events = match args.edit_history {
-        Some(events) => events.read_to_string().await?,
-        None => String::new(),
-    };
-
-    let prompt_for_events = move || (events, 0);
-    cx.update(|cx| {
-        zeta::zeta1::gather_context(
-            full_path_str,
-            &snapshot,
-            clipped_cursor,
-            prompt_for_events,
-            cloud_llm_client::PredictEditsRequestTrigger::Cli,
-            cx,
-        )
-    })?
-    .await
-}
-
-fn main() {
-    zlog::init();
-    zlog::init_output_stderr();
-    let args = ZetaCliArgs::parse();
-    let http_client = Arc::new(ReqwestClient::new());
-    let app = Application::headless().with_http_client(http_client);
-
-    app.run(move |cx| {
-        let app_state = Arc::new(headless::init(cx));
-        cx.spawn(async move |cx| {
-            match args.command {
-                None => {
-                    if args.printenv {
-                        ::util::shell_env::print_env();
-                        return;
-                    } else {
-                        panic!("Expected a command");
-                    }
-                }
-                Some(Command::ContextStats(arguments)) => {
-                    let result = retrieval_stats(
-                        arguments.worktree,
-                        app_state,
-                        arguments.extension,
-                        arguments.limit,
-                        arguments.skip,
-                        zeta2_args_to_options(&arguments.zeta2_args, false),
-                        cx,
-                    )
-                    .await;
-                    println!("{}", result.unwrap());
-                }
-                Some(Command::Context(context_args)) => {
-                    let result = match context_args.provider {
-                        ContextProvider::Zeta1 => {
-                            let context =
-                                zeta1_context(context_args, &app_state, cx).await.unwrap();
-                            serde_json::to_string_pretty(&context.body).unwrap()
-                        }
-                        ContextProvider::Syntax => {
-                            zeta2_syntax_context(context_args, &app_state, cx)
-                                .await
-                                .unwrap()
-                        }
-                    };
-                    println!("{}", result);
-                }
-                Some(Command::Predict(arguments)) => {
-                    run_predict(arguments, &app_state, cx).await;
-                }
-                Some(Command::Eval(arguments)) => {
-                    run_evaluate(arguments, &app_state, cx).await;
-                }
-                Some(Command::ConvertExample {
-                    path,
-                    output_format,
-                }) => {
-                    let example = NamedExample::load(path).unwrap();
-                    example.write(output_format, io::stdout()).unwrap();
-                }
-                Some(Command::Score {
-                    golden_patch,
-                    actual_patch,
-                }) => {
-                    let golden_content = std::fs::read_to_string(golden_patch).unwrap();
-                    let actual_content = std::fs::read_to_string(actual_patch).unwrap();
-
-                    let golden_diff: Vec<DiffLine> = golden_content
-                        .lines()
-                        .map(|line| DiffLine::parse(line))
-                        .collect();
-
-                    let actual_diff: Vec<DiffLine> = actual_content
-                        .lines()
-                        .map(|line| DiffLine::parse(line))
-                        .collect();
-
-                    let score = delta_chr_f(&golden_diff, &actual_diff);
-                    println!("{:.2}", score);
-                }
-                Some(Command::Clean) => {
-                    std::fs::remove_dir_all(&*crate::paths::TARGET_ZETA_DIR).unwrap()
-                }
-            };
-
-            let _ = cx.update(|cx| cx.quit());
-        })
-        .detach();
-    });
-}