-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlib.rs
More file actions
5663 lines (5256 loc) · 237 KB
/
Copy pathlib.rs
File metadata and controls
5663 lines (5256 loc) · 237 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 serde::{Deserialize, Serialize};
use serde_json::{Map as JsonMap, Value as JsonValue};
mod log_tail;
mod quit_state;
mod routing;
mod workspaces;
// The Dock's Quit, an `osascript` quit and a logout reach AppKit without ever
// raising `RunEvent::ExitRequested` (docs/specs/standalone.md §Trigger
// interception).
#[cfg(target_os = "macos")]
mod macos_terminate;
use quit_state::{ArrivalQueue, CleanupGate, CloseMachine, QuitAction, QuitIntent, QuitMachine};
use routing::{Route, RouteView};
use std::{
collections::{HashMap, HashSet},
env,
fs::{create_dir_all, File, OpenOptions},
io::{BufRead, BufReader, Write},
path::{Path, PathBuf},
process::Stdio,
sync::atomic::{AtomicU64, AtomicUsize, Ordering},
sync::mpsc,
sync::{Arc, Mutex, MutexGuard, OnceLock},
time::{Duration, Instant, SystemTime, UNIX_EPOCH},
};
use tauri::{
menu::{Menu, PredefinedMenuItem, Submenu},
AppHandle, DragDropEvent, Emitter, Manager, RunEvent, WebviewWindowBuilder, WindowEvent,
};
#[cfg(target_os = "macos")]
use tauri::menu::MenuItem;
#[cfg(target_os = "macos")]
use tauri::menu::AboutMetadata;
use process_wrap::std::{ChildWrapper, CommandWrap};
#[cfg(windows)]
use process_wrap::std::{CreationFlags, JobObject};
#[cfg(unix)]
use process_wrap::std::ProcessGroup;
#[cfg(windows)]
use windows::Win32::System::Threading::CREATE_NO_WINDOW;
// Native Win32 clipboard reads, so a paste never spawns a console-window-popping
// PowerShell child. macOS/Linux keep the sidecar path (no console flicker there).
#[cfg(windows)]
mod clipboard_win;
// Shared with build.rs (via `#[path]`); the PE subsystem offsets live in one place.
#[cfg(windows)]
mod pe_subsystem;
type SidecarSender = mpsc::Sender<String>;
type PendingRequests = Arc<Mutex<HashMap<String, mpsc::Sender<JsonValue>>>>;
type SharedChild = Arc<Mutex<Box<dyn ChildWrapper + Send + Sync>>>;
struct SidecarState {
tx: SidecarSender,
pending_requests: PendingRequests,
next_request_id: AtomicU64,
child: SharedChild,
}
/// A lock taken for a short read or write, treating poisoning as recoverable:
/// every value behind one here is plain bookkeeping that a panicking thread
/// cannot leave half-written into an unusable shape.
fn guard<T>(lock: &Mutex<T>) -> MutexGuard<'_, T> {
lock.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
}
// ── Window ownership (docs/specs/standalone.md §Windows) ──────────────────────
//
// The sidecar has no window concept, so Rust keeps the map from PTY to window
// and routes every stdout line through `routing::route`.
/// The maps a sidecar line is routed against, behind **one** lock: they are
/// always read together, so a PTY chunk costs one acquisition rather than one
/// per map, and every label the routing table hands back stays borrowed out of
/// this guard instead of being cloned per line.
#[derive(Default)]
struct RoutingState {
/// ptyId -> window label. Minted only in `pty_spawn`, dropped by
/// `pty_kill` or a window going away — never by an exit; reassigned by a
/// transfer.
owners: HashMap<String, String>,
/// Ids whose output is suppressed until the replay their new owner is about
/// to be sent has been emitted, each with the instant it began.
awaiting_replay: HashMap<String, Instant>,
/// dor requestId -> the window handling it, so a cancel reaches the window
/// holding the subscription, watch or completion claim it releases.
dor_targets: HashMap<String, String>,
/// Ids between a transfer's invoke and the sidecar's `marked` line, each
/// with the source still consuming (`routing::RouteView::marking`).
marking: HashMap<String, String>,
// Source cut points survive target replay until the arrival settles.
transfer_marks: HashMap<String, u64>,
}
impl RoutingState {
/// Begin replay suppression at the source cut after its mark arrives.
fn mark_transfer(&mut self, id: &str, mark: u64) {
if self.marking.remove(id).is_some() {
self.transfer_marks.insert(id.to_string(), mark);
self.awaiting_replay.insert(id.to_string(), Instant::now());
}
}
/// What `routing::route` reads, borrowed out of this state.
fn view<'a>(&'a self, registry: &'a workspaces::Registry) -> RouteView<'a> {
RouteView {
owners: &self.owners,
awaiting_replay: &self.awaiting_replay,
dor_targets: &self.dor_targets,
registry,
marking: &self.marking,
}
}
}
#[derive(Default)]
struct WindowState {
routing: Mutex<RoutingState>,
/// `awaiting_replay.len()`, readable without the lock. Nothing is
/// transferring in the steady state, and this is what lets a chunk skip the
/// sweep and the `Instant::now()` it needs.
suppressed: AtomicUsize,
/// Window labels, most recently focused first.
focus_order: Mutex<Vec<String>>,
/// Every Workspace in flight, from the source's invoke until its target
/// adopts it or dies (`routing::Arrival`), and the teardown requests
/// deferred behind them (`ArrivalQueue`). Pulled, never pushed.
///
/// **Never take this lock while holding `routing`.** `dispatch_sidecar_event`
/// reads it before it takes `routing`, so the two are only ever acquired in
/// that order.
arrivals: Mutex<ArrivalQueue>,
/// The window currently showing a cross-window drop caret, so the previous
/// one can be told to clear it.
hover_target: Mutex<Option<String>>,
/// Labels whose snapshot has been deliberately removed. A save arriving
/// from a webview that is going away must not put the file back; the entry
/// is dropped once that webview is destroyed and can no longer save.
closing: Mutex<HashSet<String>>,
/// The next `ws-<n>`, seeded above every live and saved label at setup.
next_ws: AtomicU64,
/// Every window's Workspaces under their stable refs (§Workspace registry).
registry: Mutex<workspaces::Registry>,
/// The next `workspace-<n>`, seeded above every id on disk at setup and
/// handed out in blocks so a webview can mint synchronously.
next_workspace: AtomicU64,
}
impl RoutingState {
/// Every id `label` owns.
fn owned_by(&self, label: &str) -> Vec<String> {
self.owners
.iter()
.filter(|(_, owner)| owner.as_str() == label)
.map(|(id, _)| id.clone())
.collect()
}
}
impl WindowState {
fn owned_by(&self, label: &str) -> Vec<String> {
guard(&self.routing).owned_by(label)
}
/// A window spawned a PTY: it owns it until a transfer moves it.
///
/// Clears any suppression left under this id. A spawn reusing an id whose
/// transfer never completed would otherwise start life silenced, with no
/// replay coming to lift it — the sweep's 5 s of a dead pane.
fn mint(&self, id: &str, label: &str) {
let mut routing = guard(&self.routing);
routing.owners.insert(id.to_string(), label.to_string());
routing.transfer_marks.remove(id);
routing.awaiting_replay.remove(id);
self.suppressed
.store(routing.awaiting_replay.len(), Ordering::Relaxed);
}
/// Refuse every later `save_session` for `label` (a deliberate close removed
/// its snapshot). Cleared by `Destroyed`, after which no save can arrive.
fn begin_closing(&self, label: &str) {
guard(&self.closing).insert(label.to_string());
}
fn refuses_save(&self, label: &str) -> bool {
guard(&self.closing).contains(label)
}
/// Move ownership and open source routing under one lock, before any chunk
/// can observe the target owner without the source's marking phase.
fn begin_transfer(&self, ids: &[String], source: &str, target: &str) {
let mut routing = guard(&self.routing);
for id in ids {
if let Some(owner) = routing.owners.get_mut(id) {
*owner = target.to_string();
}
routing.awaiting_replay.remove(id);
routing.transfer_marks.remove(id);
routing.marking.insert(id.clone(), source.to_string());
}
self.suppressed.store(routing.awaiting_replay.len(), Ordering::Relaxed);
}
/// Give every id back to `source` that no kill dropped — an exited one too,
/// and one whose target window went away (`drop_window` drops its owner,
/// never its transfer records) — suppressed behind a replay of its cut when
/// it has one, otherwise straight back. Returns the cuts it drained, by id.
fn hand_back(&self, ids: &[String], source: &str) -> JsonValue {
let mut routing = guard(&self.routing);
let mut marks = serde_json::Map::new();
for id in ids {
let mark = routing.transfer_marks.remove(id);
if let Some(mark) = mark { marks.insert(id.clone(), JsonValue::from(mark)); }
let transferring = routing.marking.remove(id).is_some() || mark.is_some();
// A kill drops the owner and the transfer records alike.
if !transferring && !routing.owners.contains_key(id) { continue; }
routing.owners.insert(id.clone(), source.to_string());
if mark.is_some() { routing.awaiting_replay.insert(id.clone(), Instant::now()); }
else { routing.awaiting_replay.remove(id); }
}
self.suppressed.store(routing.awaiting_replay.len(), Ordering::Relaxed);
JsonValue::Object(marks)
}
/// The Session is gone (`pty_kill`, or its window went away): ownership and
/// every transfer record with it, the cut included, since a kill discards
/// the buffer it indexes.
fn forget_pty(&self, id: &str) {
let mut routing = guard(&self.routing);
routing.owners.remove(id);
routing.transfer_marks.remove(id);
routing.awaiting_replay.remove(id);
routing.marking.remove(id);
self.suppressed.store(routing.awaiting_replay.len(), Ordering::Relaxed);
}
/// The PTY exited on its own. **Ownership stays until the Session is
/// killed**: the pane still shows it, and the sidecar's `alert:state` for it
/// — a dismiss, a TODO cleared — must still reach that window (§Alerts). The
/// cut stays too: the sidecar retains the buffer a replay reads. **So does
/// a transfer's marking phase**: the sidecar marks an exited id like a live
/// one, and that `pty:marked` belongs to the source serializing the pane.
fn exited_pty(&self, id: &str) {
let mut routing = guard(&self.routing);
routing.awaiting_replay.remove(id);
self.suppressed.store(routing.awaiting_replay.len(), Ordering::Relaxed);
}
/// Drop any suppression on `ids`, leaving ownership alone. What settles an
/// adopted arrival: each replay lifted its own on the way out, and this is
/// the defensive clear for an id whose mark or replay never arrived.
fn clear_suppression(&self, ids: &[String]) {
let mut routing = guard(&self.routing);
for id in ids {
routing.awaiting_replay.remove(id);
routing.transfer_marks.remove(id);
routing.marking.remove(id);
}
self.suppressed
.store(routing.awaiting_replay.len(), Ordering::Relaxed);
}
/// Forget a window: its ownership, its outstanding `dor` requests, its
/// deferred close and its focus entry. Returns the arrivals it can no longer
/// take — **whose shells are deliberately not in the second half** — and the
/// ids it owned outright, which the caller reaps.
fn drop_window(&self, label: &str) -> (Vec<routing::Arrival>, Vec<String>) {
// Taken first, and their ids dropped from `owners` before `owned_by`
// reads it: an arriving shell belongs to its source again, which
// `hand_back` returns it to, and reaping it here would kill a terminal
// the source is still showing.
let lost = {
let mut arrivals = guard(&self.arrivals);
arrivals.forget_deferred_close(label);
routing::take_arrivals_to(&mut arrivals, label)
};
let owned = {
let mut routing = guard(&self.routing);
for id in lost.iter().flat_map(|arrival| &arrival.terminal_ids) {
routing.owners.remove(id);
routing.awaiting_replay.remove(id);
}
let owned = routing.owned_by(label);
for id in &owned {
routing.owners.remove(id);
}
// Its answers can never arrive, so neither can the cancels that
// would have retired them.
routing.dor_targets.retain(|_, target| target != label);
self.suppressed
.store(routing.awaiting_replay.len(), Ordering::Relaxed);
owned
};
guard(&self.focus_order).retain(|entry| entry != label);
(lost, owned)
}
fn touch_focus(&self, label: &str) {
let mut order = guard(&self.focus_order);
order.retain(|entry| entry != label);
order.insert(0, label.to_string());
}
/// The most recently focused window: where a sidecar event naming no window
/// is delivered (`Route::Focused`). The quit walk never reads focus — its
/// order is `quit_order`, `main` last and the rest unordered.
fn focused(&self) -> Option<String> {
guard(&self.focus_order).first().cloned()
}
}
/// Where one sidecar line goes, owning its label so the routing lock can be
/// released before anything is serialized or emitted.
enum Delivery {
Nowhere,
Broadcast,
To(String),
UnownedSurface { request_id: String, surface_id: String },
}
static EMPTY_REGISTRY: std::sync::LazyLock<workspaces::Registry> =
std::sync::LazyLock::new(workspaces::Registry::default);
/// Route one sidecar stdout line to the window it belongs to.
///
/// The hot path — once per PTY chunk — so it takes the routing lock once, reads
/// no clock unless something is actually mid-transfer, and copies only the one
/// label it needs.
///
/// **Never hold the routing lock across an emit.** Serializing the payload and
/// queueing it are unbounded work with the main thread possibly parked in
/// `pty_spawn` waiting for this very lock, and Tauri's `tracing` feature swaps
/// the emit for one that blocks on a main-thread reply — which would deadlock.
fn dispatch_sidecar_event(app: &AppHandle, event: &str, data: JsonValue) {
let Some(state) = app.try_state::<WindowState>() else {
let _ = app.emit(event, data);
return;
};
let mut released: Vec<String> = Vec::new();
let delivery = {
// Before the routing lock, never inside it (§`arrivals`). Nothing is
// transferring in the steady state, so this second acquisition is paid
// only while something is.
let arriving = if state.suppressed.load(Ordering::Relaxed) > 0 {
routing::arrival_ids(&guard(&state.arrivals))
} else {
HashSet::new()
};
// Only a `dor` request consults the registry; a PTY chunk never pays
// for the lock. Taken before the routing lock and released with it.
let registry_guard = (event == "dor:controlRequest").then(|| guard(&state.registry));
let registry: &workspaces::Registry = match registry_guard.as_deref() {
Some(registry) => registry,
None => &EMPTY_REGISTRY,
};
let mut routing = guard(&state.routing);
if state.suppressed.load(Ordering::Relaxed) > 0 {
released = routing::sweep_awaiting(
&mut routing.awaiting_replay,
Instant::now(),
routing::AWAITING_REPLAY_MAX,
&arriving,
);
if !released.is_empty() {
state.suppressed.store(routing.awaiting_replay.len(), Ordering::Relaxed);
}
}
match routing::route(event, &data, &routing.view(registry)) {
Route::Drop => Delivery::Nowhere,
Route::Broadcast => Delivery::Broadcast,
Route::EmitTo(label) => Delivery::To(label.to_string()),
// Resolved here, where the focus order is a sibling of the map the
// table read; the lock over it is separate and taken for one clone.
Route::Focused => match state.focused() {
Some(label) => Delivery::To(label),
None => Delivery::Broadcast,
},
Route::UnownedSurface {
request_id,
surface_id,
} => Delivery::UnownedSurface {
request_id: request_id.to_string(),
surface_id: surface_id.to_string(),
},
}
};
let mut delivered: Option<&str> = None;
match &delivery {
Delivery::Nowhere => {}
Delivery::Broadcast => {
let _ = app.emit(event, &data);
}
Delivery::To(label) => {
delivered = Some(label.as_str());
let _ = app.emit_to(label.as_str(), event, &data);
}
Delivery::UnownedSurface {
request_id,
surface_id,
} => {
// Never a sibling window: acting on the wrong terminal is worse
// than failing (docs/specs/dor-cli.md → "Standalone").
if let Some(sidecar) = app.try_state::<SidecarState>() {
let response = serde_json::json!({
"event": "dor:controlResponse",
"data": {
"requestId": request_id,
"ok": false,
"error": format!("No Dormouse window owns surface '{surface_id}'"),
},
});
send_to_sidecar(&sidecar, response.to_string());
}
}
}
// Bookkeeping strictly after the emit, so a replay lifts its own suppression
// only once the new owner has actually been sent it. Only these events pay
// a second acquisition; a PTY chunk takes the lock once and is done.
let id = || data.get("id").and_then(JsonValue::as_str);
let request_id = || data.get("requestId").and_then(JsonValue::as_str);
match event {
"pty:exit" => {
if let Some(id) = id() {
state.exited_pty(id);
}
}
// The source has been sent everything before the mark; from here the
// id is silent until the target's replay of everything after it.
"pty:marked" => {
if let Some(id) = id() {
let mut routing = guard(&state.routing);
if let Some(mark) = data.get("mark").and_then(JsonValue::as_u64) {
routing.mark_transfer(id, mark);
state
.suppressed
.store(routing.awaiting_replay.len(), Ordering::Relaxed);
}
}
}
"pty:replay" => {
if let Some(id) = id() {
let mut routing = guard(&state.routing);
routing.awaiting_replay.remove(id);
state
.suppressed
.store(routing.awaiting_replay.len(), Ordering::Relaxed);
}
}
"dor:controlRequest" => {
if let (Some(label), Some(request_id)) = (delivered, request_id()) {
guard(&state.routing)
.dor_targets
.insert(request_id.to_string(), label.to_string());
}
}
"dor:controlCancel" => {
if let Some(request_id) = request_id() {
guard(&state.routing).dor_targets.remove(request_id);
}
}
// The collector settles on having heard from every window the ask
// reached, and only Rust knows this one reached exactly its Surface's
// owner (docs/specs/standalone.md -> "Burrow service").
"burrow:ask" => {
if let (Some(label), Some(sidecar)) =
(delivered, app.try_state::<SidecarState>())
{
if let Some(burrow_request_id) =
data.get("burrowRequestId").and_then(JsonValue::as_str)
{
send_to_sidecar(
&sidecar,
serde_json::json!({
"event": "burrow:askDelivered",
"data": { "burrowRequestId": burrow_request_id, "windows": [label] },
})
.to_string(),
);
}
}
}
_ => {}
}
// Logged outside the lock: a chatty log write must never sit in front of the
// next PTY chunk's routing decision.
for id in released {
append_log(format!(
"[window] suppression for {id} expired with no arrival claiming it; releasing"
));
}
}
/// Tell the sidecar's Burrow which webviews will answer an ask
/// (docs/specs/standalone.md §Burrow service). Labels, not a count: the
/// collector settles on having heard from each named window, so it can tell a
/// window that closed mid-fan-out from one that answered twice.
fn send_window_labels(app: &AppHandle) {
let Some(state) = app.try_state::<SidecarState>() else {
return;
};
let labels = window_labels(app);
send_to_sidecar(
&state,
serde_json::json!({ "event": "burrow:windows", "data": { "labels": labels } }).to_string(),
);
}
// ── Quit interception ─────────────────────────────────────────────────────────
//
// Every quit trigger funnels through `request_quit`, which asks each window's
// orchestrator (standalone/src/quit.ts) to vote, then walks them one at a time.
// Protocol + watchdog phases: docs/specs/standalone.md §Quit flow.
#[derive(Default)]
struct QuitState {
machine: Mutex<QuitMachine>,
close: Mutex<CloseMachine>,
cleanup: Mutex<CleanupGate>,
}
fn exit_after_cleanup(app: &AppHandle) -> bool {
let Some(state) = app.try_state::<QuitState>() else { return true; };
let (exit, start_watchdog) = {
let mut gate = guard(&state.cleanup);
let was_waiting = gate.exit_requested;
let exit = gate.request_exit();
(exit, !exit && !was_waiting)
};
if start_watchdog {
let app = app.clone();
tauri::async_runtime::spawn_blocking(move || {
std::thread::sleep(Duration::from_millis(QUIT_PHASE_TIMEOUT_MS));
let force = app.try_state::<QuitState>()
.is_some_and(|state| guard(&state.cleanup).force_if_waiting());
if force {
append_log("[quit] hand-back cleanup timed out; forcing exit");
if let Some(state) = app.try_state::<QuitState>() {
guard(&state.machine).approved = true;
}
app.exit(0);
}
});
}
exit
}
// Phase 1: no ack within this window ⇒ a webview listener is dead — exit.
const QUIT_ACK_TIMEOUT_MS: u64 = 2_000;
// Phase 3: per-phase budget once teardown is running. Each reported phase
// (teardown, install) refreshes it, so it bounds a single stalled phase, not the
// sum of all teardown work. Sits above the webview's own teardown
// ceiling (docs/specs/standalone.md §Quit flow) — `QUIT_TEARDOWN_CEILING_MS` in
// `standalone/src/quit.ts`, pinned under this by
// `lib/src/lib/mirrored-constants.test.ts`.
const QUIT_PHASE_TIMEOUT_MS: u64 = 14_000;
const QUIT_POLL_STEP_MS: u64 = 500;
// A per-window close whose webview never acks: its listener is dead, so close it.
const CLOSE_ACK_TIMEOUT_MS: u64 = 2_000;
fn quit_approved(app: &AppHandle) -> bool {
app.try_state::<QuitState>()
.is_some_and(|state| guard(&state.machine).approved)
}
/// Whether the windows are already being torn down, in which case a `destroy`
/// must not re-enter the quit as a fresh close.
fn quit_walking(app: &AppHandle) -> bool {
app.try_state::<QuitState>().is_some_and(|state| {
matches!(
guard(&state.machine).phase,
quit_state::QuitPhase::Walking { .. }
)
})
}
fn window_labels(app: &AppHandle) -> Vec<String> {
app.webview_windows().keys().cloned().collect()
}
/// Perform what a `QuitMachine` transition asked for.
fn apply_quit_actions(app: &AppHandle, actions: Vec<QuitAction>) {
for action in actions {
match action {
QuitAction::RequestAll { requester } => {
let _ = app.emit(
"dormouse://quit-requested",
serde_json::json!({ "requester": requester }),
);
}
QuitAction::CancelAll => {
let _ = app.emit("dormouse://quit-cancelled", ());
}
QuitAction::Teardown { label, last } => {
let _ = app.emit_to(
label.as_str(),
"dormouse://quit-teardown",
serde_json::json!({ "last": last }),
);
}
QuitAction::Destroy { label } => {
// The snapshot stays on disk — that is what separates a quit
// from a per-window close. Ownership and the sidecar's window
// list are settled by the `Destroyed` arm.
if let Some(window) = app.get_webview_window(&label) {
let _ = window.destroy();
}
}
QuitAction::Exit => {
if !exit_after_cleanup(app) { continue; }
if let Some(state) = app.try_state::<QuitState>() {
guard(&state.machine).approved = true;
}
app.exit(0);
}
}
}
}
/// Re-enter the normal admission and confirmation paths after a transfer
/// settles. Requests queue in the `ArrivalQueue` under the arrivals lock, so a
/// settlement cannot miss one queued concurrently. The callback takes requests
/// only when it runs.
fn redrive_deferred_teardown(app: &AppHandle) {
let retry = app.clone();
if let Err(error) = app.run_on_main_thread(move || {
let Some(windows) = retry.try_state::<WindowState>() else { return; };
let (quit, closes) =
guard(&windows.arrivals).take_ready(|| window_labels(&retry).into_iter().collect());
if let Some(intent) = quit { request_quit(&retry, intent); }
else {
for label in closes {
if retry.get_webview_window(&label).is_some() { request_close_or_quit(&retry, &label); }
}
}
}) {
append_log(format!("[quit] could not retry deferred teardown: {error}"));
}
}
/// Only the last window's close is a quit (§Per-window close).
fn request_close_or_quit(app: &AppHandle, label: &str) {
if app.webview_windows().len() > 1 {
request_window_close(app, label);
} else {
request_quit(app, QuitIntent::default());
}
}
/// Start (or join) a quit with `intent` (docs/specs/standalone.md -> "Restart").
/// Returns whether the quit this trigger landed in relaunches.
fn request_quit(app: &AppHandle, intent: QuitIntent) -> bool {
let Some(state) = app.try_state::<QuitState>() else {
return false;
};
let (my_seq, actions, relaunches) = {
// Lock order: arrivals, quit machine, close machine. No disk I/O or
// event emission under these locks. Arrival admission takes this same
// lock before checking the quit phase, so membership cannot change
// between this check and beginning the vote.
let windows = app.state::<WindowState>();
let mut arrivals = guard(&windows.arrivals);
if let Some(relaunches) = arrivals.defer_quit(&intent) {
drop(arrivals);
append_log("[quit] transfer in progress; quit queued until settlement");
return relaunches;
}
let labels = window_labels(app);
let mut machine = guard(&state.machine);
let (seq, actions) = machine.request(&labels, intent);
(seq, actions, machine.intent().restart)
};
apply_quit_actions(app, actions);
// Watchdog: a cloned handle polls the machine so a dead or wedged webview
// can't make quit hang. A repeated trigger bumps seq, so this (now-stale)
// watchdog returns and the fresh request_quit spawns a replacement.
let app = app.clone();
std::thread::spawn(move || {
std::thread::sleep(Duration::from_millis(QUIT_ACK_TIMEOUT_MS));
let give_up = |reason: &str| {
append_log(format!("[quit] {reason}; exiting"));
if let Some(state) = app.try_state::<QuitState>() {
guard(&state.machine).approved = true;
}
app.exit(0);
};
let Some(acked) = read_quit(&app, my_seq, QuitMachine::all_acked) else {
return;
};
if !acked {
give_up("a window never acked");
return;
}
// Phase 2: acked but no window has begun tearing down. Each may be
// parked on its confirmation dialog waiting for a human, who must never
// be force-quit out from under it — so hold with no deadline.
loop {
let Some(walking) = read_quit(&app, my_seq, |machine| {
machine.walking_progress().is_some()
}) else {
return;
};
if walking {
break;
}
std::thread::sleep(Duration::from_millis(QUIT_POLL_STEP_MS));
}
// Phase 3: one window is tearing down. Bound it, but a `quit_progress`
// bump (a phase boundary) or the walk advancing to the next window
// refreshes the deadline, so each phase gets its own budget.
let mut last = read_quit(&app, my_seq, QuitMachine::walking_progress);
let mut elapsed = 0u64;
loop {
std::thread::sleep(Duration::from_millis(QUIT_POLL_STEP_MS));
let Some(now) = read_quit(&app, my_seq, QuitMachine::walking_progress) else {
return;
};
if Some(&now) != last.as_ref() {
last = Some(now);
elapsed = 0;
continue;
}
elapsed += QUIT_POLL_STEP_MS;
if elapsed >= QUIT_PHASE_TIMEOUT_MS {
give_up("teardown phase stalled");
return;
}
}
});
relaunches
}
/// Read the quit machine on behalf of a watchdog spawned for `seq`. `None`
/// means the watchdog has been superseded (a repeat trigger or a cancel) or the
/// app is already exiting, and it must stand down without acting.
fn read_quit<T>(app: &AppHandle, seq: u64, read: impl FnOnce(&QuitMachine) -> T) -> Option<T> {
let state = app.try_state::<QuitState>()?;
let machine = guard(&state.machine);
if machine.stale(seq) {
return None;
}
Some(read(&machine))
}
/// Ask one window to close itself (docs/specs/standalone.md §Per-window close).
/// The app keeps running; only the last window's close is a quit.
fn request_window_close(app: &AppHandle, label: &str) {
let Some(state) = app.try_state::<QuitState>() else {
return;
};
append_log(format!("[window] close requested for {label}"));
let my_seq = {
let windows = app.state::<WindowState>();
let mut arrivals = guard(&windows.arrivals);
if arrivals.defer_close(label) {
drop(arrivals);
append_log(format!("[window] {label} transfer in progress; close queued until settlement"));
return;
}
guard(&state.close).request(label)
};
let _ = app.emit_to(label, "dormouse://window-close-requested", ());
let app = app.clone();
let label = label.to_string();
std::thread::spawn(move || {
std::thread::sleep(Duration::from_millis(CLOSE_ACK_TIMEOUT_MS));
let Some(state) = app.try_state::<QuitState>() else {
return;
};
let close = guard(&state.close);
if close.stale(&label, my_seq) || close.acked(&label) {
return;
}
drop(close);
append_log(format!(
"[window] {label} never acked its close; closing it anyway"
));
finish_window_close(&app, &label);
});
}
/// The last step of a per-window close: take the window's snapshot off disk and
/// destroy it. Called from `close_window`, and from the ack watchdog when the
/// webview never answered.
///
/// The rest — forgetting its PTYs, telling the quit machine, telling the
/// sidecar's Burrow — happens in the `Destroyed` arm, which is the first moment
/// Tauri has actually taken the label out of `webview_windows()`.
fn finish_window_close(app: &AppHandle, label: &str) {
append_log(format!("[window] closing {label} and removing its snapshot"));
if let Some(state) = app.try_state::<WindowState>() {
// Before the removal, not after: a save already in flight from this
// webview would otherwise put the snapshot back. Reached from the
// watchdog too, where the webview never called `remove_window_session`.
state.begin_closing(label);
}
if let Some(state) = app.try_state::<QuitState>() {
guard(&state.close).clear(label);
}
if let Ok(dir) = sessions_dir(app) {
if let Err(err) = close_window_snapshot(&dir, label) {
append_log(format!("[session] {err}"));
}
}
if let Some(window) = app.get_webview_window(label) {
let _ = window.destroy();
}
}
/// SIGTERM the PTYs a window left behind, and drop their Sessions' alert
/// entries with them: no window will ever show those Sessions again.
///
/// Reached whenever a window goes away still owning shells — the close
/// ack-timeout path ran no teardown at all, and a teardown that overran its
/// budget can leave stragglers. Unowned output routes nowhere
/// (`routing::owner`), so without this they would run on invisibly.
fn reap_orphaned_ptys(app: &AppHandle, label: &str, ids: Vec<String>) {
if ids.is_empty() {
return;
}
let Some(sidecar) = app.try_state::<SidecarState>() else {
return;
};
append_log(format!(
"[window] {label} left {} PTY(s) with no owner; killing them",
ids.len()
));
send_to_sidecar(&sidecar, pty_reap_message(&ids));
}
/// The `pty:reap` line `reap_orphaned_ptys` sends. Not `pty:gracefulKill`,
/// which the quit teardown sends for PTYs whose windows still show them.
fn pty_reap_message(ids: &[String]) -> String {
sidecar_line("pty:reap", serde_json::json!({ "ids": ids, "timeout": 2000 }))
}
const LOG_FILE_ENV: &str = "DORMOUSE_LOG_FILE";
fn log_timestamp() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|duration| duration.as_secs())
.unwrap_or_default()
}
fn default_log_path() -> PathBuf {
if let Some(path) = env::var_os(LOG_FILE_ENV) {
return PathBuf::from(path);
}
#[cfg(target_os = "windows")]
if let Some(local_app_data) = env::var_os("LOCALAPPDATA") {
return PathBuf::from(local_app_data)
.join("Dormouse Terminal")
.join("dormouse.log");
}
env::temp_dir().join("dormouse.log")
}
fn log_path() -> &'static Path {
static PATH: OnceLock<PathBuf> = OnceLock::new();
PATH.get_or_init(default_log_path)
}
// `append_log` runs per stdout/stderr line from the sidecar; reopening
// the file each call costs a syscall + dir-walk per chatty subprocess
// log line. Cache an append handle for the life of the process.
fn log_file() -> Option<&'static Mutex<File>> {
static FILE: OnceLock<Option<Mutex<File>>> = OnceLock::new();
FILE.get_or_init(|| {
let path = log_path();
if let Some(parent) = path.parent() {
let _ = create_dir_all(parent);
}
OpenOptions::new()
.create(true)
.append(true)
.open(path)
.ok()
.map(Mutex::new)
})
.as_ref()
}
fn init_log() {
let path = log_path();
if let Some(parent) = path.parent() {
let _ = create_dir_all(parent);
}
if let Ok(mut file) = OpenOptions::new()
.create(true)
.write(true)
.truncate(true)
.open(path)
{
let _ = writeln!(
file,
"[{}] Dormouse log started at {}",
log_timestamp(),
path.display()
);
}
}
fn append_log(message: impl AsRef<str>) {
let Some(file) = log_file() else { return };
if let Ok(mut file) = file.lock() {
let _ = writeln!(file, "[{}] {}", log_timestamp(), message.as_ref());
}
}
#[cfg(target_os = "macos")]
fn set_macos_dock_icon() {
use objc2::{AllocAnyThread, MainThreadMarker};
use objc2_app_kit::{NSApplication, NSImage};
use objc2_foundation::NSData;
let mtm = unsafe { MainThreadMarker::new_unchecked() };
let app = NSApplication::sharedApplication(mtm);
// The largest size exploded from icon.icns (1024×1024) — it carries the
// built-in transparent padding the bundle's edge-to-edge 128x128@2x.png lacks.
let data = NSData::with_bytes(include_bytes!("../icons/dock-icon.png"));
let Some(app_icon) = NSImage::initWithData(NSImage::alloc(), &data) else {
append_log("[app] failed to create macOS dock icon image");
return;
};
unsafe {
app.setApplicationIconImage(Some(&app_icon));
}
}
fn read_log_tail(max_bytes: usize) -> Result<String, String> {
let path = log_path();
File::open(path)
.and_then(|mut file| log_tail::read_utf8_tail(&mut file, max_bytes))
.map_err(|e| format!("read {}: {e}", path.display()))
}
#[derive(Serialize, Deserialize, Clone)]
struct PtySpawnOptions {
helper: Option<JsonValue>,
cols: Option<u16>,
rows: Option<u16>,
cwd: Option<String>,
shell: Option<String>,
args: Option<Vec<String>>,
/// A cold restore's persisted alert state, seeded by the sidecar's
/// AlertManager behind the spawn. Opaque here, like `helper`.
alert: Option<JsonValue>,
}
#[derive(Serialize, Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
struct DorControlResponse {
request_id: String,
ok: bool,
#[serde(skip_serializing_if = "Option::is_none")]
result: Option<JsonValue>,
#[serde(skip_serializing_if = "Option::is_none")]
error: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
struct DorCliPaths {
bin_dir: PathBuf,
entrypoint: PathBuf,
}
fn send_to_sidecar(state: &SidecarState, line: String) {
let _ = state.tx.send(line);
}
/// One sidecar line, `{event, data}`, serialized straight from `data`: no
/// intermediate `JsonValue`, so a payload is never deep-cloned on its way out.
fn sidecar_line(event: &str, data: impl Serialize) -> String {
#[derive(Serialize)]
struct Line<'a, T> {
event: &'a str,
data: T,
}
serde_json::to_string(&Line { event, data }).expect("a sidecar line is plain JSON")
}
fn request_from_sidecar(
state: &SidecarState,
event: &str,
data: JsonValue,
) -> Result<JsonValue, String> {
request_from_sidecar_timeout(state, event, data, Duration::from_secs(1))
}