-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib.rs
More file actions
1780 lines (1617 loc) · 66.6 KB
/
Copy pathlib.rs
File metadata and controls
1780 lines (1617 loc) · 66.6 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 base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};
use serde::{Deserialize, Serialize};
use serde_json::{Map as JsonMap, Value as JsonValue};
use std::{
collections::HashMap,
env,
fs::{create_dir_all, File, OpenOptions},
io::{BufRead, BufReader, Write},
path::{Path, PathBuf},
process::Stdio,
sync::atomic::{AtomicBool, AtomicU64, Ordering},
sync::mpsc,
sync::{Arc, Mutex, OnceLock},
time::{Duration, SystemTime, UNIX_EPOCH},
};
use tauri::{
menu::{Menu, PredefinedMenuItem, Submenu},
AppHandle, DragDropEvent, Emitter, Manager, RunEvent, WindowEvent,
};
#[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,
}
// ── Quit interception ─────────────────────────────────────────────────────────
//
// Every quit trigger funnels through `request_quit`, which asks the webview's
// orchestrator (standalone/src/quit.ts) to tear down and call back
// `quit_proceed`. Protocol + watchdog phases: docs/specs/standalone.md §Quit flow.
#[derive(Default)]
struct QuitState {
// The webview acknowledged quit-requested — its listener is alive.
acked: AtomicBool,
// Teardown has actually begun (user confirmed, or there was nothing to
// confirm). Until this is set the webview may be parked on the confirmation
// dialog waiting for a human, so the teardown deadline below must stay
// suspended — a slow user must not be force-quit out from under the dialog.
tearing_down: AtomicBool,
// Bumped by `quit_progress` at each teardown phase boundary (teardown start,
// install start). The phase-3 watchdog treats a bump as "still making
// progress" and refreshes its deadline, so a long-but-live install isn't cut
// off by a long teardown — each phase gets its own budget rather than sharing
// one total.
progress: AtomicU64,
// Teardown finished (or a watchdog gave up): cleared to exit. Gates the
// CloseRequested/ExitRequested arms so the final app.exit(0) isn't re-caught.
approved: AtomicBool,
// Bumped on every request_quit and on quit_cancel. A watchdog captures the
// seq it was spawned for; if it no longer matches, a repeated trigger or a
// cancel has superseded it and the watchdog exits without acting.
seq: AtomicU64,
}
// Phase 1: no ack within this window ⇒ 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. Comfortably exceeds the webview's own 8 s teardown
// ceiling (docs/specs/standalone.md §Quit flow).
const QUIT_PHASE_TIMEOUT_MS: u64 = 12_000;
const QUIT_POLL_STEP_MS: u64 = 500;
fn quit_approved(app: &AppHandle) -> bool {
app.try_state::<QuitState>()
.is_some_and(|q| q.approved.load(Ordering::SeqCst))
}
fn request_quit(app: &AppHandle) {
let Some(quit) = app.try_state::<QuitState>() else {
return;
};
quit.acked.store(false, Ordering::SeqCst);
// Deliberately do NOT reset `tearing_down` here. A cancel happens before
// teardown, so it's already false for a genuinely fresh quit; and once
// teardown begins it only ever ends in `quit_proceed` (app exit), so a repeat
// trigger fired mid-teardown must keep the flag set — otherwise the fresh
// watchdog would drop into the unbounded phase-2 wait and stop bounding the
// in-flight teardown.
// fetch_add returns the prior value; our watchdog's seq is that + 1.
let my_seq = quit.seq.fetch_add(1, Ordering::SeqCst) + 1;
let _ = app.emit("dormouse://quit-requested", ());
// Watchdog: a cloned handle polls QuitState 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 Some(quit) = app.try_state::<QuitState>() else {
return;
};
// Superseded (seq bumped by a repeated trigger or a cancel) or already
// exiting (approved) ⇒ this watchdog has nothing to do.
let stale = |quit: &QuitState| {
quit.seq.load(Ordering::SeqCst) != my_seq || quit.approved.load(Ordering::SeqCst)
};
if stale(&quit) {
return;
}
if !quit.acked.load(Ordering::SeqCst) {
append_log("[quit] no ack from webview; exiting");
quit.approved.store(true, Ordering::SeqCst);
app.exit(0);
return;
}
// Phase 2: acked but teardown hasn't begun. The webview may be parked on
// the confirmation dialog waiting for a human, so hold with no deadline —
// only proceed (approved) or cancel (seq bump) ends the wait.
while !quit.tearing_down.load(Ordering::SeqCst) {
std::thread::sleep(Duration::from_millis(QUIT_POLL_STEP_MS));
if stale(&quit) {
return;
}
}
// Phase 3: teardown running. Bound it, but a `quit_progress` bump (a phase
// boundary: teardown start, install start) refreshes the deadline so one
// long phase can't starve the next — each phase gets its own budget.
let mut last_progress = quit.progress.load(Ordering::SeqCst);
let mut elapsed = 0u64;
loop {
std::thread::sleep(Duration::from_millis(QUIT_POLL_STEP_MS));
if stale(&quit) {
return;
}
let progress = quit.progress.load(Ordering::SeqCst);
if progress != last_progress {
last_progress = progress;
elapsed = 0;
continue;
}
elapsed += QUIT_POLL_STEP_MS;
if elapsed >= QUIT_PHASE_TIMEOUT_MS {
append_log("[quit] teardown phase stalled; exiting");
quit.approved.store(true, Ordering::SeqCst);
app.exit(0);
return;
}
}
});
}
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();
let contents = std::fs::read_to_string(path)
.map_err(|e| format!("read {}: {e}", path.display()))?;
if contents.len() <= max_bytes {
return Ok(contents);
}
// Slice on a char boundary so we never split a multi-byte sequence.
let start = contents.len() - max_bytes;
let start = (start..contents.len())
.find(|&i| contents.is_char_boundary(i))
.unwrap_or(contents.len());
Ok(contents[start..].to_string())
}
#[derive(Serialize, Deserialize, Clone)]
struct PtySpawnOptions {
cols: Option<u16>,
rows: Option<u16>,
cwd: Option<String>,
shell: Option<String>,
args: Option<Vec<String>>,
}
#[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);
}
fn request_from_sidecar(
state: &SidecarState,
event: &str,
data: JsonValue,
) -> Result<JsonValue, String> {
request_from_sidecar_timeout(state, event, data, Duration::from_secs(1))
}
/// INVARIANT: every `#[tauri::command]` that reaches these two blocking helpers
/// must be declared `#[tauri::command(async)]` (or be an `async fn`). Tauri runs
/// a plain sync command on the **main thread**, where the `recv_timeout` below
/// stops the webview from painting for the whole round trip — up to
/// `AGENT_BROWSER_TIMEOUT` (30s) for a hung agent-browser, and a visible ~3s
/// freeze on a cold `agent-browser open`, which is long enough to look like a
/// pane that never appeared. `(async)` moves the same blocking body onto a
/// runtime worker, so the UI keeps rendering while the sidecar works.
fn request_from_sidecar_timeout(
state: &SidecarState,
event: &str,
data: JsonValue,
timeout: Duration,
) -> Result<JsonValue, String> {
let request_id = format!(
"req-{}",
state.next_request_id.fetch_add(1, Ordering::Relaxed)
);
let (tx, rx) = mpsc::channel();
state
.pending_requests
.lock()
.map_err(|_| "failed to lock pending request map".to_string())?
.insert(request_id.clone(), tx);
let mut payload = match data {
JsonValue::Object(map) => map,
_ => JsonMap::new(),
};
payload.insert("requestId".into(), JsonValue::String(request_id.clone()));
let msg = serde_json::json!({
"event": event,
"data": JsonValue::Object(payload)
});
send_to_sidecar(state, msg.to_string());
match rx.recv_timeout(timeout) {
Ok(response) => Ok(response),
Err(err) => {
if let Ok(mut pending) = state.pending_requests.lock() {
pending.remove(&request_id);
}
// Disconnected means the reaper cleared pending_requests because
// the sidecar exited — surface that distinctly from a real timeout.
match err {
mpsc::RecvTimeoutError::Timeout => {
Err(format!("timed out waiting for {event}"))
}
mpsc::RecvTimeoutError::Disconnected => {
Err(format!("sidecar exited before responding to {event}"))
}
}
}
}
}
// ── Tauri commands ──────────────────────────────────────────────────────────
#[tauri::command]
fn pty_spawn(state: tauri::State<'_, SidecarState>, id: String, options: Option<PtySpawnOptions>) {
let msg = serde_json::json!({
"event": "pty:spawn",
"data": { "id": id, "options": options }
});
send_to_sidecar(&state, msg.to_string());
}
#[tauri::command]
fn pty_write(state: tauri::State<'_, SidecarState>, id: String, data: String) {
let msg = serde_json::json!({
"event": "pty:input",
"data": { "id": id, "data": data }
});
send_to_sidecar(&state, msg.to_string());
}
#[tauri::command]
fn pty_resize(state: tauri::State<'_, SidecarState>, id: String, cols: u16, rows: u16) {
let msg = serde_json::json!({
"event": "pty:resize",
"data": { "id": id, "cols": cols, "rows": rows }
});
send_to_sidecar(&state, msg.to_string());
}
#[tauri::command]
fn pty_kill(state: tauri::State<'_, SidecarState>, id: String) {
let msg = serde_json::json!({
"event": "pty:kill",
"data": { "id": id }
});
send_to_sidecar(&state, msg.to_string());
}
#[tauri::command]
fn pty_request_init(state: tauri::State<'_, SidecarState>) {
let msg = serde_json::json!({ "event": "pty:requestInit" });
send_to_sidecar(&state, msg.to_string());
}
#[tauri::command]
fn dor_control_response(state: tauri::State<'_, SidecarState>, response: DorControlResponse) {
let msg = serde_json::json!({
"event": "dor:controlResponse",
"data": response,
});
send_to_sidecar(&state, msg.to_string());
}
#[tauri::command(async)]
fn pty_get_cwd(
state: tauri::State<'_, SidecarState>,
id: String,
) -> Result<Option<String>, String> {
let response = request_from_sidecar(&state, "pty:getCwd", serde_json::json!({ "id": id }))?;
Ok(response
.get("cwd")
.and_then(|cwd| cwd.as_str().map(String::from)))
}
// Mirrors `OPEN_PORT_TIMEOUT_MS` in `lib/src/lib/platform/types.ts` — keep in sync.
const OPEN_PORT_TIMEOUT_MS: u64 = 3000;
#[tauri::command(async)]
fn pty_get_open_ports(
state: tauri::State<'_, SidecarState>,
id: String,
) -> Result<JsonValue, String> {
let response = request_from_sidecar_timeout(
&state,
"pty:getOpenPorts",
serde_json::json!({ "id": id }),
Duration::from_millis(OPEN_PORT_TIMEOUT_MS),
)?;
Ok(response
.get("ports")
.cloned()
.unwrap_or_else(|| JsonValue::Array(Vec::new())))
}
#[tauri::command(async)]
fn pty_get_scrollback(
state: tauri::State<'_, SidecarState>,
id: String,
) -> Result<Option<String>, String> {
let response =
request_from_sidecar(&state, "pty:getScrollback", serde_json::json!({ "id": id }))?;
Ok(response
.get("data")
.and_then(|data| data.as_str().map(String::from)))
}
// Unlike pty_kill / kill_sidecar_now this preserves scrollback so the caller can
// capture final output afterward. Async: waits up to `timeout + 1500ms` (margin
// for the round trip beyond the sidecar's own kill timer) and must not block the
// main thread for that long.
#[tauri::command]
async fn pty_graceful_kill_all(
state: tauri::State<'_, SidecarState>,
timeout: u64,
) -> Result<(), String> {
request_from_sidecar_timeout(
&state,
"pty:gracefulKillAll",
serde_json::json!({ "timeout": timeout }),
Duration::from_millis(timeout + 1500),
)?;
Ok(())
}
// Stands up the loopback iframe proxy in the sidecar and returns the
// IframeProxyResult JSON the webview's IframePanel expects. The proxy server is
// the shared lib/src/host/iframe-proxy.ts; this only bridges the request.
#[tauri::command(async)]
fn iframe_create_proxy_url(
state: tauri::State<'_, SidecarState>,
target: String,
) -> Result<JsonValue, String> {
let response = request_from_sidecar_timeout(
&state,
"iframe:createProxyUrl",
serde_json::json!({ "target": target }),
Duration::from_secs(5),
)?;
Ok(response.get("result").cloned().unwrap_or(JsonValue::Null))
}
// ── agent-browser host (docs/specs/dor-browser.md → "Agent-Browser Host Capabilities").
// Thin forwarders to the Node sidecar, which runs the shared
// lib/src/host/agent-browser-host.ts — the very same module the VS Code
// extension host runs. Mirrors iframe_create_proxy_url; the logic lives in lib,
// not here, so the two hosts can't drift. ──────────────────────────────────────
// agent-browser launches Chrome (slow on first run), and pop-out is a
// close + relaunch, so allow a generous window before a forward times out.
const AGENT_BROWSER_TIMEOUT: Duration = Duration::from_secs(30);
fn agent_browser_forward(
state: &SidecarState,
event: &str,
data: JsonValue,
) -> Result<JsonValue, String> {
let response = request_from_sidecar_timeout(state, event, data, AGENT_BROWSER_TIMEOUT)?;
Ok(response.get("result").cloned().unwrap_or(JsonValue::Null))
}
#[tauri::command(async)]
fn agent_browser_command(
state: tauri::State<'_, SidecarState>,
session: String,
args: Vec<String>,
binary_path: Option<String>,
) -> Result<JsonValue, String> {
agent_browser_forward(
&state,
"agentBrowser:command",
serde_json::json!({ "session": session, "args": args, "binaryPath": binary_path }),
)
}
#[tauri::command(async)]
fn agent_browser_edit(
state: tauri::State<'_, SidecarState>,
session: String,
op: String,
binary_path: Option<String>,
) -> Result<JsonValue, String> {
agent_browser_forward(
&state,
"agentBrowser:edit",
serde_json::json!({ "session": session, "op": op, "binaryPath": binary_path }),
)
}
#[tauri::command(async)]
fn agent_browser_stream_status(
state: tauri::State<'_, SidecarState>,
session: String,
binary_path: Option<String>,
) -> Result<JsonValue, String> {
agent_browser_forward(
&state,
"agentBrowser:streamStatus",
serde_json::json!({ "session": session, "binaryPath": binary_path }),
)
}
#[tauri::command(async)]
fn agent_browser_open(
state: tauri::State<'_, SidecarState>,
url: String,
headed: Option<bool>,
binary_path: Option<String>,
) -> Result<JsonValue, String> {
agent_browser_forward(
&state,
"agentBrowser:open",
serde_json::json!({ "url": url, "headed": headed, "binaryPath": binary_path }),
)
}
// `rect` is accepted by the adapter but unused — no window positioning today.
#[tauri::command(async)]
fn agent_browser_pop_out(
state: tauri::State<'_, SidecarState>,
session: String,
url: Option<String>,
binary_path: Option<String>,
) -> Result<JsonValue, String> {
agent_browser_forward(
&state,
"agentBrowser:popOut",
serde_json::json!({ "session": session, "url": url, "binaryPath": binary_path }),
)
}
#[tauri::command(async)]
fn agent_browser_pop_in(
state: tauri::State<'_, SidecarState>,
session: String,
url: Option<String>,
binary_path: Option<String>,
) -> Result<JsonValue, String> {
agent_browser_forward(
&state,
"agentBrowser:popIn",
serde_json::json!({ "session": session, "url": url, "binaryPath": binary_path }),
)
}
// The sidecar hands back the screenshot's temp-file PATH (bytes no longer ride
// the JSON-lines stdio shared with PTY traffic). Read the file here and return a
// raw tauri::ipc::Response so the webview gets an ArrayBuffer (the path the panel
// decodes with createImageBitmap). A base64 `bytesBase64` field is kept as a
// fallback for a stale sidecar bundle (dev-time version skew), but the path
// branch is preferred.
#[tauri::command(async)]
fn agent_browser_screenshot(
state: tauri::State<'_, SidecarState>,
session: String,
format: Option<String>,
quality: Option<u32>,
binary_path: Option<String>,
) -> Result<tauri::ipc::Response, String> {
let result = agent_browser_forward(
&state,
"agentBrowser:screenshot",
serde_json::json!({ "session": session, "format": format, "quality": quality, "binaryPath": binary_path }),
)?;
if result.get("ok").and_then(JsonValue::as_bool) != Some(true) {
return Err(result
.get("error")
.and_then(JsonValue::as_str)
.unwrap_or("screenshot failed")
.to_string());
}
if let Some(path) = result.get("path").and_then(JsonValue::as_str) {
let bytes = std::fs::read(path)
.map_err(|err| format!("could not read screenshot file '{path}': {err}"))?;
return Ok(tauri::ipc::Response::new(bytes));
}
// Fallback: an older sidecar bundle still base64s the bytes over stdio.
let b64 = result
.get("bytesBase64")
.and_then(JsonValue::as_str)
.ok_or("screenshot returned no path or bytes")?;
let bytes = BASE64
.decode(b64)
.map_err(|err| format!("bad screenshot base64: {err}"))?;
Ok(tauri::ipc::Response::new(bytes))
}
// Clipboard reads run natively on Windows (see clipboard_win) to avoid the
// console-window flicker of shelling out to PowerShell; other platforms keep the
// sidecar path (pbpaste/xclip never pop a console window).
#[tauri::command(async)]
fn read_clipboard_file_paths(
state: tauri::State<'_, SidecarState>,
) -> Result<Vec<String>, String> {
#[cfg(windows)]
{
let _ = &state;
return Ok(clipboard_win::read_file_paths());
}
#[cfg(not(windows))]
{
let response =
request_from_sidecar_timeout(&state, "clipboard:readFiles", serde_json::json!({}), Duration::from_secs(5))?;
Ok(response
.get("paths")
.and_then(|v| serde_json::from_value(v.clone()).ok())
.unwrap_or_default())
}
}
#[tauri::command(async)]
fn read_clipboard_image_as_file_path(
state: tauri::State<'_, SidecarState>,
) -> Result<Option<String>, String> {
#[cfg(windows)]
{
let _ = &state;
return Ok(clipboard_win::read_image_as_file_path());
}
#[cfg(not(windows))]
{
let response =
request_from_sidecar_timeout(&state, "clipboard:readImage", serde_json::json!({}), Duration::from_secs(10))?;
Ok(response
.get("path")
.and_then(|path| path.as_str().map(String::from)))
}
}
#[tauri::command(async)]
fn read_clipboard_text(
state: tauri::State<'_, SidecarState>,
) -> Result<String, String> {
#[cfg(windows)]
{
let _ = &state;
return Ok(clipboard_win::read_text().unwrap_or_default());
}
#[cfg(not(windows))]
{
let response =
request_from_sidecar_timeout(&state, "clipboard:readText", serde_json::json!({}), Duration::from_secs(5))?;
Ok(response
.get("text")
.and_then(|v| v.as_str().map(String::from))
.unwrap_or_default())
}
}
#[tauri::command]
fn read_update_log() -> Result<String, String> {
read_log_tail(10_000)
}
// --- Per-window session persistence (docs/specs/standalone.md §Persistence) ---
//
// The webview's persisted-session blob (a `PersistedWindow`) is stored as one
// atomic file per Tauri window, keyed by the window label. This replaces webview
// `localStorage`, whose WKWebView SQLite WAL grew unbounded because WebKit pins
// its own WAL with a long-lived reader and never truncates during a days-long
// session. A plain file we overwrite atomically has no WAL and cannot grow.
//
// Window identity is implicit: each command keys by the invoking window's label,
// so the frontend stays window-agnostic and a second window (`win-2`, …) persists
// to its own file without ever rewriting the first window's blob.
fn sessions_dir(app: &AppHandle) -> Result<PathBuf, String> {
Ok(app
.path()
.app_data_dir()
.map_err(|e| format!("app_data_dir unavailable: {e}"))?
.join("sessions"))
}
// Window labels are app-controlled (e.g. "main"), but sanitize defensively so a
// label can never escape the sessions directory or embed a path separator.
fn session_file_name(label: &str) -> String {
let safe: String = label
.chars()
.map(|c| {
if c.is_ascii_alphanumeric() || c == '-' || c == '_' {
c
} else {
'_'
}
})
.collect();
format!("{safe}.json")
}
fn read_session_from(dir: &Path, label: &str) -> Result<Option<String>, String> {
let path = dir.join(session_file_name(label));
match std::fs::read_to_string(&path) {
Ok(contents) => Ok(Some(contents)),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
Err(e) => Err(format!("read session {label}: {e}")),
}
}
fn write_session_to(dir: &Path, label: &str, state: &str) -> Result<(), String> {
create_dir_all(dir).map_err(|e| format!("create sessions dir: {e}"))?;
let file_name = session_file_name(label);
let path = dir.join(&file_name);
let tmp = dir.join(format!("{file_name}.tmp"));
// Atomic replace: write a sibling temp file, fsync it, then rename over the
// target so a crash mid-write can never truncate the previous good snapshot.
{
let mut f = File::create(&tmp).map_err(|e| format!("open temp: {e}"))?;
f.write_all(state.as_bytes())
.map_err(|e| format!("write temp: {e}"))?;
f.sync_all().map_err(|e| format!("fsync temp: {e}"))?;
}
std::fs::rename(&tmp, &path).map_err(|e| format!("rename session {label}: {e}"))?;
// The temp file's own fsync doesn't make the rename durable — on unix the
// directory entry that now points at the new inode must be fsynced too, or a
// crash right after quit could leave the rename unrecorded. Best-effort: a
// failure here doesn't invalidate the (already-written) data. Windows has no
// equivalent dir-fsync concept, so this is unix-only.
#[cfg(unix)]
{
if let Ok(d) = std::fs::File::open(dir) {
let _ = d.sync_all();
}
}
Ok(())
}
// Async so the file IO (and save's two fsyncs — temp file + dir, both
// F_FULLFSYNC on macOS) runs off the main/event-loop thread. Ordering is safe:
// the webview store issues at most one save_session at a time (its coalescer).
#[tauri::command]
async fn load_session(window: tauri::Window) -> Result<Option<String>, String> {
read_session_from(&sessions_dir(window.app_handle())?, window.label())
}
#[tauri::command]
async fn save_session(window: tauri::Window, state: String) -> Result<(), String> {
write_session_to(&sessions_dir(window.app_handle())?, window.label(), &state)
}
#[tauri::command]
fn kill_sidecar_now(state: tauri::State<'_, SidecarState>) {
kill_sidecar_and_wait(&state.child);
}
// ── Quit protocol commands (docs/specs/standalone.md §Quit flow) ─────────────
// The webview's quit orchestrator received quit-requested and its listener is
// alive; stand the phase-1 ack watchdog down.
#[tauri::command]
fn quit_ack(state: tauri::State<'_, QuitState>) {
state.acked.store(true, Ordering::SeqCst);
}
// The orchestrator has started (or advanced) teardown: the confirmation wait is
// over, and this phase boundary refreshes the watchdog's per-phase deadline. The
// webview calls this at teardown start and again before installing an update, so
// a long install gets its own budget instead of sharing the teardown clock.
#[tauri::command]
fn quit_progress(state: tauri::State<'_, QuitState>) {
state.tearing_down.store(true, Ordering::SeqCst);
state.progress.fetch_add(1, Ordering::SeqCst);
}
// The user declined the quit (confirmation cancel). Bumping seq invalidates any
// live watchdog for this quit so nothing exits; the next request_quit starts
// fresh (it re-clears `acked` itself).
#[tauri::command]
fn quit_cancel(state: tauri::State<'_, QuitState>) {
state.seq.fetch_add(1, Ordering::SeqCst);
}
// Teardown is done (or the orchestrator bailed under its own timeout); approve so
// the app.exit(0) below re-enters ExitRequested with approved=true and proceeds.
#[tauri::command]
fn quit_proceed(app: AppHandle, state: tauri::State<'_, QuitState>) {
state.approved.store(true, Ordering::SeqCst);
app.exit(0);
}
// Normal app quit should let the Node sidecar run its shutdown handler first:
// that handler closes headed agent-browser pop-out windows before killing PTYs.
// If the sidecar is wedged, fall back to the same hard kill path so quit remains
// bounded.
fn shutdown_sidecar_and_wait(state: &SidecarState) {
const POLL_INTERVAL: Duration = Duration::from_millis(20);
const MAX_POLLS: u32 = 125;
append_log("[sidecar] requesting graceful shutdown");
send_to_sidecar(
state,
serde_json::json!({ "event": "sidecar:shutdown", "data": {} }).to_string(),
);
let Ok(mut guard) = state.child.lock() else {
return;
};
for _ in 0..MAX_POLLS {
match guard.try_wait() {
Ok(Some(status)) => {
append_log(format!(
"[sidecar] confirmed graceful exit (status: {status})"
));
return;
}
Ok(None) => std::thread::sleep(POLL_INTERVAL),
Err(err) => {
append_log(format!(
"[sidecar] wait error during graceful shutdown: {err}"
));
return;
}
}
}
append_log("[sidecar] graceful shutdown timed out (~2.5s); killing");
let _ = guard.start_kill();
}
// Job Object on Windows / process group on Unix — kill propagates to the
// sidecar's grandchildren (the spawned shells). On Unix this is SIGKILL to
// the whole process group, which is more thorough than the previous
// SIGTERM-to-just-node path that left node-pty grandchildren orphaned.
//
// The updater calls this before launching the Windows NSIS installer: NSIS
// overwrites files inside the bundled sidecar (e.g. node-pty's `conpty.node`),
// and Windows refuses to overwrite a native module the live sidecar still has
// loaded — surfacing as "Error opening file for writing". Releasing those
// handles first requires the node process to be gone, not merely signalled.
//
// We poll `try_wait` rather than block on `wait()`: `try_wait` is idempotent
// and can't hang, whereas the job-object `wait()` consumes a completion-port
// message the reaper thread may already have drained (e.g. if the sidecar had
// crashed earlier), which would block forever. The ~5s cap means a wedged
// sidecar can't stall quit indefinitely.
fn kill_sidecar_and_wait(child: &SharedChild) {
// Poll for exit at this cadence, up to ~5s total (MAX_POLLS × POLL_INTERVAL).
const POLL_INTERVAL: Duration = Duration::from_millis(20);
const MAX_POLLS: u32 = 250;
let Ok(mut guard) = child.lock() else { return };
append_log(format!(
"[sidecar] killing and waiting for exit (pid={})",
guard.id()
));
let _ = guard.start_kill();
for _ in 0..MAX_POLLS {
match guard.try_wait() {
Ok(Some(status)) => {
append_log(format!("[sidecar] confirmed exit during kill (status: {status})"));
return;
}
Ok(None) => std::thread::sleep(POLL_INTERVAL),
Err(err) => {
append_log(format!("[sidecar] wait error during kill: {err}"));
return;
}
}
}
append_log("[sidecar] kill wait timed out (~5s); proceeding anyway");
}
#[derive(Serialize, Deserialize, Clone)]
struct ShellInfo {
name: String,
path: String,
#[serde(default)]
args: Vec<String>,
}
#[tauri::command(async)]
fn get_available_shells(state: tauri::State<'_, SidecarState>) -> Result<Vec<ShellInfo>, String> {
let response = request_from_sidecar_timeout(&state, "pty:getShells", serde_json::json!({}), Duration::from_secs(10))?;
let shells: Vec<ShellInfo> = response
.get("shells")
.and_then(|v| serde_json::from_value(v.clone()).ok())
.unwrap_or_default();
Ok(shells)
}
fn resolve_sidecar_path(resource_dir: Option<PathBuf>, manifest_dir: &Path) -> PathBuf {
if let Some(ref dir) = resource_dir {
// Tauri maps `../sidecar` to `_up_/sidecar` when bundling resources
for prefix in &["sidecar", "_up_/sidecar"] {
let path = dir.join(prefix).join("main.js");
if path.is_file() {
// resource_dir() hands back a `\\?\` verbatim path in the
// bundled/dev layout. Normalize once here, at the boundary, so
// every consumer (the node script arg, the dor-cli paths derived
// from this path's parent) gets a plain path. cmd.exe can't
// execute a batch file via a verbatim path; Rust's APIs accept
// both, so stripping is always safe.
return strip_windows_verbatim_prefix(&path.to_string_lossy()).unwrap_or(path);
}
}
}
manifest_dir.join("..").join("sidecar").join("main.js")
}
fn strip_windows_verbatim_prefix(path_string: &str) -> Option<PathBuf> {
if let Some(stripped) = path_string.strip_prefix(r"\\?\UNC\") {
return Some(PathBuf::from(format!(r"\\{stripped}")));
}
if let Some(stripped) = path_string.strip_prefix(r"\\?\") {
return Some(PathBuf::from(stripped));
}
None
}
fn resolve_node_binary_path() -> Result<PathBuf, String> {
let exe = env::current_exe().map_err(|e| format!("current_exe: {e}"))?;
let dir = exe
.parent()
.ok_or_else(|| "current_exe has no parent".to_string())?;
find_node_binary(dir, env!("TAURI_ENV_TARGET_TRIPLE"))
.ok_or_else(|| format!("node sidecar not found in {}", dir.display()))
}
// tauri-bundler sometimes strips the target-triple suffix (e.g. install dir
// has `node.exe`, dev/bundle has `node-x86_64-pc-windows-msvc.exe`).
fn find_node_binary(dir: &Path, target_triple: &str) -> Option<PathBuf> {
let suffix = if cfg!(windows) { ".exe" } else { "" };
let candidates = [
dir.join(format!("node-{target_triple}{suffix}")),
dir.join(format!("node{suffix}")),
];
candidates.into_iter().find(|p| p.is_file())
}
// The node the `dor` CLI runs under. On Windows the bundled node.exe is patched
// to the GUI subsystem at build time (build.rs `force_windows_gui_subsystem`) so
// spawning the sidecar from our GUI process doesn't trigger Win11's DefTerm
// handoff and flash a stray terminal window. A GUI-subsystem node, however, does
// not attach to an *inherited* console: when `dor` runs inside a shell's ConPTY