-
Notifications
You must be signed in to change notification settings - Fork 3.3k
Expand file tree
/
Copy pathlib.rs
More file actions
2885 lines (2621 loc) · 116 KB
/
lib.rs
File metadata and controls
2885 lines (2621 loc) · 116 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Suppress warnings about rustdoc style.
#![allow(clippy::doc_lazy_continuation)]
mod ai;
mod alloc;
mod antivirus;
#[cfg(target_os = "macos")]
mod app_menus;
mod app_services;
mod app_state;
mod auth;
mod autoupdate;
mod banner;
mod billing;
mod changelog_model;
mod chip_configurator;
mod cloud_object;
mod code;
mod code_review;
mod coding_entrypoints;
mod coding_panel_enablement_state;
mod command_palette;
mod completer;
#[allow(dead_code)]
mod context_chips;
#[cfg(enable_crash_recovery)]
mod crash_recovery;
#[cfg(feature = "crash_reporting")]
mod crash_reporting;
mod debounce;
mod debug_dump;
mod default_terminal;
mod download_method;
mod drive;
#[cfg(windows)]
mod dynamic_libraries;
mod env_vars;
mod experiments;
mod external_secrets;
#[cfg(target_family = "wasm")]
mod font_fallback;
mod global_resource_handles;
mod gpu_state;
mod input_classifier;
mod interval_timer;
mod linear;
#[cfg(any(target_os = "macos", target_os = "windows"))]
mod login_item;
mod menu;
mod modal;
mod network;
mod notebooks;
mod notification;
mod palette;
mod persistence;
mod platform;
#[cfg(feature = "plugin_host")]
mod plugin;
mod prefix;
#[cfg(target_os = "macos")]
mod preview_config_migration;
mod pricing;
mod profiling;
mod projects;
mod prompt;
mod quit_warning;
mod referral_theme_status;
#[allow(dead_code)]
mod remote_server;
mod resource_limits;
mod reward_view;
mod safe_triangle;
mod search_bar;
mod server;
mod session_management;
mod shell_indicator;
mod suggestions;
mod system;
mod tab;
#[cfg(test)]
mod test_util;
mod throttle;
mod tips;
mod tracing;
mod ui_components;
mod undo_close;
mod uri;
mod user_config;
pub mod util;
mod view_components;
mod vim_registers;
mod voice;
mod voltron;
mod warp_managed_paths_watcher;
#[cfg(target_family = "wasm")]
mod wasm_nux_dialog;
mod window_settings;
mod word_block_editor;
mod workspaces;
// PLEASE DO NOT ADD MORE PUBLIC MODULES!
//
// Any modules which we make public outside of the `warp` crate lose dead code
// checking support, as the compiler cannot make any assumptions about whether
// or not the function/type is used by another crate that pulls in this one as
// a dependency.
//
// If you feel the need to export a module so that a type or function within it
// can be used by an integration test, you should define a new assertion function
// in the warp::integration_testing::assertions module (or a sub-module). These
// functions will allow us to keep types internal to this crate and expose a
// simpler API for integration tests to consume.
pub mod ai_assistant;
pub mod appearance;
pub mod channel;
pub mod editor;
pub mod features;
pub mod input_suggestions;
#[cfg(feature = "integration_tests")]
pub mod integration_testing;
pub mod keyboard;
pub mod launch_configs;
pub mod pane_group;
pub mod resource_center;
pub mod root_view;
pub mod search;
pub mod settings;
pub mod settings_view;
pub mod tab_configs;
pub mod terminal;
pub mod themes;
use crate::ai::active_agent_views_model::ActiveAgentViewsModel;
#[cfg(not(target_family = "wasm"))]
use crate::ai::aws_credentials::AwsCredentialRefresher as _;
use crate::ai::mcp::FileBasedMCPManager;
use crate::ai::mcp::FileMCPWatcher;
use crate::uri::web_intent_parser::maybe_rewrite_web_url_to_intent;
use ::ai::index::full_source_code_embedding::manager::CodebaseIndexManager;
use ::ai::index::full_source_code_embedding::SyncTask;
use ::ai::index::DEFAULT_SYNC_REQUESTS_PER_MIN;
use ::ai::project_context::model::ProjectContextModel;
pub use ai::agent::{todos::AIAgentTodoList, AIAgentActionResultType, FileEdit, TodoOperation};
use ai::agent_conversations_model::AgentConversationsModel;
use ai::agent_management::AgentNotificationsModel;
use ai::ambient_agents::scheduled::ScheduledAgentManager;
use ai::blocklist::{BlocklistAIHistoryModel, BlocklistAIPermissions};
use ai::execution_profiles::editor::ExecutionProfileEditorManager;
use ai::execution_profiles::profiles::AIExecutionProfilesModel;
use ai::persisted_workspace::PersistedWorkspace;
use auth::auth_state::AuthStateProvider;
use auth::{auth_manager::AuthManager, auth_state::AuthState};
use code::editor_management::CodeManager;
use code::opened_files::OpenedFilesModel;
use code_review::GlobalCodeReviewModel;
use quit_warning::UnsavedStateSummary;
use server::network_log_pane_manager::NetworkLogPaneManager;
use server::network_logging::NetworkLogModel;
use server::telemetry::context_provider::AppTelemetryContextProvider;
use server::voice_transcriber::ServerVoiceTranscriber;
#[cfg(feature = "local_fs")]
use settings::import::model::ImportedConfigModel;
use voice::transcriber::VoiceTranscriber;
use warp_cli::GlobalOptions;
use warp_cli::{agent::AgentCommand, CliCommand};
#[cfg(feature = "local_fs")]
use repo_metadata::{
repositories::DetectedRepositories, watcher::DirectoryWatcher, RepoMetadataModel,
};
#[cfg(feature = "local_fs")]
use watcher::HomeDirectoryWatcher;
use settings_view::pane_manager::SettingsPaneManager;
use terminal::general_settings::GeneralSettings;
use terminal::keys_settings::KeysSettings;
#[cfg(all(not(target_family = "wasm"), feature = "local_tty"))]
use terminal::local_shell::LocalShellState;
pub use util::bindings::cmd_or_ctrl_shift;
pub mod workflows;
pub mod workspace;
#[cfg(feature = "integration_tests")]
pub use persistence::testing as sqlite_testing;
use ::settings::{Setting, ToggleableSetting};
pub use warp_core::errors::{report_error, report_if_error};
#[cfg(feature = "plugin_host")]
pub use plugin::{run_plugin_host, PLUGIN_HOST_FLAG};
use warp_core::user_preferences::GetUserPreferences as _;
use warpui::modals::{AlertDialogWithCallbacks, AppModalCallback};
use warpui::platform::app::ApproveTerminateResult;
use window_settings::WindowSettings;
use workflows::manager::WorkflowManager;
use crate::ai::ambient_agents::github_auth_notifier::GitHubAuthNotifier;
use crate::ai::document::ai_document_model::AIDocumentModel;
use crate::ai::facts::manager::AIFactManager;
use crate::ai::llms::LLMPreferences;
use crate::ai::mcp::MCPGalleryManager;
use crate::ai::mcp::TemplatableMCPServerManager;
use crate::ai::outline::RepoOutlines;
use crate::ai::restored_conversations::RestoredAgentConversations;
use crate::ai::skills::SkillManager;
use crate::ai::AIRequestUsageModel;
use crate::autoupdate::{AutoupdateState, RelaunchModel};
use crate::changelog_model::ChangelogModel;
use crate::cloud_object::model::actions::ObjectActions;
use crate::cloud_object::model::view::CloudViewModel;
use crate::code::global_buffer_model::GlobalBufferModel;
#[cfg(feature = "local_fs")]
use crate::code::language_server_shutdown_manager::LanguageServerShutdownManager;
use crate::context_chips::prompt::Prompt;
use crate::default_terminal::DefaultTerminal;
use crate::drive::export::ExportManager;
use crate::env_vars::manager::EnvVarCollectionManager;
use crate::gpu_state::GPUState;
use crate::network::NetworkStatus;
use crate::notebooks::editor::keys::NotebookKeybindings;
use crate::notebooks::manager::NotebookManager;
use crate::notebooks::CloudNotebook;
use crate::palette::PaletteMode;
use crate::persistence::PersistenceWriter;
use crate::projects::ProjectManagementModel;
use crate::server::cloud_objects::{listener::Listener, update_manager::UpdateManager};
use crate::server::experiments::ServerExperiments;
use crate::server::sync_queue::{QueueItem, SyncQueue};
use crate::session_management::{RunningSessionSummary, SessionNavigationData};
use crate::settings::cloud_preferences_syncer::initialize_cloud_preferences_syncer;
use crate::settings::manager::SettingsManager;
use crate::settings::{AccessibilitySettings, ScrollSettings, SelectionSettings};
use crate::settings_view::keybindings::KeybindingChangedNotifier;
use crate::settings_view::DisplayCount;
use crate::suggestions::ignored_suggestions_model::IgnoredSuggestionsModel;
use crate::system::SystemStats;
use crate::terminal::cli_agent_sessions::CLIAgentSessionsModel;
use crate::terminal::keys::TerminalKeybindings;
use crate::terminal::resizable_data::ResizableData;
use crate::terminal::view::inline_banner::ByoLlmAuthBannerSessionState;
use crate::terminal::{AudibleBell, History};
use crate::undo_close::UndoCloseStack;
use crate::user_config::WarpConfig;
use crate::vim_registers::VimRegisters;
use crate::warp_managed_paths_watcher::{ensure_warp_watch_roots_exist, WarpManagedPathsWatcher};
use crate::workflows::aliases::WorkflowAliases;
use crate::workflows::local_workflows::LocalWorkflows;
use crate::workspace::{ActiveSession, OneTimeModalModel, ToastStack};
use crate::workspaces::team_tester::TeamTesterStatus;
use crate::workspaces::user_profiles::UserProfiles;
#[cfg(feature = "local_tty")]
use anyhow::Context;
use anyhow::{anyhow, Result};
use appearance::{Appearance, AppearanceManager};
use channel::ChannelState;
use interval_timer::IntervalTimer;
use itertools::Itertools;
use referral_theme_status::ReferralThemeStatus;
use rust_embed::RustEmbed;
use server::server_api::ServerApiProvider;
use settings::{ExtraMetaKeys, PrivacySettings};
use std::borrow::Cow;
use std::collections::HashSet;
use std::ops::Deref;
use std::sync::Arc;
use terminal::input;
use terminal::session_settings::SessionSettings;
use url::Url;
use warp_core::execution_mode::{AppExecutionMode, ExecutionMode};
use warp_managed_secrets::ManagedSecretManager;
use workspace::sync_inputs::SyncedInputState;
use warpui::{integration::TestDriver, App, AssetProvider, Event};
use self::features::FeatureFlag;
use crate::app_state::AppState;
use crate::cloud_object::model::actions::ObjectAction;
use crate::cloud_object::model::persistence::CloudModel;
use crate::drive::CloudObjectTypeAndId;
use crate::experiments::ImprovedPaletteSearch;
pub use crate::global_resource_handles::{GlobalResourceHandles, GlobalResourceHandlesProvider};
use crate::notification::NotificationContext;
use crate::root_view::{
quake_mode_window_id, quake_mode_window_is_open, OpenFromRestoredArg, OpenPath,
};
pub use crate::server::telemetry::{
AgentModeEntrypoint, AgentModeEntrypointSelectionType, TelemetryEvent,
};
use crate::server::telemetry::{AppStartupInfo, CloseTarget, PaletteSource, TelemetryCollector};
use crate::terminal::CustomSecretRegexUpdater;
use crate::util::bindings::is_binding_cross_platform;
use crate::workspace::{PaneViewLocator, Workspace, WorkspaceAction};
use crate::workspaces::update_manager::TeamUpdateManager;
use crate::workspaces::user_workspaces::UserWorkspaces;
use warp_logging::LogDestination;
// Re-export the send_telemetry_from_ctx macro at the crate root level
pub use warp_core::send_telemetry_from_app_ctx;
pub use warp_core::send_telemetry_from_ctx;
// Re-export the safe logging macros at the crate root level for backwards compatibility
pub use warp_core::{safe_debug, safe_error, safe_info, safe_warn};
use crate::antivirus::AntivirusInfo;
#[cfg(feature = "local_fs")]
use warp_files::FileModel;
use warpui::platform::TerminationMode;
use warpui::windowing::state::ApplicationStage;
use warpui::{AppContext, SingletonEntity, WindowId};
#[derive(Clone, Copy, RustEmbed)]
#[folder = "assets"]
#[include = "bundled/**"] // Should be kept in sync with BUNDLED_ASSETS_DIR.
#[include = "async/**"] // Should be kept in sync with ASYNC_ASSETS_DIR.
#[cfg_attr(target_family = "wasm", exclude = "async/**")]
// Excludes take precedence.
// Standalone CLI builds (the `oz` tarball) are headless and never render the
// onboarding/theme imagery in `async/`, so we exclude those bytes from the
// embedded asset set to keep the CLI binary small — mirroring the carve-out
// already applied for the WASM target above.
#[cfg_attr(feature = "standalone", exclude = "async/**")]
pub struct Assets;
pub static ASSETS: Assets = Assets;
fn determine_agent_source(
launch_mode: &LaunchMode,
) -> Option<crate::ai::ambient_agents::AgentSource> {
match launch_mode {
LaunchMode::CommandLine { .. } => {
if std::env::var("GITHUB_ACTIONS").ok().as_deref() == Some("true") {
Some(crate::ai::ambient_agents::AgentSource::GitHubAction)
} else {
Some(crate::ai::ambient_agents::AgentSource::Cli)
}
}
LaunchMode::App { .. } | LaunchMode::Test { .. } => {
Some(crate::ai::ambient_agents::AgentSource::CloudMode)
}
// RemoteServerProxy and RemoteServerDaemon are headless server
// processes that don't use the agent subsystem.
LaunchMode::RemoteServerProxy | LaunchMode::RemoteServerDaemon => None,
}
}
/// Launch mode for how to start up Warp.
#[allow(clippy::large_enum_variant)]
pub enum LaunchMode {
/// Run the regular GUI application.
App {
args: warp_cli::AppArgs,
/// API key for server authentication, if provided via `--api-key` or `WARP_API_KEY`.
/// Only used on dogfood channels.
api_key: Option<String>,
},
/// Run the Warp command-line SDK.
CommandLine {
command: warp_cli::CliCommand,
global_options: GlobalOptions,
debug: bool,
/// Whether this CLI invocation is running in a sandboxed environment.
is_sandboxed: bool,
/// Override for computer use permission from CLI flags. If None, uses default behavior.
computer_use_override: Option<bool>,
},
/// Run a test - this may be an integration test or an eval.
Test {
driver: Box<Option<TestDriver>>,
is_integration_test: bool,
},
/// Remote server proxy — bridges SSH stdio to the daemon's Unix socket.
/// This is a short-lived process that runs for the lifetime of an SSH session.
RemoteServerProxy,
/// Remote server daemon — long-lived headless process serving remote
/// connections via a Unix domain socket.
RemoteServerDaemon,
}
impl LaunchMode {
fn args(&self) -> Cow<'_, warp_cli::AppArgs> {
match self {
LaunchMode::App { args, .. } => Cow::Borrowed(args),
LaunchMode::CommandLine { .. }
| LaunchMode::Test { .. }
| LaunchMode::RemoteServerProxy
| LaunchMode::RemoteServerDaemon => Cow::Owned(warp_cli::AppArgs::default()),
}
}
/// Returns `true` if this process is running an integration test.
fn is_integration_test(&self) -> bool {
match self {
LaunchMode::Test {
is_integration_test,
..
} => *is_integration_test,
LaunchMode::App { .. }
| LaunchMode::CommandLine { .. }
| LaunchMode::RemoteServerProxy
| LaunchMode::RemoteServerDaemon => false,
}
}
fn take_test_driver(&mut self) -> Option<TestDriver> {
match self {
LaunchMode::Test { driver, .. } => driver.take(),
LaunchMode::App { .. }
| LaunchMode::CommandLine { .. }
| LaunchMode::RemoteServerProxy
| LaunchMode::RemoteServerDaemon => None,
}
}
/// Add an URL to open. Only supported for [`LaunchMode::App`]
#[allow(dead_code)]
fn add_url(&mut self, url: Url) {
if let LaunchMode::App { ref mut args, .. } = self {
args.urls.push(url);
}
}
fn execution_mode(&self) -> ExecutionMode {
match self {
LaunchMode::App { .. } => ExecutionMode::App,
LaunchMode::CommandLine { .. } => ExecutionMode::Sdk,
LaunchMode::Test { .. } => ExecutionMode::App,
// RemoteServerProxy and RemoteServerDaemon don't use execution
// mode, but Sdk is the closest match (headless, no GUI).
LaunchMode::RemoteServerProxy | LaunchMode::RemoteServerDaemon => ExecutionMode::Sdk,
}
}
fn is_sandboxed(&self) -> bool {
match self {
LaunchMode::CommandLine { is_sandboxed, .. } => *is_sandboxed,
LaunchMode::App { .. }
| LaunchMode::Test { .. }
| LaunchMode::RemoteServerProxy
| LaunchMode::RemoteServerDaemon => false,
}
}
/// Returns `true` if Warp should run headlessly, without a visible UI.
fn is_headless(&self) -> bool {
match self {
LaunchMode::CommandLine { command, .. } => match command {
CliCommand::Agent(AgentCommand::Run(args)) => !args.gui,
_ => true,
},
LaunchMode::RemoteServerProxy | LaunchMode::RemoteServerDaemon => true,
LaunchMode::App { .. } | LaunchMode::Test { .. } => false,
}
}
/// Returns `true` if running in app mode or via `agent run` to permit codebase indexing.
fn supports_indexing(&self) -> bool {
match self {
LaunchMode::CommandLine { command, .. } => {
matches!(command, CliCommand::Agent(AgentCommand::Run { .. }))
}
LaunchMode::App { .. } | LaunchMode::Test { .. } => true,
LaunchMode::RemoteServerProxy | LaunchMode::RemoteServerDaemon => false,
}
}
/// Whether or not to start a crash recovery process (on platforms that support it).
#[cfg(enable_crash_recovery)]
pub(crate) fn crash_recovery_enabled(&self) -> bool {
match self {
LaunchMode::App { .. } => true,
LaunchMode::CommandLine { .. }
| LaunchMode::Test { .. }
| LaunchMode::RemoteServerProxy
| LaunchMode::RemoteServerDaemon => false,
}
}
/// Whether Sentry / crash reporting should be initialized in `init_common`.
#[cfg_attr(not(feature = "crash_reporting"), allow(dead_code))]
fn needs_crash_reporting(&self) -> bool {
match self {
LaunchMode::App { .. }
| LaunchMode::CommandLine { .. }
| LaunchMode::Test { .. }
| LaunchMode::RemoteServerDaemon
| LaunchMode::RemoteServerProxy => true,
}
}
/// Whether profiling and tracing should be initialized in `init_common`.
fn needs_profiling(&self) -> bool {
match self {
LaunchMode::App { .. }
| LaunchMode::CommandLine { .. }
| LaunchMode::Test { .. }
| LaunchMode::RemoteServerDaemon
| LaunchMode::RemoteServerProxy => true,
}
}
/// Log destination for this mode.
fn log_destination(&self) -> Option<LogDestination> {
match self {
LaunchMode::CommandLine { debug, .. } => {
if *debug {
Some(LogDestination::Stderr)
} else {
Some(LogDestination::File)
}
}
// Proxy must log to stderr because stdout is the protocol channel.
LaunchMode::RemoteServerProxy => Some(LogDestination::Stderr),
LaunchMode::RemoteServerDaemon => Some(LogDestination::File),
LaunchMode::App { .. } | LaunchMode::Test { .. } => None,
}
}
#[cfg(test)]
pub(crate) fn new_for_unit_test() -> Self {
LaunchMode::Test {
driver: Box::new(None),
is_integration_test: false,
}
}
}
impl AssetProvider for Assets {
fn get(&self, path: &str) -> Result<Cow<'_, [u8]>> {
<Assets as RustEmbed>::get(path)
.map(|f| f.data)
.ok_or_else(|| anyhow!("no asset exists at path {}", path))
}
}
/// If the given event is a key down event containing alt modifiers, and those
/// alt modifiers should be treated as meta keys, then remove the alts and
/// prefix the keys with an escape. See WAR-472.
fn apply_extra_meta_keys(event: &mut Event, extra_metas: ExtraMetaKeys) {
if let Event::KeyDown {
keystroke, details, ..
} = event
{
let left_as_meta = extra_metas.left_alt && details.left_alt;
let right_as_meta = extra_metas.right_alt && details.right_alt;
if left_as_meta || right_as_meta {
let side = match (left_as_meta, right_as_meta) {
(true, true) => "left+right alt",
(true, false) => "left alt",
(false, true) => "right alt",
(false, false) => unreachable!(),
};
log::info!("Treating {side} as meta");
keystroke.alt = false;
keystroke.meta = true;
}
}
}
fn apply_scroll_multiplier(event: &mut Event, app: &AppContext) {
if let Event::ScrollWheel { delta, precise, .. } = event {
if !*precise {
let scroll_multiplier = *ScrollSettings::as_ref(app).mouse_scroll_multiplier.value();
*delta *= scroll_multiplier;
}
}
}
/// Runs the app. If a subcommand was requested, it'll be run instead of the main application.
pub fn run() -> Result<()> {
// Perform any necessary platform-specific initialization.
platform::init();
// Ensure feature flags are initialized before parsing command-line arguments.
init_feature_flags();
// Parse command-line arguments.
let args = warp_cli::Args::from_env();
// Server URL overrides are only honored on internal dev channels. Release channels silently
// ignore `--server-root-url` / `--ws-server-url` / `--session-sharing-server-url` (and their
// `WARP_*` env-var equivalents) so shipped builds can't be redirected away from their
// baked-in server URLs. See `Channel::allows_server_url_overrides`.
if ChannelState::channel().allows_server_url_overrides() {
if let Some(url) = args.server_root_url() {
if let Err(e) = ChannelState::override_server_root_url(url.to_owned()) {
eprintln!("Error: Invalid server root URL: {e:#}");
}
}
if let Some(url) = args.ws_server_url() {
if let Err(e) = ChannelState::override_ws_server_url(url.to_owned()) {
eprintln!("Error: Invalid websocket server URL: {e:#}");
}
}
if let Some(url) = args.session_sharing_server_url() {
if let Err(e) = ChannelState::override_session_sharing_server_url(url.to_owned()) {
eprintln!("Error: Invalid session sharing server URL: {e:#}");
}
}
}
if let Some(command) = args.command() {
#[cfg(windows)]
if command.prints_to_stdout() {
// We attach a console to ensure that all standard output gets printed correctly.
warp_util::windows::attach_to_parent_console();
}
match command {
#[cfg(all(feature = "local_tty", unix))]
warp_cli::Command::Worker(warp_cli::WorkerCommand::TerminalServer(args)) => {
// If we were asked to run as a terminal server (as opposed to the main
// GUI application), do so immediately. Ideally, the terminal server would
// be a separate binary, but it's much easier to distribute a single binary,
// so starting the terminal server event loop immediately is the closest
// approximation we can get to running a separate binary.
crate::terminal::local_tty::server::run_terminal_server(args);
return Ok(());
}
#[cfg(feature = "plugin_host")]
warp_cli::Command::Worker(warp_cli::WorkerCommand::PluginHost { .. }) => {
return crate::run_plugin_host();
}
#[cfg(feature = "local_tty")]
warp_cli::Command::Worker(warp_cli::WorkerCommand::MinidumpServer { socket_name }) => {
cfg_if::cfg_if! {
if #[cfg(all(linux_or_windows, feature = "crash_reporting"))] {
return crate::crash_reporting::run_minidump_server(socket_name);
} else {
let _ = socket_name;
panic!("The minidump server is not supported on this platform");
}
}
}
#[cfg(not(target_family = "wasm"))]
warp_cli::Command::Worker(warp_cli::WorkerCommand::RemoteServerProxy(args)) => {
init_common(&LaunchMode::RemoteServerProxy, None)?;
return crate::remote_server::run_proxy(args.identity_key.clone());
}
#[cfg(not(target_family = "wasm"))]
warp_cli::Command::Worker(warp_cli::WorkerCommand::RemoteServerDaemon(args)) => {
init_common(&LaunchMode::RemoteServerDaemon, None)?;
return crate::remote_server::run_daemon(args.identity_key.clone());
}
#[cfg(not(target_family = "wasm"))]
warp_cli::Command::Worker(warp_cli::WorkerCommand::RipgrepSearch {
parent,
ignore_case,
multiline,
pattern,
paths,
}) => {
warp_ripgrep::search::run_search_subprocess(
std::slice::from_ref(pattern),
paths.clone(),
*ignore_case,
*multiline,
parent.pid,
)
.map_err(|err| anyhow!(err.to_string()))?;
return Ok(());
}
#[cfg(not(any(
feature = "local_tty",
feature = "plugin_host",
not(target_family = "wasm")
)))]
warp_cli::Command::Worker(worker) => {
// Need this case to handle platforms where there are no enum variants in
// warp_cli::WorkerCommand, as we still need to check Command::Worker.
// On wasm, specifically, we should fail spectacularly if we get here.
#[cfg(target_family = "wasm")]
panic!("Worker process not supported on WASM: {worker:?}")
}
warp_cli::Command::Completions { shell } => {
return warp_cli::completions::generate_to_stdout(*shell);
}
warp_cli::Command::CommandLine(cmd) => {
let (is_sandboxed, computer_use_override) = match cmd.as_ref() {
warp_cli::CliCommand::Agent(warp_cli::agent::AgentCommand::Run(run_args)) => (
run_args.sandboxed,
run_args.computer_use.computer_use_override(),
),
_ => (false, None),
};
return run_internal(LaunchMode::CommandLine {
command: cmd.as_ref().clone(),
global_options: GlobalOptions {
output_format: args.output_format(),
api_key: args.api_key().cloned(),
},
debug: args.debug(),
is_sandboxed,
computer_use_override,
});
}
warp_cli::Command::DumpDebugInfo => {
return debug_dump::run();
}
#[cfg(not(target_family = "wasm"))]
warp_cli::Command::PrintTelemetryEvents => {
return TelemetryEvent::print_telemetry_events_json();
}
}
}
// If running as a standalone CLI binary or invoked as "oz", print help
// instead of launching the GUI app.
let is_cli_binary = cfg!(feature = "standalone")
|| warp_cli::binary_name().is_some_and(|name| name.starts_with("oz"))
|| std::env::var_os("WARP_CLI_MODE").is_some();
if is_cli_binary {
warp_cli::Args::clap_command().print_help()?;
return Ok(());
}
let api_key = args.api_key().cloned();
run_internal(LaunchMode::App {
args: args.into_app_args(),
api_key,
})
}
/// Runs an integration test using the provided test driver.
pub fn run_integration_test(driver: TestDriver) -> Result<()> {
let is_integration_test = std::env::var("WARP_INTEGRATION").is_ok();
let launch = LaunchMode::Test {
driver: Box::new(Some(driver)),
is_integration_test,
};
run_internal(launch)
}
/// Shared early initialization for **every** process type (app, CLI, proxy,
/// daemon). Every step in this function runs for all modes, including
/// lightweight ones like Proxy. Think carefully before adding here — if
/// the step is only needed by the full app, add it to `run_internal`
/// instead.
fn init_common(launch_mode: &LaunchMode, timer: Option<&mut IntervalTimer>) -> Result<()> {
#[cfg(windows)]
dynamic_libraries::configure_library_loading();
if launch_mode.needs_profiling() {
profiling::init();
}
// The `run` function already initializes feature flags, but ensure they're initialized here
// for other entrypoints.
init_feature_flags();
#[cfg(feature = "crash_reporting")]
if launch_mode.needs_crash_reporting() {
// Ensure that the main/root Sentry hub is initialized on the main
// thread. PtySpawner creates a background thread to receive logs from
// the terminal server process, and we don't want it to be the host of
// the primary sentry::Hub.
sentry::Hub::main();
}
if launch_mode.needs_profiling() {
tracing::init()?;
}
let log_destination = launch_mode.log_destination();
let is_cli = log_destination.is_some();
cfg_if::cfg_if! {
if #[cfg(enable_crash_recovery)] {
if crash_recovery::is_crash_recovery_process(launch_mode.args().as_ref()) {
warp_logging::init_for_crash_recovery_process()?;
} else {
warp_logging::init(warp_logging::LogConfig { is_cli, log_destination })?;
}
} else {
warp_logging::init(warp_logging::LogConfig { is_cli, log_destination })?;
}
}
if let Some(timer) = timer {
timer.mark_interval_end("LOG_FILE_SETUP_COMPLETE");
}
// Adjust resource limits early, before doing other work, to ensure that
// any children we spawn (like the terminal server) inherit our adjusted
// rlimits.
resource_limits::adjust_resource_limits();
// Configure rustls to use its default crypto provider. This MUST be called
// before making any network requests that use TLS, otherwise rustls will
// panic.
#[cfg(not(target_family = "wasm"))]
rustls::crypto::aws_lc_rs::default_provider()
.install_default()
.expect("must be able to initialize crypto provider for TLS support");
Ok(())
}
/// Runs the app.
///
/// Note that every initialization step in this function is specific to the GUI app and Oz. If you want
/// to add setup steps that should be generic to all launch modes (e.g. remote server). It should be added
/// in init_common instead.
fn run_internal(mut launch_mode: LaunchMode) -> Result<()> {
let mut timer = IntervalTimer::new();
init_common(&launch_mode, Some(&mut timer))?;
// For wasm builds we have this special case to parse out the intent
// from the url that is used to visite the app on web.
#[cfg(target_family = "wasm")]
{
use uri::web_intent_parser;
if let Some(intent) = web_intent_parser::parse_web_intent_from_current_url() {
launch_mode.add_url(intent);
}
web_intent_parser::set_context_flags_from_current_url();
}
// Collect errors that occur in run_internal() before the Sentry client is initialized,
// so they can be replayed to Sentry once it's ready.
#[cfg_attr(
not(all(feature = "release_bundle", any(windows, target_os = "linux"))),
expect(unused_mut)
)]
let mut pre_sentry_errors: Vec<anyhow::Error> = Vec::new();
#[cfg(all(feature = "release_bundle", target_os = "linux"))]
if let LaunchMode::App { .. } = launch_mode {
match app_services::linux::pass_startup_args_to_existing_instance(
launch_mode.args().as_ref(),
) {
// If we were able to contact an existing application instance, quit -
// we only want to run a single instance of Warp at a time.
Ok(_) => std::process::exit(0),
// If Warp isn't already running, we're good to go.
Err(app_services::linux::StartupArgsForwardingError::NoExistingInstance) => {}
// If we just finished an auto-update, we should continue running.
Err(app_services::linux::StartupArgsForwardingError::IgnoredAfterAutoUpdate) => {}
// If we were unable to perform the forwarding for an unknown reason,
// it's better to run a second instance than potentially end up in a
// state where Warp refuses to run even a first instance.
Err(err) => {
let err = anyhow::Error::from(err).context("Failed to forward startup args");
log::error!("{err:#}");
pre_sentry_errors.push(err);
}
}
}
#[cfg(all(feature = "release_bundle", windows))]
if let LaunchMode::App { .. } = launch_mode {
match app_services::windows::pass_startup_args_to_existing_instance(
launch_mode.args().as_ref(),
) {
// If we were able to contact an existing application instance, quit -
// we only want to run a single instance of Warp at a time.
Ok(_) => std::process::exit(0),
// If Warp isn't already running, we're good to go.
Err(app_services::windows::StartupArgsForwardingError::NoExistingInstance) => {}
// If we just finished an auto-update, we should continue running.
Err(app_services::windows::StartupArgsForwardingError::IgnoredAfterAutoUpdate) => {}
// If we were unable to perform the forwarding for an unknown reason,
// it's better to run a second instance than potentially end up in a
// state where Warp refuses to run even a first instance.
Err(err) => {
let err = anyhow::Error::from(err).context("Failed to forward startup args");
log::error!("{err:#}");
pre_sentry_errors.push(err);
}
}
}
// Sets up a Job Object that we associate with the Warp process to handle
// shared fate with its child processes. This should be called before we
// start spawning any child processes.
#[cfg(windows)]
command::windows::init();
let private_preferences = settings::init_private_user_preferences();
let (public_preferences, startup_toml_parse_error) = settings::init_public_user_preferences();
// When the SettingsFile feature flag is enabled, public settings live in
// the TOML-backed store. When disabled, they live in the platform-native
// store (same backend as private). Use the correct one for pre-app reads.
#[cfg_attr(not(any(enable_crash_recovery, target_os = "linux")), expect(unused))]
let prefs_for_public_settings: &dyn warpui_extras::user_preferences::UserPreferences =
if FeatureFlag::SettingsFile.is_enabled() {
public_preferences.as_ref()
} else {
private_preferences.deref()
};
#[cfg(enable_crash_recovery)]
let crash_recovery =
crash_recovery::CrashRecovery::new(&launch_mode, prefs_for_public_settings);
// Set up the pty spawner before doing any meaningful work. We want to
// ensure that the process is in the cleanest possible state (minimal opened
// files, modified signal handlers, etc.) to avoid unexpected effects on
// spawned ptys.
#[cfg(feature = "local_tty")]
let pty_spawner =
terminal::local_tty::spawner::PtySpawner::new().context("Failed to create pty spawner")?;
let mut app_builder = if launch_mode.is_headless() {
warpui::platform::AppBuilder::new_headless(
app_callbacks(launch_mode.is_integration_test()),
Box::new(ASSETS),
launch_mode.take_test_driver(),
)
} else {
warpui::platform::AppBuilder::new(
app_callbacks(launch_mode.is_integration_test()),
Box::new(ASSETS),
launch_mode.take_test_driver(),
)
};
#[cfg(target_os = "macos")]
{
use warpui::platform::mac::AppExt;
let activate_on_launch = !launch_mode.is_integration_test()
|| std::env::var("WARPUI_USE_REAL_DISPLAY_IN_INTEGRATION_TESTS").is_ok();
app_builder.set_activate_on_launch(activate_on_launch);
let dev_icon = ASSETS.get("bundled/png/local.png")?;
app_builder.set_dev_icon(dev_icon);
app_builder.set_menu_bar_builder(app_menus::menu_bar);
app_builder.set_dock_menu_builder(|_| app_menus::dock_menu());
}
#[cfg(target_os = "linux")]
{
use crate::settings::ForceX11;
use warpui::platform::linux::{self, AppBuilderExt};
app_builder.set_window_class(ChannelState::app_id().to_string());
let force_x11 = ForceX11::read_from_preferences(prefs_for_public_settings)
.unwrap_or(ForceX11::default_value());
// Force use of wayland if the user has passed the `WARP_ENABLE_WAYLAND` env var.
let allow_wayland = linux::is_wayland_env_var_set() || !force_x11;
app_builder.force_x11(!allow_wayland);
}
#[cfg(target_os = "windows")]
{
use warpui::platform::windows::AppBuilderExt;
app_builder.set_app_user_model_id(ChannelState::app_id().to_string());
// Only use DXC for DirectX shader compilation if we're not running in a Parallels VM
// Parallels VMs can have issues with DXC shader compilation
let is_parallels_vm = crate::util::vm_detection::is_running_in_windows_parallels_vm();
if !is_parallels_vm {
log::info!("Using DXC for DirectX shader compilation");
use warpui::platform::windows::DXCPath;
app_builder.use_dxc_for_directx_shader_compilation(DXCPath {
dxc_path: "dxcompiler.dll".to_string(),
dxil_path: "dxil.dll".to_string(),
});
} else {
log::info!("Skipping DXC for DirectX shader compilation; running in a Parallels VM");
}
}
// Override any bindings that have a `Custom` trigger to a `Keystroke`-based trigger. In theory,
// this should be a noop on Mac (since the keystrokes registered via the Mac menus first
// intercept the binding), but just to be safe we only enable this in cases where we don't
// include mac menus.
#[cfg(not(target_os = "macos"))]
app_builder.convert_custom_triggers_to_keystroke_triggers(
crate::util::bindings::custom_tag_to_keystroke,
);
#[cfg(target_os = "macos")]
app_builder.register_default_keystroke_triggers_for_custom_actions(
crate::util::bindings::custom_tag_to_keystroke,
);
app_builder.run(move |ctx| {
#[cfg(not(target_family = "wasm"))]
// Rotate the log files in the background.
ctx.background_executor()
.spawn(warp_logging::rotate_log_files())
.detach();
ctx.add_singleton_model(|ctx| {
AppExecutionMode::new(
launch_mode.execution_mode(),
launch_mode.is_sandboxed(),
ctx,
)