cydonia 0.1.8

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
//! The projects sidebar: a folding heading per project, and every session,
//! article and table in it. The window's grid lives in [`crate::view::root`];
//! this draws on it.

use crate::{
    model::{session::ChatSession, settings::Features, update},
    view::{
        article::TogglePlainText,
        component::{
            menu::{self, Menu},
            transcript,
        },
        keymap::{self, Command},
        root::{self, CommitName, Cydonia, DismissName, NewSession, OpenProject, Pane},
        settings::Section,
    },
};
use bezel::ui::scroll as scrollbars;
use bezel::{
    agent::orbs::{OrbState, engine::Frame},
    gpui::{
        self, AnyElement, App, Bounds, Context, Div, Empty, Entity, Focusable as _, FontWeight,
        Hsla, MouseButton, Pixels, Point, ScrollStrategy, SharedString, Stateful,
        UniformListDecoration, Window, div, prelude::*, px, uniform_list,
    },
    theme::{TextStyle, Theme, Typeset},
    ui::{
        icons::{self, Icon},
        input::Case,
        menu::Item,
        popover,
        surface::Surfaced as _,
        tooltip::Tooltip,
        widgets::{Buttons, Content, Layout},
    },
};
use std::{cell::RefCell, cmp::Reverse, ops::Range, rc::Rc, time::Duration};

/// What the sidebar needs of a session to draw its row, read out of the model
/// before the row is built: a turn in flight puts a thinking orb in the mark's
/// place, and the orb leases the frame clock, which wants the app mutably.
struct SessionRow {
    project: usize,
    id: u64,
    label: String,
    icon: Option<Icon>,
    /// The turn in flight, as the orb needs it: which of the twelve, how long
    /// it has been running, and the buffer it paints into. `None` when nothing
    /// is in flight, which is what puts the agent's own mark back.
    working: Option<Working>,
    archived: bool,
}

/// A session's orb, read off the model with the row.
struct Working {
    state: OrbState,
    since: Duration,
    frame: Rc<RefCell<Frame>>,
}

/// One line of the sidebar. An address, not content: the label behind it is
/// read when the row is built, which [`uniform_list`] only does for the rows on
/// screen.
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum Row {
    Project(usize),
    /// The line the archived entries are folded under.
    Archive(usize),
    Session {
        project: usize,
        id: u64,
    },
    Board {
        project: usize,
        ix: usize,
    },
    Article {
        project: usize,
        ix: usize,
    },
    Table {
        project: usize,
        ix: usize,
    },
}

/// Whether the kind a row names is switched on. Articles have no switch, and
/// neither do the two rows that are not entries — a project heading and the
/// line its archive folds under stand whatever is listed beneath them.
fn shown(row: Row, features: &Features) -> bool {
    match row {
        Row::Session { .. } => features.sessions,
        Row::Board { .. } => features.boards,
        Row::Table { .. } => features.tables,
        Row::Project(_) | Row::Archive(_) | Row::Article { .. } => true,
    }
}

/// What the sidebar's name field is attached to. One field for all of them,
/// because only one row can be being named at a time. Each entry is held by
/// what identifies it — a session, a table's key — never by an index: that
/// moves the moment a neighbour is made or dropped, and the field would follow
/// it onto whichever entry slid underneath.
///
/// No article here: its title is the first line of its own page, which is
/// where it is written — see [`crate::view::article`].
#[derive(Clone, PartialEq, Eq)]
pub(crate) enum Renaming {
    Session(u64),
    Table(String),
    /// A lane on the open board. The one entry here that no row in the sidebar
    /// stands for — the field is drawn in the column's own header instead,
    /// which works because only one thing is ever being named.
    Column(String),
}

/// What an entry's row is written in: the one on screen at full strength, one
/// put away a step back from the rest.
pub(crate) fn tint(selected: bool, archived: bool, theme: &Theme) -> Hsla {
    match (selected, archived) {
        (true, _) => theme.text,
        (false, true) => theme.text_faint,
        (false, false) => theme.text_muted,
    }
}

/// A project on its way to another place in the list. The index is safe to
/// carry: nothing reorders the list while a drag is in flight.
#[derive(Clone)]
pub(crate) struct ProjectDrag(usize);

/// What rides under the cursor while a project is being carried.
struct Carried(SharedString);

impl Render for Carried {
    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
        let theme = Theme::of(cx).clone();
        popover::popover_card(&theme)
            .px(px(10.))
            .py(px(4.))
            .text_style(TextStyle::Callout)
            .text_color(theme.text)
            .child(self.0.clone())
    }
}

/// An entry's own name in the element tree: two rows must never share one.
fn key_of(entry: Row) -> String {
    match entry {
        Row::Project(ix) => format!("project-{ix}"),
        Row::Archive(ix) => format!("archive-{ix}"),
        Row::Session { project, id } => format!("session-{project}-{id}"),
        Row::Board { project, ix } => format!("board-{project}-{ix}"),
        Row::Article { project, ix } => format!("article-{project}-{ix}"),
        Row::Table { project, ix } => format!("table-{project}-{ix}"),
    }
}

/// The wash a row paints, and — with the 1px either side of it that used to be
/// the column's gap — the pitch the list lays every row out at. One height for
/// headings and rows alike, because [`uniform_list`] measures a single row and
/// gives every other one the same.
const ROW_PILL: f32 = 30.;
pub(crate) const ROW_HEIGHT: f32 = ROW_PILL + 2.;

/// How far the pinned heading's glass runs past the band it is seen in, and is
/// clipped away.
///
/// A lens bends what is behind it within [`bezel::theme::SurfaceSpec::rim`] of
/// its own edge, and lights the edge itself. On a bar one row tall that is the
/// whole of it: two bands and two hairlines, reading as a line ruled along the
/// top and the bottom. Run the glass out past the clip and only its middle —
/// the flat blur — is left in view.
const PINNED_BLEED: f32 = 20.;

/// Shared row styling keeps selection backgrounds full-width when indented.
pub(crate) fn row(
    id: impl Into<gpui::ElementId>,
    group: &'static str,
    selected: bool,
    indent: bool,
    theme: &Theme,
) -> Stateful<Div> {
    div()
        .id(id)
        .group(group)
        .h(px(ROW_PILL))
        .ml(px(root::SIDEBAR_GUTTER))
        .mr(px(root::SIDEBAR_GUTTER))
        .px(px(root::SIDEBAR_GUTTER))
        .when(indent, |el| el.pl(px(root::SIDEBAR_GUTTER + 14.)))
        .flex()
        .flex_row()
        .items_center()
        .gap(px(8.))
        .rounded(px(Theme::control_radius()))
        .cursor_pointer()
        .when(selected, |el| el.bg(theme.element_active))
        // Only off the open row: the hover wash is the weaker rung, and
        // painting it over the selection would dim what the pointer is on.
        .when(!selected, |el| el.hover(|el| el.bg(theme.element_hover)))
}

/// A row's name. The line height is what the field pins itself to: left to
/// gpui's default the label's box is φ×13, and renaming would resize the row
/// under the name being typed.
fn row_label(name: String, tint: Hsla) -> AnyElement {
    div()
        .flex_1()
        .min_w_0()
        .truncate()
        .text_style(TextStyle::Body)
        .line_height(px(18.))
        .text_color(tint)
        .child(name)
        .into_any_element()
}

/// The heading of the project whose entries are under the scroll, held at the
/// top of the list while they pass beneath it.
///
/// A decoration rather than a child of the column, because this is the one
/// place the scroll offset for the frame being drawn is known. Read off the
/// handle in `render` it would be the offset of the frame before, and the
/// heading would lag the rows it belongs to by one.
struct PinnedHead(Entity<Cydonia>);

impl UniformListDecoration for PinnedHead {
    fn compute(
        &self,
        visible: Range<usize>,
        _bounds: Bounds<Pixels>,
        scroll: Point<Pixels>,
        item_height: Pixels,
        _count: usize,
        _window: &mut Window,
        cx: &mut App,
    ) -> AnyElement {
        self.0.update(cx, |this, cx| {
            this.pinned_head(visible.start, scroll.y, item_height, cx)
        })
    }
}

impl Cydonia {
    fn sidebar_hover(&mut self, menu: Menu, hovered: bool, cx: &mut Context<Self>) {
        if hovered {
            if self.sidebar_hovered.as_ref() == Some(&menu) {
                return;
            }
            self.sidebar_hovered = Some(menu);
        } else if self.sidebar_hovered.as_ref() == Some(&menu) {
            self.sidebar_hovered = None;
        } else {
            return;
        }
        cx.notify();
    }

    pub(crate) fn sidebar(&self, cx: &mut Context<Self>) -> impl IntoElement + use<> {
        let theme = Theme::of(cx).clone();
        // Taken here, where the workspace is already open, because the two
        // tooltips below are built inside closures that outlive this borrow.
        let shortcuts = &self.workspace.read(cx).settings.shortcuts;
        let settings_chord = keymap::label(Command::OpenSettings, shortcuts);
        let open_chord = keymap::label(Command::OpenProject, shortcuts);
        let rows = self.rows(cx);
        let count = rows.len();
        div()
            .flex_none()
            .w(px(self.sidebar_width))
            .h_full()
            .bg(root::sidebar_bg(&theme))
            .flex()
            .flex_col()
            // The fold out at the trailing edge: the lights float in the
            // leading half of the strip, which is what leaves nothing there to
            // pad them clear of.
            .child(
                div()
                    .flex_none()
                    .h(px(root::HEADER_HEIGHT))
                    .pr(px(8.))
                    .flex()
                    .flex_row()
                    .items_center()
                    .justify_end()
                    .child(self.fold_toggle(theme.text_faint, cx)),
            )
            .child(
                div()
                    .relative()
                    .flex_1()
                    .min_h_0()
                    .child(
                        uniform_list(
                            "project-list",
                            count,
                            cx.processor(move |this, range: Range<usize>, _, cx| {
                                range.map(|ix| this.sidebar_row(rows[ix], cx)).collect()
                            }),
                        )
                        .track_scroll(&self.rail)
                        .with_decoration(PinnedHead(cx.entity()))
                        .size_full(),
                    )
                    .child(
                        scrollbars::Overlay::new(
                            "sidebar-bar",
                            &self.rail.0.borrow().base_handle,
                            bezel::gpui::Axis::Vertical,
                        )
                        .visibility(
                            self.workspace
                                .read(cx)
                                .settings
                                .appearance
                                .sidebar_scrollbars
                                .into(),
                        ),
                    ),
            )
            .children(self.restart_notice(cx))
            .child(
                div()
                    .flex_none()
                    .mx(px(8.))
                    .mb(px(8.))
                    .flex()
                    .flex_row()
                    .items_center()
                    .justify_between()
                    .child(
                        theme
                            .ghost("settings")
                            .px(px(8.))
                            .py(px(6.))
                            // The mark alone, like every other control on this
                            // line. What it opens is said in the tooltip, which
                            // is where the two beside it say theirs.
                            // The chord read off the table the keymap was
                            // built from rather than typed beside the label:
                            // it is the reader's to move, and a tooltip naming
                            // the one it used to be is a lie nothing catches.
                            .tooltip(move |window, cx| match settings_chord.clone() {
                                Some(chord) => {
                                    Tooltip::with_keystroke("Settings", chord, window, cx)
                                }
                                None => Tooltip::text("Settings", window, cx),
                            })
                            .child(
                                icons::icon(icons::account::Settings)
                                    .size(px(13.))
                                    .text_color(theme.text_faint),
                            )
                            .on_click(cx.listener(|this, _, _, cx| {
                                this.open_settings(Section::General, cx)
                            })),
                    )
                    .child(
                        div().flex().flex_row().items_center().gap(px(2.)).child(
                            theme
                                .ghost("open-project")
                                .px(px(8.))
                                .py(px(6.))
                                .tooltip(move |window, cx| match open_chord.clone() {
                                    Some(chord) => {
                                        Tooltip::with_keystroke("Open project", chord, window, cx)
                                    }
                                    None => Tooltip::text("Open project", window, cx),
                                })
                                .child(
                                    icons::icon(icons::files::FolderPlus)
                                        .size(px(13.))
                                        .text_color(theme.text_faint),
                                )
                                .on_click(cx.listener(|this, _, window, cx| {
                                    this.open_project_action(&OpenProject, window, cx);
                                })),
                        ),
                    ),
            )
    }

    /// The one place outside settings that says a release is in hand: a line at
    /// the foot of the sidebar, over the controls, that restarts into it.
    ///
    /// Here rather than in the header because it is news and not a control for
    /// what is on screen — and the foot of this column is already where the
    /// things that are about the app itself live. It takes a row rather than
    /// floating over one, so nothing it appears in front of is ever covered.
    ///
    /// Nothing shows here until a bundle is staged and verified, which on most
    /// days is never — see [`crate::model::update`], and the Developer section
    /// for the switch that puts it on screen without one.
    fn restart_notice(&self, cx: &mut Context<Self>) -> Option<impl IntoElement + use<>> {
        let updater = update::of(cx)?;
        let version = updater.read(cx).ready()?;
        let theme = Theme::of(cx).clone();
        let ready = SharedString::from(format!("cydonia {version} is ready"));
        Some(
            theme
                .ghost("restart-to-update")
                .flex_none()
                .mx(px(8.))
                .mb(px(8.))
                .px(px(8.))
                .py(px(6.))
                .gap(px(6.))
                // No plate under it: `ghost` paints one on hover, and anything
                // at rest would have to be quieter than that to leave the hover
                // anything to say. What gives the line its weight is the mark,
                // which is the only accent-coloured thing in the column.
                .tooltip(move |window, cx| Tooltip::text(ready.clone(), window, cx))
                .child(
                    icons::icon(icons::development::CircleFadingArrowUp)
                        .size(px(13.))
                        .flex_none()
                        .text_color(theme.accent),
                )
                .child(
                    div()
                        .flex_1()
                        .min_w_0()
                        .truncate()
                        .text_style(TextStyle::Footnote)
                        .child("Restart to update"),
                )
                .child(theme.badge(version))
                .on_click(cx.listener(move |_, _, _, cx| {
                    updater.update(cx, |updater, cx| updater.restart(cx));
                })),
        )
    }

    /// The control that folds the sidebar away and brings it back. It belongs
    /// to whichever column runs along the window's left edge, so it changes
    /// strip across the collapse — and takes that strip's tone with it.
    pub(crate) fn fold_toggle(
        &self,
        tint: Hsla,
        cx: &mut Context<Self>,
    ) -> impl IntoElement + use<> {
        let theme = Theme::of(cx).clone();
        let label = if self.sidebar_open {
            "Hide sidebar"
        } else {
            "Show sidebar"
        };
        theme
            .ghost("toggle-sidebar")
            .p(px(4.))
            .tooltip(move |window, cx| Tooltip::text(label, window, cx))
            .child(
                icons::icon(if self.sidebar_open {
                    icons::layout::PanelLeftClose
                } else {
                    icons::layout::PanelLeftOpen
                })
                .size(px(14.))
                .text_color(tint),
            )
            .on_click(cx.listener(|this, _, _, cx| this.toggle_sidebar(cx)))
    }

    /// The heading held at the top of the list, and where to hold it.
    ///
    /// Measured in the list's own space — the decoration is laid out over the
    /// whole run of rows, so `y` here is counted from the first of them rather
    /// than from the top of what is on screen.
    fn pinned_head(
        &self,
        first: usize,
        scroll: Pixels,
        item_height: Pixels,
        cx: &mut Context<Self>,
    ) -> AnyElement {
        let rows = self.rows(cx);
        let head = |row: &Row| matches!(row, Row::Project(_));
        let Some(at) = rows
            .get(..=first)
            .and_then(|above| above.iter().rposition(head))
        else {
            return Empty.into_any_element();
        };
        let Row::Project(ix) = rows[at] else {
            return Empty.into_any_element();
        };
        // The next heading pushes this one out rather than sliding under it,
        // which is what keeps two of them from ever reading as one block.
        let next = rows[at + 1..]
            .iter()
            .position(head)
            .map(|after| item_height * (at + 1 + after) - item_height);
        let rest = item_height * at;
        let y = next.map_or(-scroll, |limit| (-scroll).min(limit));
        // Above its own place there is nothing to hold: the row itself is on
        // screen, in the list, where it belongs.
        if y <= rest {
            return Empty.into_any_element();
        }
        div()
            .size_full()
            .relative()
            .child(
                // Stateful, and so an id scope of its own: the copy inside
                // carries the same ids as the row it stands for.
                //
                // The band the glass is seen in, and what clips it to one row.
                div()
                    .id("pinned-head")
                    .absolute()
                    .top(y)
                    .left_0()
                    .w_full()
                    .h(px(ROW_HEIGHT))
                    .overflow_hidden()
                    .child(self.project_head(ix, true, cx)),
            )
            .into_any_element()
    }

    /// One project's heading: it folds, and its `+` opens what can be made in
    /// the project.
    ///
    /// `pinned` is the copy [`Cydonia::pinned_head`] holds at the top of the
    /// list. It gives up the pill for the column's full width, and takes the
    /// glass the floating cluster below it is cut from — a heading with rows
    /// running under it has to be read against whatever is passing.
    fn project_head(&self, ix: usize, pinned: bool, cx: &mut Context<Self>) -> AnyElement {
        let theme = Theme::of(cx).clone();
        let (name, expanded) = match self.workspace.read(cx).projects.get(ix) {
            Some(project) => (project.name(), project.expanded),
            None => return Empty.into_any_element(),
        };
        let carried = SharedString::from(name.clone());
        let head = div()
            .id(("project", ix))
            .group("project-head")
            .on_hover(cx.listener(move |this, hovered: &bool, _, cx| {
                this.sidebar_hover(Menu::Add(ix), *hovered, cx);
            }))
            // Pinned it runs edge to edge, and past the band it shows in at
            // the top and the bottom — see [`PINNED_BLEED`]. The label keeps
            // the x the pill's own margin and padding put it at.
            .when(pinned, |el| {
                el.absolute()
                    .top(px(-PINNED_BLEED))
                    .left_0()
                    .right_0()
                    .h(px(ROW_HEIGHT + 2. * PINNED_BLEED))
                    .px(px(8. + 6.))
            })
            .when(!pinned, |el| {
                el.relative()
                    .mx(px(8.))
                    .px(px(6.))
                    .h(px(ROW_PILL))
                    .rounded(px(Theme::control_radius()))
            })
            .flex()
            .flex_row()
            .items_center()
            .gap(px(6.))
            .cursor_pointer()
            // On the head, not the label: a name's colour is fixed when
            // its text is laid out, and only this div is stateful enough
            // to carry the hover that far.
            .text_color(theme.text_faint)
            .hover(|el| el.text_color(theme.text))
            .child(
                theme
                    .ghost(("project-fold", ix))
                    .flex_none()
                    .p(px(2.))
                    .child(
                        icons::icon(match expanded {
                            true => icons::files::FolderOpen,
                            false => icons::files::Folder,
                        })
                        .size(px(14.))
                        .text_color(theme.text_faint)
                        .group_hover("project-head", |el| el.text_color(theme.text)),
                    )
                    .on_click(cx.listener(move |this, _, _, cx| {
                        cx.stop_propagation();
                        this.toggle_project(ix, cx);
                    })),
            )
            .child(
                div()
                    .flex_1()
                    .min_w_0()
                    .truncate()
                    .text_style(TextStyle::Callout)
                    .font_weight(FontWeight::MEDIUM)
                    .child(name),
            )
            .child(
                self.menu_button(
                    ("project-add", ix),
                    Some("project-head"),
                    icons::icon(icons::math::Plus)
                        .size(px(12.))
                        .text_color(theme.text_faint)
                        .group_hover("project-head", |el| el.text_color(theme.text)),
                    Menu::Add(ix),
                    cx,
                )
                .children(self.add_menu(ix, cx)),
            )
            .children(self.project_menu(ix, cx))
            .on_mouse_down(
                MouseButton::Right,
                cx.listener(move |this, _, _, cx| this.toggle_menu(Menu::Project(ix), cx)),
            )
            // A press on the copy is a press on where it came from: the list
            // goes back to the heading it is standing in for, rather than
            // folding away the project you are reading. Its own folder mark
            // still folds — that press stops before it reaches here.
            .on_click(cx.listener(move |this, _, _, cx| match pinned {
                true => this.scroll_to_project(ix, cx),
                false => this.toggle_project(ix, cx),
            }))
            // Carried by its heading, and dropped on the heading it is to sit
            // in front of. Nothing else in the column is draggable: what the
            // entries are ordered by is when they were last written.
            .on_drag(ProjectDrag(ix), move |_, _, _, cx| {
                let carried = carried.clone();
                cx.new(|_| Carried(carried))
            })
            .drag_over::<ProjectDrag>(move |style, _, _, cx| style.bg(Theme::of(cx).element_active))
            .on_drop(cx.listener(move |this, drag: &ProjectDrag, _, cx| {
                this.move_project(drag.0, ix, cx);
            }));
        // Its own menu opens on the press rather than the click, so the note
        // has to be here too — read stale, a right press would swallow.
        let head = self.menu_press(head, Menu::Project(ix), cx);
        match pinned {
            // The same token the cluster at the foot of the column mounts on,
            // so the two glasses in the sidebar move together.
            true => head
                .surface(&theme, theme.popover_surface)
                .into_any_element(),
            false => head.into_any_element(),
        }
    }

    /// Entries ordered by last user submission for sessions, last edit otherwise.
    ///
    /// One list rather than four: the kinds are told apart by their marks, and
    /// grouping by kind buries the table you are working in under every article
    /// you are not. Only the addresses are ordered — each kind's own list keeps
    /// the indices these carry.
    pub(crate) fn entries(&self, project: usize, cx: &App) -> Vec<Row> {
        let workspace = self.workspace.read(cx);
        let Some(open) = workspace.projects.get(project) else {
            return Vec::new();
        };
        let features = &workspace.settings.features;
        let sessions = open.sessions.iter().map(|chat| {
            (
                chat.closed,
                chat.touched(),
                Row::Session {
                    project,
                    id: chat.id,
                },
            )
        });
        let boards = open
            .boards
            .iter()
            .enumerate()
            .map(|(ix, board)| (board.archived, board.touched, Row::Board { project, ix }));
        let articles = open.articles.iter().enumerate().map(|(ix, article)| {
            (
                article.archived,
                article.touched,
                Row::Article { project, ix },
            )
        });
        // The store keeps seconds; every other stamp here is milliseconds.
        let tables = open.tables.iter().enumerate().map(|(ix, table)| {
            let at = table.updated_at.unwrap_or(table.created_at).max(0) as u128;
            (table.archived, at * 1000, Row::Table { project, ix })
        });
        let mut entries: Vec<(bool, u128, Row)> = sessions
            .chain(boards)
            .chain(articles)
            .chain(tables)
            .collect();
        // A project is read off disk whole whatever is switched on, so what a
        // switch hides it hides here — the entries stay in the project and in
        // memory, and turning it back on lists them again with nothing to
        // rescan.
        entries.retain(|(_, _, row)| shown(*row, features));
        // Archived entries sink; each half follows the entry's recency stamp.
        entries.sort_by_key(|(archived, touched, _)| (*archived, Reverse(*touched)));
        let split = entries.iter().position(|(archived, ..)| *archived);
        let mut rows: Vec<Row> = entries
            .iter()
            .take(split.unwrap_or(entries.len()))
            .map(|(_, _, row)| *row)
            .collect();
        if let Some(split) = split {
            rows.push(Row::Archive(project));
            if open.archive_open {
                rows.extend(entries[split..].iter().map(|(_, _, row)| *row));
            }
        }
        rows
    }

    /// Every line the sidebar shows, in order. Addresses only: a project with a
    /// thousand articles costs a thousand `Row`s here and reads a title for
    /// none of them.
    pub(crate) fn rows(&self, cx: &Context<Self>) -> Vec<Row> {
        let mut rows = Vec::new();
        for p in 0..self.workspace.read(cx).projects.len() {
            rows.push(Row::Project(p));
            if self.workspace.read(cx).projects[p].expanded {
                rows.extend(self.entries(p, cx));
            }
        }
        rows
    }

    /// Open what a row points at — what a keyboard step does with its landing.
    /// The pointer never comes through here: each row carries its own
    /// `on_click`, which needs no [`Row`] to know what it is.
    pub(crate) fn open_row(&mut self, row: Row, window: &mut Window, cx: &mut Context<Self>) {
        match row {
            Row::Project(ix) => self.select_project(ix, cx),
            Row::Archive(ix) => self.toggle_archive(ix, cx),
            Row::Session { id, .. } => self.select_session(id, cx),
            Row::Board { project, ix } => self.open_board(project, ix, cx),
            Row::Article { project, ix } => self.open_article(project, ix, window, cx),
            Row::Table { project, ix } => self.open_table(project, ix, cx),
        }
    }

    /// Take the list back to where a project starts, heading and all.
    fn scroll_to_project(&mut self, ix: usize, cx: &mut Context<Self>) {
        let Some(at) = self
            .rows(cx)
            .iter()
            .position(|row| *row == Row::Project(ix))
        else {
            return;
        };
        self.rail.scroll_to_item(at, ScrollStrategy::Top);
        cx.notify();
    }

    /// Scroll the rail to a row, if it is not already on screen. `Nearest`
    /// rather than `Top`: a step to the neighbour below should move the list by
    /// a row, not throw the one you came from off the top of it.
    pub(crate) fn reveal(&mut self, row: Row, cx: &Context<Self>) {
        if let Some(ix) = self.rows(cx).iter().position(|at| *at == row) {
            self.rail.scroll_to_item(ix, ScrollStrategy::Nearest);
        }
    }

    /// One line, built when the list scrolls it into view. The box around it is
    /// what holds the pitch: the row inside paints the wash, and the pixel
    /// either side of it is the gap between two.
    fn sidebar_row(&self, row: Row, cx: &mut Context<Self>) -> AnyElement {
        let workspace = self.workspace.read(cx);
        let inner = match row {
            Row::Project(ix) => self.project_head(ix, false, cx),
            Row::Archive(ix) => self.archive_divider(ix, cx),
            Row::Session { project, id } => match self.session_of(project, id, cx) {
                Some(session) => self.session_row(session, cx),
                None => Empty.into_any_element(),
            },
            Row::Board { project, ix } => {
                match workspace
                    .projects
                    .get(project)
                    .and_then(|open| open.boards.get(ix).map(|board| board.label().to_owned()))
                {
                    Some(name) => self.board_row(project, ix, name, cx),
                    None => Empty.into_any_element(),
                }
            }
            Row::Article { project, ix } => {
                match workspace.projects.get(project).and_then(|open| {
                    open.articles
                        .get(ix)
                        .map(|article| article.label().to_owned())
                }) {
                    Some(title) => self.article_row(project, ix, title, cx).into_any_element(),
                    None => Empty.into_any_element(),
                }
            }
            Row::Table { project, ix } => {
                match workspace
                    .projects
                    .get(project)
                    .and_then(|open| open.tables.get(ix).map(|table| table.name.clone()))
                {
                    Some(name) => self.table_row(project, ix, name, cx).into_any_element(),
                    None => Empty.into_any_element(),
                }
            }
        };
        div()
            .id(SharedString::from(format!("sidebar-hover-{}", key_of(row))))
            .when(!matches!(row, Row::Project(_) | Row::Archive(_)), |el| {
                el.on_hover(cx.listener(move |this, hovered: &bool, _, cx| {
                    this.sidebar_hover(Menu::Entry(row), *hovered, cx);
                }))
            })
            .h(px(ROW_HEIGHT))
            .py(px(1.))
            .child(inner)
            .into_any_element()
    }

    /// What the sidebar needs of a session, read when its row comes on screen.
    fn session_of(&self, project: usize, id: u64, cx: &Context<Self>) -> Option<SessionRow> {
        let workspace = self.workspace.read(cx);
        let chat = workspace.projects.get(project)?.session(id)?;
        Some(SessionRow {
            project,
            id: chat.id,
            label: chat.label(),
            icon: workspace.agent_icon(&chat.entry.name),
            working: chat.streaming.then(|| Working {
                state: transcript::orb_of(chat),
                since: chat.elapsed().unwrap_or_default(),
                frame: chat.transcript.mark.clone(),
            }),
            archived: chat.closed,
        })
    }

    /// The line the archive folds under: what is put away is still listed, a
    /// step below everything still in hand.
    fn archive_divider(&self, project: usize, cx: &mut Context<Self>) -> AnyElement {
        let theme = Theme::of(cx).clone();
        let open = self
            .workspace
            .read(cx)
            .projects
            .get(project)
            .is_some_and(|open| open.archive_open);
        row(
            ("archive", project),
            "archive-row",
            false,
            self.workspace.read(cx).indent_project_rows,
            &theme,
        )
        .child(theme.disclosure(open).text_color(theme.text_faint))
        .child(
            div()
                .flex_none()
                .text_style(TextStyle::Callout)
                .text_color(theme.text_faint)
                .child("Archived"),
        )
        .child(div().flex_1().h(px(1.)).bg(theme.border))
        .on_click(cx.listener(move |this, _, _, cx| this.toggle_archive(project, cx)))
        .into_any_element()
    }

    fn toggle_archive(&mut self, project: usize, cx: &mut Context<Self>) {
        self.commit(cx);
        self.workspace.update(cx, |workspace, cx| {
            if let Some(open) = workspace.projects.get_mut(project) {
                open.archive_open = !open.archive_open;
            }
            cx.notify();
        });
    }

    /// Menus address a project by its place in the list, so the one open when
    /// it moves would be pointing at whichever project slid underneath.
    fn move_project(&mut self, from: usize, to: usize, cx: &mut Context<Self>) {
        self.menu = None;
        self.workspace
            .update(cx, |workspace, cx| workspace.move_project(from, to, cx));
    }

    fn toggle_project(&mut self, ix: usize, cx: &mut Context<Self>) {
        self.commit(cx);
        self.workspace
            .update(cx, |workspace, cx| workspace.toggle_project(ix, cx));
    }

    /// What the `+` starts here. Session first: it is what the sidebar is for.
    ///
    /// With more than one agent installed the session row asks which, since
    /// the one `⌘N` would pick is whoever the project last talked to — which
    /// leaves every other agent with no way in.
    fn add_menu(&self, ix: usize, cx: &mut Context<Self>) -> Option<AnyElement> {
        if self.menu != Some(Menu::Add(ix)) {
            return None;
        }
        let workspace = self.workspace.read(cx);
        let features = &workspace.settings.features;
        let (sessions, boards, tables) = (features.sessions, features.boards, features.tables);
        let agents: Vec<(String, Option<Icon>)> = workspace
            .settings
            .agents
            .iter()
            .map(|entry| (entry.name.clone(), workspace.agent_icon(&entry.name)))
            .collect();
        let mut rows = Vec::new();
        if sessions && agents.len() > 1 {
            let picks = agents
                .into_iter()
                .enumerate()
                .map(|(at, (name, icon))| {
                    let icon = icon.unwrap_or_else(|| icons::social::MessageCircle.into());
                    menu::row(Item::action(name).with_icon(icon), move |this, _, cx| {
                        this.select_project(ix, cx);
                        this.pick_agent(at, cx);
                    })
                })
                .collect();
            rows.push(menu::submenu(
                "New session",
                icons::social::MessageCirclePlus,
                picks,
            ));
        } else if sessions {
            rows.push(menu::row(
                Item::action("New session").with_icon(icons::social::MessageCirclePlus),
                move |this, window, cx| {
                    this.select_project(ix, cx);
                    this.new_session_action(&NewSession, window, cx);
                },
            ));
        }
        if boards {
            rows.push(menu::row(
                Item::action("New board").with_icon(icons::development::SquareKanban),
                move |this, window, cx| this.ask_new_board(ix, window, cx),
            ));
        }
        rows.push(menu::row(
            Item::action("New article").with_icon(icons::files::FilePlus),
            move |this, window, cx| this.new_article(ix, window, cx),
        ));
        if tables {
            rows.push(menu::row(
                Item::action("New table").with_icon(icons::files::Table2),
                move |this, _, cx| this.new_table(ix, cx),
            ));
        }
        let id = SharedString::from(format!("add-menu-{ix}"));
        Some(popover::anchored_menu_below(
            id.clone(),
            self.menu_card(id, rows, cx),
            None,
        ))
    }

    /// What a press on the heading opens. Removing closes the tab — the
    /// directory and everything in it stays where it is.
    fn project_menu(&self, ix: usize, cx: &mut Context<Self>) -> Option<AnyElement> {
        if self.menu != Some(Menu::Project(ix)) {
            return None;
        }
        let rows = vec![menu::row(
            Item::action("Remove project").with_icon(icons::files::FolderMinus),
            move |this, _, cx| this.close_project(ix, cx),
        )];
        let id = SharedString::from(format!("project-menu-{ix}"));
        Some(popover::anchored_menu_below(
            id.clone(),
            self.menu_card(id, rows, cx),
            None,
        ))
    }

    /// One session: its mark and its name.
    fn session_row(&self, session: SessionRow, cx: &mut Context<Self>) -> AnyElement {
        let entry = Row::Session {
            project: session.project,
            id: session.id,
        };
        let theme = Theme::of(cx).clone();
        let id = session.id;
        let selected =
            self.showing(cx) == Some(Pane::Chat) && self.workspace.read(cx).active_id() == Some(id);
        let tint = tint(selected, session.archived, &theme);
        // The agent's own mark, in the label's colour rather than any of its
        // own: every icon the registry publishes is a `currentColor` glyph, so
        // tinting is the only colour it will ever have. While a turn is in
        // flight the orb stands in its place — the same one the transcript
        // works under.
        let mark = if let Some(working) = session.working {
            // Wider than the slot it sits in, and left to spill: the orb is a
            // sphere where the marks around it are glyphs, and widening the
            // column for it would move every label in the sidebar to make room
            // for a row that is only sometimes working.
            transcript::orb(working.state, working.since, &working.frame, cx)
        } else {
            match session.icon {
                Some(icon) => icons::icon(icon)
                    .size(px(14.))
                    .text_color(tint)
                    .into_any_element(),
                None => Empty.into_any_element(),
            }
        };

        // The band draws the field when it is showing this entry — see
        // [`Cydonia::header_renaming`], which is what keeps one field from
        // being claimed by two places at once.
        let label = match self.renaming == Some(Renaming::Session(id))
            && self.header_renaming(cx).is_none()
        {
            true => self.name_field(cx),
            false => row_label(session.label, tint),
        };

        row(
            ("session", id),
            "session-row",
            selected,
            self.workspace.read(cx).indent_project_rows,
            &theme,
        )
        .child(
            div()
                .flex_none()
                .size(px(14.))
                .flex()
                .items_center()
                .justify_center()
                .child(mark),
        )
        .child(label)
        .child(self.archive_button(("session-archive", id), entry, session.archived, cx))
        .on_click(cx.listener(move |this, _, _, cx| {
            this.select_session(id, cx);
        }))
        .into_any_element()
    }

    /// One board: its mark and its name.
    fn board_row(
        &self,
        project: usize,
        ix: usize,
        name: String,
        cx: &mut Context<Self>,
    ) -> AnyElement {
        let theme = Theme::of(cx).clone();
        let workspace = self.workspace.read(cx);
        let selected = self.showing(cx) == Some(Pane::Board)
            && workspace.active == Some(project)
            && workspace
                .projects
                .get(project)
                .is_some_and(|open| open.board == Some(ix));
        let entry = Row::Board { project, ix };
        let board = workspace
            .projects
            .get(project)
            .and_then(|open| open.boards.get(ix));
        let archived = board.is_some_and(|board| board.archived);
        let tint = tint(selected, archived, &theme);
        // No inline field on a board's row, ever: a board is named by its panel
        // — see [`Self::rename_entry`].
        let label = row_label(name, tint);

        row(
            SharedString::from(format!("board-{project}-{ix}")),
            "board-row",
            selected,
            workspace.indent_project_rows,
            &theme,
        )
        .child(
            icons::icon(icons::development::SquareKanban)
                .size(px(14.))
                .flex_none()
                .text_color(tint),
        )
        .child(label)
        .child(self.archive_button(
            SharedString::from(format!("board-archive-{project}-{ix}")),
            entry,
            archived,
            cx,
        ))
        .on_click(cx.listener(move |this, _, _, cx| this.open_board(project, ix, cx)))
        .into_any_element()
    }

    /// The button every sidebar row carries in place of a menu: one press puts
    /// the entry away, or takes it back out. Rename and delete are the header's
    /// — see [`Self::entry_menu`].
    ///
    /// Shown only while the pointer is on the row, resolved from
    /// `sidebar_hovered` during render: GPUI can resolve a hover style
    /// differently in prepaint and paint.
    pub(crate) fn archive_button(
        &self,
        id: impl Into<gpui::ElementId>,
        entry: Row,
        archived: bool,
        cx: &Context<Self>,
    ) -> Stateful<Div> {
        let theme = Theme::of(cx).clone();
        let mark = match archived {
            true => icons::files::ArchiveRestore,
            false => icons::files::Archive,
        };
        theme
            .ghost(id)
            .flex_none()
            .when(
                self.sidebar_hovered.as_ref() != Some(&Menu::Entry(entry)),
                |el| el.hidden(),
            )
            .p(px(3.))
            .child(icons::icon(mark).size(px(14.)).text_color(theme.text_faint))
            .tooltip(move |window, cx| {
                Tooltip::text(
                    match archived {
                        true => "Unarchive",
                        false => "Archive",
                    },
                    window,
                    cx,
                )
            })
            .on_click(cx.listener(move |this, _, _, cx| {
                cx.stop_propagation();
                this.archive_entry(entry, !archived, cx);
            }))
    }

    /// The `···` in the band: everything for the entry filling the window.
    ///
    /// Delete is offered here and not from a sidebar row. In the sidebar you
    /// are running a pointer down a list and the row under it is whichever one
    /// you stopped on; in the header there is one thing it could mean, and it
    /// is the thing filling the window. A row carries archive alone — see
    /// [`Self::archive_button`].
    pub(crate) fn entry_menu(
        &self,
        at: Menu,
        entry: Row,
        archived: bool,
        cx: &mut Context<Self>,
    ) -> Option<AnyElement> {
        if self.menu.as_ref() != Some(&at) {
            return None;
        }
        let put = match archived {
            true => Item::action("Unarchive").with_icon(icons::files::ArchiveRestore),
            false => Item::action("Archive").with_icon(icons::files::Archive),
        };
        // `../desktop`'s rule for what a `···` may carry: only commands with no
        // affordance on the object. An article's title is the head of its own
        // page and a board's name in the band opens its identity panel, so
        // neither is offered a second route here. Everywhere else the name is
        // display-only and this is the way.
        let named = !matches!(entry, Row::Article { .. } | Row::Board { .. });
        let mut rows = vec![menu::row(put, move |this, _, cx| {
            this.archive_entry(entry, !archived, cx)
        })];
        if named {
            rows.insert(
                0,
                menu::row(
                    Item::action("Rename").with_icon(icons::text::SquarePen),
                    move |this, window, cx| this.rename_entry(entry, window, cx),
                ),
            );
        }
        // A page's measure. An article is never `named`, so nothing it could
        // sit above is here.
        if matches!(entry, Row::Article { .. }) {
            let workspace = self.workspace.read(cx);
            let plain_chord = keymap::label(Command::PlainText, &workspace.settings.shortcuts)
                .unwrap_or_default();
            let held = workspace
                .active_article()
                .and_then(|article| article.full_width);
            let wide = held.unwrap_or(workspace.wide_pages);
            // Only for a page carrying a measure of its own. On every other
            // page it is already what is happening, and a row that undoes
            // nothing is a row nobody can read the point of.
            if held.is_some() {
                rows.insert(
                    0,
                    menu::row(
                        Item::action("Use default width").with_icon(icons::layout::Columns2),
                        move |this, _, cx| this.set_full_width(None, cx),
                    ),
                );
            }
            rows.insert(
                0,
                menu::row(
                    Item::action("Full width")
                        .with_icon(icons::layout::UnfoldHorizontal)
                        .checked(wide),
                    move |this, _, cx| this.set_full_width(Some(!wide), cx),
                ),
            );
            // The markdown itself, for the times the document is in the way of
            // it. Above the width, which is about the page rather than what is
            // being edited on it.
            rows.insert(
                0,
                menu::row(
                    Item::action("Plain text")
                        .with_icon(icons::text::Code)
                        .with_keystroke(plain_chord)
                        .checked(self.plain_text(cx).unwrap_or_default()),
                    move |this, window, cx| this.toggle_plain_text(&TogglePlainText, window, cx),
                ),
            );
        }
        rows.push(menu::row(
            Item::action("Delete").with_icon(icons::files::Trash),
            move |this, _, cx| this.ask_delete(entry, cx),
        ));
        let id = SharedString::from("header-menu-card");
        Some(popover::anchored_menu_below(
            id.clone(),
            self.menu_card(id, rows, cx),
            None,
        ))
    }

    /// Drop an entry, file and all. Deleting the session on screen lands on
    /// the first remaining entry in the sidebar's displayed order.
    pub(crate) fn delete_entry(&mut self, entry: Row, window: &mut Window, cx: &mut Context<Self>) {
        let landing_project = match entry {
            Row::Session { project, id }
                if self.showing(cx) == Some(Pane::Chat)
                    && self.workspace.read(cx).active == Some(project)
                    && self.workspace.read(cx).active_id() == Some(id) =>
            {
                Some(project)
            }
            _ => None,
        };
        self.commit(cx);
        self.workspace.update(cx, |workspace, cx| match entry {
            Row::Session { id, .. } => workspace.close_session(id, cx),
            Row::Board { project, ix } => workspace.delete_board(project, ix, cx),
            Row::Article { project, ix } => workspace.delete_article(project, ix, cx),
            Row::Table { project, ix } => workspace.delete_table(project, ix, cx),
            Row::Project(_) | Row::Archive(_) => {}
        });
        if let Some(project) = landing_project
            && let Some(landing) = self
                .entries(project, cx)
                .into_iter()
                .find(|row| !matches!(row, Row::Archive(_)))
        {
            self.open_row(landing, window, cx);
            self.reveal(landing, cx);
        }
        cx.notify();
    }

    /// Put the name field on an entry's row, for the kinds named that way.
    /// Each is addressed by what identifies it, so the field cannot slide onto
    /// its neighbour if the list reorders under it.
    ///
    /// A board is named by two things at once, so it opens its identity panel
    /// instead — which lives under the band, so the board is brought to the
    /// front first. One way to name a board, wherever you asked from.
    fn rename_entry(&mut self, entry: Row, window: &mut Window, cx: &mut Context<Self>) {
        if let Row::Board { project, ix } = entry {
            let id = self
                .workspace
                .read(cx)
                .projects
                .get(project)
                .and_then(|open| open.boards.get(ix))
                .map(|board| board.id.clone());
            if let Some(id) = id {
                self.open_board(project, ix, cx);
                self.open_info(&id, window, cx);
            }
            return;
        }
        let workspace = self.workspace.read(cx);
        let what = match entry {
            Row::Session { id, .. } => Some(Renaming::Session(id)),
            Row::Table { project, ix } => workspace
                .projects
                .get(project)
                .and_then(|open| open.tables.get(ix))
                .map(|table| Renaming::Table(table.key.clone())),
            // An article is named in its own page, and the two that are not
            // entries have no name to take.
            Row::Article { .. } | Row::Board { .. } | Row::Project(_) | Row::Archive(_) => None,
        };
        if let Some(what) = what {
            self.start_rename(what, window, cx);
        }
    }

    /// Put an entry away, or bring it back. Where the flag lives is each
    /// kind's own business — a board's file, an article's properties, a row in
    /// the store — and the sidebar asks for it the same way.
    fn archive_entry(&mut self, entry: Row, archived: bool, cx: &mut Context<Self>) {
        self.workspace.update(cx, |workspace, cx| match entry {
            Row::Session { id, .. } => workspace.archive_session(id, archived, cx),
            Row::Board { project, ix } => {
                if let Some(id) = workspace
                    .projects
                    .get(project)
                    .and_then(|open| open.boards.get(ix))
                    .map(|board| board.id.clone())
                {
                    workspace.archive_board(&id, archived, cx);
                }
            }
            Row::Article { project, ix } => {
                if let Some(path) = workspace
                    .projects
                    .get(project)
                    .and_then(|open| open.articles.get(ix))
                    .map(|article| article.path.clone())
                {
                    workspace.archive_article(&path, archived, cx);
                }
            }
            Row::Table { project, ix } => {
                if let Some(key) = workspace
                    .projects
                    .get(project)
                    .and_then(|open| open.tables.get(ix))
                    .map(|table| table.key.clone())
                {
                    workspace.archive_table(&key, archived, cx);
                }
            }
            Row::Project(_) | Row::Archive(_) => {}
        });
    }

    /// The field, in the row's place. It carries its own press: `TextField`
    /// does not focus itself, and a press that reached the row would open what
    /// is being named out from under the name.
    pub(crate) fn name_field(&self, cx: &mut Context<Self>) -> AnyElement {
        div()
            .flex_1()
            .min_w_0()
            .on_mouse_down(
                MouseButton::Left,
                cx.listener(|this, _, window, cx| {
                    cx.stop_propagation();
                    window.focus(&this.name_field.read(cx).focus_handle(cx), cx);
                }),
            )
            // Pressing anywhere else is finishing, not abandoning — the name
            // typed is the name meant. `escape` is what discards.
            .on_mouse_down_out(cx.listener(|this, _, window, cx| {
                this.commit_name(&CommitName, window, cx);
            }))
            .child(self.name_field.clone())
            .into_any_element()
    }

    pub(crate) fn start_rename(
        &mut self,
        what: Renaming,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) {
        let workspace = self.workspace.read(cx);
        let label = match &what {
            Renaming::Session(id) => workspace
                .session(*id)
                .map(ChatSession::label)
                .unwrap_or_default(),
            Renaming::Table(key) => workspace
                .projects
                .iter()
                .flat_map(|open| open.tables.iter())
                .find(|table| table.key == *key)
                .map(|table| table.name.clone())
                .unwrap_or_default(),
            Renaming::Column(id) => workspace
                .active_board()
                .and_then(|board| board.column(id))
                .map(|column| column.name.clone())
                .unwrap_or_default(),
        };
        // A lane is named in one case — see [`artifact::board::column::heading`]
        // — and the field is put in it before the name lands, so what is typed
        // and what is stored are the same string.
        let case = match &what {
            Renaming::Column(_) => Case::Upper,
            _ => Case::Mixed,
        };
        self.name_field.update(cx, |field, cx| {
            field.set_case(case);
            field.set_content(label, cx);
        });
        // See [`Cydonia::open_info`] — the other way round.
        self.info = None;
        self.renaming = Some(what);
        window.focus(&self.name_field.read(cx).focus_handle(cx), cx);
        cx.notify();
    }

    pub(crate) fn commit_name(&mut self, _: &CommitName, _: &mut Window, cx: &mut Context<Self>) {
        let Some(what) = self.renaming.take() else {
            return;
        };
        let name = self.name_field.read(cx).content().to_string();
        self.workspace.update(cx, |workspace, cx| match what {
            Renaming::Session(id) => workspace.rename_session(id, name, cx),
            Renaming::Table(key) => workspace.rename_table(&key, name, cx),
            Renaming::Column(id) => workspace.rename_column(&id, name, cx),
        });
        cx.notify();
    }

    pub(crate) fn dismiss_name(&mut self, _: &DismissName, _: &mut Window, cx: &mut Context<Self>) {
        self.renaming = None;
        cx.notify();
    }
}