-
Notifications
You must be signed in to change notification settings - Fork 5.5k
Expand file tree
/
Copy pathserver_model.rs
More file actions
3549 lines (3362 loc) · 148 KB
/
Copy pathserver_model.rs
File metadata and controls
3549 lines (3362 loc) · 148 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
use std::collections::{HashMap, HashSet};
use std::future::Future;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use ::ai::index::full_source_code_embedding::manager::{
CodebaseIndexManager, CodebaseIndexManagerEvent,
FragmentMetadataLookupError as LocalFragmentMetadataLookupError,
};
use ::ai::index::full_source_code_embedding::{
ContentHash, FragmentMetadata as LocalFragmentMetadata, NodeHash,
};
use futures::StreamExt as _;
use remote_server::proto::OpenBufferSuccess;
use repo_metadata::repositories::{DetectedRepositories, RepoDetectionSource};
use repo_metadata::{RepoMetadataEvent, RepoMetadataModel, RepositoryIdentifier};
use warp_core::channel::ChannelState;
use warp_core::{safe_error, SessionId};
use warp_files::{FileModel, FileModelEvent};
use warp_util::content_version::ContentVersion;
use warp_util::file::FileId;
use warp_util::standardized_path::StandardizedPath;
use warpui::platform::TerminationMode;
use warpui::r#async::{Spawnable, SpawnableOutput, SpawnedFutureHandle};
use warpui::{Entity, ModelContext, ModelHandle, SingletonEntity};
use super::codebase_index_status::{
codebase_index_status_to_proto, disabled_codebase_index_status,
not_enabled_codebase_index_status, queued_codebase_index_status,
unavailable_codebase_index_status,
};
use super::diff_state_proto;
use super::diff_state_tracker::{
DiffModelKey, DiffStateUpdate, RemoteDiffStateManager, SubscribeOutcome,
};
use super::proto::{
client_message, delete_file_response, discard_files_response, get_diff_state_response,
get_fragment_metadata_from_hash_response, git_commit_chain_response, git_create_pr_response,
git_generate_commit_message_response, git_get_committed_branch_files_response,
git_get_pr_info_response, git_push_response, host_scoped_request, notification,
resolve_conflict_response, ripgrep_search_response, run_command_response, save_buffer_response,
server_message, session_scoped_request, write_file_response, Abort, Authenticate, BranchInfo,
BufferEdit, BufferUpdatedPush, ClientMessage, CloseBuffer, CodebaseIndexLimits,
CodebaseIndexStatus, CodebaseIndexStatusUpdated, CodebaseIndexStatusesSnapshot,
CodebaseResyncMode, DeleteFile, DeleteFileResponse, DeleteFileSuccess, DiscardFilesError,
DiscardFilesResponse, DiscardFilesSuccess, DropCodebaseIndex, ErrorCode, ErrorResponse,
FailedFileRead, FileContextProto, FileOperationError,
FragmentMetadata as ProtoFragmentMetadata,
FragmentMetadataLookupError as ProtoFragmentMetadataLookupError,
FragmentMetadataLookupErrorCode, GetBranchesError, GetBranchesResponse, GetBranchesSuccess,
GetDiffStateResponse, GetFragmentMetadataFromHash, GetFragmentMetadataFromHashResponse,
GetFragmentMetadataFromHashSuccess, GitCommitChainMode, GitCommitChainRequest,
GitCommitChainResponse, GitCommitChainSuccess, GitCreatePrRequest, GitCreatePrResponse,
GitGenerateCommitMessageRequest, GitGenerateCommitMessageResponse,
GitGetCommittedBranchFilesRequest, GitGetCommittedBranchFilesResponse,
GitGetCommittedBranchFilesSuccess, GitGetPrInfoRequest, GitGetPrInfoResponse,
GitGetPrInfoSuccess, GitOpDelta, GitOpError, GitPushRequest, GitPushResponse, IndexCodebase,
Initialize, InitializeResponse, MissingFragmentMetadata, NavigatedToDirectory,
NavigatedToDirectoryResponse, OpenBuffer, OpenBufferResponse, ReadFileContextResponse,
ResolveConflict, ResolveConflictResponse, ResolveConflictSuccess, ResyncCodebase,
RipgrepSearchError, RipgrepSearchMatch, RipgrepSearchRequest, RipgrepSearchResponse,
RipgrepSearchSubmatch, RipgrepSearchSuccess, RunCommandError, RunCommandErrorCode,
RunCommandRequest, RunCommandResponse, RunCommandSuccess, SaveBuffer, SaveBufferResponse,
SaveBufferSuccess, ServerMessage, SessionBootstrapped, TextEdit, UploadHandoffSnapshot,
WriteFile, WriteFileResponse, WriteFileSuccess,
};
use super::server_buffer_tracker::{PendingBufferRequestKind, ServerBufferTracker};
use crate::code::global_buffer_model::{GlobalBufferModel, GlobalBufferModelEvent};
use crate::code_review::diff_state::{CommitChainMode, DiffMode, FileStatusInfo};
#[cfg(feature = "local_tty")]
use crate::terminal::local_shell::LocalShellState;
use crate::terminal::shell::ShellType;
/// How long the daemon waits with no connections before exiting.
pub const GRACE_PERIOD: std::time::Duration = std::time::Duration::from_secs(10 * 60);
/// Server-side cap on the number of branches returned by `GetBranches`.
/// Prevents a client from forcing the daemon to enumerate an arbitrarily
/// large ref list.
const MAX_BRANCH_COUNT_CAP: usize = 500;
/// Server-side cap on the number of matched lines returned by `RipgrepSearch`.
const MAX_RIPGREP_SEARCH_MATCH_CAP: usize = 5_000;
/// Approximate payload budget for one remote search response.
///
/// Eight MB keeps transfer latency and memory well below the protocol's
/// 64 MB frame limit. Individual matches are never truncated because doing so
/// could remove a late submatch and corrupt its preview and click location.
const MAX_RIPGREP_SEARCH_RESPONSE_BYTES: usize = 8 * 1024 * 1024;
/// Unique identifier for a connected proxy session in daemon mode.
pub type ConnectionId = uuid::Uuid;
use super::protocol::RequestId;
use crate::ai::agent::FileLocations;
use crate::ai::blocklist::handoff::snapshot::upload_result_to_proto;
use crate::ai::blocklist::{read_local_file_context, ReadFileContextResult};
use crate::auth::auth_state::{AuthState, AuthStateProvider};
use crate::code_review::git_actions;
use crate::features::FeatureFlag;
use crate::server::server_api::ServerApiProvider;
use crate::terminal::model::session::command_executor::{
ExecuteCommandOptions, LocalCommandExecutor,
};
use crate::util::git;
/// Outcome of dispatching a request-style `ClientMessage`.
///
/// Notifications (fire-and-forget messages like `SessionBootstrapped` and
/// `Abort`) do not produce a `HandlerOutcome`; they are dispatched inline in
/// `handle_message` and return early.
#[allow(clippy::large_enum_variant)]
enum HandlerOutcome {
/// The response is ready synchronously — the caller sends it immediately.
Sync(server_message::Message),
/// The handler initiated async work whose response will be sent later.
///
/// When the handle is `Some`, the caller inserts it into `in_progress`
/// so the request can be cancelled via `Abort`. Removal on
/// completion/abort is arranged by [`ServerModel::spawn_request_handler`].
///
/// `None` is used for async work whose completion is delivered through
/// a separate event subscription and is not currently cancellable via
/// `Abort` (e.g. `FileModel` events for file writes and deletes, which
/// are tracked by `FileId` in `pending_file_ops` rather than by
/// `RequestId` in `in_progress`).
Async(Option<SpawnedFutureHandle>),
}
struct CodebaseIndexRequest {
repo_path: PathBuf,
}
struct CodebaseIndexRequestParams<'a> {
operation_name: &'a str,
repo_path: String,
auth_token: String,
auth_operation: &'a str,
path_kind: CodebaseIndexRequestPathKind,
}
#[derive(Clone, Copy)]
enum CodebaseIndexRequestPathKind {
Canonicalized,
Requested,
}
/// Tracks an in-flight file write or delete so the async completion
/// event can be correlated back to the originating client request.
enum FileOpKind {
Write,
Delete,
}
struct PendingFileOp {
request_id: RequestId,
conn_id: ConnectionId,
kind: FileOpKind,
}
/// Manages pending file operations and ensures that the corresponding
/// `FileModel` entry is always cleaned up when an operation completes
/// or fails, preventing `FileState` leaks.
struct PendingFileOps {
ops: HashMap<FileId, PendingFileOp>,
}
impl PendingFileOps {
fn new() -> Self {
Self {
ops: HashMap::new(),
}
}
/// Registers a file path with `FileModel`, sets the initial version,
/// and tracks the pending operation. Returns the `FileId` and
/// `ContentVersion` for the caller to initiate the actual I/O.
fn insert(
&mut self,
path: &Path,
request_id: RequestId,
conn_id: ConnectionId,
kind: FileOpKind,
ctx: &mut ModelContext<ServerModel>,
) -> (FileId, ContentVersion) {
let file_model = FileModel::handle(ctx);
let file_id = file_model.update(ctx, |m, ctx| m.register_file_path(path, false, ctx));
let version = ContentVersion::new();
file_model.update(ctx, |m, _| m.set_version(file_id, version));
self.ops.insert(
file_id,
PendingFileOp {
request_id,
conn_id,
kind,
},
);
(file_id, version)
}
fn get(&self, file_id: &FileId) -> Option<&PendingFileOp> {
self.ops.get(file_id)
}
/// Removes a pending operation and unsubscribes the file from `FileModel`,
/// preventing the `FileState` entry from leaking.
fn remove(
&mut self,
file_id: FileId,
ctx: &mut ModelContext<ServerModel>,
) -> Option<PendingFileOp> {
let op = self.ops.remove(&file_id)?;
FileModel::handle(ctx).update(ctx, |m, ctx| m.unsubscribe(file_id, ctx));
Some(op)
}
}
/// The top-level server-side orchestrator model.
///
/// Receives `ClientMessage`s from connected proxy sessions and routes
/// `ServerMessage` responses and push notifications back through each
/// connection's dedicated sender channel.
pub struct ServerModel {
/// Per-connection outbound channels, keyed by `ConnectionId`.
///
/// The daemon can serve multiple proxy connections simultaneously — one
/// per SSH session / Warp tab connecting to this host. Each entry maps
/// a connection's `Uuid` to the channel the connection task drains to
/// write `ServerMessage`s back to its proxy.
connection_senders: HashMap<ConnectionId, async_channel::Sender<ServerMessage>>,
/// Per-connection set of repo roots for which we've already sent a
/// snapshot in this connection's lifetime.
///
/// Used to avoid sending duplicate snapshots on repeated
/// `NavigatedToDirectory` calls while the user `cd`s within the same repo.
snapshot_sent_roots_by_connection: HashMap<ConnectionId, HashSet<StandardizedPath>>,
/// Abort handle for the active grace timer, if any.
/// Calling `.abort()` cancels the timer before it fires.
grace_timer_cancel: Option<SpawnedFutureHandle>,
/// Tracks in-progress requests that can be cancelled via `Abort`.
/// Calling `.abort()` on the handle cancels the background future and
/// triggers its `on_abort` callback.
in_progress: HashMap<RequestId, SpawnedFutureHandle>,
/// Stable host identifier generated once at process startup.
/// Returned in every `InitializeResponse` so clients can deduplicate
/// host-scoped models.
host_id: String,
/// Per-session command executors created from `SessionBootstrapped` notifications.
executors: HashMap<SessionId, Arc<LocalCommandExecutor>>,
/// Tracks in-flight file write/delete operations and handles cleanup.
pending_file_ops: PendingFileOps,
/// Daemon-wide auth credentials and user identity.
auth_state: Arc<AuthState>,
/// Tracks open buffers, per-buffer connection sets, and pending async
/// buffer requests (OpenBuffer, SaveBuffer).
buffers: ServerBufferTracker,
/// Manages per-(repo, mode) diff state models and per-connection subscriptions.
diff_states: ModelHandle<RemoteDiffStateManager>,
/// In-flight host-scoped requests whose response may be delivered on
/// a different connection if the originating connection disconnects.
host_scoped_requests: HashMap<RequestId, ConnectionId>,
}
impl Entity for ServerModel {
type Event = ();
}
impl SingletonEntity for ServerModel {}
impl ServerModel {
pub fn new(ctx: &mut ModelContext<Self>) -> Self {
let host_id = uuid::Uuid::new_v4().to_string();
log::info!(
"Daemon started: PID={}, host_id={}",
std::process::id(),
host_id
);
let mut model = Self {
connection_senders: HashMap::new(),
snapshot_sent_roots_by_connection: HashMap::new(),
grace_timer_cancel: None,
in_progress: HashMap::new(),
host_id,
executors: HashMap::new(),
pending_file_ops: PendingFileOps::new(),
auth_state: AuthStateProvider::as_ref(ctx).get().clone(),
buffers: ServerBufferTracker::new(),
diff_states: ctx.add_model(|_| RemoteDiffStateManager::new()),
host_scoped_requests: HashMap::new(),
};
// Subscribe to FileModel and RepoMetadataModel events
// file operation results and repo metadata pushes are forwarded to all
// connected proxy sessions.
{
let file_model = FileModel::handle(ctx);
ctx.subscribe_to_model(&file_model, |me, event, ctx| {
let file_id = event.file_id();
let Some(pending_kind) = me.pending_file_ops.get(&file_id).map(|op| &op.kind)
else {
return; // Not a file op we're tracking.
};
let response_message = match (event, pending_kind) {
(FileModelEvent::FileSaved { .. }, FileOpKind::Write) => {
server_message::Message::WriteFileResponse(WriteFileResponse {
result: Some(write_file_response::Result::Success(WriteFileSuccess {})),
})
}
(FileModelEvent::FileSaved { .. }, FileOpKind::Delete) => {
server_message::Message::DeleteFileResponse(DeleteFileResponse {
result: Some(delete_file_response::Result::Success(
DeleteFileSuccess {},
)),
})
}
(FileModelEvent::FailedToSave { error, .. }, FileOpKind::Write) => {
server_message::Message::WriteFileResponse(WriteFileResponse {
result: Some(write_file_response::Result::Error(FileOperationError {
message: format!("{error}"),
})),
})
}
(FileModelEvent::FailedToSave { error, .. }, FileOpKind::Delete) => {
server_message::Message::DeleteFileResponse(DeleteFileResponse {
result: Some(delete_file_response::Result::Error(FileOperationError {
message: format!("{error}"),
})),
})
}
(FileModelEvent::FileLoaded { .. }, _)
| (FileModelEvent::FailedToLoad { .. }, _)
| (FileModelEvent::FileUpdated { .. }, _) => return,
};
// Remove the pending op and unsubscribe from FileModel.
let pending = me
.pending_file_ops
.remove(file_id, ctx)
.expect("pending op was confirmed present");
me.send_server_message(
Some(pending.conn_id),
Some(&pending.request_id),
response_message,
);
});
}
{
let repo_model = RepoMetadataModel::handle(ctx);
ctx.subscribe_to_model(&repo_model, |me, event, ctx| match event {
RepoMetadataEvent::IncrementalUpdateReady { update } => {
me.send_server_message(
None,
None,
server_message::Message::RepoMetadataUpdate(update.into()),
);
}
RepoMetadataEvent::RepositoryUpdated {
id: RepositoryIdentifier::Local(path),
} => {
// A repo finished indexing — push the full tree as a snapshot.
let id = RepositoryIdentifier::local(path.clone());
let repo_model = RepoMetadataModel::handle(ctx);
if let Some(state) = repo_model.as_ref(ctx).get_repository(&id, ctx) {
let entries = super::repo_metadata_proto::file_tree_entry_to_snapshot_proto(
&state.entry,
);
let standing_results = repo_model
.as_ref(ctx)
.standing_query_results(&id, ctx)
.map(|results| (&results.as_snapshot_delta()).into());
me.send_server_message(
None,
None,
server_message::Message::RepoMetadataSnapshot(
super::proto::RepoMetadataSnapshot {
repo_path: path.to_string(),
entries,
sync_complete: true,
standing_results,
},
),
);
// Mark this root as snapshot-sent for all active connections
// so subsequent NavigatedToDirectory calls skip re-sending.
for sent_roots in me.snapshot_sent_roots_by_connection.values_mut() {
sent_roots.insert(path.clone());
}
}
}
RepoMetadataEvent::RepositoryRemoved { .. }
| RepoMetadataEvent::FileTreeUpdated { .. }
| RepoMetadataEvent::FileTreeEntryUpdated { .. }
| RepoMetadataEvent::StandingQueryResultsUpdated { .. }
| RepoMetadataEvent::UpdatingRepositoryFailed { .. }
| RepoMetadataEvent::RepositoryUpdated {
id: RepositoryIdentifier::Remote(_),
} => {}
});
}
let index_manager = CodebaseIndexManager::handle(ctx);
ctx.subscribe_to_model(&index_manager, |me, event, ctx| {
me.handle_codebase_index_manager_event(event, ctx);
});
// Subscribe to GlobalBufferModel events for server-local buffers.
{
let gbm = GlobalBufferModel::handle(ctx);
ctx.subscribe_to_model(&gbm, |me, event, ctx| match event {
GlobalBufferModelEvent::BufferLoaded { file_id, .. } => {
// Complete all pending OpenBuffer requests for this file.
let pending = me.buffers.take_pending_by_kind(
file_id,
PendingBufferRequestKind::OpenBuffer,
);
if !pending.is_empty() {
let gbm = GlobalBufferModel::handle(ctx);
let content = gbm.as_ref(ctx).content_for_file(*file_id, ctx);
let server_version = gbm
.as_ref(ctx)
.sync_clock_for_server_local(*file_id)
.map(|c| c.server_version.as_u64());
for req in pending {
let message = match (&content, server_version) {
(Some(content), Some(sv)) => {
server_message::Message::OpenBufferResponse(OpenBufferResponse{
result: Some(remote_server::proto::open_buffer_response::Result::Success(OpenBufferSuccess {
content: content.clone(),
server_version: sv,
}))
})
}
_ => server_message::Message::Error(ErrorResponse {
code: ErrorCode::Internal.into(),
message: format!(
"Buffer loaded but content or sync clock unavailable for file {file_id:?}"
),
}),
};
me.send_server_message(
Some(req.connection_id),
Some(&req.request_id),
message,
);
}
}
}
GlobalBufferModelEvent::ServerLocalBufferUpdated {
file_id,
edits,
new_server_version,
expected_client_version,
} => {
// Push incremental edits to all connections that have this buffer open,
// except connections with a pending OpenBuffer request (they will
// receive the content via OpenBufferResponse instead).
let Some(conns) = me.buffers.connections_for_buffer(file_id) else {
return;
};
let excluded =
me.buffers.pending_connections_for_open_buffer(file_id);
// Find the path for this file_id.
let path = me.buffers.path_for_file_id(*file_id).unwrap_or_default();
let proto_edits: Vec<TextEdit> = edits
.iter()
.map(|edit| TextEdit {
start_offset: edit.start.as_usize() as u64,
end_offset: edit.end.as_usize() as u64,
text: edit.text.clone(),
})
.collect();
// Collect to break the immutable borrow on `me.buffers`
// before calling `me.send_server_message(&mut self)`.
let conns: Vec<_> = conns.iter().copied().collect();
for conn_id in conns {
if excluded.contains(&conn_id) {
continue;
}
me.send_server_message(
Some(conn_id),
None,
server_message::Message::BufferUpdated(BufferUpdatedPush {
path: path.clone(),
new_server_version: new_server_version.as_u64(),
expected_client_version: expected_client_version.as_u64(),
edits: proto_edits.clone(),
}),
);
}
}
GlobalBufferModelEvent::FileSaved { file_id } => {
for req in me.buffers.take_pending_by_kind(
file_id,
PendingBufferRequestKind::SaveBuffer,
) {
me.send_server_message(
Some(req.connection_id),
Some(&req.request_id),
server_message::Message::SaveBufferResponse(SaveBufferResponse {
result: Some(save_buffer_response::Result::Success(
SaveBufferSuccess {},
)),
}),
);
}
for req in me.buffers.take_pending_by_kind(
file_id,
PendingBufferRequestKind::ResolveConflict,
) {
me.send_server_message(
Some(req.connection_id),
Some(&req.request_id),
server_message::Message::ResolveConflictResponse(
ResolveConflictResponse {
result: Some(
resolve_conflict_response::Result::Success(
ResolveConflictSuccess {},
),
),
},
),
);
}
}
GlobalBufferModelEvent::FailedToSave { file_id, error } => {
for req in me.buffers.take_pending_by_kind(
file_id,
PendingBufferRequestKind::SaveBuffer,
) {
me.send_server_message(
Some(req.connection_id),
Some(&req.request_id),
server_message::Message::SaveBufferResponse(SaveBufferResponse {
result: Some(save_buffer_response::Result::Error(
FileOperationError {
message: format!("{error}"),
},
)),
}),
);
}
for req in me.buffers.take_pending_by_kind(
file_id,
PendingBufferRequestKind::ResolveConflict,
) {
me.send_server_message(
Some(req.connection_id),
Some(&req.request_id),
server_message::Message::ResolveConflictResponse(
ResolveConflictResponse {
result: Some(resolve_conflict_response::Result::Error(
FileOperationError {
message: format!("{error}"),
},
)),
},
),
);
}
}
GlobalBufferModelEvent::FailedToLoad { file_id, error } => {
for req in me.buffers.take_pending_by_kind(
file_id,
PendingBufferRequestKind::OpenBuffer,
) {
me.send_server_message(
Some(req.connection_id),
Some(&req.request_id),
server_message::Message::OpenBufferResponse(OpenBufferResponse{
result: Some(remote_server::proto::open_buffer_response::Result::Error(FileOperationError {
message: format!("Failed to load buffer: {error}"),
}))
}),
);
}
}
GlobalBufferModelEvent::BufferUpdatedFromFileEvent {
file_id,
success,
..
} => {
// When a file-watcher update couldn't be applied because
// the buffer has unsaved client edits, forward the conflict
// to connected clients so they can show a resolution banner.
if !success {
if let Some(conns) = me.buffers.connections_for_buffer(file_id) {
// Collect to break the immutable borrow on `me.buffers`
// before calling `me.send_server_message(&mut self)`.
let conns: Vec<_> = conns.iter().copied().collect();
let path = me.buffers.path_for_file_id(*file_id).unwrap_or_default();
for conn_id in conns {
me.send_server_message(
Some(conn_id),
None,
server_message::Message::BufferConflictDetected(
super::proto::BufferConflictDetected {
path: path.clone(),
},
),
);
}
}
}
}
GlobalBufferModelEvent::RemoteBufferConflict { .. } => {
// Not relevant for server-local buffers.
}
});
}
// Subscribe to diff state manager events — convert domain dispatches
// to proto messages and send them to connected clients.
{
let diff_states = model.diff_states.clone();
ctx.subscribe_to_model(&diff_states, |me, dispatch, _ctx| {
me.handle_diff_state_update(dispatch);
});
}
// Start the grace timer immediately so the daemon exits if no proxy
// connects within GRACE_PERIOD. In practice the spawning proxy connects
// within milliseconds, so the risk of premature shutdown is negligible;
// register_connection will cancel the timer the moment the first proxy
// arrives.
model.start_grace_timer(ctx);
model
}
/// Called when a proxy connects. Inserts `conn_tx` into the connection
/// map so `send_server_message` can route responses to this proxy, and
/// cancels the grace timer if it was running.
pub fn register_connection(
&mut self,
conn_id: ConnectionId,
conn_tx: async_channel::Sender<ServerMessage>,
ctx: &mut ModelContext<Self>,
) {
log::info!(
"Daemon: connection {conn_id} registered — {} active, host_id={}",
self.connection_senders.len() + 1,
self.host_id
);
if let Some(handle) = self.grace_timer_cancel.take() {
handle.abort();
}
self.connection_senders.insert(conn_id, conn_tx);
self.snapshot_sent_roots_by_connection
.insert(conn_id, HashSet::new());
ctx.notify();
}
/// Called when a proxy disconnects. Removes it from the connection map
/// and starts the grace timer if no connections remain.
pub fn deregister_connection(&mut self, conn_id: ConnectionId, ctx: &mut ModelContext<Self>) {
self.snapshot_sent_roots_by_connection.remove(&conn_id);
// Guard against double-deregister (reader and writer tasks both call
// this on connection close; the second call must be a safe no-op).
if self.connection_senders.remove(&conn_id).is_none() {
return;
}
// Host-scoped in-flight requests that were sent through the dead
// connection are NOT eagerly reassigned here. Instead,
// `send_server_message` handles failover at delivery time: when it
// finds the target connection is gone, it picks any other open
// connection. If no connections remain at delivery time, the
// response is dropped (logged). If no connections remain NOW and
// there are in-progress handlers, abort them so they don't run
// to completion pointlessly.
if self.connection_senders.is_empty() {
let orphaned: Vec<RequestId> = self.host_scoped_requests.keys().cloned().collect();
for rid in orphaned {
self.host_scoped_requests.remove(&rid);
if let Some(handle) = self.in_progress.remove(&rid) {
log::warn!("Daemon: no connections remain, aborting host-scoped request {rid}");
handle.abort();
}
}
}
// Remove this connection from all buffer connection sets.
// Orphaned buffers (no connections left) are deallocated automatically.
self.buffers.remove_connection(conn_id, ctx);
// Remove this connection from diff state subscriptions.
// Orphaned models (no subscribers) are dropped automatically.
self.diff_states
.update(ctx, |mgr, _| mgr.remove_connection(conn_id));
let remaining = self.connection_senders.len();
log::info!("Daemon: connection {conn_id} deregistered — {remaining} active remaining");
if remaining == 0 {
log::info!("Daemon: grace timer started ({GRACE_PERIOD:?})");
self.start_grace_timer(ctx);
}
ctx.notify();
}
/// Starts (or restarts) a timer that shuts the daemon down after
/// [`GRACE_PERIOD`] with no connected proxies. If a timer is already
/// running its abort handle is cancelled before the new one is stored.
/// When a proxy connects, `register_connection` aborts the handle,
/// preventing the shutdown.
fn start_grace_timer(&mut self, ctx: &mut ModelContext<Self>) {
if let Some(handle) = self.grace_timer_cancel.take() {
handle.abort();
}
let handle = ctx.spawn_abortable(
async_io::Timer::after(GRACE_PERIOD),
|_, _, ctx| {
log::info!("Daemon: grace period expired, shutting down");
ctx.terminate_app(TerminationMode::ForceTerminate, None);
},
|_, _| {
log::debug!("Daemon: grace timer cancelled");
},
);
self.grace_timer_cancel = Some(handle);
}
/// Called by the background stdin reader task via `ModelSpawner`.
///
/// Dispatches on the `oneof message` variant. Notifications are handled
/// inline; request-style messages return a `HandlerOutcome` that is
/// centrally acted on here: `Sync` responses are sent immediately and
/// `Async` handles are tracked in `in_progress` so they can be aborted.
pub fn handle_message(
&mut self,
conn_id: ConnectionId,
msg: ClientMessage,
ctx: &mut ModelContext<Self>,
) {
let request_id = RequestId::from(msg.request_id);
let (outcome, is_host_scoped) = match msg.message {
// ── Host-scoped requests (daemon owns failover delivery) ───
Some(client_message::Message::HostScoped(wrapper)) => {
let outcome = match wrapper.message {
Some(host_scoped_request::Message::WriteFile(m)) => {
self.handle_write_file(m, &request_id, conn_id, ctx)
}
Some(host_scoped_request::Message::DeleteFile(m)) => {
self.handle_delete_file(m, &request_id, conn_id, ctx)
}
Some(host_scoped_request::Message::ReadFileContext(m)) => {
self.handle_read_file_context(m, &request_id, conn_id, ctx)
}
Some(host_scoped_request::Message::SaveBuffer(m)) => {
self.handle_save_buffer(m, &request_id, conn_id, ctx)
}
Some(host_scoped_request::Message::ResolveConflict(m)) => {
self.handle_resolve_conflict(m, &request_id, conn_id, ctx)
}
Some(host_scoped_request::Message::DiscardFiles(m)) => {
self.handle_discard_files(m, &request_id, ctx)
}
Some(host_scoped_request::Message::IndexCodebase(m)) => {
self.handle_index_codebase(m, &request_id, conn_id, ctx)
}
Some(host_scoped_request::Message::DropCodebaseIndex(m)) => {
self.handle_drop_codebase_index(m, &request_id, conn_id, ctx)
}
Some(host_scoped_request::Message::GetFragmentMetadataFromHash(m)) => {
self.handle_get_fragment_metadata_from_hash(m, &request_id, conn_id, ctx)
}
Some(host_scoped_request::Message::GetBranches(m)) => {
self.handle_get_branches(m, &request_id, conn_id, ctx)
}
Some(host_scoped_request::Message::ResyncCodebase(m)) => {
self.handle_resync_codebase(m, &request_id, conn_id, ctx)
}
Some(host_scoped_request::Message::UploadHandoffSnapshot(m)) => {
self.handle_upload_handoff_snapshot(m, &request_id, conn_id, ctx)
}
Some(host_scoped_request::Message::GitCommitChain(m)) => {
self.handle_git_commit_chain(m, &request_id, conn_id, ctx)
}
Some(host_scoped_request::Message::GitPush(m)) => {
self.handle_git_push(m, &request_id, conn_id, ctx)
}
Some(host_scoped_request::Message::GitCreatePr(m)) => {
self.handle_create_pr(m, &request_id, conn_id, ctx)
}
Some(host_scoped_request::Message::GitGetPrInfo(m)) => {
self.handle_get_pr_info(m, &request_id, conn_id, ctx)
}
Some(host_scoped_request::Message::GitGenerateCommitMessage(m)) => {
self.handle_generate_git_commit_message(m, &request_id, conn_id, ctx)
}
Some(host_scoped_request::Message::GitGetCommittedBranchFiles(m)) => {
self.handle_get_committed_branch_files(m, &request_id, conn_id, ctx)
}
Some(host_scoped_request::Message::RipgrepSearch(m)) => {
self.handle_ripgrep_search(m, &request_id, conn_id, ctx)
}
None => {
log::warn!(
"HostScopedRequest with no inner message (request_id={request_id})"
);
HandlerOutcome::Sync(server_message::Message::Error(ErrorResponse {
code: ErrorCode::InvalidRequest.into(),
message: "HostScopedRequest had no message variant set".to_string(),
}))
}
};
(outcome, true)
}
// ── Session-scoped requests (response tied to originating connection) ───
Some(client_message::Message::SessionScoped(wrapper)) => {
let outcome = match wrapper.message {
Some(session_scoped_request::Message::Initialize(m)) => {
self.handle_initialize(m, &request_id, ctx)
}
Some(session_scoped_request::Message::NavigatedToDirectory(m)) => {
self.handle_navigated_to_directory(m, &request_id, conn_id, ctx)
}
Some(session_scoped_request::Message::LoadRepoMetadataDirectory(m)) => {
self.handle_load_repo_metadata_directory(m, &request_id, ctx)
}
Some(session_scoped_request::Message::RunCommand(m)) => {
self.handle_run_command(m, &request_id, conn_id, ctx)
}
// Subscription-establishing ops: their per-connection
// subscription state is bound to this connection, so the
// response (and later pushes) must stay on it — never
// failed over to a sibling.
Some(session_scoped_request::Message::OpenBuffer(m)) => {
self.handle_open_buffer(m, &request_id, conn_id, ctx)
}
Some(session_scoped_request::Message::GetDiffState(m)) => {
self.handle_get_diff_state(m, &request_id, conn_id, ctx)
}
None => {
log::warn!(
"SessionScopedRequest with no inner message (request_id={request_id})"
);
HandlerOutcome::Sync(server_message::Message::Error(ErrorResponse {
code: ErrorCode::InvalidRequest.into(),
message: "SessionScopedRequest had no message variant set".to_string(),
}))
}
};
(outcome, false)
}
// ── Notifications (fire-and-forget) ───
Some(client_message::Message::Notification(wrapper)) => {
match wrapper.message {
Some(notification::Message::Abort(m)) => {
self.handle_abort(m, &request_id, ctx);
}
Some(notification::Message::Authenticate(m)) => {
self.handle_authenticate(m);
}
Some(notification::Message::UpdatePreferences(m)) => {
self.handle_update_preferences(m, ctx);
}
Some(notification::Message::SessionBootstrapped(m)) => {
self.handle_session_bootstrapped(m);
}
Some(notification::Message::BufferEdit(m)) => {
self.handle_buffer_edit(m, ctx);
}
Some(notification::Message::CloseBuffer(m)) => {
self.handle_close_buffer(m, conn_id, ctx);
}
Some(notification::Message::UnsubscribeDiffState(m)) => {
self.handle_unsubscribe_diff_state(m, conn_id, ctx);
}
None => {
log::warn!("Notification with no inner message (request_id={request_id})");
}
}
return; // Notifications never produce a response.
}
None => {
log::warn!(
"Received ClientMessage with no message variant (request_id={request_id})"
);
(
HandlerOutcome::Sync(server_message::Message::Error(ErrorResponse {
code: ErrorCode::InvalidRequest.into(),
message: "ClientMessage had no message variant set".to_string(),
})),
false,
)
}
};
// Track host-scoped requests for failover delivery.
if is_host_scoped && !request_id.is_empty() {
self.host_scoped_requests
.insert(request_id.clone(), conn_id);
}
match outcome {
HandlerOutcome::Sync(server_message::Message::InitializeResponse(response)) => {
self.send_server_message(
Some(conn_id),
Some(&request_id),
server_message::Message::InitializeResponse(response),
);
self.push_codebase_index_statuses_snapshot(conn_id, ctx);
}
HandlerOutcome::Sync(message) => {
self.send_server_message(Some(conn_id), Some(&request_id), message);
}
HandlerOutcome::Async(Some(handle)) => {
self.in_progress.insert(request_id, handle);
}
HandlerOutcome::Async(None) => {
// Async work tracked elsewhere (e.g. `pending_file_ops`);
// the response will be sent via an event subscription.
}
}
}
fn handle_codebase_index_manager_event(
&mut self,
event: &CodebaseIndexManagerEvent,
ctx: &mut ModelContext<Self>,
) {
if !FeatureFlag::RemoteCodebaseIndexing.is_enabled() {
return;
}
match event {
CodebaseIndexManagerEvent::SyncStateUpdated { root_path }
| CodebaseIndexManagerEvent::NewIndexCreated { root_path } => {
self.push_codebase_index_status(root_path, ctx);
}
CodebaseIndexManagerEvent::RemoveExpiredIndexMetadata { expired_metadata } => {
for repo_path in expired_metadata.iter() {
self.push_codebase_index_status_update(disabled_codebase_index_status(
repo_path.to_string_lossy().to_string(),
));
}
}
CodebaseIndexManagerEvent::RetrievalRequestCompleted { .. }
| CodebaseIndexManagerEvent::RetrievalRequestFailed { .. }
| CodebaseIndexManagerEvent::IndexMetadataUpdated { .. } => {}
}
}
fn push_codebase_index_status(&mut self, repo_path: &Path, ctx: &mut ModelContext<Self>) {
let Some(status) = self.codebase_index_status(repo_path, ctx) else {
return;
};
self.push_codebase_index_status_update(status);
}
fn push_codebase_index_status_update(&mut self, status: CodebaseIndexStatus) {
self.send_server_message(
None,
None,
server_message::Message::CodebaseIndexStatusUpdated(CodebaseIndexStatusUpdated {
status: Some(status),
}),
);
}
fn push_codebase_index_statuses_snapshot(
&mut self,
conn_id: ConnectionId,
ctx: &mut ModelContext<Self>,
) {
if !FeatureFlag::RemoteCodebaseIndexing.is_enabled() {
log::info!(
"[Remote codebase indexing] Daemon skipping bootstrap codebase index statuses snapshot because remote indexing is disabled: conn_id={conn_id}"
);
return;
}
let snapshot = self.codebase_index_statuses_snapshot(ctx);
let status_count = snapshot.statuses.len();
log::debug!(
"[Remote codebase indexing] Daemon pushing bootstrap codebase index statuses snapshot: conn_id={conn_id} bootstrap_status_count={status_count}"
);
self.send_server_message(
Some(conn_id),
None,
server_message::Message::CodebaseIndexStatusesSnapshot(snapshot),
);
}
fn codebase_index_statuses_snapshot(
&self,
ctx: &mut ModelContext<Self>,
) -> CodebaseIndexStatusesSnapshot {
let index_manager = CodebaseIndexManager::handle(ctx);
let statuses = index_manager
.as_ref(ctx)
.get_codebase_index_statuses(ctx)
.map(|(repo_path, status)| codebase_index_status_to_proto(repo_path.as_path(), &status))
.collect();
CodebaseIndexStatusesSnapshot { statuses }
}
fn codebase_index_status(
&self,
repo_path: &Path,
ctx: &mut ModelContext<Self>,
) -> Option<CodebaseIndexStatus> {
let index_manager = CodebaseIndexManager::handle(ctx);
index_manager
.as_ref(ctx)
.get_codebase_index_status_for_path(repo_path, ctx)
.map(|status| codebase_index_status_to_proto(repo_path, &status))
}