cydonia 0.1.6

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
//! The detail column: whichever pane is showing, and everything the turn in
//! flight stacks under it — plan, permission, queue, composer.

use crate::{
    model::session::{ChatSession, Choice},
    view::{
        component::{composer, transcript},
        root::{self, Cydonia, NewSession, Pane},
        settings::Section,
    },
};
use artifact::session::chat::PlanStatus;
use bezel::{
    gpui::{
        AnyElement, App, Axis, Context, DragMoveEvent, Empty, FocusHandle, Focusable as _,
        SharedString, Window, div, prelude::*, px,
    },
    motion::{Fade, Painter},
    theme::{TextStyle, Theme, Typeset},
    ui::{
        icons::{self, Icon},
        surface,
        widgets::{
            ButtonStyle, Buttons, Content, Controls, Layout, SPLIT_HANDLE_HIT, SplitStyle, Status,
        },
    },
};
use cacp::schema::{
    PermissionOptionKind, SessionConfigKind, SessionConfigOptionCategory, SessionConfigOptionValue,
    SessionConfigSelectOption, SessionConfigSelectOptions, SessionModeState,
};
use std::path::Path;
use surface::Surfaced as _;

/// Separate from the sidebar's payload so its resize listener stays idle.
struct ChangesResize;

struct TerminalResize;

/// Reserve 240px for chat, or split narrow windows evenly.
fn panel_width(preferred: f32, available: f32) -> f32 {
    let min = 240.0_f32.min(available / 2.);
    preferred.clamp(min, (available - 240.).max(min))
}

fn panel_height(preferred: f32, available: f32) -> f32 {
    let min = 120.0_f32.min(available / 2.);
    preferred.clamp(min, (available - 160.).max(min))
}

/// What the live session can be switched between, flattened to the one shape
/// the composer draws: its config options, then its modes.
///
/// Config first, because the model is a config option and it is the one people
/// came for. Booleans are left out — a menu of two rows is a toggle wearing a
/// menu, and the agent menu has nowhere to put a real one yet.
fn switches(chat: &ChatSession) -> Vec<composer::Switch> {
    let mut switches: Vec<composer::Switch> = chat
        .config
        .iter()
        .filter_map(|option| {
            let SessionConfigKind::Select(select) = &option.kind else {
                return None;
            };
            let options = select_options(&select.options);
            // A select with nothing to select is a menu with no rows.
            (!options.is_empty()).then(|| composer::Switch {
                id: composer::SwitchId::Config(option.id.to_string().into()),
                name: option.name.clone().into(),
                current: Some(select.current_value.to_string().into()),
                options,
            })
        })
        .collect();
    if let Some(modes) = chat
        .modes
        .as_ref()
        .filter(|modes| !modes.available_modes.is_empty())
        .filter(|modes| !covered_by_config(chat, modes))
    {
        switches.push(composer::Switch {
            id: composer::SwitchId::Mode,
            name: "Mode".into(),
            current: Some(modes.current_mode_id.to_string().into()),
            options: modes
                .available_modes
                .iter()
                .map(|mode| composer::SwitchOption {
                    id: mode.id.to_string().into(),
                    name: mode.name.clone().into(),
                })
                .collect(),
        });
    }
    switches
}

/// Whether the agent is already offering these modes as a config option.
///
/// Some agents report their modes twice — once through `session/new`'s `modes`
/// and again as a config option — and two switches onto one piece of state is
/// two ways to disagree about it. The config option wins: it is the general
/// mechanism, and its update is what confirms a change.
///
/// Matched on the values as well as on the category, because the category is
/// optional and an agent that leaves it off still sends the same list twice.
fn covered_by_config(chat: &ChatSession, modes: &SessionModeState) -> bool {
    chat.config.iter().any(|option| {
        if option.category == Some(SessionConfigOptionCategory::Mode) {
            return true;
        }
        let SessionConfigKind::Select(select) = &option.kind else {
            return false;
        };
        let values = select_options(&select.options);
        modes
            .available_modes
            .iter()
            .all(|mode| values.iter().any(|value| value.id.as_ref() == &*mode.id))
    })
}

/// A select's values, with a group's rows folded in beside the ungrouped ones.
/// A switch gets one flat card, and a group is a heading it has nowhere to put.
fn select_options(options: &SessionConfigSelectOptions) -> Vec<composer::SwitchOption> {
    fn one(option: &SessionConfigSelectOption) -> composer::SwitchOption {
        composer::SwitchOption {
            id: option.value.to_string().into(),
            name: option.name.clone().into(),
        }
    }
    match options {
        SessionConfigSelectOptions::Ungrouped(options) => options.iter().map(one).collect(),
        SessionConfigSelectOptions::Grouped(groups) => groups
            .iter()
            .flat_map(|group| group.options.iter().map(one))
            .collect(),
    }
}

/// A path as it is shown: `~` for a home directory nobody needs spelled out.
fn shown_path(path: &Path) -> String {
    let full = path.display().to_string();
    dirs::home_dir()
        .and_then(|home| {
            full.strip_prefix(home.to_str()?)
                .map(|rest| format!("~{rest}"))
        })
        .unwrap_or(full)
}

/// One of the two answers a permission request comes down to, with the *once*
/// and *always* forms of it read as one.
pub struct Verdict<'a> {
    /// What the button says: the once-form's own label, whatever the checkbox
    /// is set to. Agents word the always-form as a sentence — "Yes, and allow
    /// access to repos/ and ls commands" — and a sentence is not a button.
    label: &'a str,
    once: &'a str,
    always: Option<&'a str>,
}

impl Verdict<'_> {
    /// The option id this answer sends with the checkbox in that state. An
    /// always with no form to send falls back to the once: an agent offering
    /// "allow always" and no "reject always" still has to be refusable.
    pub fn id(&self, always: bool) -> String {
        match always {
            true => self.always.unwrap_or(self.once).to_owned(),
            false => self.once.to_owned(),
        }
    }
}

/// The request as an alert — a yes, a no, and a checkbox — or `None` when it
/// is not one.
///
/// ACP's four option kinds are two answers times "for how long", which is the
/// macOS permission alert exactly. It holds only while the two sides account
/// for every option the agent sent: the count is what catches a second option
/// of a kind already taken, and a kind we do not know. Dropping something the
/// agent asked about is not ours to do, so anything else falls to the stack.
pub fn alert(options: &[Choice]) -> Option<(Verdict<'_>, Verdict<'_>)> {
    let deny = verdict(options, false)?;
    let allow = verdict(options, true)?;
    let covered = 2 + usize::from(deny.always.is_some()) + usize::from(allow.always.is_some());
    (covered == options.len()).then_some((deny, allow))
}

/// One side of the request, if the agent offered its once-form. Without one
/// there is no button to put the checkbox under.
fn verdict(options: &[Choice], allow: bool) -> Option<Verdict<'_>> {
    let (once, ever) = match allow {
        true => (
            PermissionOptionKind::AllowOnce,
            PermissionOptionKind::AllowAlways,
        ),
        false => (
            PermissionOptionKind::RejectOnce,
            PermissionOptionKind::RejectAlways,
        ),
    };
    let of = |kind: PermissionOptionKind| options.iter().find(move |o| o.kind == kind);
    let once = of(once)?;
    Some(Verdict {
        label: &once.name,
        once: &once.id,
        always: of(ever).map(|option| option.id.as_str()),
    })
}

/// What is left to do where there is no agent to reach — the line under
/// [`agent_missing`]. `agent` is the one the session was opened on, and
/// nothing where a session was asked for and never opened; `others` is whether
/// `settings.toml` names any agent at all.
///
/// Three states with three ways out, and the shortest is worth saying. A
/// session whose own agent has gone while another is still here is the only
/// thing stranded, and opening one on that agent beats a download. Alone, it
/// is the install. Asked for on a machine with nothing on it, there is no
/// session yet to be stranded and the install is the whole of it.
pub fn adrift(agent: Option<&str>, others: bool) -> &'static str {
    match (agent, others) {
        (Some(_), true) => "Open a session on an agent that is, or install this one again.",
        (Some(_), false) => "No other agent is installed either.",
        (None, _) => "Install one to open a session here.",
    }
}

/// The title over it: which agent is missing, or that none is here at all — a
/// session asked for on a machine with nothing installed has no agent to name.
pub fn agent_missing(agent: Option<&str>) -> String {
    match agent {
        Some(agent) => format!("{agent} is not installed"),
        None => "No agent installed".to_owned(),
    }
}

/// The same said in one line, for the strip that stands under a transcript.
///
/// It names the place, where [`adrift`] does not: the empty state has a button
/// under it and the strip has only itself, so the destination has to be in the
/// words rather than on a control beneath them.
pub fn adrift_line(agent: &str, others: bool) -> String {
    let missing = agent_missing(Some(agent));
    match others {
        true => format!(
            "{missing} — open a session on an agent that is, or install it again in Settings › Agents."
        ),
        false => format!("{missing} — install one in Settings › Agents."),
    }
}

impl Cydonia {
    pub(crate) fn show_terminal(&mut self, window: &mut Window, cx: &mut Context<Self>) {
        if self.showing(cx) != Some(Pane::Chat) {
            return;
        }
        let Some(chat) = self.workspace.read(cx).active_session() else {
            return;
        };
        let (id, cwd) = (chat.id, chat.cwd.clone());
        let (_, terminal) = self.terminals.entry(id).or_insert_with(|| {
            (
                false,
                cx.new(|cx| super::component::terminal::Terminal::new(&cwd, cx)),
            )
        });
        window.focus(&terminal.focus_handle(cx), cx);
        self.terminals.get_mut(&id).unwrap().0 = true;
        cx.notify();
    }

    pub(crate) fn toggle_terminal(
        &mut self,
        _: &root::ToggleTerminal,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) {
        let id = self.workspace.read(cx).active_id();
        if let Some((visible, _)) = id.and_then(|id| self.terminals.get_mut(&id))
            && *visible
        {
            *visible = false;
            window.focus(&self.composer_focus_handle(cx), cx);
            cx.notify();
        } else {
            self.show_terminal(window, cx);
        }
    }

    pub fn composer_focus_handle(&self, cx: &App) -> FocusHandle {
        self.composer.focus_handle(cx)
    }

    /// Run `f` on the active session. Every composer action is this shape:
    /// the view knows which session is in front, the model owns it.
    fn with_active(&mut self, cx: &mut Context<Self>, f: impl FnOnce(&mut ChatSession)) {
        let Some(id) = self.workspace.read(cx).active_id() else {
            return;
        };
        self.workspace
            .update(cx, |workspace, cx| workspace.with_session(id, cx, f));
    }

    pub(crate) fn submit(&mut self, text: String, cx: &mut Context<Self>) {
        let Some(id) = self.workspace.read(cx).active_id() else {
            return;
        };
        self.workspace
            .update(cx, |workspace, cx| workspace.send(id, text, cx));
    }

    pub(crate) fn cancel_turn(&mut self, cx: &mut Context<Self>) {
        self.with_active(cx, |chat| chat.cancel());
    }

    /// The composer's agent chip. An ACP session is bound to the process that
    /// serves it, so picking another agent opens a session rather than
    /// swapping one out from under a transcript.
    pub(crate) fn pick_agent(&mut self, ix: usize, cx: &mut Context<Self>) {
        let entry = self.workspace.read(cx).settings.agents.get(ix).cloned();
        if let Some(entry) = entry {
            self.show_pane(Pane::Chat, cx);
            self.workspace
                .update(cx, |workspace, cx| workspace.new_session(entry, None, cx));
        }
    }

    /// What the composer needs from the session it is pointed at: the agent's
    /// name, its commands, whether a turn is in flight, and the agents it can
    /// be swapped for.
    pub(crate) fn sync_composer(&mut self, cx: &mut Context<Self>) {
        let workspace = self.workspace.read(cx);
        self.terminals
            .retain(|id, _| workspace.session(*id).is_some());
        let agents: Vec<composer::Agent> = workspace
            .settings
            .agents
            .iter()
            .map(|entry| composer::Agent {
                name: entry.name.clone().into(),
                icon: workspace.agent_icon(&entry.name),
            })
            .collect();
        let chat = workspace.active_session();
        let placeholder = chat.map_or_else(
            || "message the agent…".to_owned(),
            |chat| format!("message {}…", chat.entry.name),
        );
        let commands = chat.map(|chat| chat.commands.clone()).unwrap_or_default();
        let streaming = chat.is_some_and(|chat| chat.streaming);
        let current = chat
            .map(|chat| chat.entry.name.clone())
            .and_then(|name| agents.iter().position(|agent| agent.name == name));
        // Both belong to the agent process rather than to the transcript, so a
        // session read back off disk offers neither until it reconnects.
        let live = chat.filter(|chat| chat.live());
        let switches = live.map(switches).unwrap_or_default();
        let usage = live.and_then(|chat| chat.usage);
        self.composer.update(cx, |composer, cx| {
            composer.set_placeholder(&placeholder, cx);
            composer.set_commands(&commands, cx);
            composer.set_streaming(streaming, cx);
            composer.set_agents(&agents, current, cx);
            composer.set_switches(&switches, cx);
            composer.set_usage(usage, cx);
        });
    }

    pub(crate) fn detail(
        &self,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) -> impl IntoElement + use<> {
        let theme = Theme::of(cx).clone();
        // Nothing to send to: no session at all, or one whose agent has gone
        // from settings.toml, leaving nothing to reconnect it to.
        let live = self.workspace.read(cx).reachable();
        let showing = self.showing(cx);
        let body = match showing {
            None => self.launch(cx),
            Some(Pane::Chat) => self.conversation(window, cx),
            Some(Pane::Board) => self.board(window, cx),
            // An entry can be named and not yet loaded — an article holds no
            // editor until it is opened. The front door stands in for the
            // moment in between.
            Some(Pane::Article) => self.article(window, cx).unwrap_or_else(|| self.launch(cx)),
            Some(Pane::Table) => self.table(cx).unwrap_or_else(|| self.launch(cx)),
        };

        let content = div()
            .flex_1()
            .min_h_0()
            .flex()
            .flex_col()
            .overflow_hidden()
            // The band is drawn over the column, so the room it needs is taken
            // here. Held on the pane rather than inside each pane's scroll,
            // which is where it wants to end up — `../desktop` reserves it
            // inside the scroll so content slides under the glass, and doing
            // that means every pane's own scroll box, not this one div.
            .pt(px(root::HEADER_HEIGHT))
            .child(body);

        let footer_height = self
            .workspace
            .read(cx)
            .active_session()
            .map(|chat| chat.transcript.footer_height.clone());
        let main = div()
            .flex_1()
            .min_h_0()
            .min_w_0()
            .relative()
            .bg(root::content_bg(&theme))
            .flex()
            .flex_col()
            .child(content)
            // After the content, so it draws over it.
            .child(self.pane_header(window, cx))
            // Out of flow so the transcript runs under it: the composer's glass
            // has something to bend only where the messages reach its edge.
            //
            // A chat with nowhere to send stands the reason there in its place
            // — the slot is what the eye goes to for what happens next, and a
            // composer simply withheld leaves it answering nothing.
            .when(showing == Some(Pane::Chat), |column| match live {
                true => column.child(footer(
                    div()
                        .flex()
                        .flex_col()
                        .gap(px(8.))
                        .children(self.plan(cx))
                        .children(self.permission(cx))
                        .children(self.queue(cx))
                        .child(self.composer.clone()),
                    footer_height.clone(),
                )),
                false => column.children(
                    self.adrift_strip(cx)
                        .map(|strip| footer(strip, footer_height.clone())),
                ),
            });
        let terminal = (showing == Some(Pane::Chat))
            .then(|| self.workspace.read(cx).active_id())
            .flatten()
            .and_then(|id| self.terminals.get(&id))
            .filter(|(visible, _)| *visible)
            .map(|(_, terminal)| terminal.clone());
        let available = f32::from(window.viewport_size().width)
            - if self.sidebar_open {
                self.sidebar_width
            } else {
                0.
            };
        let width = panel_width(self.changes_width, available.max(0.));
        let height = panel_height(
            self.terminal_height,
            f32::from(window.viewport_size().height),
        );
        div()
            .id("session-panels")
            .relative()
            .flex_1()
            .min_w_0()
            .min_h_0()
            .flex()
            .flex_col()
            .on_drag_move(
                cx.listener(|this, event: &DragMoveEvent<TerminalResize>, _, cx| {
                    this.terminal_height = panel_height(
                        f32::from(event.bounds.bottom() - event.event.position.y),
                        f32::from(event.bounds.size.height),
                    );
                    cx.notify();
                }),
            )
            .child(
                div()
                    .id("session-detail")
                    .relative()
                    .flex_1()
                    .min_h_0()
                    .flex()
                    .flex_row()
                    .on_drag_move(cx.listener(
                        |this, event: &DragMoveEvent<ChangesResize>, _, cx| {
                            this.changes_width = panel_width(
                                f32::from(event.bounds.right() - event.event.position.x),
                                f32::from(event.bounds.size.width),
                            );
                            cx.notify();
                        },
                    ))
                    .child(main)
                    .children(self.changes.clone().map(|panel| {
                        div()
                            .relative()
                            .w(px(width))
                            .min_w_0()
                            .flex_none()
                            .border_l_1()
                            .border_color(theme.border)
                            .child(panel)
                    }))
                    .when(self.changes.is_some(), |row| {
                        row.child(
                            theme
                                .split_handle(Axis::Horizontal, SplitStyle::Ghost)
                                .id("changes-split")
                                .absolute()
                                .top_0()
                                .right(px(width - SPLIT_HANDLE_HIT / 2.))
                                .on_drag(ChangesResize, |_, _, _, cx| cx.new(|_| Empty)),
                        )
                    }),
            )
            .children(terminal.clone().map(|terminal| {
                div()
                    .h(px(height))
                    .flex_none()
                    .border_t_1()
                    .border_color(theme.border)
                    .child(terminal)
            }))
            .when(terminal.is_some(), |column| {
                column.child(
                    theme
                        .split_handle(Axis::Vertical, SplitStyle::Ghost)
                        .id("terminal-split")
                        .absolute()
                        .left_0()
                        .bottom(px(height - SPLIT_HANDLE_HIT / 2.))
                        .on_drag(TerminalResize, |_, _, _, cx| cx.new(|_| Empty)),
                )
            })
    }
}

/// Where the composer floats, and where anything standing in for it goes: out
/// of flow at the column's foot, held to the composer's own width so the two
/// land on the same edges.
fn footer(
    inner: impl IntoElement,
    height: Option<std::rc::Rc<std::cell::Cell<bezel::gpui::Pixels>>>,
) -> impl IntoElement {
    div()
        .absolute()
        .bottom(px(root::COMPOSER_BOTTOM))
        .left_0()
        .right_0()
        .flex()
        .justify_center()
        .child(
            div()
                .w_full()
                .max_w(px(root::COMPOSER_COLUMN))
                .px(px(root::COMPOSER_MARGIN))
                .relative()
                .child(inner)
                .child(
                    bezel::gpui::canvas(
                        move |bounds, window, _| {
                            if let Some(height) = &height {
                                if (height.replace(bounds.size.height) - bounds.size.height).abs()
                                    > px(0.5)
                                {
                                    window.refresh();
                                }
                            }
                        },
                        |_, _, _, _| {},
                    )
                    .absolute()
                    .size_full(),
                ),
        )
}

/// The invitation's rows as one block: left-aligned so every glyph lands on the
/// same edge, and held off the line above it — `empty_state` centres its
/// children, which would otherwise centre each row on its own width.
fn make_list(rows: impl IntoIterator<Item = AnyElement>) -> impl IntoElement {
    div()
        .mt(px(14.))
        .flex()
        .flex_col()
        .items_start()
        .gap(px(8.))
        .children(rows)
}

impl Cydonia {
    /// The front door, and what stands where a pane would be if one were
    /// showing: a project to open, or the first entry to make in the one that
    /// already is.
    fn launch(&self, cx: &mut Context<Self>) -> AnyElement {
        match self.workspace.read(cx).active_project().is_some() {
            true => self.nothing_open(cx),
            false => self.no_project(cx),
        }
    }

    /// What to do when there is nothing to show: make the first entry in the
    /// project that is open. The kinds are listed rather than named in a hint,
    /// because a list can be clicked — and only the kinds that are switched on
    /// are listed, so under the shipped defaults this is one line.
    fn nothing_open(&self, cx: &mut Context<Self>) -> AnyElement {
        let theme = Theme::of(cx).clone();
        let workspace = self.workspace.read(cx);
        let Some(ix) = workspace.active else {
            return self.no_project(cx);
        };
        let features = &workspace.settings.features;
        let (sessions, boards, tables) = (features.sessions, features.boards, features.tables);
        let name = workspace
            .projects
            .get(ix)
            .map(|project| shown_path(&project.path))
            .unwrap_or_default();
        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<AnyElement> = Vec::new();
        // One row per agent once there is a choice to make: a single "New
        // session" opens on whichever agent is first, and nothing on this
        // screen would say which.
        if sessions && agents.len() > 1 {
            for (at, (name, icon)) in agents.into_iter().enumerate() {
                let icon = icon.unwrap_or_else(|| icons::social::MessageCircle.into());
                rows.push(self.make_row(
                    format!("session-{at}"),
                    format!("New {name} session"),
                    icon,
                    cx,
                    move |this, _, cx| this.pick_agent(at, cx),
                ));
            }
        } else if sessions {
            rows.push(self.make_row(
                "session",
                "New session",
                icons::social::MessageCirclePlus,
                cx,
                move |this, window, cx| this.new_session_action(&NewSession, window, cx),
            ));
        }
        if boards {
            rows.push(self.make_row(
                "board",
                "New board",
                icons::development::SquareKanban,
                cx,
                move |this, window, cx| this.ask_new_board(ix, window, cx),
            ));
        }
        rows.push(self.make_row(
            "article",
            "New article",
            icons::files::FilePlus,
            cx,
            move |this, window, cx| this.new_article(ix, window, cx),
        ));
        if tables {
            rows.push(self.make_row(
                "table",
                "New table",
                icons::files::Table2,
                cx,
                move |this, _, cx| this.new_table(ix, cx),
            ));
        }
        theme
            .empty_state(icons::files::Folder, "Nothing open", format!("in {name}"))
            .flex_1()
            .child(make_list(rows))
            .into_any_element()
    }

    /// One line of the invitation: a glyph, a label, and what it makes.
    fn make_row(
        &self,
        id: impl Into<SharedString>,
        label: impl Into<SharedString>,
        glyph: impl Into<Icon>,
        cx: &mut Context<Self>,
        make: impl Fn(&mut Self, &mut Window, &mut Context<Self>) + 'static,
    ) -> AnyElement {
        let theme = Theme::of(cx).clone();
        let (id, label) = (id.into(), label.into());
        // An svg paints in its own `text_color` and inherits none, so the glyph
        // cannot ride the row's hover. Both halves take the row's group instead,
        // which lights them together — the group is named per row so hovering
        // one does not light the rest.
        div()
            .id(id.clone())
            .group(id.clone())
            .flex()
            .items_center()
            .gap(px(8.))
            .cursor_pointer()
            .text_style(TextStyle::Callout)
            .child(
                icons::icon(glyph)
                    .size(px(14.))
                    .flex_none()
                    .text_color(theme.text_muted)
                    .group_hover(id.clone(), |el| el.text_color(theme.text)),
            )
            .child(
                div()
                    .text_color(theme.text_muted)
                    .group_hover(id, |el| el.text_color(theme.text))
                    .child(label),
            )
            .on_click(cx.listener(move |this, _, window, cx| make(this, window, cx)))
            .into_any_element()
    }

    /// The session in front. It has one: the chat pane is named by `showing`
    /// only where a session is open in it, so the empty case is unreachable
    /// rather than a state this has to draw.
    fn conversation(&self, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
        let theme = Theme::of(cx).clone();
        let workspace = self.workspace.read(cx);
        let Some(chat) = workspace.active_session() else {
            // No session, and the pane showing regardless: one was asked for
            // with no agent to open it on — see [`Cydonia::asked_session`].
            return match self.asked_session {
                true => self.no_agent(None, false, cx),
                false => div().flex_1().into_any_element(),
            };
        };
        // Nothing has been said yet, so what the session has to show for
        // itself is the directory the agent was started in.
        if chat.unsaid() {
            let agent = chat.entry.name.clone();
            let cwd = workspace
                .active_project()
                .map(|project| shown_path(&project.path))
                .unwrap_or_default();
            // Except where the agent is not here to be started in it. A
            // transcript that has nothing to show *and* nowhere to send is the
            // whole pane, so the way out goes here rather than under it.
            let others = !workspace.settings.agents.is_empty();
            if !workspace.reachable() {
                return self.no_agent(Some(&agent), others, cx);
            }
            return theme
                .empty_state(icons::files::Folder, cwd, format!("{agent} runs here"))
                .flex_1()
                .into_any_element();
        }
        let id = chat.id;
        self.workspace
            .update(cx, |workspace, cx| match workspace.session(id) {
                Some(chat) => transcript::render(chat, window, cx),
                None => div().flex_1().into_any_element(),
            })
    }

    /// No agent to say anything to: what is missing, and the way to put it
    /// there. The whole pane, because there is nothing else in it.
    ///
    /// Two ways in. A session with nothing said in it whose agent has gone —
    /// uninstalled while it was still on the rail — which before this drew
    /// blank: a transcript with no messages, under a composer withheld for
    /// having nowhere to send, which together are nothing at all. And a
    /// session asked for on a machine with no agent on it, which has no
    /// transcript of its own to stand over and names none.
    fn no_agent(&self, agent: Option<&str>, others: bool, cx: &mut Context<Self>) -> AnyElement {
        let theme = Theme::of(cx).clone();
        let painter = Painter::of(cx);
        theme
            .empty_state(
                icons::files::Download,
                agent_missing(agent),
                adrift(agent, others),
            )
            .flex_1()
            .child(
                theme
                    .button(
                        "Install an agent…",
                        ButtonStyle::Prominent,
                        Some(Fade::new(painter, "install-agent-empty")),
                    )
                    .id("install-agent-empty")
                    .on_click(
                        cx.listener(|this, _, _, cx| this.open_settings(Section::Agents, cx)),
                    ),
            )
            .into_any_element()
    }

    /// What stands where the composer would be over a transcript there is no
    /// longer anywhere to answer into. The strip is the click: it names where
    /// the agent is installed, and going there is all it has to offer.
    ///
    /// Nothing at all where the session has said nothing — [`Self::no_agent`]
    /// is the whole pane then, and this under it would say it twice.
    fn adrift_strip(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
        let theme = Theme::of(cx).clone();
        let workspace = self.workspace.read(cx);
        let chat = workspace.active_session().filter(|chat| !chat.unsaid())?;
        let message = adrift_line(&chat.entry.name, !workspace.settings.agents.is_empty());
        Some(
            theme
                .warning_strip(message)
                .id("adrift")
                .mt(px(0.))
                .cursor_pointer()
                .on_click(cx.listener(|this, _, _, cx| this.open_settings(Section::Agents, cx)))
                .into_any_element(),
        )
    }

    /// The agent's plan, while it still has something left to do.
    fn plan(&self, cx: &Context<Self>) -> Option<impl IntoElement + use<>> {
        let theme = Theme::of(cx).clone();
        let chat = self.workspace.read(cx).active_session()?;
        if chat.plan.is_empty() || chat.plan.iter().all(|(_, s)| *s == PlanStatus::Done) {
            return None;
        }
        Some(
            div()
                .rounded(px(Theme::surface_radius()))
                .px(px(12.))
                .py(px(8.))
                .flex()
                .flex_col()
                .gap(px(4.))
                .text_style(TextStyle::Callout)
                .children(chat.plan.iter().map(|(text, status)| {
                    let (icon, tone) = match status {
                        PlanStatus::Done => (icons::notifications::Check, theme.success),
                        PlanStatus::Active => (icons::arrows::ChevronRight, theme.accent),
                        PlanStatus::Pending => (icons::text::ListChecks, theme.text_faint),
                    };
                    div()
                        .flex()
                        .flex_row()
                        .items_start()
                        .gap(px(8.))
                        .text_color(theme.text_muted)
                        .child(icons::icon(icon).size(px(12.)).text_color(tone))
                        .child(text.clone())
                }))
                .surface(&theme, composer::SURFACE),
        )
    }

    /// The agent's tool-authorization request.
    ///
    /// A macOS permission alert: what is being asked for, the two answers, and
    /// a checkbox saying how long the answer holds. See [`alert`] for why two
    /// buttons carry four options, and for what an agent has to ask to get the
    /// stack of rows instead.
    fn permission(&self, cx: &Context<Self>) -> Option<impl IntoElement + use<>> {
        let theme = Theme::of(cx).clone();
        let chat = self.workspace.read(cx).active_session()?;
        let prompt = chat.permission.as_ref()?;
        let id = chat.id;
        let painter = Painter::of(cx);
        // One button, whichever layout it lands in. `key` is the element's and
        // the hover wash's both — the wash store is one map for the whole app,
        // so the session is in it too.
        let answer = |key: &str, option_id: String, label: &str, style| {
            let fade = Fade::new(painter, format!("permission-{id}-{key}"));
            theme
                .button(label.to_owned(), style, Some(fade))
                .id(SharedString::from(key.to_owned()))
                .on_click(cx.listener(move |this, _, _, cx| {
                    let option_id = option_id.clone();
                    this.workspace.update(cx, |workspace, cx| {
                        workspace.with_session(id, cx, |chat| chat.respond_permission(option_id));
                    });
                }))
        };
        let body = match alert(&prompt.options) {
            // How long the answer holds, then the answers — the affirmative
            // last, where macOS puts the default.
            Some((deny, allow)) => div()
                .flex()
                .flex_row()
                .items_center()
                .gap(px(8.))
                // An agent offering neither *always* form has no second
                // question to ask, and the row is just the two buttons.
                .children((deny.always.is_some() || allow.always.is_some()).then(|| {
                    div()
                        .id("permission-always")
                        .flex()
                        .flex_row()
                        .items_center()
                        .gap(px(8.))
                        .cursor_pointer()
                        .child(theme.checkbox(prompt.always))
                        .child(
                            div()
                                .text_style(TextStyle::Callout)
                                .text_color(theme.text_muted)
                                .child("Always allow"),
                        )
                        .on_click(cx.listener(move |this, _, _, cx| {
                            this.workspace.update(cx, |workspace, cx| {
                                workspace
                                    .with_session(id, cx, |chat| chat.toggle_permission_always());
                            });
                        }))
                }))
                // Whatever is on the left is on the left: the answers hold the
                // trailing edge whether or not the checkbox is there.
                .child(div().flex_1())
                .child(answer(
                    "deny",
                    deny.id(prompt.always),
                    deny.label,
                    ButtonStyle::Ghost,
                ))
                .child(answer(
                    "allow",
                    allow.id(prompt.always),
                    allow.label,
                    ButtonStyle::Prominent,
                ))
                .into_any_element(),
            // Every option the agent sent, one full-width row each. A label of
            // any length reads here, which is the whole point of stacking them.
            None => div()
                .flex()
                .flex_col()
                .gap(px(6.))
                .children(prompt.options.iter().enumerate().map(|(ix, option)| {
                    let style = match option.kind {
                        PermissionOptionKind::AllowOnce => ButtonStyle::Prominent,
                        _ => ButtonStyle::Ghost,
                    };
                    answer(
                        &format!("option-{ix}"),
                        option.id.clone(),
                        &option.name,
                        style,
                    )
                    .w_full()
                    .justify_center()
                }))
                .into_any_element(),
        };
        Some(
            div()
                .rounded(px(Theme::surface_radius()))
                .px(px(14.))
                .py(px(12.))
                .flex()
                .flex_col()
                .gap(px(12.))
                .child(
                    div()
                        .flex()
                        .flex_row()
                        .items_start()
                        .gap(px(8.))
                        .child(
                            icons::icon(icons::security::Key)
                                .size(px(14.))
                                .flex_none()
                                // A glyph's box is its size and the line beside
                                // it is taller, so it drops to meet the text.
                                .mt(px(3.))
                                .text_color(theme.text_muted),
                        )
                        .child(
                            div()
                                .flex_1()
                                .min_w_0()
                                .text_style(TextStyle::Body)
                                .text_color(theme.text)
                                .child(prompt.title.clone()),
                        ),
                )
                .child(body)
                .surface(&theme, composer::SURFACE),
        )
    }

    /// A pick from one of the composer's switches — the session's mode, or a
    /// config option like the model.
    pub(crate) fn switch(
        &mut self,
        id: &composer::SwitchId,
        value: &SharedString,
        cx: &mut Context<Self>,
    ) {
        let Some(session) = self.workspace.read(cx).active_session().map(|chat| chat.id) else {
            return;
        };
        let value = value.to_string();
        self.workspace.update(cx, |workspace, cx| match id {
            composer::SwitchId::Mode => workspace.set_session_mode(session, value, cx),
            composer::SwitchId::Config(config) => workspace.set_session_config(
                session,
                config.to_string(),
                SessionConfigOptionValue::ValueId {
                    value: value.into(),
                },
                cx,
            ),
        });
        cx.notify();
    }

    /// Prompts waiting for the in-flight turn — a steer, drawn as what it is:
    /// the message you have already written, not yet sent. The same bubble the
    /// transcript gives a sent one, held back to the muted tone, and an ✕ to
    /// take it back while it is still yours to take back.
    fn queue(&self, cx: &Context<Self>) -> Option<impl IntoElement + use<>> {
        let theme = Theme::of(cx).clone();
        let chat = self.workspace.read(cx).active_session()?;
        if chat.queue.is_empty() {
            return None;
        }
        let id = chat.id;
        Some(div().flex().flex_col().items_end().gap(px(6.)).children(
            chat.queue.iter().enumerate().map(|(ix, text)| {
                // An svg paints in its own `text_color` and inherits none,
                // so the ✕ takes the bubble's group to light with it.
                let group = SharedString::from(format!("steer-{ix}"));
                div()
                    .group(group.clone())
                    .max_w(px(440.))
                    .px(px(14.))
                    .py(px(9.))
                    .rounded(px(Theme::surface_radius()))
                    .bg(theme.surface_raised.opacity(0.6))
                    .flex()
                    .flex_row()
                    .items_start()
                    .gap(px(10.))
                    .child(
                        div()
                            .flex_1()
                            .min_w_0()
                            .text_style(TextStyle::Body)
                            .text_color(theme.text_muted)
                            .child(text.clone()),
                    )
                    .child(
                        div()
                            .id(("unqueue", ix))
                            .flex_none()
                            // Onto the first line's baseline, so a steer
                            // that wraps keeps its ✕ at the top.
                            .mt(px(4.))
                            .cursor_pointer()
                            .child(
                                icons::icon(icons::notifications::X)
                                    .size(px(12.))
                                    .text_color(theme.text_faint)
                                    .group_hover(group, |el| el.text_color(theme.text)),
                            )
                            .on_click(cx.listener(move |this, _, _, cx| {
                                this.workspace.update(cx, |workspace, cx| {
                                    workspace.with_session(id, cx, |chat| chat.unqueue(ix));
                                });
                            })),
                    )
            }),
        ))
    }
}