Repository navigation
Expand file tree
/
Copy pathrouting.rs
More file actions
2165 lines (2049 loc) · 78.7 KB
/
Copy pathrouting.rs
File metadata and controls
2165 lines (2049 loc) · 78.7 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
//! Where a written capture goes among OpenCode sessions: Scrawl's router
//! (`crates/router`) run in Hex's process with `capture.routing` and
//! Scrawl's own router folders, so `scrawl router undo`, Scrawl's rule
//! offers, and its evals see Hex's sends as Scrawl's.
//!
//! The collector starts a [`Look`] at the tab, terminal, and sessions the
//! moment a capture stops, beside its writing. Once it is written, the
//! finisher hands it to the one `capture-route` thread ([`Routes`]), which
//! decides, sends a saved rule's answer at once, and carries out the
//! capsule's Send and Undo for the newest capture, in the order
//! they came. Every change lands in the snapshot's `last.route`.
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::mpsc::{self, Receiver, RecvTimeoutError, SyncSender, TrySendError};
use std::thread::{self, JoinHandle};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use scrawl_capture::capture::RouteContext;
use scrawl_capture::delivery::{self, Delivery};
use scrawl_capture::model::{Destination, ScrawlBundle};
use scrawl_capture::routing::{self, Shown, jev, look, policy, smart, undo};
use scrawl_capture::{Router, RouterConfig, RouterDirs, RuleKind, Undone};
use super::{SharedOutcomes, lock};
/// How often sends OpenCode didn't take are retried.
const RETRY_EVERY: Duration = Duration::from_secs(15);
/// How long taking back a send may wait on OpenCode.
const UNDO_DEADLINE: Duration = Duration::from_secs(10);
const QUEUE: usize = 16;
// ---------------------------------------------------------------------------
// What views see.
/// A written capture's route: the router's answer and what became of the
/// send.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CaptureRoute {
pub answer: RouteAnswer,
pub delivery: Option<RouteDelivery>,
/// The site or app a rule could now send straight to where this
/// capture went, as two sends agreed: `Send { to: <that session>,
/// always: true }` saves it.
pub offer: Option<String>,
}
impl CaptureRoute {
fn of(answer: RouteAnswer) -> Self {
Self {
answer,
delivery: None,
offer: None,
}
}
/// The written capture, while the router works out where it goes.
pub(super) fn looking() -> Self {
Self::of(RouteAnswer::Looking)
}
}
/// The route of a capture the router never got to.
pub(super) fn unrouted() -> CaptureRoute {
CaptureRoute::of(RouteAnswer::NoAnswer { recent: Vec::new() })
}
/// An OpenCode session a capture can go to.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct RouteDest {
pub session: String,
/// The session's title as the router labels it.
pub name: String,
/// A quiet word on why: `rule`, `dev server`, `guess`, `2 min ago`.
pub why: String,
}
/// `recent` is every other session the look read, newest first.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum RouteAnswer {
/// Written; the router is still working.
Looking,
/// A rule the person saved (`routing.sites` or `routing.apps`, a
/// Shift pick's among them) says where it goes: sent to `to`
/// at once, and the capsule's Undo takes it back. `site` is what the
/// rule matches, for an always-rule sending it elsewhere instead.
Rule {
to: RouteDest,
suggested: Vec<RouteDest>,
recent: Vec<RouteDest>,
site: Option<String>,
},
/// Guesses, best first: everything else the router found (Jev's pick,
/// HOME when Jev couldn't tell, a dev server's port, a page or its
/// publisher, a name that was said). Nothing is sent until one is
/// picked; picking one with `always` saves a rule for `site`, which is
/// what an always-rule would match (the site's host or the app's name),
/// `None` when no rule can be made.
Guess {
suggested: Vec<RouteDest>,
recent: Vec<RouteDest>,
site: Option<String>,
},
/// Nothing fits: recent sessions only.
Nothing { recent: Vec<RouteDest> },
/// The router failed.
NoAnswer { recent: Vec<RouteDest> },
/// OpenCode's sessions couldn't be read, so there is nowhere to offer;
/// `why` says what went wrong in a few words ("didn't answer in time").
Unreachable { why: String },
}
/// What became of a capture's send; `to` is the session's name.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum RouteDelivery {
Sending {
to: String,
},
Sent {
to: String,
},
/// OpenCode didn't take it; retried every 15 s. `why` says what went
/// wrong in a few words ("OpenCode isn't running").
Queued {
to: String,
why: String,
},
/// Never sent, withdrawn, reverted, or disowned.
TakenBack,
/// The session already acted on it.
TooLate {
to: String,
},
Failed {
to: String,
why: String,
},
}
// ---------------------------------------------------------------------------
// The router.
/// The router with Hex's `capture.routing` and Scrawl's folders under
/// `~/Library/Application Support/scrawl`. Never reads
/// `~/.config/scrawl`. Its own log lines name sites and sessions, so they
/// go to tracing's debug level, except how sends went (`deliver: …`).
pub fn router() -> Router {
let settings = crate::app_settings::capture_settings();
let config = settings.routing.config().clone();
let support = dirs::home_dir()
.unwrap_or_default()
.join("Library/Application Support/scrawl");
let dirs = RouterDirs::under(
&support.join("router"),
Some(support.join("routing-decisions.jsonl")),
Some(settings.captures_dir()),
);
Router::new(config, dirs)
.with_log(|line| {
if line.starts_with("deliver:") {
tracing::info!(line, "capture router");
} else {
tracing::debug!(line, "capture router");
}
})
.with_summary(scrawl_capture::sketch::summary_markdown)
}
fn sends(config: &RouterConfig) -> bool {
config.send_captures && std::env::var_os("SCRAWL_NO_OPENCODE").is_none() && !opencode_managed()
}
/// Whether an organization turned OpenCode processing off, which includes
/// sending captures to OpenCode sessions (`DisableOpenCodeProcessing`).
fn opencode_managed() -> bool {
crate::policy::Policy::current().locks(crate::policy::Lock::OpenCodeProcessing)
}
/// The tab, terminal, and sessions behind a capture that just stopped,
/// read while it is written.
pub(super) struct Look {
router: Router,
seen: Receiver<Option<look::Live>>,
/// When routing stops waiting for it.
until: Instant,
}
/// How long past its deadline a look's last step may run before routing
/// goes on without it.
const LOOK_GRACE: Duration = Duration::from_secs(1);
/// Starts looking, or `None` when captures aren't sent (`autoSend` off).
/// The whole look has [`look::LOOK_DEADLINE`]: the steps not begun by then
/// are skipped, and routing waits at most [`LOOK_GRACE`] more for the one
/// under way (the tab's osascript, 6 s at worst), then goes on without it.
pub(super) fn look(context: RouteContext) -> Option<Look> {
look_with(context, router(), look::Senses::default())
}
fn look_with(context: RouteContext, router: Router, senses: look::Senses) -> Option<Look> {
if !sends(router.config()) {
return None;
}
let deadline = Instant::now() + look::LOOK_DEADLINE;
let (found, seen) = mpsc::sync_channel(1);
{
let router = router.clone();
thread::Builder::new()
.name("capture-look".into())
.spawn(move || {
let live = router.run(|| {
routing::look_capture(
context.front_bundle_id.as_deref(),
context.captured_bundle_id.as_deref(),
context.app_pid,
deadline,
&senses,
)
});
let _ = found.try_send(live);
})
.inspect_err(|error| tracing::warn!(%error, "could not look for a capture's route"))
.ok()?;
}
Some(Look {
router,
seen,
until: deadline + LOOK_GRACE,
})
}
// ---------------------------------------------------------------------------
// The capture-route thread.
pub(super) enum Job {
Written {
bundle: PathBuf,
look: Look,
},
Send {
to: String,
always: bool,
},
Undo,
/// `hex capture send`: any capture, to `to` or where its route or its
/// last send says.
#[cfg_attr(target_os = "windows", allow(dead_code))]
SendBundle {
bundle: PathBuf,
to: Option<String>,
always: bool,
reply: SyncSender<Result<String, String>>,
},
}
/// The running host's route queue, for `hex capture send`, with the
/// [`Routes`] it belongs to.
static JOBS: Mutex<Option<(u64, SyncSender<Job>)>> = Mutex::new(None);
static NEXT_ROUTES: AtomicU64 = AtomicU64::new(0);
/// How long `hex capture send` waits for the send, inside the control
/// deadline.
#[cfg_attr(target_os = "windows", allow(dead_code))]
const CLI_WAIT: Duration = Duration::from_secs(8);
/// Sends `bundle` through the `capture-route` thread and says what became
/// of it: as the capsule's pick when it is the newest capture, so its
/// route and Undo follow.
#[cfg_attr(target_os = "windows", allow(dead_code))]
pub(super) fn send_bundle(
bundle: PathBuf,
to: Option<String>,
always: bool,
) -> Result<String, String> {
let jobs = JOBS
.lock()
.unwrap_or_else(|error| error.into_inner())
.as_ref()
.map(|(_, jobs)| jobs.clone())
.ok_or("captures are off")?;
let (reply, answer) = mpsc::sync_channel(1);
let job = Job::SendBundle {
bundle,
to,
always,
reply,
};
if !send(&jobs, job) {
return Err("the capture router is busy; try again shortly".into());
}
answer
.recv_timeout(CLI_WAIT)
.unwrap_or_else(|_| Ok("Still sending; `hex capture show` tells how it went".into()))
}
/// The `capture-route` thread and its queue.
pub(super) struct Routes {
id: u64,
jobs: SyncSender<Job>,
thread: JoinHandle<()>,
}
impl Routes {
pub(super) fn start(outcomes: SharedOutcomes) -> std::io::Result<Self> {
let (jobs, queued) = mpsc::sync_channel(QUEUE);
let thread = thread::Builder::new()
.name("capture-route".into())
.spawn(move || Worker::new(outcomes).run(&queued))?;
let id = NEXT_ROUTES.fetch_add(1, Ordering::Relaxed);
*JOBS.lock().unwrap_or_else(|error| error.into_inner()) = Some((id, jobs.clone()));
Ok(Self { id, jobs, thread })
}
pub(super) fn jobs(&self) -> SyncSender<Job> {
self.jobs.clone()
}
/// Queues `job` without waiting; a full queue drops it.
pub(super) fn send(&self, job: Job) -> bool {
send(&self.jobs, job)
}
/// Ends the thread once its queue is empty and every other sender is
/// gone.
pub(super) fn stop(self, deadline: Instant) {
let mut global = JOBS.lock().unwrap_or_else(|error| error.into_inner());
if global.as_ref().is_some_and(|(id, _)| *id == self.id) {
*global = None;
}
drop(global);
drop(self.jobs);
super::join_by(self.thread, deadline, "capture-route");
}
}
pub(super) fn send(jobs: &SyncSender<Job>, job: Job) -> bool {
match jobs.try_send(job) {
Ok(()) => true,
Err(TrySendError::Full(_)) => {
tracing::warn!("the capture router is behind; dropping a request");
false
}
Err(TrySendError::Disconnected(_)) => false,
}
}
/// The newest routed capture, which the capsule's commands act on.
struct Routed {
bundle: PathBuf,
router: Router,
url: Option<String>,
app: Option<String>,
/// What an always-rule would match.
rule: Option<(RuleKind, String)>,
candidates: Vec<smart::Candidate>,
route: CaptureRoute,
/// How to take the send back, once OpenCode took it.
sent: Option<Sent>,
/// The rule offered after the send ([`CaptureRoute::offer`]).
offered: Option<scrawl_capture::OfferRule>,
/// The rule a Shift pick saved with this send, which Undo takes back.
saved: Option<SavedRule>,
}
/// A rule saved with a send, and what its key held before.
struct SavedRule {
kind: RuleKind,
key: String,
before: Option<String>,
was_refused: bool,
}
struct Sent {
delivery_id: String,
session: String,
}
/// Posts a capture to an OpenCode session.
type Forward = fn(&Path, &str) -> anyhow::Result<scrawl_capture::handoff::Posted>;
struct Worker {
outcomes: SharedOutcomes,
current: Option<Routed>,
retry_at: Instant,
forward: Forward,
}
impl Worker {
fn new(outcomes: SharedOutcomes) -> Self {
Self {
outcomes,
current: None,
retry_at: Instant::now() + RETRY_EVERY,
forward: scrawl_capture::handoff::send_bundle,
}
}
fn run(mut self, jobs: &Receiver<Job>) {
loop {
match jobs.recv_timeout(self.retry_at.saturating_duration_since(Instant::now())) {
Ok(job) => self.handle(job),
Err(RecvTimeoutError::Timeout) => {}
Err(RecvTimeoutError::Disconnected) => break,
}
if Instant::now() >= self.retry_at {
self.retry();
self.retry_at = Instant::now() + RETRY_EVERY;
}
}
}
fn handle(&mut self, job: Job) {
match job {
Job::Written { bundle, look } => self.written(bundle, look),
Job::Send { to, always } => self.chosen(&to, always),
Job::Undo => self.undo(),
Job::SendBundle {
bundle,
to,
always,
reply,
} => {
let _ = reply.try_send(self.send_bundle(&bundle, to.as_deref(), always));
}
}
}
/// `hex capture send`: the newest capture as the capsule's pick, any
/// other straight to `to` or where it last went. `always` (newest only)
/// also saves a rule for its site or app, as the capsule's ⇧⏎ does.
fn send_bundle(
&mut self,
bundle: &Path,
to: Option<&str>,
always: bool,
) -> Result<String, String> {
// Named by the CLI, the routed capture is acted on even when a newer
// one has taken the capsule.
if self.is_current(bundle) {
let current = self.current.as_ref().ok_or("no capture")?;
let to = match to {
Some(to) => to.to_owned(),
None => match ¤t.route.answer {
RouteAnswer::Rule { to, .. } => to.session.clone(),
RouteAnswer::Guess { suggested, .. } if !suggested.is_empty() => {
suggested[0].session.clone()
}
_ => recorded_destination(bundle)
.map(|dest| dest.session)
.ok_or("its route names no session; say where with --to")?,
},
};
let Some(dest) = self.listed_as(&to) else {
return Err(format!("{to} isn't a session this capture lists"));
};
if always && current.rule.is_none() && current.offered.is_none() {
return Err("no rule can be made for this capture's site or app".into());
}
self.choose(dest, always);
let current = self.current.as_ref().ok_or("no capture")?;
return Ok(current
.route
.delivery
.as_ref()
.map_or_else(|| "Nothing sent".into(), describe));
}
if always {
return Err("only the last routed capture can save a rule".into());
}
let dest = match to {
Some(to) if to.starts_with("ses") => Destination {
session: to.to_owned(),
title: to.to_owned(),
via: "chosen".into(),
url: None,
directory: None,
},
Some(_) => return Err("an older capture is sent to a session id (ses…)".into()),
None => recorded_destination(bundle)
.ok_or("it was never sent anywhere; say where with --to")?,
};
let loaded = scrawl_capture::handoff::load_bundle(bundle)
.map_err(|error| format!("couldn't read the capture: {error:#}"))?;
let (delivery, _, _) = deliver(&router(), bundle, &dest, loaded.1.target.app, self.forward);
tracing::info!(
bundle = %bundle_name(bundle),
session = dest.session,
delivery = delivery_kind(&delivery),
"capture sent from the CLI"
);
match delivery {
RouteDelivery::Failed { why, .. } => Err(why),
delivery => Ok(describe(&delivery)),
}
}
fn written(&mut self, bundle: PathBuf, look: Look) {
let Look {
router,
seen,
until,
} = look;
let live = seen
.recv_timeout(until.saturating_duration_since(Instant::now()))
.unwrap_or_else(|error| {
match error {
RecvTimeoutError::Timeout => {
tracing::warn!("looking for a capture's route took too long");
}
RecvTimeoutError::Disconnected => {
tracing::error!("looking for a capture's route panicked");
}
}
None
});
let loaded = scrawl_capture::handoff::load_bundle(&bundle)
.map(|(_, loaded)| loaded)
.inspect_err(|error| tracing::warn!(error = %format!("{error:#}"), "could not read a capture to route"))
.ok();
let candidates = live
.as_ref()
.map(|live| live.candidates.clone())
.unwrap_or_default();
if let Some(live) = &live
&& let Some(error) = &live.error
{
tracing::warn!(
bundle = %bundle_name(&bundle),
error,
read = live.candidates.len(),
"a capture's look couldn't read all of OpenCode's sessions"
);
}
let unread = live.as_ref().and_then(sessions_unread);
// Judged even without the sessions: a rule, page, or publisher names
// one outright, and the record keeps what was seen for a replay.
let (decision, url) = router.run(|| match (live, &loaded) {
(Some(live), Some(loaded)) => {
let (judgement, url) = routing::judge_capture(&bundle, loaded, live);
(judged(judgement.decision, unread.as_deref()), url)
}
(Some(live), None) => (Decided::Failed, live.url),
(None, _) => (Decided::Failed, None),
});
let bundle_id = loaded
.as_ref()
.and_then(|loaded| loaded.target.bundle_id.clone());
let app = loaded.as_ref().and_then(|loaded| loaded.target.app.clone());
let rule = policy::rule_key(url.as_deref(), bundle_id.as_deref());
let site = rule.as_ref().map(|(kind, key)| match kind {
RuleKind::Site => key
.split_once("://")
.map_or(key.as_str(), |(_, host)| host)
.to_owned(),
RuleKind::App => app.clone().unwrap_or_else(|| key.clone()),
});
let Answered {
answer,
send: rule_send,
shown,
} = answer_for(decision, url.as_deref(), site, &candidates, now_ms());
tracing::info!(
bundle = %bundle_name(&bundle),
answer = answer_kind(&answer),
why = shown.as_ref().map(|shown| shown.why.as_str()),
"capture routed"
);
if let Some(shown) = &shown
&& let Err(error) = routing::record_shown(&bundle, shown)
{
tracing::warn!(error = %format!("{error:#}"), "could not record how a capture's route was shown");
}
self.current = Some(Routed {
bundle,
router,
url,
app,
rule,
candidates,
route: CaptureRoute::of(answer),
sent: None,
offered: None,
saved: None,
});
self.publish();
// A saved rule sends at once; the capsule's Undo takes it back.
if let Some(dest) = rule_send {
self.send_current(dest, None);
}
}
/// The capsule's pick: sends the newest capture to `to` now, after
/// taking back a send elsewhere. `always` also saves a rule for its
/// site or app.
fn chosen(&mut self, to: &str, always: bool) {
if let Some(dest) = self.resolve(to) {
self.choose(dest, always);
}
}
fn choose(&mut self, dest: Destination, always: bool) {
let Some(current) = self.current.as_ref() else {
return;
};
let already = match (¤t.sent, ¤t.route.delivery) {
(Some(sent), _) => Some(sent.session == dest.session),
(None, Some(RouteDelivery::Queued { .. })) => Some(false),
_ => None,
};
if always {
self.save_rule(&dest.session);
}
match already {
// Accepting the offered rule, or a second click.
Some(true) => {}
Some(false) => self.redirect_to(dest),
None => {
self.correct(jev::Action::Redirect, "chip", Some(&dest));
self.send_current(dest, Some("chosen"));
}
}
}
fn redirect_to(&mut self, dest: Destination) {
self.take_back();
self.correct(jev::Action::Redirect, "reroute", Some(&dest));
self.send_current(dest, Some("chosen"));
}
fn undo(&mut self) {
if !self.acting_on_last() {
return;
}
if let Some(saved) = self
.current
.as_mut()
.and_then(|current| current.saved.take())
{
forget_rule(&saved);
}
if self.take_back() {
self.publish();
}
}
/// Takes back the current capture's send, whatever state it is in;
/// `false` when there was none. One OpenCode wouldn't give back is too
/// late.
fn take_back(&mut self) -> bool {
let Some(current) = self.current.as_mut() else {
return false;
};
let to = delivered_to(current.route.delivery.as_ref());
if let Some(sent) = current.sent.take() {
let undone = current.router.undo(&sent.delivery_id, UNDO_DEADLINE);
let delivery = match undone {
Ok(report) if report.undone != Undone::Unfinished => {
tracing::info!(
bundle = %bundle_name(¤t.bundle),
undone = report.undone.label(),
"capture send taken back"
);
match report.undone {
Undone::Withdrawn | Undone::Reverted | Undone::Disowned => {
RouteDelivery::TakenBack
}
Undone::Gone | Undone::TooOld | Undone::Unfinished => {
RouteDelivery::TooLate {
to: to.unwrap_or_default(),
}
}
}
}
// Still where it went (or staged for removal, which
// another undo can finish): the capsule, already showing
// it taken back, hears that it's too late.
failed => {
let error = match failed {
Ok(report) => report.text(),
Err(error) => format!("{error:#}"),
};
tracing::warn!(error = %error, "could not take a capture's send back");
current.sent = Some(sent);
current.route.delivery = Some(RouteDelivery::TooLate {
to: to.unwrap_or_default(),
});
return true;
}
};
current.route.offer = None;
current.offered = None;
current.route.delivery = Some(delivery);
return true;
}
if matches!(current.route.delivery, Some(RouteDelivery::Queued { .. })) {
// Its retries stop with the marker.
let _ = std::fs::remove_file(current.bundle.join(delivery::PENDING));
self.correct(jev::Action::Cancel, "dismiss", None);
self.set_delivery(RouteDelivery::TakenBack);
return true;
}
false
}
fn send_current(&mut self, mut dest: Destination, via: Option<&str>) {
if let Some(via) = via {
via.clone_into(&mut dest.via);
}
self.set_delivery(RouteDelivery::Sending {
to: dest.title.clone(),
});
self.publish();
let Some(current) = self.current.as_mut() else {
return;
};
let (delivery, sent, offered) = deliver(
¤t.router,
¤t.bundle,
&dest,
current.app.clone(),
self.forward,
);
tracing::info!(
bundle = %bundle_name(¤t.bundle),
session = dest.session,
delivery = delivery_kind(&delivery),
"capture sent"
);
current.sent = sent;
current.route.offer = offered.as_ref().map(|offer| offer.key.clone());
current.offered = offered;
current.route.delivery = Some(delivery);
self.publish();
}
/// Saves an always-rule from the current capture's site or app to
/// `session`'s project (or the session itself), on top of what
/// `settings.json` holds now.
fn save_rule(&mut self, session: &str) {
let Some((kind, key, target)) = self.rule_for(session) else {
tracing::info!("no rule can be made for this capture");
return;
};
let mut saved = None;
let result = edit_routing(|config| {
let key = key.trim();
saved = Some(SavedRule {
kind,
key: key.to_owned(),
before: rules_of(config, kind).get(key).cloned(),
was_refused: config.refused_rules.iter().any(|k| k == key),
});
config
.with_rule(kind, key, &target)
.map_err(|error| color_eyre::eyre::eyre!("{error:#}"))
});
match result {
Ok(()) => {
tracing::info!("saved a capture routing rule");
if let Some(current) = self.current.as_mut() {
current.saved = saved;
}
}
Err(error) => tracing::warn!(%error, "could not save a capture routing rule"),
}
}
/// The always-rule sending the current capture's site or app to
/// `session` itself: its site or app, else the key of the rule offered
/// after its send. Never `session`'s folder: a folder rule sends to the
/// newest session in that repository, which is another session
/// whenever two work in it (a worktree's beside its main checkout's).
fn rule_for(&self, session: &str) -> Option<(RuleKind, String, String)> {
let current = self.current.as_ref()?;
let (kind, key) = current.rule.clone().or_else(|| {
let offer = current.offered.as_ref()?;
Some((offer.kind, offer.key.clone()))
})?;
Some((kind, key, session.to_owned()))
}
/// Logs the person correcting or confirming the router (with Jev routing
/// on); `detail` is how (`chip`, `reroute`, `dismiss`).
fn correct(&self, action: jev::Action, detail: &str, to: Option<&Destination>) {
if let Some(current) = &self.current {
current.router.run(|| {
jev::correct_capture(
¤t.bundle,
action,
detail,
to.map(|to| (to.session.as_str(), to.title.as_str())),
);
});
}
}
/// The session `to` names for the newest capture: a session ID, or a
/// name from its route, suggestions first. `None` (logged) when there
/// is no routed capture or nothing matches.
fn resolve(&self, to: &str) -> Option<Destination> {
if !self.acting_on_last() {
return None;
}
self.listed_as(to)
}
/// The routed capture's session named `to`: listed by id or title, or
/// any session id.
fn listed_as(&self, to: &str) -> Option<Destination> {
let current = self.current.as_ref()?;
let to = to.trim();
let listed = listed(¤t.route.answer);
let found = listed.iter().find(|dest| dest.session == to).or_else(|| {
listed
.iter()
.find(|dest| dest.name.eq_ignore_ascii_case(to))
});
let (session, title) = match found {
Some(dest) => (dest.session.clone(), dest.name.clone()),
None if to.starts_with("ses") => (to.to_owned(), to.to_owned()),
None => {
tracing::info!("the capsule named a session the route doesn't list");
return None;
}
};
let directory = current
.candidates
.iter()
.find(|candidate| candidate.id == session)
.and_then(|candidate| candidate.directory.as_ref())
.map(|dir| dir.display().to_string());
Some(Destination {
session,
title,
via: "chosen".into(),
url: current.url.clone(),
directory,
})
}
/// Commands act on the snapshot's newest capture only, and only when
/// it is the one routed.
fn acting_on_last(&self) -> bool {
let last = lock(&self.outcomes)
.last
.as_ref()
.map(|last| last.bundle.clone());
self.current
.as_ref()
.is_some_and(|current| Some(¤t.bundle) == last.as_ref())
}
fn is_current(&self, bundle: &Path) -> bool {
self.current
.as_ref()
.is_some_and(|current| current.bundle == bundle)
}
fn set_delivery(&mut self, delivery: RouteDelivery) {
if let Some(current) = self.current.as_mut() {
current.route.delivery = Some(delivery);
}
}
fn publish(&self) {
if let Some(current) = &self.current {
lock(&self.outcomes).routed(¤t.bundle, current.route.clone());
}
}
/// Retries sends OpenCode didn't take, unless another process owns
/// retries: Scrawl's app, or anything serving Scrawl's ingest port.
fn retry(&mut self) {
if cfg!(test)
|| opencode_managed()
|| crate::app_settings::scrawl_app_running()
|| ingest_port_served()
{
return;
}
let router = router();
let captures = crate::app_settings::capture_settings().captures_dir();
let report = router.run(|| {
delivery::retry_due(
&captures,
now_ms(),
scrawl_capture::handoff::send_bundle_to_session,
)
});
let outbox = router.retry_outbox();
if !report.sent.is_empty() || !outbox.sent.is_empty() {
tracing::info!(
captures = report.sent.len(),
prompts = outbox.sent.len(),
"retried sends went"
);
}
let sent_now = self
.current
.as_ref()
.is_some_and(|current| report.sent.iter().any(|(dir, _)| *dir == current.bundle));
if sent_now
&& let Some(current) = self.current.as_mut()
&& let Some(RouteDelivery::Queued { to, .. }) = current.route.delivery.take()
{
current.route.delivery = Some(RouteDelivery::Sent { to });
self.publish();
}
}
}
/// What the router made of a capture, before it is shown.
enum Decided {
Judged(smart::Decision),
/// OpenCode's sessions couldn't be read: why, in a few words.
Unreachable(String),
Failed,
}
/// Why a look read no sessions at all, when its read failed.
fn sessions_unread(live: &look::Live) -> Option<String> {
live.candidates
.is_empty()
.then(|| live.error.clone())
.flatten()
}
/// A decision as shown: nowhere to go for want of the sessions reads
/// Unreachable; anything a clue named outright still routes.
fn judged(decision: smart::Decision, unread: Option<&str>) -> Decided {
match (decision, unread) {
(smart::Decision::Keep { .. }, Some(error)) => Decided::Unreachable(unreachable_why(error)),
(decision, _) => Decided::Judged(decision),
}
}
/// A failed session read (`couldn't list sessions: …`, outer context
/// first) in the few words the capsule shows under "Couldn't reach
/// OpenCode".
fn unreachable_why(error: &str) -> String {
let error = ["couldn't list sessions: ", "couldn't list every session: "]
.into_iter()
.find_map(|prefix| error.strip_prefix(prefix))
.unwrap_or(error);
if error.contains("didn't answer in time") || error.contains("took over") {
"didn't answer in time".into()
} else if error.contains("Could not reach server") {
"it isn't running".into()
} else {
error.to_owned()
}
}
/// A send to an OpenCode server on another Mac, with no agent host to copy
/// the bundle there first.
const FILES_UNSEEN: &str = "OpenCode can't see files";
/// A failed send (`{err:#}`, outer context first) in the few words the
/// capsule shows under "Copied". What OpenCode said comes first: it was
/// reached. `agent_host` is whether bundles are copied to its Mac first.
fn send_why(error: &str, agent_host: bool) -> String {
let fit = |line: &str| match line.char_indices().nth(60) {
Some((end, _)) => format!("{}…", &line[..end]),
None => line.to_owned(),
};
// The server reads the contact sheet from its own disk.
if error.contains("Unable to read attachment") && !agent_host {
return FILES_UNSEEN.into();
}
if error.contains("HTTP 404") {
return "session not found".into();
}
if let Some(said) = error.strip_prefix("OpenCode said: ") {
let said = said.split(": OpenCode API failed").next().unwrap_or(said);
return fit(said.lines().next().unwrap_or(said));
}
if error.starts_with("Could not reach server") {
"OpenCode isn't running".into()
} else if error.contains("didn't answer in time") {
"OpenCode didn't answer".into()
} else {
fit(&delivery::short(error))
}
}
/// `routing.sites` or `routing.apps`, as `kind` says.
fn rules_of(
config: &scrawl_capture::RouterConfig,
kind: RuleKind,
) -> &std::collections::BTreeMap<String, String> {
match kind {
RuleKind::Site => &config.sites,
RuleKind::App => &config.apps,
}
}
/// Saves `settings.json`'s routing as `edit` makes it, then has the app
/// reload its settings.
fn edit_routing(