cydonia 0.1.10

Desktop workspace for the ACP agents you run, keeping what they produce as files on your disk
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
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
//! The board pane: lanes of cards or a list of them, and the one field that
//! writes them.

use crate::{
    model::session::ChatSession,
    view::{
        component::{
            menu::{self, Menu},
            transcript,
        },
        leaf::Pane,
        root::{Cydonia, NewBoard},
        sidebar::Renaming,
    },
};
use artifact::{
    board::{Card, Status, View},
    layout::Member,
};
use bezel::agent::orbs::engine::Frame;
use bezel::ui::scroll as scrollbars;
use bezel::{
    gpui::{
        self, AnyElement, App, ClipboardItem, Context, Div, DragMoveEvent, Entity, Focusable as _,
        FontWeight, KeyBinding, Pixels, Render, ScrollHandle, SharedString, Stateful, Window,
        actions, div, prelude::*, px,
    },
    theme::{TextStyle, Theme, Typeset},
    ui::{
        icons,
        input::{self, Shape, TextField},
        menu::Item,
        popover,
        scroll::{self, Axes, DriftState, FollowState},
        tooltip::Tooltip,
        widgets::Buttons,
    },
};
use markdown::Typography;
use std::{cell::RefCell, collections::HashMap, rc::Rc};

actions!(
    cydonia_board,
    [CommitCard, DismissCard, FindCard, DismissFind]
);

/// Claimed on top of `TextField`, so `enter` files the card here and stays a
/// newline in every other multi-line field.
const KEY_CONTEXT: &str = "CydoniaCard";

/// The find field's own, so `escape` puts the bar away and stays whatever it is
/// everywhere else.
const FIND_CONTEXT: &str = "CydoniaBoardFind";

const COLUMN_WIDTH: f32 = 272.;

/// What the board holds itself off the window's edges by, and how far short of
/// the foot a lane's bar stops — the session's bar clears its composer the same
/// way, through [`scroll::Overlay::end_inset`].
const BOARD_INSET: f32 = 16.;

/// What separates two lanes, and the room the lane's scrollbar sits in. Handed
/// to the bar through [`scroll::Overlay::channel`], which centres the thumb in
/// it.
const LANE_CHANNEL: Pixels = px(18.);

/// The list's metrics: the heading over a group, a card's row, the line the
/// row shows of the card, and the column its handle is set in. A row is one
/// line tall by construction — see [`first_line`].
const LIST_HEADING_HEIGHT: f32 = 30.;
const LIST_ROW_HEIGHT: f32 = 36.;
const LIST_LINE: f32 = 22.;
const LIST_HANDLE_WIDTH: f32 = 64.;

/// What the list leaves clear at its foot for the pill floating there — see
/// [`Cydonia::view_pill`].
const PILL_CLEARANCE: f32 = 32.;

/// How much of a card is shown before it is cut off. A card is a card: what
/// does not fit in this much of a lane is read by opening it.
const CARD_MAX_HEIGHT: f32 = 140.;

/// Where the card editor would start scrolling inside itself. Set past any
/// card worth a lane, which is to say never: a scroll box inside a scrolling
/// column is two wheels for one gesture, and a run dragged into the half that
/// is not showing cannot be reached. The lane is the scroller, and the editor
/// grows until the lane has to move — which is where GitHub's boards draw the
/// same line.
///
/// A number rather than no cap, because [`Shape::Grow`] takes one.
const CARD_EDITOR_MAX_ROWS: usize = 512;

/// What the document ladder is brought down to on a card — `Callout` over
/// `Body`, which is the size a card's prose was set at when it was one flat
/// string. Every role moves together, so a `#` heading on a card still reads
/// as a heading, in a lane 272 wide rather than on a page.
const CARD_TEXT_SCALE: f32 = TextStyle::Callout.size() / TextStyle::Body.size();

pub fn bindings() -> Vec<KeyBinding> {
    let ctx = Some(KEY_CONTEXT);
    vec![
        KeyBinding::new("enter", CommitCard, ctx),
        KeyBinding::new("shift-enter", input::InsertNewline, ctx),
        KeyBinding::new("escape", DismissCard, ctx),
        KeyBinding::new("escape", DismissFind, Some(FIND_CONTEXT)),
    ]
}

/// The board's find field — one per pane, so two boards side by side are
/// narrowed separately.
pub fn find_field(cx: &mut App) -> Entity<TextField> {
    cx.new(|cx| {
        TextField::new(cx)
            .with_key_context(FIND_CONTEXT)
            .with_placeholder("find a card…")
    })
}

/// Does this card answer the query? Matched against what a card is named by:
/// its handle, which is how `DEV-38` gets referred to in prose, and its text.
fn card_matches(card: &Card, handle: Option<&str>, query: &str) -> bool {
    let query = query.trim().to_lowercase();
    if query.is_empty() {
        return true;
    }
    card.text.to_lowercase().contains(&query)
        || handle.is_some_and(|handle| handle.to_lowercase().contains(&query))
}

/// The board's one text field — whichever card is being written or rewritten.
/// Only ever one is open, and a field per card would mint an entity for every
/// row on the board.
pub fn field(cx: &mut App) -> Entity<TextField> {
    cx.new(|cx| {
        TextField::new(cx)
            .with_shape(Shape::Grow {
                min: 2,
                max: CARD_EDITOR_MAX_ROWS,
            })
            .with_key_context(KEY_CONTEXT)
            .with_placeholder("what needs doing…")
    })
}

/// The statuses a chip is drawn for, which is the ones with no motion of their
/// own. `busy` is the orb instead — see the `running` a card is built with.
fn resting(status: Option<Status>) -> Option<Status> {
    status.filter(|status| *status != Status::Busy)
}

/// How the work on a card is going, said in a word — see
/// [`artifact::board::Status`]. Written by whoever is doing the work, which is
/// usually an agent through `board_set_card_status`.
fn status_chip(status: Status, theme: &Theme) -> AnyElement {
    let tint = match status {
        // Never drawn — see [`resting`]. Named so the match stays total if the
        // set grows.
        Status::Busy => theme.accent,
        Status::Blocked => theme.danger,
        Status::Done => theme.text_faint,
    };
    div()
        .flex_none()
        .px(px(5.))
        .rounded_full()
        .border_1()
        .border_color(tint)
        .text_style(TextStyle::Caption)
        .text_color(tint)
        .child(status.key())
        .into_any_element()
}

/// What a lane holds, and what the find query leaves of it. The two are the
/// same number on a board nobody is searching.
#[derive(Clone, Copy)]
struct Tally {
    held: usize,
    shown: usize,
}

/// A card's text, read as the document it is. Somebody writing `- [ ] ship it`
/// on a card meant a box to tick, not three characters of punctuation — and the
/// field that writes the card is one click away, which is where the source
/// belongs.
///
/// The document renderer rather than a pass over the inline marks: a card takes
/// whatever was typed on it, and a list, a fence or a link is no less a card for
/// being one. What does not fit is cut off by [`CARD_MAX_HEIGHT`], the same as a
/// long paragraph.
fn card_body(text: &str, window: &mut Window, cx: &mut App) -> AnyElement {
    markdown::render_with(
        &markdown::parse(text),
        markdown::Editing {
            // A picture in a lane this narrow is a picture. Its alt text spelled
            // out underneath would be most of the card.
            caption: markdown::Caption::Hidden,
            typography: Some(Typography::of(cx).scaled(CARD_TEXT_SCALE)),
            ..Default::default()
        },
        window,
        cx,
    )
}

/// The card's first line, which is what a row of the list shows of it.
///
/// A card can be a document, and a row is one line tall: what a row leaves out
/// is read by opening the card, the way a lane cuts one off at
/// [`CARD_MAX_HEIGHT`].
fn first_line(text: &str) -> &str {
    text.lines()
        .map(str::trim)
        .find(|line| !line.is_empty())
        .unwrap_or("")
}

/// What the field is attached to. By id, never by position: a re-read
/// renumbers, and the field would follow the number onto whatever slid under.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Editing {
    /// A card being written, to land at this end of this column.
    New(Place, String),
    /// A card being rewritten.
    Card(String),
}

/// Which end of a lane a card being written lands at. The field is drawn at
/// that end too, so what is typed is where it will sit.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Place {
    Top,
    End,
}

/// Where a [`Cydonia::landing_mark`] hangs.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Mark {
    /// In the gap over the card the drop would land in front of.
    Above,
    /// Inside the top of a lane's first card. The gap over that one is outside
    /// the pane, and a mark drawn there is clipped away by the very scroller
    /// that makes the lane a lane.
    Top,
    /// In the gap under the last card, which is a drop at the end of the lane.
    Below,
    /// On the foot of the last row of a group in the list, which is a drop at
    /// the end of that group. The list's rows meet with no gap between them, so
    /// a mark hung in one would lie over the row under it.
    Foot,
    /// In the flow of an empty lane, which has nothing under it to push down.
    Flow,
}

/// A card in flight, named rather than carried: the board is read afresh
/// wherever the drop lands, and a copy of the card travelling with the pointer
/// would be a second one to keep in step with it.
///
/// It says which board it left as well as which card it is: a layout can have
/// two boards on screen, and the lane a card lands on cannot tell where it came
/// from.
#[derive(Clone)]
pub struct CardDrag {
    card: String,
    project: usize,
    board: usize,
}

/// Where the card in the air would land — the lane, and the card it would go
/// in front of, `None` being the end of the lane.
///
/// Held as a card rather than a position for the reason
/// [`artifact::board::Board::move_card_before`] takes one: a position means
/// whatever the lane looked like when it was counted.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Landing {
    pub column: String,
    pub before: Option<String>,
}

/// Where one board sits, wherever it is drawn.
///
/// Keyed by board id on the window rather than held by the pane: the same board
/// arranged in a layout and opened on its own is one board, and a handle per
/// pane leaves the two disagreeing about where it is scrolled to.
#[derive(Default)]
pub struct Scrolls(RefCell<HashMap<String, Scroll>>);

/// Everything the panes showing one board scroll by. Cheap to clone — every
/// field is a handle onto shared state, which is what makes two panes on one
/// board move together.
#[derive(Clone, Default)]
pub struct Scroll {
    /// The lanes across.
    pub across: ScrollHandle,
    /// The list down, which scrolls the other way — see [`artifact::board::View`].
    /// Its own handle rather than the lanes': one offset read along both axes
    /// would land the list wherever the lanes were scrolled to.
    pub down: ScrollHandle,
    /// What carries a held card past the edge of the window — a lane out of
    /// sight is one a drag cannot reach, because reaching for it means letting
    /// go.
    pub drift: DriftState,
    /// The same, per lane — see [`Lanes`].
    pub lanes: Rc<Lanes>,
}

impl Scrolls {
    /// What `board` is scrolled to, minted the first time it is drawn. Kept for
    /// as long as the window is open, on the same terms as [`Lanes`].
    pub fn of(&self, board: &str) -> Scroll {
        self.0
            .borrow_mut()
            .entry(board.to_owned())
            .or_default()
            .clone()
    }
}

/// The buffer each card's orb paints into, by card id — the same shape as
/// [`Lanes`] and kept on the same terms.
///
/// One apiece and never shared: [`bezel::agent::orbs::orb_element`] fills the
/// buffer as the element is built and reads it back at paint, so two orbs on
/// one buffer would both draw whatever the second put there.
#[derive(Default)]
pub struct Marks(RefCell<HashMap<String, Rc<RefCell<Frame>>>>);

impl Marks {
    fn of(&self, card: &str) -> Rc<RefCell<Frame>> {
        self.0
            .borrow_mut()
            .entry(card.to_owned())
            .or_default()
            .clone()
    }
}

/// A card's orb, read off the model with the card — the thinking orb the
/// sidebar's session row and the transcript already use, because a card
/// reporting a run is reporting the same run they are.
struct Working {
    state: bezel::agent::orbs::OrbState,
    since: std::time::Duration,
    frame: Rc<RefCell<Frame>>,
}

/// When this window opened, for the one orb with nothing better to count from
/// — see [`Cydonia::card_working`].
static SINCE: std::sync::LazyLock<std::time::Instant> =
    std::sync::LazyLock::new(std::time::Instant::now);

/// One scroll, one drift and one follow per lane, minted the first time the
/// lane is drawn.
///
/// gpui keys a pane's own scroll state by element id and needs nothing from
/// us, but a drift moves that scroll from outside, and moving it takes a
/// handle the view holds. Kept for as long as the window is open: a lane
/// deleted and remade is a new id, and a handful of dropped handles is cheaper
/// than a sweep that has to know which lanes are still on the board.
#[derive(Default)]
pub struct Lanes(RefCell<HashMap<String, (ScrollHandle, DriftState, FollowState)>>);

impl Lanes {
    fn of(&self, id: &str) -> (ScrollHandle, DriftState, FollowState) {
        self.0
            .borrow_mut()
            .entry(id.to_owned())
            .or_default()
            .clone()
    }

    /// Pin the lane to its end again. A lane remembers being scrolled away
    /// from, and opening an editor at its foot is asking to be taken there.
    fn follow(&self, id: &str) {
        self.of(id).2.follow();
    }
}

/// The card under the pointer while it is being carried.
///
/// An entity because that is what gpui paints a drag with, and the window's
/// top layer is the only place this can be drawn: a ghost inside the lane
/// would be clipped by the very edge it is being carried over.
pub struct HeldCard {
    text: String,
}

impl Render for HeldCard {
    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
        let theme = Theme::of(cx).clone();
        div()
            .w(px(COLUMN_WIDTH))
            .max_h(px(CARD_MAX_HEIGHT))
            .overflow_hidden()
            .p(px(10.))
            .rounded(px(Theme::control_radius()))
            .border_1()
            .border_color(theme.accent)
            .bg(theme.surface_raised)
            .child(card_body(&self.text, window, cx))
    }
}

/// Where a card sits, as the lane draws it: which board it is on, which lane,
/// whether it is the first in that lane, and what comes under it.
///
/// One value rather than five arguments — what the lane knows about a card's
/// place travels together.
/// Where a lane sits, as the board draws it: which board it is on, its place
/// among that board's lanes, and the pane drawing it.
struct Lane<'a> {
    project: usize,
    board: usize,
    id: &'a str,
    at: usize,
    lanes: usize,
    on: Option<&'a Member>,
}

struct Slot<'a> {
    project: usize,
    board: usize,
    id: &'a str,
    column: &'a str,
    first: bool,
    next: Option<&'a str>,
}

impl Cydonia {
    // ── mutations ────────────────────────────────────────────────

    pub fn show_pane(&mut self, pane: Pane, cx: &mut Context<Self>) {
        self.commit(cx);
        self.leaf_mut().pane = pane;
        cx.notify();
    }

    /// The menu's New Board. The sidebar's `+` names a project by the heading
    /// it sits under; the menu bar has only the one in front. Both raise the
    /// dialog that names it — see [`Cydonia::ask_new_board`].
    pub(crate) fn new_board_action(
        &mut self,
        _: &NewBoard,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) {
        let Some(project) = self.workspace.read(cx).active else {
            return;
        };
        self.ask_new_board(project, window, cx);
    }

    pub(crate) fn open_board(&mut self, project: usize, ix: usize, cx: &mut Context<Self>) {
        self.commit(cx);
        self.workspace
            .update(cx, |workspace, cx| workspace.open_board(project, ix, cx));
        self.leaf_mut().pane = Pane::Board;
        cx.notify();
    }

    /// Point the field at `at`, filing whatever was already open first — so
    /// clicking straight from one card to another never drops an edit.
    /// Lay a board out the other way — the pill at its foot. The board the pane
    /// is showing rather than the one in front: a layout can have two on screen.
    fn set_board_view(&mut self, id: &str, view: View, cx: &mut Context<Self>) {
        self.workspace
            .update(cx, |workspace, cx| workspace.set_board_view(id, view, cx));
        cx.notify();
    }

    fn edit(&mut self, at: Editing, window: &mut Window, cx: &mut Context<Self>) {
        self.commit(cx);
        let text = match &at {
            Editing::New(..) => String::new(),
            Editing::Card(id) => self
                .workspace
                .read(cx)
                .active_board()
                .and_then(|board| board.card(id))
                .map(|card| card.text.clone())
                .unwrap_or_default(),
        };
        self.leaf()
            .card_field
            .update(cx, |field, cx| field.set_content(text, cx));
        // A lane scrolled away from earlier stays where it was left; opening a
        // card at its foot is asking to be taken back there.
        if let Editing::New(Place::End, column) = &at
            && let Some(id) = self
                .workspace
                .read(cx)
                .active_board()
                .map(|board| board.id.clone())
        {
            self.boards.of(&id).lanes.follow(column);
        }
        self.leaf_mut().editing = Some(at);
        window.focus(&self.leaf().card_field.read(cx).focus_handle(cx), cx);
        cx.notify();
    }

    /// File whatever is open before leaving it. Every way out of a pane goes
    /// through here.
    ///
    /// An empty card is not a card — committing nothing drops it rather than
    /// leaving a blank on the board.
    pub(crate) fn commit(&mut self, cx: &mut Context<Self>) {
        self.commit_cell(cx);
        self.rest_ribbon(cx);
        let Some(at) = self.leaf_mut().editing.take() else {
            return;
        };
        let text = self.leaf().card_field.read(cx).content().trim().to_owned();
        self.leaf()
            .card_field
            .update(cx, |field, cx| field.clear(cx));
        self.workspace.update(cx, |workspace, cx| {
            let Some(board) = workspace.active_board_mut() else {
                return;
            };
            match at {
                Editing::New(place, column) => {
                    if !text.is_empty() {
                        match place {
                            Place::Top => board.prepend_card(&column, text),
                            Place::End => board.add_card(&column, text),
                        };
                    }
                }
                Editing::Card(id) => {
                    if text.is_empty() {
                        board.remove_card(&id);
                    } else {
                        board.rewrite_card(&id, &text);
                    }
                }
            }
            workspace.save_board();
            cx.notify();
        });
    }

    /// Let go of an edit a re-read made meaningless, and keep one it did not.
    /// Held by id, so a card that merely moved keeps its open field; only one
    /// that has gone leaves the field pointing at nothing.
    pub(crate) fn drop_stale_edit(&mut self, cx: &mut Context<Self>) {
        let Some(at) = self.leaf().editing.clone() else {
            return;
        };
        let board = self.workspace.read(cx).active_board();
        let alive = match &at {
            Editing::New(_, column) => board.is_some_and(|board| board.column(column).is_some()),
            Editing::Card(card) => board.is_some_and(|board| board.card(card).is_some()),
        };
        if !alive {
            self.leaf_mut().editing = None;
            self.leaf()
                .card_field
                .update(cx, |field, cx| field.clear(cx));
        }
    }

    fn commit_card(&mut self, _: &CommitCard, _: &mut Window, cx: &mut Context<Self>) {
        self.commit(cx);
        cx.notify();
    }

    /// Escape abandons the edit — the one way to leave a card as it was.
    fn dismiss_card(&mut self, _: &DismissCard, _: &mut Window, cx: &mut Context<Self>) {
        self.leaf_mut().editing = None;
        self.leaf()
            .card_field
            .update(cx, |field, cx| field.clear(cx));
        cx.notify();
    }

    /// Where the pointer is, as the lanes and cards under it answer in turn.
    ///
    /// gpui runs a frame's listeners outermost first in the capture phase, so
    /// the answers arrive coarsest first: the board clears what the last move
    /// said, the lane the pointer is inside claims the end of itself, and the
    /// card it is over refines that to a place in the lane. Each one only ever
    /// overwrites something vaguer than itself.
    fn aim_card(&mut self, landing: Option<Landing>, cx: &mut Context<Self>) {
        if self.leaf().landing != landing {
            self.leaf_mut().landing = landing;
            cx.notify();
        }
    }

    /// Let the card go, into the lane the release actually landed on — gpui
    /// hit tests a drop, so that much is this frame's answer however stale
    /// anything else is.
    ///
    /// Where in the lane comes from the aim instead, which is a move old: hold
    /// a card at the edge until the board has drifted a lane under it and let
    /// go without moving, and the aim still names the lane that was there.
    /// Aimed at another lane means the end of this one, which is where a lane
    /// nothing was aimed at takes a card anyway.
    /// Let a carried card go on `at` — the board under the pointer, which is
    /// not always the board it was picked up from.
    fn drop_card(
        &mut self,
        drag: &CardDrag,
        at: (usize, usize),
        column: &str,
        cx: &mut Context<Self>,
    ) {
        let before = self
            .leaf_mut()
            .landing
            .take()
            .filter(|landing| landing.column == column)
            .and_then(|landing| landing.before);
        self.commit(cx);
        let (card, column) = (drag.card.clone(), column.to_owned());
        let from = (drag.project, drag.board);
        self.workspace.update(cx, |workspace, cx| {
            match from == at {
                true => {
                    workspace.move_card_within(at, &card, &column, before.as_deref());
                }
                // A card that came off another board arrives under a handle of
                // this one's. Where it lands is the lane it was dropped on,
                // and the place within that lane is not carried over: it is a
                // new card here.
                false => {
                    workspace.carry_card(from, at, &card, Some(&column));
                }
            }
            cx.notify();
        });
        cx.notify();
    }

    pub(crate) fn delete_card(&mut self, card: &str, cx: &mut Context<Self>) {
        self.commit(cx);
        let card = card.to_owned();
        self.workspace.update(cx, |workspace, cx| {
            let gone = workspace
                .active_board_mut()
                .and_then(|board| board.remove_card(&card))
                .is_some();
            if gone {
                workspace.save_board();
            }
            cx.notify();
        });
        cx.notify();
    }

    /// A lane at the right-hand end, opened straight into its name.
    fn new_column(&mut self, window: &mut Window, cx: &mut Context<Self>) {
        self.commit(cx);
        let id = self
            .workspace
            .update(cx, |workspace, cx| workspace.new_column(cx));
        if let Some(id) = id {
            self.start_rename(Renaming::Column(id), window, cx);
        }
    }

    /// A lane beside the one the menu is on, opened straight into its name —
    /// the same as [`Self::new_column`], which only ever writes at the end.
    fn new_column_beside(
        &mut self,
        id: &str,
        after: bool,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) {
        self.commit(cx);
        let id = id.to_owned();
        let minted = self.workspace.update(cx, |workspace, cx| {
            workspace.new_column_beside(&id, after, cx)
        });
        if let Some(minted) = minted {
            self.start_rename(Renaming::Column(minted), window, cx);
        }
    }

    /// Drop a lane. Offered only while it is empty — see
    /// [`artifact::board::Board::remove_column`].
    fn drop_column(&mut self, id: &str, cx: &mut Context<Self>) {
        self.commit(cx);
        let id = id.to_owned();
        self.workspace
            .update(cx, |workspace, cx| workspace.remove_column(&id, cx));
        cx.notify();
    }

    /// The card's markdown, as it was written. The source and not what the lane
    /// paints: a card is a document, and the text is what somebody would paste
    /// into the next one.
    fn copy_card(&mut self, card: &str, cx: &mut Context<Self>) {
        let Some(text) = self
            .workspace
            .read(cx)
            .active_board()
            .and_then(|board| board.card(card))
            .map(|card| card.text.clone())
        else {
            return;
        };
        cx.write_to_clipboard(ClipboardItem::new_string(text));
    }

    /// Hand the card to an agent: a session of its own, opened in the project
    /// with the card's text as its first prompt.
    ///
    /// A session of its own rather than the one in front, so the card's dot
    /// reports its own run — and so dispatching a second card doesn't queue
    /// behind the first. The board stays up: the card goes live where you are
    /// looking, and clicking it is what follows the work into the transcript.
    fn dispatch_card(&mut self, card: &str, cx: &mut Context<Self>) {
        self.commit(cx);
        let card = card.to_owned();
        self.workspace.update(cx, |workspace, cx| {
            let text = workspace
                .active_board()
                .and_then(|board| board.card(&card))
                .map(|card| card.text.clone());
            let (Some(text), Some(entry)) = (text, workspace.preferred_agent()) else {
                return;
            };
            // Nothing to link to is nothing to write: clearing the field on a
            // refused dispatch would take the card's last session off it.
            let Some(record) = workspace
                .new_session(entry, Some(text), cx)
                .and_then(|id| workspace.mint_record(id))
            else {
                return;
            };
            if workspace
                .active_board_mut()
                .is_some_and(|board| board.dispatch_card(&card, record))
            {
                // The link is on the board now, so the board has to be written
                // — it is what the ▶ reads after a quit.
                workspace.save_board();
            }
        });
        cx.notify();
    }

    /// The `···` on a card: what the row of glyphs underneath should not carry,
    /// because it cannot be undone.
    fn card_menu(&self, card: &str, cx: &mut Context<Self>) -> Option<AnyElement> {
        if self.menu.as_ref() != Some(&Menu::Card(card.to_owned())) {
            return None;
        }
        let (copied, doomed) = (card.to_owned(), card.to_owned());
        // The card at rest is a rendered document, not a run of text somebody
        // can drag over — so without this there is no way to get a card's words
        // back out of it short of opening the editor and selecting them.
        let rows = vec![
            menu::row(
                Item::action("Copy text").with_icon(icons::text::Copy),
                move |this, _, cx| this.copy_card(&copied, cx),
            ),
            menu::row(
                Item::action("Delete").with_icon(icons::files::Trash),
                move |this, _, cx| this.ask_delete_card(&doomed, cx),
            ),
        ];
        let id = SharedString::from(format!("card-menu-card-{card}"));
        Some(popover::anchored_menu_below(
            id.clone(),
            self.menu_card(id, rows, cx),
            None,
        ))
    }

    /// The session a card was dispatched to, while it is still open — a card
    /// whose session has been closed is a card you can run again.
    fn card_session<'a>(&self, card: &Card, cx: &'a App) -> Option<&'a ChatSession> {
        let record = card.session.as_deref()?;
        self.workspace.read(cx).session_by_record(record)
    }

    /// The orb a card spins, and nothing for a card at rest.
    ///
    /// The thinking orb the sidebar's session row and the transcript already
    /// use — a card reporting a run is reporting the same run they are, and a
    /// second kind of orb for it would read as a second kind of work.
    /// What a card's orb needs, read out of the model before the card is built
    /// — the sidebar's [`SessionRow`] rule, and for the same reason: the orb
    /// leases the frame clock, which wants the app mutably.
    ///
    /// Nothing for a card at rest.
    fn card_working(&self, card: &Card, chat: Option<&ChatSession>) -> Option<Working> {
        match chat.filter(|chat| chat.streaming) {
            Some(chat) => Some(Working {
                state: transcript::orb_of(chat),
                since: chat.elapsed().unwrap_or_default(),
                frame: chat.transcript.mark.clone(),
            }),
            // Tagged busy by an agent with no session in this window — see
            // `board_set_card_status`. Nothing was written down when the tag
            // went on, so it runs off the window's own clock: the animation is
            // periodic, so where in the cycle it starts says nothing.
            None => (card.status == Some(Status::Busy)).then(|| Working {
                state: transcript::orb_for(&card.text),
                since: SINCE.elapsed(),
                frame: self.card_marks.of(&card.id),
            }),
        }
    }

    /// Where the board at `board_at` sits — see [`Scrolls`].
    fn scrolls(&self, project: usize, board_at: usize, cx: &App) -> Scroll {
        let id = self
            .workspace
            .read(cx)
            .board_in(project, board_at)
            .map(|board| board.id.clone())
            .unwrap_or_default();
        self.boards.of(&id)
    }

    // ── finding ──────────────────────────────────────────────────

    /// What the board is narrowed by right now, and the empty string when it is
    /// not narrowed at all. Empty while the bar is down whatever the field
    /// still holds, so a query never outlives the thing on screen saying so.
    fn board_query(&self, on: Option<&Member>, cx: &App) -> String {
        let leaf = self.leaf_of(on);
        match leaf.finding {
            true => leaf.find_field.read(cx).content().to_string(),
            false => String::new(),
        }
    }

    /// A lane's name, how many cards it holds, and the ids of the ones the query
    /// leaves standing — in the lane's own order.
    fn lane_cards(
        &self,
        project: usize,
        board_at: usize,
        id: &str,
        query: &str,
        cx: &App,
    ) -> Option<(String, usize, Vec<String>)> {
        let board = self.workspace.read(cx).board_in(project, board_at)?;
        let column = board.column(id)?;
        let cards: Vec<String> = column
            .cards
            .iter()
            .filter(|card| card_matches(card, board.handle_of(card).as_deref(), query))
            .map(|card| card.id.clone())
            .collect();
        Some((column.name.clone(), column.cards.len(), cards))
    }

    /// Put the find bar up, take the caret back to a field already up, or —
    /// where the caret is in it already — put it away. The chord that raises a
    /// bar is the one a reader reaches for to be rid of it, and the bar is the
    /// query: dismissing it clears what the board is narrowed by.
    pub(crate) fn find_card(&mut self, _: &FindCard, window: &mut Window, cx: &mut Context<Self>) {
        let field = self.leaf().find_field.clone();
        if self.leaf().finding && field.read(cx).focus_handle(cx).is_focused(window) {
            self.dismiss_find(&DismissFind, window, cx);
            return;
        }
        self.leaf_mut().finding = true;
        window.focus(&field.read(cx).focus_handle(cx), cx);
        cx.notify();
    }

    /// Done finding: the field goes and takes its query with it.
    pub(crate) fn dismiss_find(&mut self, _: &DismissFind, _: &mut Window, cx: &mut Context<Self>) {
        let field = self.leaf().find_field.clone();
        self.leaf_mut().finding = false;
        field.update(cx, |field, cx| field.clear(cx));
        cx.notify();
    }

    /// The bar at the board's top right. Up exactly while the query is —
    /// [`Leaf::finding`] carries no second state for a bar the reader may put
    /// away: a filter with nothing on screen to explain it is a board that has
    /// quietly lost cards.
    fn find_bar(&self, on: Option<&Member>, cx: &mut Context<Self>) -> Option<AnyElement> {
        if !self.leaf_of(on).finding || cx.has_active_drag() {
            return None;
        }
        let theme = Theme::of(cx).clone();
        Some(
            div()
                .absolute()
                .top(px(BOARD_INSET))
                .right(px(BOARD_INSET))
                .w(px(COLUMN_WIDTH))
                .flex()
                .flex_row()
                .items_center()
                .gap(px(6.))
                .px(px(8.))
                .py(px(2.))
                .rounded_full()
                .border_1()
                .border_color(theme.border)
                .bg(theme.surface_raised)
                .child(
                    icons::icon(icons::text::Search)
                        .size(px(14.))
                        .text_color(theme.text_faint),
                )
                .child(
                    div()
                        .flex_1()
                        .min_w_0()
                        .child(self.leaf_of(on).find_field.clone()),
                )
                .child(
                    theme
                        .ghost("board-find-close")
                        .p(px(4.))
                        .rounded_full()
                        .child(
                            icons::icon(icons::notifications::X)
                                .size(px(12.))
                                .text_color(theme.text_faint),
                        )
                        .tooltip(|window, cx| Tooltip::text("Stop finding", window, cx))
                        .on_click(cx.listener(|this, _, window, cx| {
                            cx.stop_propagation();
                            this.dismiss_find(&DismissFind, window, cx);
                        })),
                )
                .into_any_element(),
        )
    }

    // ── chrome ───────────────────────────────────────────────────

    /// The board, laid out the way the board says — see
    /// [`artifact::board::View`]. Everything either layout shares sits here:
    /// the pane's actions, and the aim a drag leaving every lane clears.
    pub fn board(
        &self,
        project: usize,
        board_at: usize,
        on: Option<&Member>,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) -> AnyElement {
        let Some((id, view)) = self
            .workspace
            .read(cx)
            .board_in(project, board_at)
            .map(|board| (board.id.clone(), board.view))
        else {
            return div().flex_1().into_any_element();
        };
        let body = match view {
            View::Lanes => self.lanes(project, board_at, on, window, cx),
            View::List => self.list(project, board_at, on, window, cx),
        };
        div()
            .flex_1()
            .min_h_0()
            .relative()
            .on_action(cx.listener(Self::commit_card))
            .on_action(cx.listener(Self::dismiss_card))
            .on_action(cx.listener(Self::dismiss_find))
            // Outermost, so it runs first: every move starts from nowhere, and
            // the lane and card the pointer is inside put it back. A pointer
            // over no lane at all leaves nothing aimed, which is what makes
            // dragging a card off the board mean nothing.
            //
            // The drift aimed is this pane's, the one drawn below — a layout
            // can have two boards up, and the focused one is not always the
            // one being dragged over.
            .on_drag_move(cx.listener({
                let drift = self.boards.of(&id).drift;
                move |this, event: &DragMoveEvent<CardDrag>, _, cx| {
                    drift.aim(event.event.position);
                    this.aim_card(None, cx);
                }
            }))
            // A release no lane took.
            .on_drop(cx.listener(|this, _: &CardDrag, _, cx| this.aim_card(None, cx)))
            .child(body)
            .children(self.view_pill(&id, view, cx))
            .children(self.find_bar(on, cx))
            .into_any_element()
    }

    /// The pill at the foot of a board: which way it is laid out, and the press
    /// that lays it out the other way.
    ///
    /// In the pane rather than in the band, because a pane of a layout has no
    /// band — see [`crate::view::arrangement`]. `../desktop` floats its controls
    /// at the same edge.
    ///
    /// Nothing at all while a card is in the air: the pill stands over the
    /// corner the card would be dropped in, and a drop it swallowed would be a
    /// card put back where it came from.
    fn view_pill(&self, id: &str, view: View, cx: &mut Context<Self>) -> Option<AnyElement> {
        if cx.has_active_drag() {
            return None;
        }
        let theme = Theme::of(cx).clone();
        let mut pill = div()
            .absolute()
            .right(px(BOARD_INSET))
            .bottom(px(BOARD_INSET))
            .flex()
            .flex_row()
            .items_center()
            .gap(px(2.))
            .p(px(2.))
            .rounded_full()
            .border_1()
            .border_color(theme.border)
            .bg(theme.surface_raised);
        for (at, glyph, label) in [
            (View::Lanes, icons::development::SquareKanban, "Lanes"),
            (View::List, icons::layout::LayoutList, "List"),
        ] {
            let held = id.to_owned();
            let on = at == view;
            pill = pill.child(
                theme
                    .ghost(SharedString::from(format!("board-view-{}", at.key())))
                    .p(px(5.))
                    .rounded_full()
                    .when(on, |el| el.bg(theme.element_active))
                    .child(icons::icon(glyph).size(px(14.)).text_color(match on {
                        true => theme.text,
                        false => theme.text_faint,
                    }))
                    .tooltip(move |window, cx| Tooltip::text(label, window, cx))
                    .on_click(cx.listener(move |this, _, _, cx| {
                        // The pill floats over the board, so the card or row
                        // under it answers for the same press — see the run on
                        // a card, which is held off its own card this way.
                        cx.stop_propagation();
                        this.set_board_view(&held, at, cx);
                    })),
            );
        }
        Some(pill.into_any_element())
    }

    /// The lanes across. A board opens with none, so the lane that makes one is
    /// always drawn — on an empty board it is the whole pane.
    fn lanes(
        &self,
        project: usize,
        board_at: usize,
        on: Option<&Member>,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) -> AnyElement {
        let scroll = self.scrolls(project, board_at, cx);
        let Some(board) = self.workspace.read(cx).board_in(project, board_at) else {
            return div().flex_1().into_any_element();
        };
        // Read out before drawing: each column borrows the board again.
        let ids: Vec<String> = board
            .columns
            .iter()
            .map(|column| column.id.clone())
            .collect();
        let lanes = ids.len();
        let columns: Vec<AnyElement> = ids
            .iter()
            .enumerate()
            .map(|(at, id)| {
                self.column(
                    Lane {
                        project,
                        board: board_at,
                        id,
                        at,
                        lanes,
                        on,
                    },
                    window,
                    cx,
                )
            })
            .collect();
        div()
            .size_full()
            .relative()
            .child(
                scroll::pane("board", Axes::Horizontal)
                    .size_full()
                    .flex()
                    .flex_row()
                    .px(px(BOARD_INSET))
                    .pt(px(BOARD_INSET))
                    .track_scroll(&scroll.across)
                    .children(columns)
                    .child(self.new_column_lane(cx)),
            )
            .child(scrollbars::Overlay::new(
                "board-bar",
                &scroll.across,
                bezel::gpui::Axis::Horizontal,
            ))
            // A lane off the side of the window is one a drag cannot reach:
            // reaching for it would mean letting go.
            .child(scroll::drift(
                &scroll.across,
                &scroll.drift,
                Axes::Horizontal,
            ))
            .into_any_element()
    }

    // ── the list ─────────────────────────────────────────────────

    /// The list down: every card of the board in one scroller, under the
    /// heading of the lane it sits in.
    ///
    /// The same cards, the same handles and the same drags as the lanes — a
    /// list is where they are drawn, not a second board. What it trades away is
    /// the lanes side by side; what it buys is a card's whole line at the width
    /// of the pane.
    fn list(
        &self,
        project: usize,
        board_at: usize,
        on: Option<&Member>,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) -> AnyElement {
        let scroll = self.scrolls(project, board_at, cx);
        let Some(board) = self.workspace.read(cx).board_in(project, board_at) else {
            return div().flex_1().into_any_element();
        };
        // Read out before drawing: each group borrows the board again.
        let ids: Vec<String> = board
            .columns
            .iter()
            .map(|column| column.id.clone())
            .collect();
        let lanes = ids.len();
        let groups: Vec<AnyElement> = ids
            .iter()
            .enumerate()
            .map(|(at, id)| {
                self.list_group(
                    Lane {
                        project,
                        board: board_at,
                        id,
                        at,
                        lanes,
                        on,
                    },
                    window,
                    cx,
                )
            })
            .collect();
        div()
            .size_full()
            .relative()
            .child(
                scroll::pane("board-list", Axes::Vertical)
                    .size_full()
                    .flex()
                    .flex_col()
                    // Room at the foot for the pill, which floats over the full
                    // width of the last row — see [`Self::view_pill`]. The lanes
                    // need none: what the pill covers there is the empty half of
                    // `Add a column`.
                    .pb(px(BOARD_INSET + PILL_CLEARANCE))
                    .track_scroll(&scroll.down)
                    .children(groups)
                    .child(self.new_column_row(cx)),
            )
            .child(scrollbars::Overlay::new(
                "board-list-bar",
                &scroll.down,
                bezel::gpui::Axis::Vertical,
            ))
            // A group off the foot of the window is one a drag cannot reach:
            // reaching for it would mean letting go.
            .child(scroll::drift(&scroll.down, &scroll.drift, Axes::Vertical))
            .into_any_element()
    }

    /// One lane as a group: its heading, its rows, and the row that writes a
    /// card into it.
    fn list_group(
        &self,
        lane: Lane<'_>,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) -> AnyElement {
        let Lane {
            project,
            board: board_at,
            id,
            at,
            lanes,
            on,
        } = lane;
        let theme = Theme::of(cx).clone();
        let id = id.to_owned();
        let query = self.board_query(on, cx);
        let Some((name, held, cards)) = self.lane_cards(project, board_at, &id, &query, cx) else {
            return div().into_any_element();
        };
        let mut rows: Vec<AnyElement> = cards
            .iter()
            .enumerate()
            .map(|(row, card)| {
                let next = cards.get(row + 1).map(String::as_str);
                self.list_row(
                    Slot {
                        project,
                        board: board_at,
                        id: card,
                        column: &id,
                        first: row == 0,
                        next,
                    },
                    on,
                    window,
                    cx,
                )
            })
            .collect();
        // An empty group has no row to hang the mark off, and nothing under it
        // to be pushed down by one drawn in the flow.
        if cards.is_empty() && self.aimed_at(&id, on, cx) {
            rows.push(self.landing_mark(Mark::Flow, cx));
        }
        // At the end the field is written into is drawn at: what is being
        // typed sits where the card will.
        if let Some(Editing::New(place, at)) = &self.leaf_of(on).editing
            && *at == id
        {
            let editor = div()
                .px(px(BOARD_INSET))
                .py(px(6.))
                .child(self.card_editor(on, cx))
                .into_any_element();
            match place {
                Place::Top => rows.insert(0, editor),
                Place::End => rows.push(editor),
            }
        }
        let lane = id.clone();
        let taken = id.clone();
        let written = id.clone();
        div()
            .flex_none()
            .flex()
            .flex_col()
            // The whole group, heading and all: a card held over the name of a
            // lane is being put in that lane. Coarser than the rows below it
            // and run before them, so whichever one the pointer is actually
            // over has the last word.
            .on_drag_move(cx.listener({
                let drift = self.scrolls(project, board_at, cx).drift;
                move |this, event: &DragMoveEvent<CardDrag>, _, cx| {
                    if !event.bounds.contains(&event.event.position) {
                        return;
                    }
                    drift.aim(event.event.position);
                    this.aim_card(
                        Some(Landing {
                            column: lane.clone(),
                            before: None,
                        }),
                        cx,
                    );
                }
            }))
            .on_drop(cx.listener(move |this, drag: &CardDrag, _, cx| {
                this.drop_card(drag, (project, board_at), &taken, cx);
            }))
            .child(self.list_group_header(
                &id,
                name,
                Tally {
                    held,
                    shown: cards.len(),
                },
                at,
                lanes,
                cx,
            ))
            .children(rows)
            // Nothing to write into a narrowed lane: a card that does not
            // answer the query would be filed and vanish in one gesture.
            .children((query.trim().is_empty()).then(|| {
                theme
                    .ghost(SharedString::from(format!("list-add-card-{id}")))
                    .flex_none()
                    .px(px(BOARD_INSET))
                    .py(px(6.))
                    .gap(px(6.))
                    .child(
                        icons::icon(icons::math::Plus)
                            .size(px(12.))
                            .text_color(theme.text_faint),
                    )
                    .child(
                        div()
                            .text_style(TextStyle::Callout)
                            .text_color(theme.text_faint)
                            .child("Add a card"),
                    )
                    .on_click(cx.listener(move |this, _, window, cx| {
                        this.edit(Editing::New(Place::End, written.clone()), window, cx);
                    }))
            }))
            .into_any_element()
    }

    /// A group's heading: the lane's name and count, and the `···` that moves
    /// or drops it — the lane's own header, on a row the width of the pane.
    ///
    /// `held` is the whole lane and `shown` what the query left of it. The
    /// `···` is built from `held`: Delete is refused on a lane holding cards,
    /// not on one showing them.
    fn list_group_header(
        &self,
        id: &str,
        name: String,
        tally: Tally,
        at: usize,
        lanes: usize,
        cx: &mut Context<Self>,
    ) -> AnyElement {
        let Tally { held, shown } = tally;
        let theme = Theme::of(cx).clone();
        let row = div()
            .flex_none()
            .h(px(LIST_HEADING_HEIGHT))
            .px(px(BOARD_INSET))
            .flex()
            .flex_row()
            .items_center()
            .gap(px(6.))
            .bg(theme.surface_raised)
            .border_b_1()
            .border_color(theme.border)
            .text_style(TextStyle::Subheadline);
        if matches!(&self.renaming, Some(Renaming::Column(at)) if at == id) {
            return row.child(self.name_field(cx)).into_any_element();
        }
        let named = id.to_owned();
        row.group("list-group")
            .child(
                div()
                    .id(SharedString::from(format!("list-group-name-{id}")))
                    .font_weight(FontWeight::MEDIUM)
                    .text_color(theme.text_muted)
                    .cursor_pointer()
                    .child(name)
                    .on_click(cx.listener(move |this, _, window, cx| {
                        this.start_rename(Renaming::Column(named.clone()), window, cx);
                    })),
            )
            .child(
                div()
                    .text_color(theme.text_faint)
                    .child(match shown == held {
                        true => held.to_string(),
                        false => format!("{shown}/{held}"),
                    }),
            )
            .child(div().flex_1())
            .child(
                self.menu_button(
                    SharedString::from(format!("list-group-menu-{id}")),
                    Some("list-group"),
                    icons::icon(icons::layout::Ellipsis)
                        .size(px(14.))
                        .text_color(theme.text_faint),
                    Menu::Lane(id.to_owned()),
                    cx,
                )
                .children(self.lane_menu(id, held, at, lanes, View::List, cx)),
            )
            .into_any_element()
    }

    /// One card as a row: what it is called, its first line, and what is being
    /// done with it.
    ///
    /// The first line rather than the card's whole text — see [`first_line`].
    fn list_row(
        &self,
        at: Slot<'_>,
        on: Option<&Member>,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) -> AnyElement {
        let Slot {
            project,
            board: board_at,
            id,
            column,
            next,
            ..
        } = at;
        if matches!(&self.leaf_of(on).editing, Some(Editing::Card(at)) if at == id) {
            return div()
                .px(px(BOARD_INSET))
                .py(px(6.))
                .child(self.card_editor(on, cx))
                .into_any_element();
        }
        let theme = Theme::of(cx).clone();
        let Some((card, handle)) = self
            .workspace
            .read(cx)
            .board_in(project, board_at)
            .and_then(|board| board.card(id).map(|card| (card, board.handle_of(card))))
        else {
            return div().into_any_element();
        };
        let text = card.text.clone();
        let status = card.status;
        let chat = self.card_session(card, cx);
        let live = chat.map(|chat| chat.id);
        let sessions = self.workspace.read(cx).settings.features.sessions;
        let working = self.card_working(card, chat);
        let (opened, run) = (id.to_owned(), id.to_owned());
        let ahead = cx.has_active_drag()
            && self
                .leaf_of(on)
                .landing
                .as_ref()
                .is_some_and(|at| at.before.as_deref() == Some(id));
        let behind = next.is_none() && self.aimed_at(column, on, cx);
        // The scroller's viewport, to clip the aim below with — a row scrolled
        // out of the pane still answers for the strip of window its bounds
        // landed on. The lanes clip against their lane; here there is one.
        let viewport = self.scrolls(project, board_at, cx).down;
        div()
            .id(SharedString::from(format!("list-row-{id}")))
            .group("list-row")
            .flex_none()
            .relative()
            .h(px(LIST_ROW_HEIGHT))
            .px(px(BOARD_INSET))
            .flex()
            .flex_row()
            .items_center()
            .gap(px(8.))
            .border_b_1()
            .border_color(theme.border)
            .cursor_pointer()
            .hover(|el| el.bg(theme.element_hover))
            // What to call this card out loud, in the mono face for the reason
            // the delete dialog sets a path there. Ahead of the text and at a
            // width of its own, so the lines under one another start together.
            .child(
                div()
                    .flex_none()
                    .w(px(LIST_HANDLE_WIDTH))
                    .text_style(TextStyle::Caption)
                    .font_family(theme.font_mono.clone())
                    .text_color(theme.text_faint)
                    .child(handle.unwrap_or_default()),
            )
            .child(
                div()
                    .flex_1()
                    .min_w_0()
                    .h(px(LIST_LINE))
                    .overflow_hidden()
                    .child(card_body(first_line(&text), window, cx)),
            )
            .children(resting(status).map(|status| status_chip(status, &theme)))
            // On show, not behind a hover — a card's run is what you look at
            // the board to see, and hiding it would mean hunting for the one
            // that is working.
            .children(working.map(|at| transcript::orb(at.state, at.since, &at.frame, cx)))
            .child(
                div()
                    .invisible()
                    .group_hover("list-row", |el| el.visible())
                    .flex()
                    .flex_row()
                    .items_center()
                    .gap(px(2.))
                    .children(sessions.then_some(live).flatten().map(|session| {
                        self.card_action("list-open", id, icons::social::MessageCircle, cx)
                            .on_click(cx.listener(move |this, _, window, cx| {
                                cx.stop_propagation();
                                this.select_session(session, window, cx);
                                this.show_pane(Pane::Chat, cx);
                            }))
                    }))
                    // Handing a card to an agent is refused once the card says
                    // something about itself: a tag is somebody already holding
                    // it, and a second agent at one task is work done twice.
                    // Opening the session it has stays — reading is not doing.
                    .children((sessions && live.is_none() && status.is_none()).then(|| {
                        self.card_action("list-run", id, icons::multimedia::Play, cx)
                            .on_click(cx.listener(move |this, _, _, cx| {
                                cx.stop_propagation();
                                this.dispatch_card(&run, cx);
                            }))
                    })),
            )
            .child(
                self.menu_button(
                    SharedString::from(format!("list-card-menu-{id}")),
                    Some("list-row"),
                    icons::icon(icons::layout::Ellipsis)
                        .size(px(14.))
                        .text_color(theme.text_faint),
                    Menu::Card(id.to_owned()),
                    cx,
                )
                .children(self.card_menu(id, cx)),
            )
            .on_drag(
                CardDrag {
                    card: id.to_owned(),
                    project,
                    board: board_at,
                },
                move |_, _, _, cx| {
                    let text = text.clone();
                    cx.new(|_| HeldCard { text })
                },
            )
            .on_drag_move(cx.listener({
                let (column, card, next) =
                    (column.to_owned(), id.to_owned(), next.map(str::to_owned));
                move |this, event: &DragMoveEvent<CardDrag>, _, cx| {
                    let at = event.event.position;
                    if !event.bounds.contains(&at) || !viewport.bounds().contains(&at) {
                        return;
                    }
                    // Which half of the row the pointer is in says which side
                    // of it the drop goes: in front of this one, or in front of
                    // whatever is under it — and under the last row is the end
                    // of the group.
                    let before = match at.y < event.bounds.center().y {
                        true => Some(card.clone()),
                        false => next.clone(),
                    };
                    this.aim_card(
                        Some(Landing {
                            column: column.clone(),
                            before,
                        }),
                        cx,
                    );
                }
            }))
            .on_click(cx.listener(move |this, _, window, cx| {
                this.edit(Editing::Card(opened.clone()), window, cx);
            }))
            .children(ahead.then(|| self.landing_mark(Mark::Top, cx)))
            .children(behind.then(|| self.landing_mark(Mark::Foot, cx)))
            .into_any_element()
    }

    /// The row that makes a lane, at the foot of the list — the list's answer
    /// to [`Self::new_column_lane`].
    fn new_column_row(&self, cx: &mut Context<Self>) -> AnyElement {
        let theme = Theme::of(cx).clone();
        theme
            .ghost("list-add-column")
            .flex_none()
            .px(px(BOARD_INSET))
            .py(px(8.))
            .gap(px(6.))
            .child(
                icons::icon(icons::math::Plus)
                    .size(px(12.))
                    .text_color(theme.text_faint),
            )
            .child(
                div()
                    .text_style(TextStyle::Callout)
                    .text_color(theme.text_faint)
                    .child("Add a column"),
            )
            .on_click(cx.listener(move |this, _, window, cx| {
                this.new_column(window, cx);
            }))
            .into_any_element()
    }

    // ── the lanes ────────────────────────────────────────────────

    fn column(&self, lane: Lane<'_>, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
        let Lane {
            project,
            board: board_at,
            id,
            at,
            lanes,
            on,
        } = lane;
        let theme = Theme::of(cx).clone();
        let id = id.to_owned();
        let query = self.board_query(on, cx);
        let Some((name, held, cards)) = self.lane_cards(project, board_at, &id, &query, cx) else {
            return div().into_any_element();
        };
        let mut rows: Vec<AnyElement> = cards
            .iter()
            .enumerate()
            .map(|(at, card)| {
                let next = cards.get(at + 1).map(String::as_str);
                self.card(
                    Slot {
                        project,
                        board: board_at,
                        id: card,
                        column: &id,
                        first: at == 0,
                        next,
                    },
                    on,
                    window,
                    cx,
                )
            })
            .collect();
        // An empty lane has no card to hang the mark off, and nothing under it
        // to be pushed down by one drawn in the flow.
        if cards.is_empty() && self.aimed_at(&id, on, cx) {
            rows.push(self.landing_mark(Mark::Flow, cx));
        }
        // At the end the field is written into is drawn at: what is being
        // typed sits where the card will.
        if let Some(Editing::New(place, at)) = &self.leaf_of(on).editing
            && *at == id
        {
            let editor = self.card_editor(on, cx);
            match place {
                Place::Top => rows.insert(0, editor),
                Place::End => rows.push(editor),
            }
        }

        let lane = id.clone();
        let taken = id.clone();
        // Only a card written at the foot pins the lane there — see
        // [`Self::edit`].
        let composing =
            matches!(&self.leaf_of(on).editing, Some(Editing::New(Place::End, at)) if *at == id);
        let (scroll, drift, follow) = self.scrolls(project, board_at, cx).lanes.of(&id);
        let bar_id = format!("lane-bar-{id}");
        div()
            .flex_none()
            .w(px(COLUMN_WIDTH))
            .h_full()
            .flex()
            .flex_col()
            .gap(px(8.))
            // The whole lane, header and all: a card held over the name of a
            // lane is being put in that lane. Coarser than the cards below it
            // and run before them, so whichever one the pointer is actually
            // over has the last word.
            .on_drag_move(cx.listener({
                let drift = drift.clone();
                move |this, event: &DragMoveEvent<CardDrag>, _, cx| {
                    if !event.bounds.contains(&event.event.position) {
                        return;
                    }
                    // Aimed only while the pointer is over this lane, so the
                    // lane it leaves stops rather than drifting on a pointer
                    // that has gone elsewhere.
                    drift.aim(event.event.position);
                    this.aim_card(
                        Some(Landing {
                            column: lane.clone(),
                            before: None,
                        }),
                        cx,
                    );
                }
            }))
            .on_drop(cx.listener(move |this, drag: &CardDrag, _, cx| {
                this.drop_card(drag, (project, board_at), &taken, cx);
            }))
            .child(self.column_header(
                &id,
                name,
                Tally {
                    held,
                    shown: cards.len(),
                },
                at,
                lanes,
                cx,
            ))
            .child(
                div()
                    .relative()
                    .flex_1()
                    .min_h_0()
                    .child(
                        scroll::pane(SharedString::from(format!("column-{id}")), Axes::Vertical)
                            .size_full()
                            // The space between two lanes, carried by the lane
                            // rather than as a gap on the row: a bar is clipped
                            // to the pane it reports on, so only a lane that
                            // owns the whole channel can put its thumb down the
                            // middle of it.
                            .pr(LANE_CHANNEL)
                            // The foot of the scroll, where `Add a card` sits:
                            // the lane's own gap ends at the last card, and
                            // without this the row lands on the lane's edge.
                            // `../desktop` pads the same place, by enough to
                            // clear the controls bar it floats there.
                            .pb(px(8.))
                            .track_scroll(&scroll)
                            .flex()
                            .flex_col()
                            .gap(px(8.))
                            .children(rows)
                            // Nothing to write into a narrowed lane: a card
                            // that does not answer the query would be filed
                            // and vanish in one gesture.
                            .children(query.trim().is_empty().then(|| {
                                theme
                                    .ghost(SharedString::from(format!("add-card-{id}")))
                                    .flex_none()
                                    .px(px(8.))
                                    .py(px(6.))
                                    .gap(px(6.))
                                    .child(
                                        icons::icon(icons::math::Plus)
                                            .size(px(12.))
                                            .text_color(theme.text_faint),
                                    )
                                    .child(
                                        div()
                                            .text_style(TextStyle::Callout)
                                            .text_color(theme.text_faint)
                                            .child("Add a card"),
                                    )
                                    .on_click(cx.listener(move |this, _, window, cx| {
                                        this.edit(Editing::New(Place::End, id.clone()), window, cx);
                                    }))
                            })),
                    )
                    // The lane's own half of the gesture: a card held at the
                    // foot of a full lane brings the rest of it up.
                    .child(scroll::drift(&scroll, &drift, Axes::Vertical))
                    // A new card is written at the lane's end, and grows as it
                    // is typed into: the lane stays at that end for as long as
                    // it is left there, and lets go the moment it is scrolled
                    // up — the transcript's rule, and the same element.
                    .children(composing.then(|| scroll::follow(&scroll, &follow)))
                    .child(
                        scrollbars::Overlay::new(bar_id, &scroll, bezel::gpui::Axis::Vertical)
                            .end_inset(px(BOARD_INSET))
                            .channel(LANE_CHANNEL),
                    ),
            )
            .into_any_element()
    }

    /// The lane's name and count, and the `···` that moves or drops it.
    ///
    /// `at` is where the lane sits among `lanes`, which is what decides whether
    /// it can step either way — read here rather than in the menu, which is
    /// built from what the header was drawn with.
    ///
    /// `held` is the whole lane and `shown` what the query left of it. The
    /// `···` is built from `held`: Delete is refused on a lane holding cards,
    /// not on one showing them.
    fn column_header(
        &self,
        id: &str,
        name: String,
        tally: Tally,
        at: usize,
        lanes: usize,
        cx: &mut Context<Self>,
    ) -> AnyElement {
        let Tally { held, shown } = tally;
        let theme = Theme::of(cx).clone();
        let row = div()
            .flex_none()
            .pl(px(4.))
            // The channel the lane's bar runs in, which the scroll below pads
            // its content by: the header is a box of its own and outside that
            // scroll, so it reserves the same room or the `···` stands over the
            // bar while the cards under it stop short of one.
            .pr(LANE_CHANNEL)
            .flex()
            .flex_row()
            .items_center()
            .gap(px(6.))
            .text_style(TextStyle::Subheadline);
        if matches!(&self.renaming, Some(Renaming::Column(at)) if at == id) {
            return row.child(self.name_field(cx)).into_any_element();
        }
        let named = id.to_owned();
        row.group("column")
            .child(
                div()
                    .id(SharedString::from(format!("column-name-{id}")))
                    .font_weight(FontWeight::MEDIUM)
                    .text_color(theme.text_muted)
                    .cursor_pointer()
                    .child(name)
                    .on_click(cx.listener(move |this, _, window, cx| {
                        this.start_rename(Renaming::Column(named.clone()), window, cx);
                    })),
            )
            .child(
                div()
                    .text_color(theme.text_faint)
                    .child(match shown == held {
                        true => held.to_string(),
                        false => format!("{shown}/{held}"),
                    }),
            )
            .child(div().flex_1())
            .child(
                self.menu_button(
                    SharedString::from(format!("column-menu-{id}")),
                    Some("column"),
                    icons::icon(icons::layout::Ellipsis)
                        .size(px(14.))
                        .text_color(theme.text_faint),
                    Menu::Lane(id.to_owned()),
                    cx,
                )
                .children(self.lane_menu(id, held, at, lanes, View::Lanes, cx)),
            )
            .into_any_element()
    }

    /// What the `···` does to a lane: which way it moves, and whether it stays.
    ///
    /// A lane at an end is not offered the step it cannot take, and one still
    /// holding cards carries Delete as a row it cannot choose — the refusal is
    /// worth saying, and a button simply withheld says nothing.
    ///
    /// The step is one place along the board's own order of its columns, which
    /// is the order the tools speak in — see `mcp::tools::board`. What `view`
    /// decides is only what to call it: that order runs across the lanes and
    /// down the list, so the same step is left in one and up in the other.
    fn lane_menu(
        &self,
        id: &str,
        count: usize,
        at: usize,
        lanes: usize,
        view: View,
        cx: &mut Context<Self>,
    ) -> Option<AnyElement> {
        if self.menu != Some(Menu::Lane(id.to_owned())) {
            return None;
        }
        // What each direction is called. The step and the new lane are the
        // same two directions, said the way the layout reads.
        let before = match view {
            View::Lanes => ("Add column left", "Add column right"),
            View::List => ("Add column above", "Add column below"),
        };
        let (back, on) = match view {
            View::Lanes => (
                ("Move left", icons::arrows::ArrowLeft),
                ("Move right", icons::arrows::ArrowRight),
            ),
            View::List => (
                ("Move up", icons::arrows::ArrowUp),
                ("Move down", icons::arrows::ArrowDown),
            ),
        };
        // First, and the only row here that makes something: the `Add a card`
        // at the lane's foot is a long way down a full lane, and what is
        // written from the head of one belongs at the head of it.
        let written = id.to_owned();
        let mut rows = vec![menu::row(
            Item::action("Add card").with_icon(icons::math::Plus),
            move |this, window, cx| {
                this.edit(Editing::New(Place::Top, written.clone()), window, cx)
            },
        )];
        // Then the two that write a lane either side of this one, so a board
        // is not only ever grown at its right-hand end.
        for (after, label) in [(false, before.0), (true, before.1)] {
            let beside = id.to_owned();
            rows.push(menu::row(
                Item::action(label).with_icon(icons::math::Plus),
                move |this, window, cx| this.new_column_beside(&beside, after, window, cx),
            ));
        }
        if at > 0 {
            let moved = id.to_owned();
            rows.push(menu::row(
                Item::action(back.0).with_icon(back.1),
                move |this, _, cx| this.shift_column(&moved, -1, cx),
            ));
        }
        if at + 1 < lanes {
            let moved = id.to_owned();
            rows.push(menu::row(
                Item::action(on.0).with_icon(on.1),
                move |this, _, cx| this.shift_column(&moved, 1, cx),
            ));
        }
        let drop = Item::action("Delete column").with_icon(icons::files::Trash);
        let drop = match count {
            0 => drop,
            _ => drop
                .disabled()
                .with_tooltip("A column is only where work sits — move the cards out first."),
        };
        let dropped = id.to_owned();
        rows.push(menu::row(drop, move |this, _, cx| {
            this.drop_column(&dropped, cx)
        }));
        let card = SharedString::from(format!("lane-menu-{id}"));
        Some(popover::anchored_menu_below(
            card.clone(),
            self.menu_card(card, rows, cx),
            None,
        ))
    }

    /// Step a lane one place, and keep the menu on it: moving twice is two
    /// presses on the same row, not a menu reopened between them.
    fn shift_column(&mut self, id: &str, step: isize, cx: &mut Context<Self>) {
        self.workspace
            .update(cx, |workspace, cx| workspace.move_column(id, step, cx));
        cx.notify();
    }

    /// The lane that makes a lane, always at the right-hand end.
    fn new_column_lane(&self, cx: &mut Context<Self>) -> AnyElement {
        let theme = Theme::of(cx).clone();
        div()
            .flex_none()
            .w(px(COLUMN_WIDTH))
            .h_full()
            .child(
                theme
                    .ghost("add-column")
                    .flex_none()
                    .px(px(8.))
                    .py(px(6.))
                    .gap(px(6.))
                    .child(
                        icons::icon(icons::math::Plus)
                            .size(px(12.))
                            .text_color(theme.text_faint),
                    )
                    .child(
                        div()
                            .text_style(TextStyle::Callout)
                            .text_color(theme.text_faint)
                            .child("Add a column"),
                    )
                    .on_click(cx.listener(move |this, _, window, cx| {
                        this.new_column(window, cx);
                    })),
            )
            .into_any_element()
    }

    fn card(
        &self,
        at: Slot<'_>,
        on: Option<&Member>,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) -> AnyElement {
        let Slot {
            project,
            board: board_at,
            id,
            column,
            first,
            next,
        } = at;
        if matches!(&self.leaf_of(on).editing, Some(Editing::Card(at)) if at == id) {
            return self.card_editor(on, cx);
        }
        let theme = Theme::of(cx).clone();
        let Some((card, handle)) = self
            .workspace
            .read(cx)
            .board_in(project, board_at)
            .and_then(|board| board.card(id).map(|card| (card, board.handle_of(card))))
        else {
            return div().into_any_element();
        };
        let text = card.text.clone();
        let status = card.status;
        let chat = self.card_session(card, cx);
        let live = chat.map(|chat| chat.id);
        let sessions = self.workspace.read(cx).settings.features.sessions;
        let working = self.card_working(card, chat);
        let (opened, run) = (id.to_owned(), id.to_owned());
        // The mark is drawn by the card it names, and by the last card in a
        // lane aimed at its end. Only while something is in the air: what the
        // last drop left is still sitting in `landing`.
        let ahead = cx.has_active_drag()
            && self
                .leaf_of(on)
                .landing
                .as_ref()
                .is_some_and(|at| at.before.as_deref() == Some(id));
        let behind = next.is_none() && self.aimed_at(column, on, cx);
        // The lane's viewport, to clip the aim below with. A hitbox carries
        // its content mask for the hit test but hands `on_drag_move` the raw
        // bounds, so a card scrolled out of its lane still answers for the
        // strip of window its bounds landed on — the lane's own header, most
        // of the time.
        let (viewport, ..) = self.scrolls(project, board_at, cx).lanes.of(column);
        div()
            .id(SharedString::from(format!("card-{id}")))
            .group("card")
            .flex_none()
            .relative()
            .p(px(10.))
            .rounded(px(Theme::control_radius()))
            .border_1()
            .border_color(theme.border)
            .bg(theme.surface_raised)
            .cursor_pointer()
            .hover(|el| el.border_color(theme.text_faint))
            .flex()
            .flex_col()
            .gap(px(6.))
            .child(
                div()
                    .flex()
                    .flex_row()
                    .items_start()
                    .gap(px(6.))
                    .child(
                        div()
                            .flex_1()
                            .min_w_0()
                            .max_h(px(CARD_MAX_HEIGHT))
                            .overflow_hidden()
                            .child(card_body(&text, window, cx)),
                    )
                    // What is done *to* the card. The row underneath carries
                    // the run; where the card sits is the drag.
                    .child(
                        self.menu_button(
                            SharedString::from(format!("card-menu-{id}")),
                            Some("card"),
                            icons::icon(icons::layout::Ellipsis)
                                .size(px(14.))
                                .text_color(theme.text_faint),
                            Menu::Card(id.to_owned()),
                            cx,
                        )
                        .children(self.card_menu(id, cx)),
                    ),
            )
            .child(
                div()
                    .flex()
                    .flex_row()
                    .items_center()
                    .gap(px(2.))
                    // What to call this card out loud, in the mono face for
                    // the reason the delete dialog sets a path there.
                    .children(handle.map(|handle| {
                        div()
                            .flex_none()
                            .text_style(TextStyle::Caption)
                            .font_family(theme.font_mono.clone())
                            .text_color(theme.text_faint)
                            .child(handle)
                    }))
                    .children(resting(status).map(|status| status_chip(status, &theme)))
                    .child(div().flex_1())
                    // Where ▶ stands, because it is what ▶ becomes: a card is
                    // either one you can start or one that is running, and the
                    // two belong in one slot. On show rather than behind the
                    // hover the actions sit behind — a card's run is what you
                    // look at the board to see.
                    .children(working.map(|at| transcript::orb(at.state, at.since, &at.frame, cx)))
                    .child(
                        div()
                            .invisible()
                            .group_hover("card", |el| el.visible())
                            .flex()
                            .flex_row()
                            .items_center()
                            .gap(px(2.))
                            // Handing a card to an agent is opening a session,
                            // so the control goes with them: with sessions off
                            // the play would start nothing, and the card is
                            // still a card without it.
                            .children(sessions.then_some(live).flatten().map(|session| {
                                self.card_action("open", id, icons::social::MessageCircle, cx)
                                    .on_click(cx.listener(move |this, _, window, cx| {
                                        cx.stop_propagation();
                                        this.select_session(session, window, cx);
                                        this.show_pane(Pane::Chat, cx);
                                    }))
                            }))
                            // Handing a card to an agent is refused once the card
                            // says something about itself: a tag is somebody
                            // already holding it, and a second agent at one task is
                            // the work done twice. Opening the session it has
                            // stays — reading is not doing.
                            .children((sessions && live.is_none() && status.is_none()).then(
                                || {
                                    self.card_action("run", id, icons::multimedia::Play, cx)
                                        .on_click(cx.listener(move |this, _, _, cx| {
                                            cx.stop_propagation();
                                            this.dispatch_card(&run, cx);
                                        }))
                                },
                            )),
                    ),
            )
            // Below the drag threshold nothing is picked up, so a press is
            // still the click that opens the card — and gpui drops the click
            // outright once a drag does start, so a card that was carried
            // somewhere does not also open where it landed.
            .on_drag(
                CardDrag {
                    card: id.to_owned(),
                    project,
                    board: board_at,
                },
                move |_, _, _, cx| {
                    let text = text.clone();
                    cx.new(|_| HeldCard { text })
                },
            )
            .on_drag_move(cx.listener({
                let (column, card, next) =
                    (column.to_owned(), id.to_owned(), next.map(str::to_owned));
                move |this, event: &DragMoveEvent<CardDrag>, _, cx| {
                    let at = event.event.position;
                    if !event.bounds.contains(&at) || !viewport.bounds().contains(&at) {
                        return;
                    }
                    // Which half of the card the pointer is in says which side
                    // of it the drop goes: in front of this one, or in front
                    // of whatever is under it — and under the last card is the
                    // end of the lane.
                    let before = match at.y < event.bounds.center().y {
                        true => Some(card.clone()),
                        false => next.clone(),
                    };
                    this.aim_card(
                        Some(Landing {
                            column: column.clone(),
                            before,
                        }),
                        cx,
                    );
                }
            }))
            .on_click(cx.listener(move |this, _, window, cx| {
                this.edit(Editing::Card(opened.clone()), window, cx);
            }))
            .children(
                ahead.then(|| self.landing_mark(if first { Mark::Top } else { Mark::Above }, cx)),
            )
            .children(behind.then(|| self.landing_mark(Mark::Below, cx)))
            .into_any_element()
    }

    /// Whether the card in the air would land at the end of this lane.
    fn aimed_at(&self, column: &str, on: Option<&Member>, cx: &App) -> bool {
        cx.has_active_drag()
            && self
                .leaf_of(on)
                .landing
                .as_ref()
                .is_some_and(|at| at.column == column && at.before.is_none())
    }

    /// Where the card would land, drawn in the gap between two cards rather
    /// than in the flow: a mark taking layout would push every card under it
    /// down, and the aim is read off the bounds it just moved — the mark would
    /// chase the pointer it is answering.
    fn landing_mark(&self, at: Mark, cx: &Context<Self>) -> AnyElement {
        let theme = Theme::of(cx).clone();
        let mark = div().h(px(2.)).rounded_full().bg(theme.accent);
        if at == Mark::Flow {
            return mark.flex_none().into_any_element();
        }
        let mark = mark.absolute().left_0().right_0();
        match at {
            Mark::Above => mark.top(px(-5.)),
            Mark::Top => mark.top_0(),
            Mark::Foot => mark.bottom_0(),
            _ => mark.bottom(px(-5.)),
        }
        .into_any_element()
    }

    /// One glyph on a card's hover row.
    fn card_action(
        &self,
        name: &'static str,
        id: &str,
        glyph: &'static [u8],
        cx: &Context<Self>,
    ) -> Stateful<Div> {
        let theme = Theme::of(cx).clone();
        theme
            .ghost(SharedString::from(format!("card-{name}-{id}")))
            .p(px(3.))
            .child(
                icons::icon(glyph)
                    .size(px(12.))
                    .text_color(theme.text_faint),
            )
    }

    fn card_editor(&self, on: Option<&Member>, cx: &Context<Self>) -> AnyElement {
        let theme = Theme::of(cx).clone();
        div()
            .flex_none()
            .p(px(8.))
            .rounded(px(Theme::control_radius()))
            .border_1()
            .border_color(theme.accent)
            .bg(theme.surface_raised)
            .flex()
            .flex_col()
            .gap(px(4.))
            .child(self.leaf_of(on).card_field.clone())
            .child(
                div()
                    .text_style(TextStyle::Subheadline)
                    .font_family(theme.font_mono.clone())
                    .text_color(theme.text_faint)
                    .child("enter file · esc cancel"),
            )
            .on_mouse_down_out(cx.listener(|this, _, _, cx| this.commit(cx)))
            .into_any_element()
    }
}

#[cfg(test)]
#[path = "../../tests/unit/board_find.rs"]
mod find_tests;