scv-tools 0.4.9

Workspace-scoped filesystem, process, skill, and agent tools for SCV
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
//! The daemon's workbench: one place that knows every delegated agent, background
//! job, and session of the instance, and lets the owner act on them.
//!
//! What it shows comes from the durable records every SCV process of the
//! instance writes (the job ledger, each run's activity log and state, and
//! the delegation records), so jobs and runs of `scv exec` servers, and of
//! processes that stopped, are listed too. What it does needs the live
//! objects, so only sessions of this process can be acted on: each
//! registers with [`Workbench::register_session`], and its `agent` tool
//! attaches its job store when the registry builds it.
//!
//! The owner acts on:
//!
//! - a conversation: [`Workbench::send`] gives it the owner's prompt as a
//!   new turn, queued behind a running one, or steered into it;
//! - a job: [`Workbench::cancel`] stops it, [`Workbench::resume`] runs an
//!   interrupted one again, [`Workbench::dismiss`] forgets a finished one;
//! - an approval request a background job relayed while the owner watches
//!   ([`Workbench::watch`]): it waits for [`Workbench::approve`] up to
//!   [`ATTENDED_WAIT`], then gets the session's unattended answer;
//! - a conversation taken over in its agent's own terminal
//!   ([`Workbench::attach_terminal`], or [`Workbench::interrupt_and_attach`],
//!   which stops the job running its turn once its lane is held): the owner
//!   reads its screen and types into it ([`Workbench::attach_io`]), detaches
//!   while it keeps running ([`Workbench::detach`]), and ends it
//!   ([`Workbench::end_takeover`]). A takeover ends with its session, and
//!   with the daemon. The snapshot says of each conversation whether it can
//!   be taken over now, and why not.

use std::{
    collections::{BTreeMap, HashMap, HashSet},
    path::{Path, PathBuf},
    sync::{
        Arc, Mutex, Weak,
        atomic::{AtomicBool, Ordering},
    },
    time::{Duration, Instant, SystemTime, UNIX_EPOCH},
};

use async_trait::async_trait;
use scv_client::Layout;
use scv_core::{AgentError, ApprovalGate, ApprovalRequest};
use scv_protocol::{
    AgentState, AttachOffer, AttachPage, AttachState, JobResult, MAX_JOB_RESULT_BYTES, RunLogPage,
    SendMode, WorkbenchApproval, WorkbenchJob, WorkbenchRun, WorkbenchSession, WorkbenchSnapshot,
};
use serde_json::{Value, json};
use tokio::sync::oneshot;
use tokio_util::sync::CancellationToken;

use crate::{
    delegate::{
        activity::{self, RunState},
        background::{
            BackgroundCapable, BackgroundJobs, JobMeta, LiveJob, OwnerCall,
            ledger::{self, JobRecord},
        },
        records::{DelegationRegistry, ProcessIdentity},
        takeover::{self, Takeover},
    },
    sync::lock,
};

/// How long a background job's approval request waits for the owner while
/// the owner watches, before it gets the session's unattended answer.
pub const ATTENDED_WAIT: Duration = Duration::from_secs(120);
/// How long one `watch` keeps the owner counted as watching.
pub const WATCH_TTL: Duration = Duration::from_secs(15);
/// Jobs and runs a snapshot lists at most: every unfinished one, then the
/// newest finished ones.
const MAX_LISTED: usize = 200;
/// Finished jobs and ended runs are kept this long.
pub const KEEP: Duration = Duration::from_secs(7 * 24 * 3600);
/// Ended runs kept at most.
pub const MAX_RUNS: usize = 500;
/// How long a client attached to a taken-over terminal counts as watching
/// after its last read: one that stops reading (its dashboard closed or
/// died) is detached, and the agent keeps running.
pub const ATTACH_LEASE: Duration = Duration::from_secs(30);
/// How long a takeover whose terminal closed is kept, so a client still
/// attached reads how it ended.
const CLOSED_KEPT: Duration = Duration::from_secs(60);
/// Takeovers that may run at once.
const MAX_TAKEOVERS: usize = 8;

/// The daemon's workbench.
pub struct Workbench {
    runs: PathBuf,
    jobs: PathBuf,
    worktrees: PathBuf,
    delegations: Arc<DelegationRegistry>,
    inner: Mutex<Inner>,
    watched_until: Mutex<Option<Instant>>,
    /// Jobs being resumed now, `<session>/<job>`: each is resumed once.
    resuming: Mutex<HashSet<String>>,
    /// Conversations taken over in their agents' terminals, by
    /// `<session>/<conversation>`.
    takeovers: Mutex<HashMap<String, Held>>,
    /// Held while a takeover starts, so two `attach`es of one conversation
    /// do not both start one. Attaching to one that runs never waits for it.
    attaching: tokio::sync::Mutex<()>,
    /// SCV is stopping: no takeover starts any more. Set and read with
    /// `takeovers` locked, so none is kept after they all were ended.
    closing: AtomicBool,
}

/// A takeover, and the client attached to it.
struct Held {
    takeover: Arc<Takeover>,
    /// The attached client's hold, and when it last read.
    lease: Option<(String, Instant)>,
    /// When the terminal was first seen closed.
    closed: Option<Instant>,
}

impl std::fmt::Debug for Workbench {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.debug_struct("Workbench").finish_non_exhaustive()
    }
}

#[derive(Default)]
struct Inner {
    sessions: HashMap<String, Slot>,
    approvals: BTreeMap<String, Pending>,
    next: u64,
}

/// A live session of this process.
struct Slot {
    token: u64,
    label: String,
    workspace: PathBuf,
    state: AgentState,
    detail: Option<String>,
    agent: Option<Weak<BackgroundCapable>>,
    jobs: Option<Weak<BackgroundJobs>>,
}

struct Pending {
    info: WorkbenchApproval,
    answer: Option<oneshot::Sender<bool>>,
}

/// A session's place in the workbench while it lives; dropping it removes
/// the session.
pub struct SessionHandle {
    workbench: Weak<Workbench>,
    id: String,
    token: u64,
}

impl std::fmt::Debug for SessionHandle {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("SessionHandle")
            .field("id", &self.id)
            .finish()
    }
}

impl SessionHandle {
    /// What the session is doing: a turn runs, an approval waits for its
    /// client, or it is idle.
    pub fn set_state(&self, state: AgentState, detail: Option<String>) {
        let Some(workbench) = self.workbench.upgrade() else {
            return;
        };
        if let Some(slot) = lock(&workbench.inner).sessions.get_mut(&self.id)
            && slot.token == self.token
        {
            slot.state = state;
            slot.detail = detail;
        }
    }
}

impl Drop for SessionHandle {
    fn drop(&mut self) {
        let Some(workbench) = self.workbench.upgrade() else {
            return;
        };
        let mut inner = lock(&workbench.inner);
        if inner
            .sessions
            .get(&self.id)
            .is_some_and(|slot| slot.token == self.token)
        {
            inner.sessions.remove(&self.id);
            drop(inner);
            // Its conversations go with it, taken over or not.
            workbench.end_takeovers_of(Some(&self.id));
        }
    }
}

/// What [`Workbench::send`] did with the owner's prompt.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Sent {
    /// A background job of the session runs it: `<session>/<job>`.
    Job(String),
    /// It went into the conversation's running turn.
    Steered,
}

/// What a maintenance pass did.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Maintenance {
    /// Jobs found interrupted: their SCV process stopped.
    pub interrupted_jobs: Vec<String>,
    /// Runs found interrupted.
    pub interrupted_runs: Vec<String>,
    /// Old records removed.
    pub pruned: usize,
}

impl Workbench {
    /// The workbench of the instance at `layout`, whose delegated runs
    /// `delegations` records.
    pub fn new(layout: &Layout, delegations: Arc<DelegationRegistry>) -> Arc<Self> {
        Arc::new(Self {
            runs: layout.runs(),
            jobs: layout.jobs(),
            worktrees: layout.worktrees(),
            delegations,
            inner: Mutex::default(),
            watched_until: Mutex::new(None),
            resuming: Mutex::default(),
            takeovers: Mutex::default(),
            attaching: tokio::sync::Mutex::const_new(()),
            closing: AtomicBool::new(false),
        })
    }

    /// Where the job ledger is.
    pub fn jobs_dir(&self) -> &Path {
        &self.jobs
    }

    /// Register a live session; `label` says who it serves.
    pub fn register_session(
        self: &Arc<Self>,
        id: &str,
        label: &str,
        workspace: &Path,
    ) -> SessionHandle {
        let mut inner = lock(&self.inner);
        inner.next += 1;
        let token = inner.next;
        inner.sessions.insert(
            id.to_owned(),
            Slot {
                token,
                label: label.to_owned(),
                workspace: workspace.to_owned(),
                state: AgentState::Idle,
                detail: None,
                agent: None,
                jobs: None,
            },
        );
        SessionHandle {
            workbench: Arc::downgrade(self),
            id: id.to_owned(),
            token,
        }
    }

    /// The `agent` tool and job store of live session `session`.
    pub(crate) fn attach(
        &self,
        session: &str,
        agent: Weak<BackgroundCapable>,
        jobs: Weak<BackgroundJobs>,
    ) {
        if let Some(slot) = lock(&self.inner).sessions.get_mut(session) {
            slot.agent = Some(agent);
            slot.jobs = Some(jobs);
        }
    }

    /// The owner is watching: background approval requests wait for an
    /// answer for the next [`WATCH_TTL`].
    pub fn watch(&self) {
        *lock(&self.watched_until) = Some(Instant::now() + WATCH_TTL);
    }

    fn watched(&self) -> bool {
        lock(&self.watched_until).is_some_and(|until| Instant::now() < until)
    }

    /// The approval gate for background jobs of `session`: `unattended`
    /// decides, except that a request it would deny waits up to
    /// [`ATTENDED_WAIT`] for the owner while the owner watches. It never
    /// denies what `unattended` allows.
    pub fn attended_gate(
        self: &Arc<Self>,
        session: &str,
        unattended: Arc<dyn ApprovalGate>,
    ) -> Arc<dyn ApprovalGate> {
        Arc::new(AttendedGate {
            workbench: Arc::downgrade(self),
            session: session.to_owned(),
            unattended,
        })
    }

    /// Hold `request` of a job of `session` for the owner's answer.
    async fn ask(
        &self,
        session: &str,
        request: ApprovalRequest,
        cancellation: &CancellationToken,
    ) -> Result<bool, AgentError> {
        let (sender, receiver) = oneshot::channel();
        let now = unix_now();
        let id = format!("ap-{}", &uuid::Uuid::new_v4().simple().to_string()[..12]);
        lock(&self.inner).approvals.insert(
            id.clone(),
            Pending {
                info: WorkbenchApproval {
                    id: id.clone(),
                    session: session.to_owned(),
                    job: request.call_id.clone(),
                    name: request.name.clone(),
                    risk: request.risk.as_str().to_owned(),
                    cwd: request.cwd.display().to_string(),
                    summary: request.summary.clone(),
                    since_unix_seconds: now,
                    expires_unix_seconds: now + ATTENDED_WAIT.as_secs(),
                },
                answer: Some(sender),
            },
        );
        // An answer that lands as the deadline fires is still the answer.
        // Closing the receiver and taking anything already sent stops the
        // waiter from reporting a denial after `approve` has sent `true`.
        let mut receiver = receiver;
        let answer = tokio::select! {
            biased;
            answer = &mut receiver => Ok(answer.unwrap_or(false)),
            () = tokio::time::sleep(ATTENDED_WAIT) => {
                receiver.close();
                Ok(receiver.try_recv().unwrap_or(false))
            }
            () = cancellation.cancelled() => {
                receiver.close();
                match receiver.try_recv() {
                    Ok(approved) => Ok(approved),
                    Err(_) => Err(AgentError::Cancelled),
                }
            }
        };
        lock(&self.inner).approvals.remove(&id);
        answer
    }

    /// Answer approval request `id`.
    pub fn approve(&self, id: &str, approved: bool) -> Result<String, String> {
        let pending = lock(&self.inner).approvals.get_mut(id).and_then(|pending| {
            pending
                .answer
                .take()
                .map(|answer| (answer, pending.info.clone()))
        });
        let Some((answer, info)) = pending else {
            return Err(format!(
                "no approval request {id:?} waits; it may have been answered or timed out"
            ));
        };
        if answer.send(approved).is_err() {
            return Err(format!("{} no longer waits for this answer", info.job));
        }
        Ok(format!(
            "{} {}: {}",
            if approved { "Approved" } else { "Denied" },
            info.job,
            bounded(&info.summary, 120)
        ))
    }

    /// Everything the workbench shows now. `restorable` is left for the
    /// server, which keeps session queues.
    pub fn snapshot(&self) -> WorkbenchSnapshot {
        self.expire_takeovers();
        let now = unix_now();
        let live_handles = self.live_handles();
        let (slots, approvals): (Vec<_>, Vec<_>) = {
            let inner = lock(&self.inner);
            (
                inner
                    .sessions
                    .iter()
                    .map(|(id, slot)| SlotView {
                        id: id.clone(),
                        label: slot.label.clone(),
                        workspace: slot.workspace.clone(),
                        state: slot.state,
                        detail: slot.detail.clone(),
                        agent: slot.agent.as_ref().and_then(Weak::upgrade),
                        jobs: slot.jobs.as_ref().and_then(Weak::upgrade),
                    })
                    .collect(),
                inner
                    .approvals
                    .values()
                    .map(|pending| pending.info.clone())
                    .collect(),
            )
        };
        let live_jobs: HashMap<(String, String), LiveJob> = slots
            .iter()
            .filter_map(|slot| {
                slot.jobs
                    .as_ref()
                    .map(|jobs| (slot.id.clone(), jobs.live()))
            })
            .flat_map(|(session, jobs)| {
                jobs.into_iter()
                    .map(move |job| ((session.clone(), job.id.clone()), job))
            })
            .collect();
        let live_sessions: HashSet<&str> = slots.iter().map(|slot| slot.id.as_str()).collect();
        let awaiting: HashMap<(String, String), &WorkbenchApproval> = approvals
            .iter()
            .map(|approval| ((approval.session.clone(), approval.job.clone()), approval))
            .collect();

        // A conversation handle is shown only while the live session that
        // made it still has it, so the owner can send it a prompt: one an
        // earlier daemon, or an earlier session under an ID that came back
        // (a workbench session), left names nothing now. Such a session
        // numbers its conversations after the ones its records name, so a
        // handle never comes to mean another conversation.
        let me = ProcessIdentity::current();
        let held = |owner: &ProcessIdentity, session: &str, handle: &str| {
            me.as_ref() == Some(owner)
                && slots.iter().any(|slot| {
                    slot.id == session
                        && slot.agent.as_ref().is_some_and(|agent| agent.knows(handle))
                })
        };
        // Whether the owner can take each such conversation over now.
        let taken_over = self.running_takeovers();
        let mut offers: HashMap<(String, String), Option<AttachOffer>> = HashMap::new();
        let mut offer = |session: &str, handle: &str| {
            offers
                .entry((session.to_owned(), handle.to_owned()))
                .or_insert_with(|| {
                    let slot = slots.iter().find(|slot| slot.id == session)?;
                    let offer = slot.agent.as_ref()?.attach_offer(handle)?;
                    let approval = offer.job.as_ref().and_then(|job| {
                        awaiting
                            .get(&(session.to_owned(), job.clone()))
                            .map(|approval| approval.id.as_str())
                    });
                    Some(settle_offer(offer, approval, taken_over))
                })
                .clone()
        };
        let mut states = activity::list_states(&self.runs);
        states
            .sort_by_key(|state| std::cmp::Reverse((state.last_activity_unix, state.started_unix)));
        let mut runs: Vec<WorkbenchRun> = Vec::new();
        let mut job_runs: HashMap<(String, String), &RunState> = HashMap::new();
        for state in &states {
            for job in state.jobs.iter().chain(&state.job) {
                job_runs
                    .entry((state.session.clone(), job.clone()))
                    .or_insert(state);
            }
        }
        let mut ended_listed = 0;
        for state in &states {
            if state.ended {
                if ended_listed >= MAX_LISTED {
                    continue;
                }
                ended_listed += 1;
            }
            let (mut current, mut detail) = activity::current(state, now);
            if let Some(job) = &state.job
                && let Some(approval) = awaiting.get(&(state.session.clone(), job.clone()))
                && !state.ended
            {
                current = AgentState::AwaitingInput;
                detail = Some(format!(
                    "waiting for your approval: {}",
                    bounded(&approval.summary, 200)
                ));
            }
            let conversation = state
                .conversation
                .clone()
                .filter(|handle| held(&state.owner, &state.session, handle));
            runs.push(WorkbenchRun {
                handle: state.handle.clone(),
                agent: state.agent.clone(),
                session: state.session.clone(),
                transport: state.transport.clone(),
                attach: conversation
                    .as_deref()
                    .and_then(|handle| offer(&state.session, handle)),
                conversation,
                turn: state.turn,
                job: state.job.clone(),
                jobs: state.jobs.clone(),
                cwd: state.cwd.display().to_string(),
                state: current,
                detail,
                started_unix_seconds: state.started_unix,
                last_activity_unix_seconds: state.last_activity_unix,
                live: !state.ended && live_handles.contains(&state.handle),
                steerable: state.steerable,
            });
        }

        let all = ledger::list_all(&self.jobs);
        let mut records: Vec<&JobRecord> = all.iter().filter(|record| !record.dismissed).collect();
        records.sort_by_key(|record| std::cmp::Reverse((record.created_unix, record.job.clone())));
        let mut jobs = Vec::new();
        let mut finished_listed = 0;
        // What each job was resumed as, by the record of the job resuming
        // it too, which is written first: a dismissed one's included, or
        // the job would be resumable again.
        let successors: HashMap<&str, String> = all
            .iter()
            .filter_map(|record| {
                let from = record.resumed_from.as_deref()?;
                Some((from, format!("{}/{}", record.session, record.job)))
            })
            .collect();
        for &record in &records {
            let key = (record.session.clone(), record.job.clone());
            let resumed_as = record.resumed_as.clone().or_else(|| {
                successors
                    .get(format!("{}/{}", record.session, record.job).as_str())
                    .cloned()
            });
            let live = live_jobs.get(&key);
            let run = job_runs.get(&key).copied();
            let (state, detail) = job_state(
                record,
                live,
                run,
                awaiting.get(&key).copied(),
                live_sessions.contains(record.session.as_str()),
                now,
            );
            // An interrupted job the owner can still resume stays listed
            // after the cap of other finished jobs. Counting it as finished
            // would hide it once newer completions filled the snapshot.
            let resumable_interrupted =
                state == AgentState::Interrupted && resumed_as.is_none() && !record.reviewed;
            if state.is_final() && !resumable_interrupted {
                if finished_listed >= MAX_LISTED {
                    continue;
                }
                finished_listed += 1;
            }
            let cwd = run
                .map(|run| run.cwd.display().to_string())
                .or_else(|| {
                    record
                        .worktree
                        .as_ref()
                        .map(|worktree| worktree.path.clone())
                })
                .unwrap_or_else(|| {
                    let relative = record.arguments.get("cwd").and_then(Value::as_str);
                    relative.map_or_else(
                        || record.workspace.display().to_string(),
                        |cwd| record.workspace.join(cwd).display().to_string(),
                    )
                });
            let conversation = record
                .conversation
                .clone()
                .or_else(|| run.and_then(|run| run.conversation.clone()))
                .or_else(|| {
                    record
                        .arguments
                        .get("session")
                        .and_then(Value::as_str)
                        .map(str::to_owned)
                })
                .filter(|handle| held(&record.owner, &record.session, handle));
            jobs.push(WorkbenchJob {
                session: record.session.clone(),
                job: record.job.clone(),
                agent: record.agent.clone(),
                task: record.task.clone(),
                workspace: record.workspace.display().to_string(),
                cwd,
                state,
                detail,
                started_by: record.started_by,
                attach: conversation
                    .as_deref()
                    .and_then(|handle| offer(&record.session, handle)),
                conversation,
                run: run.map(|run| run.handle.clone()),
                worktree: record.worktree.clone(),
                reviewed: record.reviewed,
                resumable: state == AgentState::Interrupted
                    && !record.reviewed
                    && resumed_as.is_none(),
                resumed_as,
                created_unix_seconds: record.created_unix,
                updated_unix_seconds: record.updated_unix,
            });
        }

        let mut sessions: Vec<WorkbenchSession> = slots
            .iter()
            .map(|slot| WorkbenchSession {
                id: slot.id.clone(),
                label: slot.label.clone(),
                workspace: slot.workspace.display().to_string(),
                live: true,
                state: slot.state,
                detail: slot.detail.clone(),
            })
            .collect();
        let mut seen: HashSet<String> = sessions.iter().map(|session| session.id.clone()).collect();
        for &record in &records {
            if seen.insert(record.session.clone()) {
                let alive = record.owner.is_alive() && record.owner.pid != std::process::id();
                sessions.push(WorkbenchSession {
                    id: record.session.clone(),
                    label: record.label.clone(),
                    workspace: record.workspace.display().to_string(),
                    live: alive,
                    state: AgentState::Unknown,
                    detail: Some(if alive {
                        format!("runs in SCV process {}", record.owner.pid)
                    } else {
                        "ended".to_owned()
                    }),
                });
            }
        }
        sessions.sort_by(|a, b| b.live.cmp(&a.live).then_with(|| a.id.cmp(&b.id)));
        WorkbenchSnapshot {
            generated_unix_seconds: now,
            sessions,
            jobs,
            runs,
            approvals,
            restorable: Vec::new(),
        }
    }

    /// The runs whose processes still run, in any SCV process of the
    /// instance.
    fn live_handles(&self) -> HashSet<String> {
        self.delegations
            .list(true)
            .into_iter()
            .filter(|entry| entry.processes > 0)
            .map(|entry| entry.record.handle)
            .collect()
    }

    /// Refuse to remove the worktree holding `path` while anything still
    /// works in it ([`Self::worktree_users`]).
    pub fn check_worktree_unused(&self, path: &Path) -> Result<(), String> {
        let users = self.worktree_users(path);
        if users.is_empty() {
            return Ok(());
        }
        Err(format!(
            "{} still work in {}; stop them before removing it",
            users.join(", "),
            path.display()
        ))
    }

    /// What still runs in the SCV worktree holding `path` (its top, or any
    /// directory in it): jobs not yet finished that recorded it, and
    /// delegated runs whose processes work inside it.
    pub fn worktree_users(&self, path: &Path) -> Vec<String> {
        let path = crate::delegate::worktree::worktree_path(&self.worktrees, path)
            .or_else(|| std::fs::canonicalize(path).ok())
            .unwrap_or_else(|| path.to_owned());
        let mut users: Vec<String> = ledger::list(&self.jobs)
            .into_iter()
            .filter(|record| {
                !record.state.is_final()
                    && record.owner.is_alive()
                    && record
                        .worktree
                        .as_ref()
                        .is_some_and(|worktree| Path::new(&worktree.path) == path)
            })
            .map(|record| format!("{}/{}", record.session, record.job))
            .collect();
        users.extend(
            self.delegations
                .list(true)
                .into_iter()
                .filter(|entry| entry.processes > 0 && entry.record.cwd.starts_with(&path))
                .map(|entry| entry.record.handle),
        );
        users
    }

    /// One page of run `handle`'s activity log after byte position `after`.
    pub fn run_log(&self, handle: &str, after: u64, limit: usize) -> Result<RunLogPage, String> {
        activity::read_page(&self.runs, handle, after, limit).map_err(|error| {
            if error.kind() == std::io::ErrorKind::NotFound {
                format!("no activity log for run {handle:?}")
            } else {
                format!("cannot read run {handle:?}: {error}")
            }
        })
    }

    /// The `agent` tool of live session `session`.
    fn agent(&self, session: &str) -> Result<(Arc<BackgroundCapable>, PathBuf), String> {
        let inner = lock(&self.inner);
        let slot = inner.sessions.get(session).ok_or_else(|| {
            format!("session {session} does not run in this daemon (it ended, or another SCV process runs it)")
        })?;
        let agent = slot
            .agent
            .as_ref()
            .and_then(Weak::upgrade)
            .ok_or_else(|| format!("session {session} runs no background agent jobs"))?;
        Ok((agent, slot.workspace.clone()))
    }

    /// Give conversation `conversation` of live session `session` the
    /// owner's `prompt`.
    pub async fn send(
        &self,
        session: &str,
        conversation: &str,
        prompt: &str,
        mode: SendMode,
    ) -> Result<Sent, String> {
        let (agent, workspace) = self.agent(session)?;
        let call = agent
            .owner_call(
                json!({"session": conversation, "prompt": prompt}),
                workspace,
                mode,
                JobMeta::default(),
            )
            .await
            .map_err(|error| error.message)?;
        Ok(match call {
            OwnerCall::Job(started) => Sent::Job(job_name(session, &started)),
            OwnerCall::Steered => Sent::Steered,
        })
    }

    /// Start the owner's own job in live session `session` with the `agent`
    /// call `arguments`. Returns `<session>/<job>`.
    pub async fn start(&self, session: &str, arguments: Value) -> Result<String, String> {
        self.start_with(session, arguments, JobMeta::default())
            .await
    }

    /// [`Self::start`], with what the job's record holds from the start.
    async fn start_with(
        &self,
        session: &str,
        arguments: Value,
        meta: JobMeta,
    ) -> Result<String, String> {
        let (agent, workspace) = self.agent(session)?;
        match agent
            .owner_call(arguments, workspace, SendMode::Queue, meta)
            .await
            .map_err(|error| error.message)?
        {
            OwnerCall::Job(started) => Ok(job_name(session, &started)),
            OwnerCall::Steered => Err("the prompt went into a running turn".into()),
        }
    }

    /// Run interrupted job `job` of `session` again as the owner's job in
    /// live session `host`, which serves the job's workspace. It continues
    /// the agent's own conversation when the agent saved one and can resume
    /// it; otherwise it starts over, told that an earlier attempt may have
    /// left changes. A queued follow-up has no run of its own: it uses the
    /// conversation's directory and worktree, continues that agent session
    /// only after the interrupted job the run served has been resumed (and
    /// then behind that conversation), and otherwise starts in a new
    /// worktree of the checkout that job recorded. Each job is resumed
    /// once, and not while an agent process of its run still goes. Returns
    /// `<host>/<new job>`.
    pub async fn resume(&self, host: &str, session: &str, job: &str) -> Result<String, String> {
        let key = format!("{session}/{job}");
        if !lock(&self.resuming).insert(key.clone()) {
            return Err(format!("{job} is being resumed already"));
        }
        // Released however this ends, a dropped request included.
        let _claim = Claim {
            claims: &self.resuming,
            key: &key,
        };
        self.resume_once(host, session, job, &key).await
    }

    async fn resume_once(
        &self,
        host: &str,
        session: &str,
        job: &str,
        key: &str,
    ) -> Result<String, String> {
        let record = ledger::load(&self.jobs, session, job)
            .ok_or_else(|| format!("no record of {session}/{job}"))?;
        let session_live = lock(&self.inner).sessions.contains_key(session);
        let interrupted = record.state == AgentState::Interrupted
            || (!record.state.is_final()
                && (!record.owner.is_alive()
                    || (record.owner.pid == std::process::id() && !session_live)));
        if !interrupted {
            return Err(format!(
                "{job} was not interrupted ({}); only an interrupted job can be resumed",
                record.state
            ));
        }
        if record.reviewed {
            return Err(
                "a reviewed job is not resumed: its journal is its record. Start a new \
                 reviewed call whose brief restates the open findings and anything already \
                 landed"
                    .into(),
            );
        }
        if let Some(resumed) = &record.resumed_as {
            return Err(format!("{job} was already resumed as {resumed}"));
        }
        let (agent, _) = self.agent(host)?;
        // Reading every record, run state, and the process table takes a
        // while.
        let (successor, run, live, blocking) = {
            let (jobs, runs) = (self.jobs.clone(), self.runs.clone());
            let delegations = Arc::clone(&self.delegations);
            let continued = record
                .arguments
                .get("session")
                .and_then(Value::as_str)
                .map(str::to_owned);
            let (session, job, key) = (session.to_owned(), job.to_owned(), key.to_owned());
            tokio::task::spawn_blocking(move || {
                // A job that names it as what it resumes settles it, should
                // SCV have stopped before this record said so, even once
                // the owner dismissed that job.
                let successor = ledger::list_all(&jobs)
                    .into_iter()
                    .find(|record| record.resumed_from.as_deref() == Some(key.as_str()))
                    .map(|record| format!("{}/{}", record.session, record.job));
                let states = activity::list_states(&runs);
                let served = |state: &activity::RunState| {
                    state.session == session
                        && (state.job.as_deref() == Some(job.as_str()) || state.jobs.contains(&job))
                };
                let own = states
                    .iter()
                    .filter(|state| served(state))
                    .max_by_key(|state| state.started_unix)
                    .cloned();
                // A queued follow-up has no run of its own. The conversation
                // it continues does, and that run has the directory and the
                // agent's session.
                let fallback = if own.is_none() {
                    continued.as_deref().and_then(|handle| {
                        states
                            .iter()
                            .filter(|state| {
                                state.session == session
                                    && state.conversation.as_deref() == Some(handle)
                            })
                            .max_by_key(|state| state.started_unix)
                            .cloned()
                    })
                } else {
                    None
                };
                let run = own.or_else(|| fallback.clone());
                // Adopting while the job that run served is still interrupted
                // would start a second process in its agent session. The
                // follow-up waits until that job is resumed, then queues
                // behind the conversation that resume adopted.
                let blocking = match &fallback {
                    Some(found) if found.vendor.is_some() && found.cwd.is_dir() => {
                        unresumed_served(&jobs, found, &job)
                    }
                    _ => Vec::new(),
                };
                let live = run.as_ref().is_some_and(|run| {
                    delegations
                        .list(true)
                        .iter()
                        .any(|entry| entry.record.handle == run.handle && entry.processes > 0)
                });
                (successor, run, live, blocking)
            })
            .await
            .map_err(|error| error.to_string())?
        };
        if let Some(resumed) = successor {
            return Err(format!("{job} was already resumed as {resumed}"));
        }
        if live {
            return Err(format!(
                "{job}'s agent ({}) still runs; SCV stops what a stopped SCV process left \
                 within a minute (or `scv agents kill` it now). Resume it after that",
                run.as_ref().map_or("", |run| run.handle.as_str())
            ));
        }
        if !blocking.is_empty() {
            let ahead = if blocking.len() == 1 { "it" } else { "them" };
            return Err(format!(
                "{job} was queued behind {}; resume {ahead} first. This follow-up then waits \
                 behind the same conversation, so one agent session is not continued twice",
                blocking.join(", ")
            ));
        }
        let mut record = record;
        let cwd_live = run.as_ref().is_some_and(|found| found.cwd.is_dir());
        if let Some(found) = &run
            && cwd_live
        {
            remember_cwd(&mut record, &found.cwd);
            if record.worktree.is_none()
                && let Some(worktree) =
                    crate::delegate::worktree::worktree_ref(&self.worktrees, &found.cwd)
            {
                record.worktree = Some(worktree);
            }
        }
        // The directory is gone (the owner removed the worktree; an
        // interrupted job does not hold it). The job that run served still
        // records the checkout, dismissed records included, which is what a
        // new worktree is made from. The run's path still names the
        // subdirectory inside it.
        if record.worktree.is_none()
            && let Some(found) = &run
            && let Some(worktree) = served_worktree(&self.jobs, found)
        {
            record.worktree = Some(worktree);
        }
        if !cwd_live
            && let Some(found) = &run
            && let Some(worktree) = &record.worktree
            && found.cwd.starts_with(Path::new(&worktree.path))
        {
            remember_cwd(&mut record, &found.cwd);
        }
        let cwd = run
            .as_ref()
            .map(|run| run.cwd.clone())
            .filter(|cwd| cwd.is_dir());
        let adopted = run
            .as_ref()
            .and_then(|run| run.vendor.as_deref().zip(cwd.as_deref()))
            .and_then(|(vendor, cwd)| agent.adopt(&record.agent, cwd, vendor));
        let mut arguments = if let Some(handle) = &adopted {
            json!({
                "session": handle,
                "prompt": format!(
                    "[SCV] SCV stopped before your last turn on this task finished (a restart \
                     or a crash), so it was cut off. Check where the work stands (files, git \
                     status, anything still running), then carry on. The task was:\n\n{}",
                    record.prompt
                ),
            })
        } else {
            rerun_arguments(&record, |option| agent.takes(&record.agent, option))
        };
        if let Some(object) = arguments.as_object_mut() {
            for key in ["timeout_seconds", "no_timeout"] {
                if let Some(value) = record.arguments.get(key) {
                    object.insert(key.into(), value.clone());
                }
            }
        }
        // The new job's record says what it resumes from its first write.
        let meta = JobMeta {
            resumed_from: Some(key.to_owned()),
            worktree: record
                .worktree
                .clone()
                .filter(|worktree| Path::new(&worktree.path).is_dir()),
            ..JobMeta::default()
        };
        let resumed = self.start_with(host, arguments, meta).await?;
        ledger::update(&self.jobs, session, job, |old| {
            old.resumed_as = Some(resumed.clone());
            if !old.state.is_final() {
                ledger::interrupt(old, "its session ended before it finished");
            }
        });
        Ok(resumed)
    }

    /// Stop job `job` of live session `session`.
    pub fn cancel(&self, session: &str, job: &str) -> Result<String, String> {
        let jobs = {
            let inner = lock(&self.inner);
            inner
                .sessions
                .get(session)
                .and_then(|slot| slot.jobs.as_ref())
                .and_then(Weak::upgrade)
        };
        let Some(jobs) = jobs else {
            return Err(format!(
                "session {session} does not run in this daemon; a job whose session ended \
                 stopped with it, and `scv agents kill` stops another process's runs"
            ));
        };
        jobs.cancel_for_owner(job)?;
        Ok(format!(
            "Stopping {job}: its agent and every process it started are stopped; work it \
             already wrote stays."
        ))
    }

    /// Forget finished or interrupted job `job` of `session`.
    pub fn dismiss(&self, session: &str, job: &str) -> Result<String, String> {
        let record = ledger::load(&self.jobs, session, job)
            .ok_or_else(|| format!("no record of {session}/{job}"))?;
        let jobs = lock(&self.inner)
            .sessions
            .get(session)
            .and_then(|slot| slot.jobs.as_ref())
            .and_then(Weak::upgrade);
        let running = jobs.as_ref().is_some_and(|jobs| {
            jobs.live()
                .iter()
                .any(|live| live.id == job && live.running)
        });
        if running || (!record.state.is_final() && record.owner.is_alive()) {
            return Err(format!("{job} is still running; stop it first"));
        }
        // A session that has yet to report the result writes its record
        // again when it does: this daemon's says so itself, and one of
        // another live SCV process by its record.
        let elsewhere =
            record.owner.is_alive() && ProcessIdentity::current().as_ref() != Some(&record.owner);
        if jobs.is_some_and(|jobs| jobs.unreported(job)) || (elsewhere && !record.reported) {
            return Err(format!(
                "{job}'s result has not reached its session yet; dismiss it once it has"
            ));
        }
        ledger::dismiss(&self.jobs, session, job).map_err(|error| error.to_string())?;
        Ok(format!("Forgot {session}/{job}."))
    }

    /// The ledger record of `job` in `session`.
    pub fn job_record(&self, session: &str, job: &str) -> Option<JobRecord> {
        ledger::load(&self.jobs, session, job)
    }

    /// Job `job` of `session` as the workbench lists it, with its reply or
    /// error once it has ended, each cut to [`MAX_JOB_RESULT_BYTES`].
    pub fn job_result(&self, session: &str, job: &str) -> Result<JobResult, String> {
        let record = ledger::load(&self.jobs, session, job)
            .ok_or_else(|| format!("no record of {session}/{job}"))?;
        let (jobs, awaiting, session_live) = {
            let inner = lock(&self.inner);
            let slot = inner.sessions.get(session);
            (
                slot.and_then(|slot| slot.jobs.as_ref())
                    .and_then(Weak::upgrade),
                inner
                    .approvals
                    .values()
                    .find(|pending| pending.info.session == session && pending.info.job == job)
                    .map(|pending| pending.info.clone()),
                slot.is_some(),
            )
        };
        let live = jobs
            .as_ref()
            .and_then(|jobs| jobs.live().into_iter().find(|live| live.id == job));
        // The run that served it last, chosen as the snapshot chooses it.
        let run = activity::list_states(&self.runs)
            .into_iter()
            .filter(|state| {
                state.session == session
                    && (state.job.as_deref() == Some(job)
                        || state.jobs.iter().any(|served| served == job))
            })
            .min_by_key(|state| std::cmp::Reverse((state.last_activity_unix, state.started_unix)));
        let (state, detail) = job_state(
            &record,
            live.as_ref(),
            run.as_ref(),
            awaiting.as_ref(),
            session_live,
            unix_now(),
        );
        let mut truncated = false;
        let mut cut = |text: Option<String>| {
            text.map(|text| {
                let kept = scv_client::text::utf8_prefix(&text, MAX_JOB_RESULT_BYTES);
                truncated |= kept.len() < text.len();
                kept.to_owned()
            })
        };
        let reply = cut(record.reply);
        let error = cut(record.error);
        Ok(JobResult {
            session: record.session,
            job: record.job,
            agent: record.agent,
            state,
            detail,
            reply,
            error,
            truncated,
            outcome: jobs.and_then(|jobs| jobs.outcome(job)),
            finished_unix_seconds: record.finished_unix,
        })
    }

    /// Take conversation `conversation` of live session `session` over in
    /// its agent's own terminal for the owner, or attach to the takeover of
    /// it already running, and return the whole screen. A second client's
    /// attach takes the terminal from the first, whose hold stops working.
    pub async fn attach_terminal(
        &self,
        session: &str,
        conversation: &str,
        cols: Option<u16>,
        rows: Option<u16>,
    ) -> Result<AttachPage, String> {
        self.take_terminal(session, conversation, cols, rows, false, None)
            .await
            .map(|(page, _)| page)
    }

    /// [`Self::attach_terminal`], stopping first the background job that
    /// runs the conversation's turn. The conversation's lane is held for
    /// the takeover before that job is stopped, so no other prompt starts a
    /// turn in between, and nothing is stopped when it cannot be held: when
    /// the agent's terminal is not offered, a takeover of it runs or is
    /// starting, a reviewed job holds it, it has no agent session yet, the
    /// running turn is no background job, that job waits for the owner's
    /// approval (which a takeover never answers or withdraws), or as many
    /// takeovers as may run do. Given the `job` the owner was told it stops,
    /// nothing is stopped either when another job runs the turn by then. A
    /// conversation running no turn is taken over as by `attach_terminal`.
    /// Also returns SCV's note naming the job it stopped.
    pub async fn interrupt_and_attach(
        &self,
        session: &str,
        conversation: &str,
        cols: Option<u16>,
        rows: Option<u16>,
        job: Option<&str>,
    ) -> Result<(AttachPage, Option<String>), String> {
        self.take_terminal(session, conversation, cols, rows, true, job)
            .await
    }

    async fn take_terminal(
        &self,
        session: &str,
        conversation: &str,
        cols: Option<u16>,
        rows: Option<u16>,
        interrupt: bool,
        named: Option<&str>,
    ) -> Result<(AttachPage, Option<String>), String> {
        self.expire_takeovers();
        let key = format!("{session}/{conversation}");
        let id = format!("at-{}", &uuid::Uuid::new_v4().simple().to_string()[..16]);
        if let Some(page) = self.attach_running(&key, &id, cols, rows) {
            return Ok((page, None));
        }
        let _starting = self.attaching.lock().await;
        // It may have started while this one waited.
        if let Some(page) = self.attach_running(&key, &id, cols, rows) {
            return Ok((page, None));
        }
        if self.closing.load(Ordering::Acquire) {
            return Err(stopping());
        }
        if self.running_takeovers() >= MAX_TAKEOVERS {
            return Err(at_cap());
        }
        let (agent, _) = self.agent(session)?;
        let size = takeover::clamp_size(cols, rows);
        let (takeover, stopped) = if interrupt {
            // Held before anything is stopped; refused, nothing is.
            let reserved = agent.reserve_takeover(conversation)?;
            if let (Some(job), Some(named)) = (&reserved.job, named)
                && job != named
            {
                return Err(not_the_named_job(conversation, named, job));
            }
            if let Some(job) = &reserved.job
                && let Some(approval) = lock(&self.inner)
                    .approvals
                    .values()
                    .find(|pending| pending.info.session == session && &pending.info.job == job)
            {
                return Err(awaits_approval(job, &approval.info.id));
            }
            let stopped = reserved.job.clone();
            (
                agent.take_over_reserved(reserved, session, size).await?,
                stopped,
            )
        } else {
            (agent.take_over(conversation, session, size).await?, None)
        };
        let note = stopped.map(|job| format!("Stopped {job} and took {conversation} over."));
        let page = takeover.page(&id, 0);
        {
            let mut takeovers = lock(&self.takeovers);
            if !self.closing.load(Ordering::Acquire) {
                takeovers.insert(
                    key,
                    Held {
                        takeover,
                        lease: Some((id, Instant::now())),
                        closed: None,
                    },
                );
                return Ok((page, note));
            }
        }
        // SCV began stopping while it started: it ends like the others.
        takeover.end().await;
        Err(stopping())
    }

    /// Attach client `id` to the takeover of `key` if it runs, sized `cols`
    /// by `rows`, and return the whole screen; forget one that closed.
    fn attach_running(
        &self,
        key: &str,
        id: &str,
        cols: Option<u16>,
        rows: Option<u16>,
    ) -> Option<AttachPage> {
        let (takeover, watched) = {
            let mut takeovers = lock(&self.takeovers);
            match takeovers.get_mut(key) {
                Some(held) if !held.takeover.is_finished() => {
                    let watched = held.lease.is_some();
                    held.lease = Some((id.to_owned(), Instant::now()));
                    (Arc::clone(&held.takeover), watched)
                }
                Some(_) => {
                    takeovers.remove(key);
                    return None;
                }
                None => return None,
            }
        };
        if !watched {
            takeover.note_attached(true);
        }
        takeover.resize(cols, rows);
        Some(takeover.page(id, 0))
    }

    /// Type `input` into the terminal client `id` is attached to, resize it,
    /// and return what changed on its screen since generation `after`.
    pub async fn attach_io(
        &self,
        id: &str,
        after: u64,
        input: &str,
        cols: Option<u16>,
        rows: Option<u16>,
    ) -> Result<AttachPage, String> {
        if input.len() > takeover::MAX_INPUT_BYTES {
            return Err(format!(
                "at most {} KiB can be typed at once",
                takeover::MAX_INPUT_BYTES / 1024
            ));
        }
        self.expire_takeovers();
        let takeover = self.leased(id)?;
        let note = takeover.input(input.as_bytes()).await;
        takeover.resize(cols, rows);
        let mut page = takeover.page(id, after);
        page.note = note;
        Ok(page)
    }

    /// Stop client `id` watching its terminal; the agent keeps running.
    pub fn detach(&self, id: &str) -> Result<String, String> {
        let takeover = {
            let mut takeovers = lock(&self.takeovers);
            let held = takeovers
                .values_mut()
                .find(|held| held.lease.as_ref().is_some_and(|(lease, _)| lease == id))
                .ok_or_else(not_attached)?;
            held.lease = None;
            Arc::clone(&held.takeover)
        };
        takeover.note_attached(false);
        Ok(if takeover.is_running() {
            format!(
                "Detached from {}; it keeps running in its terminal.",
                takeover.conversation
            )
        } else {
            format!(
                "Detached from {}, whose terminal has closed.",
                takeover.conversation
            )
        })
    }

    /// End the takeover of `conversation` of `session`: hang its terminal
    /// up, stop its process, and give the conversation back to SCV's
    /// turns. Returns SCV's note and the final screen.
    pub async fn end_takeover(
        &self,
        session: &str,
        conversation: &str,
    ) -> Result<(String, AttachPage), String> {
        let key = format!("{session}/{conversation}");
        let held = lock(&self.takeovers)
            .remove(&key)
            .ok_or_else(|| format!("{conversation} of {session} is not taken over"))?;
        held.takeover.end().await;
        let id = held.lease.map(|(id, _)| id).unwrap_or_default();
        let page = held.takeover.page(&id, 0);
        let how = page.exit.clone().unwrap_or_else(|| "closed".into());
        Ok((
            format!("Ended the takeover of {conversation}: the terminal closed ({how})."),
            page,
        ))
    }

    /// End every takeover, waiting for each: the daemon is stopping, so
    /// none starts any more.
    pub async fn end_takeovers(&self) {
        let held: Vec<Held> = {
            let mut takeovers = lock(&self.takeovers);
            self.closing.store(true, Ordering::Release);
            takeovers.drain().map(|(_, held)| held).collect()
        };
        futures_util::future::join_all(held.iter().map(|held| held.takeover.end())).await;
    }

    /// How many takeovers run.
    fn running_takeovers(&self) -> usize {
        lock(&self.takeovers)
            .values()
            .filter(|held| !held.takeover.is_finished())
            .count()
    }

    /// Sessions with a takeover still running, which count as in use.
    pub fn takeover_sessions(&self) -> HashSet<String> {
        lock(&self.takeovers)
            .values()
            .filter(|held| !held.takeover.is_finished())
            .map(|held| held.takeover.session.clone())
            .collect()
    }

    /// End the takeovers of `session` (every one with `None`) in the
    /// background: their session is gone.
    fn end_takeovers_of(&self, session: Option<&str>) {
        let ending: Vec<Arc<Takeover>> = {
            let mut takeovers = lock(&self.takeovers);
            let keys: Vec<String> = takeovers
                .iter()
                .filter(|(_, held)| session.is_none_or(|session| held.takeover.session == session))
                .map(|(key, _)| key.clone())
                .collect();
            keys.iter()
                .filter_map(|key| takeovers.remove(key))
                .map(|held| held.takeover)
                .collect()
        };
        if ending.is_empty() {
            return;
        }
        match tokio::runtime::Handle::try_current() {
            Ok(runtime) => {
                runtime.spawn(async move {
                    futures_util::future::join_all(ending.iter().map(|takeover| takeover.end()))
                        .await;
                });
            }
            Err(_) => ending.iter().for_each(|takeover| takeover.kill_now()),
        }
    }

    /// The running or recently closed takeover client `id` holds.
    fn leased(&self, id: &str) -> Result<Arc<Takeover>, String> {
        let mut takeovers = lock(&self.takeovers);
        let held = takeovers
            .values_mut()
            .find(|held| held.lease.as_ref().is_some_and(|(lease, _)| lease == id))
            .ok_or_else(not_attached)?;
        if let Some((_, read)) = &mut held.lease {
            *read = Instant::now();
        }
        Ok(Arc::clone(&held.takeover))
    }

    /// Detach clients that stopped reading, and forget takeovers whose
    /// terminal closed a while ago.
    fn expire_takeovers(&self) {
        let now = Instant::now();
        let mut detached = Vec::new();
        let mut takeovers = lock(&self.takeovers);
        takeovers.retain(|_, held| {
            if held.takeover.is_finished() {
                let closed = *held.closed.get_or_insert(now);
                return now.duration_since(closed) < CLOSED_KEPT;
            }
            if held
                .lease
                .as_ref()
                .is_some_and(|(_, read)| now.duration_since(*read) >= ATTACH_LEASE)
            {
                held.lease = None;
                detached.push(Arc::clone(&held.takeover));
            }
            true
        });
        drop(takeovers);
        for takeover in detached {
            takeover.note_attached(false);
        }
    }

    /// Settle what processes that stopped left unfinished, and remove old
    /// records: the daemon runs this at startup and every minute.
    pub fn maintain(&self) -> Maintenance {
        self.expire_takeovers();
        let interrupted_jobs = ledger::settle_orphans(&self.jobs)
            .into_iter()
            .map(|record| format!("{}/{}", record.session, record.job))
            .collect();
        let interrupted_runs = activity::settle_orphans(&self.runs);
        let pruned = ledger::prune(&self.jobs, KEEP) + activity::prune(&self.runs, KEEP, MAX_RUNS);
        Maintenance {
            interrupted_jobs,
            interrupted_runs,
            pruned,
        }
    }
}

fn stopping() -> String {
    "SCV is stopping, so it takes no conversation over now".into()
}

fn at_cap() -> String {
    format!("{MAX_TAKEOVERS} conversations are taken over already; end one first")
}

/// The refusal to stop `job`, which waits for the owner's answer to
/// approval request `id`, for a takeover.
fn awaits_approval(job: &str, id: &str) -> String {
    format!(
        "{job} waits for your approval ({id}); answer it first (`scv jobs approve` or `deny`). \
         Taking its conversation over would withdraw the request, and a takeover never answers \
         or withdraws an approval"
    )
}

/// The refusal to stop `running`, which runs conversation `conversation`'s
/// turn, for a takeover the owner was told stops `named`.
fn not_the_named_job(conversation: &str, named: &str, running: &str) -> String {
    format!(
        "{conversation} is running {running}'s turn now, not {named}'s, so nothing was stopped; \
         attach again to stop {running}"
    )
}

/// `offer` as `attach` would answer it now, with what only the workbench
/// knows: with `running` takeovers at the cap, none starts, and stopping a
/// job that waits for the owner's answer to `approval` is refused.
fn settle_offer(mut offer: AttachOffer, approval: Option<&str>, running: usize) -> AttachOffer {
    if offer.interrupt
        && let (Some(job), Some(id)) = (&offer.job, approval)
    {
        offer.detail = Some(awaits_approval(job, id));
        offer.interrupt = false;
    }
    let starts = offer.state == AttachState::Ready || offer.interrupt;
    if starts && running >= MAX_TAKEOVERS {
        offer.state = AttachState::Full;
        offer.detail = Some(at_cap());
        offer.interrupt = false;
    }
    offer
}

fn not_attached() -> String {
    "this terminal is not attached here any more (another dashboard attached to it, or its \
     takeover ended); attach again"
        .into()
}

/// A job claimed for resuming, released when dropped.
struct Claim<'a> {
    claims: &'a Mutex<HashSet<String>>,
    key: &'a str,
}

impl Drop for Claim<'_> {
    fn drop(&mut self) {
        lock(self.claims).remove(self.key);
    }
}

struct SlotView {
    id: String,
    label: String,
    workspace: PathBuf,
    state: AgentState,
    detail: Option<String>,
    agent: Option<Arc<BackgroundCapable>>,
    jobs: Option<Arc<BackgroundJobs>>,
}

/// What a job is doing, from its record, its live entry when its session
/// runs here, the run serving it, and an approval it waits on.
fn job_state(
    record: &JobRecord,
    live: Option<&LiveJob>,
    run: Option<&RunState>,
    awaiting: Option<&WorkbenchApproval>,
    session_live: bool,
    now: u64,
) -> (AgentState, Option<String>) {
    if record.state.is_final() {
        let detail = match record.state {
            AgentState::Interrupted => record.interrupted.clone(),
            AgentState::Completed => None,
            _ => record
                .error
                .as_deref()
                .and_then(|error| error.lines().find(|line| !line.trim().is_empty()))
                .map(|line| bounded(line, 200)),
        };
        return (record.state, detail);
    }
    if let Some(approval) = awaiting {
        return (
            AgentState::AwaitingInput,
            Some(format!(
                "waiting for your approval: {}",
                bounded(&approval.summary, 200)
            )),
        );
    }
    if let Some(live) = live {
        if live.waiting {
            let behind = record
                .arguments
                .get("session")
                .and_then(Value::as_str)
                .map_or_else(String::new, |handle| format!(" {handle}'s"));
            return (
                AgentState::Queued,
                Some(format!("waits for conversation{behind} running turn")),
            );
        }
        if live.running {
            if let Some(run) = run.filter(|run| !run.ended) {
                return activity::current(run, now);
            }
            return (
                AgentState::Working,
                live.progress
                    .clone()
                    .or_else(|| Some(format!("running for {} s", live.elapsed.as_secs()))),
            );
        }
    }
    if !record.owner.is_alive() {
        return (
            AgentState::Interrupted,
            Some("the SCV process that ran it stopped".into()),
        );
    }
    if record.owner.pid == std::process::id() && !session_live {
        return (
            AgentState::Interrupted,
            Some("its session ended before it finished".into()),
        );
    }
    match run {
        Some(run) if !run.ended => activity::current(run, now),
        _ => (record.state, None),
    }
}

/// The workbench's own session ID for `workspace`: stable, so the owner's
/// jobs in one workspace group under one session across daemon restarts.
pub fn host_session(workspace: &Path) -> String {
    use sha2::{Digest, Sha256};
    let digest = Sha256::digest(workspace.as_os_str().as_encoded_bytes());
    let hex: String = digest[..8]
        .iter()
        .map(|byte| format!("{byte:02x}"))
        .collect();
    format!("workbench-{hex}")
}

/// `<session>/<job>` of a job an `agent` call started.
fn job_name(session: &str, started: &Value) -> String {
    format!(
        "{session}/{}",
        started.get("job").and_then(Value::as_str).unwrap_or("job")
    )
}

/// Decides a background job's approval request: the session's unattended
/// answer, or, for one it would deny while the owner watches, the owner's.
struct AttendedGate {
    workbench: Weak<Workbench>,
    session: String,
    unattended: Arc<dyn ApprovalGate>,
}

#[async_trait]
impl ApprovalGate for AttendedGate {
    async fn approve(
        &self,
        request: ApprovalRequest,
        cancellation: CancellationToken,
    ) -> Result<bool, AgentError> {
        if self
            .unattended
            .approve(request.clone(), cancellation.clone())
            .await?
        {
            return Ok(true);
        }
        match self.workbench.upgrade() {
            Some(workbench) if workbench.watched() => {
                workbench.ask(&self.session, request, &cancellation).await
            }
            _ => Ok(false),
        }
    }
}

fn bounded(text: &str, max: usize) -> String {
    if text.chars().count() <= max {
        return text.to_owned();
    }
    let mut cut: String = text.chars().take(max.saturating_sub(1)).collect();
    cut.push('…');
    cut
}

fn unix_now() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map_or(0, |elapsed| elapsed.as_secs())
}

/// Jobs whose turns `run` served, the latest one first.
fn served_job_names(run: &RunState) -> Vec<&str> {
    let mut names = Vec::new();
    if let Some(job) = run.job.as_deref() {
        names.push(job);
    }
    for job in &run.jobs {
        if !names.contains(&job.as_str()) {
            names.push(job.as_str());
        }
    }
    names
}

/// Interrupted jobs `run` served that the owner has not resumed, as
/// `session/job`. `skip` is the follow-up being resumed.
fn unresumed_served(root: &Path, run: &RunState, skip: &str) -> Vec<String> {
    served_job_names(run)
        .into_iter()
        .filter(|name| *name != skip)
        .filter_map(|name| {
            let record = ledger::load(root, &run.session, name)?;
            record
                .resumable()
                .then(|| format!("{}/{}", run.session, name))
        })
        .collect()
}

/// The worktree recorded on a job `run` served. A follow-up has none of
/// its own, and the run's directory may already have been removed. A
/// dismissed record still carries the worktree.
fn served_worktree(root: &Path, run: &RunState) -> Option<scv_protocol::WorktreeRef> {
    served_job_names(run).into_iter().find_map(|name| {
        ledger::load_including_dismissed(root, &run.session, name)
            .and_then(|record| record.worktree)
    })
}

/// Record `cwd` on `record` when the call did not name one.
fn remember_cwd(record: &mut ledger::JobRecord, cwd: &Path) {
    let has_cwd = record
        .arguments
        .get("cwd")
        .and_then(Value::as_str)
        .is_some_and(|cwd| !cwd.is_empty());
    if !has_cwd && let Some(object) = record.arguments.as_object_mut() {
        object.insert("cwd".into(), cwd.display().to_string().into());
    }
}

/// The `agent` call that runs interrupted job `record` again from its
/// prompt in a new conversation: its options but those the host agent does
/// not `take`, and a note that an earlier attempt may have left changes. A
/// job that ran in a worktree runs in the same directory of it while the
/// worktree is there, and in a new worktree of its repository once it was
/// removed, so its work never lands in the repository's own checkout.
fn rerun_arguments(record: &JobRecord, takes: impl Fn(&str) -> bool) -> Value {
    let mut arguments = record.arguments.clone();
    if let Some(object) = arguments.as_object_mut() {
        object.remove("session");
        object.remove("worktree");
        object.remove("on_busy");
        // What this session's agent does not take is left to its own
        // defaults.
        for option in ["model", "effort"] {
            if !takes(option) {
                object.remove(option);
            }
        }
        object.insert("agent".into(), record.agent.clone().into());
        object.insert(
            "prompt".into(),
            format!(
                "[SCV] An earlier attempt at this task was cut off when SCV stopped (a restart \
                 or a crash), and its conversation could not be resumed. It may have left \
                 partial changes here: check them first, then do the task:\n\n{}",
                record.prompt
            )
            .into(),
        );
        if let Some(worktree) = &record.worktree {
            let top = Path::new(&worktree.path);
            // The call's directory inside the worktree, as it was recorded.
            let inside = object
                .get("cwd")
                .and_then(Value::as_str)
                .and_then(|cwd| Path::new(cwd).strip_prefix(top).ok())
                .map(Path::to_path_buf)
                .unwrap_or_default();
            if top.is_dir() {
                let cwd = Some(top.join(&inside))
                    .filter(|cwd| cwd.is_dir())
                    .unwrap_or_else(|| top.to_owned());
                object.insert("cwd".into(), cwd.display().to_string().into());
            } else {
                let repo = Path::new(&worktree.repo);
                let cwd = Some(repo.join(&inside))
                    .filter(|cwd| cwd.is_dir())
                    .unwrap_or_else(|| repo.to_owned());
                object.insert("cwd".into(), cwd.display().to_string().into());
                object.insert("worktree".into(), true.into());
            }
        }
    }
    arguments
}

#[cfg(test)]
mod tests;