cydonia 0.1.0

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
//! The board pane: lanes of cards, and the one field that writes them.

use crate::{
    model::{
        board::{Card, Spot},
        session::ChatSession,
    },
    view::root::{Cydonia, NewBoard, Pane},
};
use bezel::{
    gpui::{
        self, AnyElement, App, Context, Div, Entity, Focusable as _, FontWeight, KeyBinding,
        SharedString, Stateful, Window, actions, div, prelude::*, px,
    },
    motion::Painter,
    theme::{TextStyle, Theme, Typeset},
    ui::{
        icons,
        input::{self, Shape, TextField},
        loaders,
        widgets::Buttons,
    },
};

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

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

const COLUMN_WIDTH: f32 = 272.;

pub fn init(cx: &mut App) {
    let ctx = Some(KEY_CONTEXT);
    cx.bind_keys([
        KeyBinding::new("enter", CommitCard, ctx),
        KeyBinding::new("shift-enter", input::InsertNewline, ctx),
        KeyBinding::new("escape", DismissCard, ctx),
    ]);
}

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

/// What the field is attached to.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Editing {
    /// A card being written, to land at the end of this column.
    New(usize),
    /// A card being rewritten.
    Card(Spot),
}

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

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

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

    pub(crate) fn new_board(&mut self, project: usize, cx: &mut Context<Self>) {
        self.select_project(project, cx);
        let ix = self
            .workspace
            .update(cx, |workspace, cx| workspace.new_board(cx));
        if let Some(ix) = ix {
            self.open_board(project, ix, cx);
        }
    }

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

    /// Point the field at `at`, filing whatever was already open first — so
    /// clicking straight from one card to another never drops an edit.
    fn edit(&mut self, at: Editing, window: &mut Window, cx: &mut Context<Self>) {
        self.commit(cx);
        let text = match at {
            Editing::New(_) => String::new(),
            Editing::Card(spot) => self
                .workspace
                .read(cx)
                .active_board()
                .and_then(|board| board.card(spot))
                .map(|card| card.text.clone())
                .unwrap_or_default(),
        };
        self.card_field
            .update(cx, |field, cx| field.set_content(text, cx));
        self.editing = Some(at);
        window.focus(&self.card_field.read(cx).focus_handle(cx), cx);
        cx.notify();
    }

    /// File whatever is open before leaving it. Every way out of a pane goes
    /// through here.
    ///
    /// An empty card is not a card — committing nothing drops it rather than
    /// leaving a blank on the board.
    pub(crate) fn commit(&mut self, cx: &mut Context<Self>) {
        self.commit_cell(cx);
        let Some(at) = self.editing.take() else {
            return;
        };
        let text = self.card_field.read(cx).content().trim().to_owned();
        self.card_field.update(cx, |field, cx| field.clear(cx));
        self.workspace.update(cx, |workspace, cx| {
            let Some(board) = workspace.active_board_mut() else {
                return;
            };
            match at {
                Editing::New(ix) => {
                    if !text.is_empty()
                        && let Some(column) = board.columns.get_mut(ix)
                    {
                        column.cards.push(Card::new(text));
                    }
                }
                Editing::Card(spot) => {
                    if text.is_empty() {
                        board.take(spot);
                    } else if let Some(card) = board.card_mut(spot) {
                        card.text = text;
                    }
                }
            }
            board.save();
            cx.notify();
        });
    }

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

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

    /// Carry a card one column over, its session with it.
    fn move_card(&mut self, at: Spot, delta: isize, cx: &mut Context<Self>) {
        self.commit(cx);
        self.workspace.update(cx, |workspace, cx| {
            let Some(board) = workspace.active_board_mut() else {
                return;
            };
            let Some(to) = at.column.checked_add_signed(delta) else {
                return;
            };
            if to >= board.columns.len() {
                return;
            }
            if let Some(card) = board.take(at) {
                board.columns[to].cards.push(card);
            }
            board.save();
            cx.notify();
        });
        cx.notify();
    }

    fn delete_card(&mut self, at: Spot, cx: &mut Context<Self>) {
        self.commit(cx);
        self.workspace.update(cx, |workspace, cx| {
            let Some(board) = workspace.active_board_mut() else {
                return;
            };
            board.take(at);
            board.save();
            cx.notify();
        });
        cx.notify();
    }

    /// Hand the card to an agent: a session of its own, opened in the project
    /// with the card's text as its first prompt.
    ///
    /// A session of its own rather than the one in front, so the card's dot
    /// reports its own run — and so dispatching a second card doesn't queue
    /// behind the first. The board stays up: the card goes live where you are
    /// looking, and clicking it is what follows the work into the transcript.
    fn dispatch_card(&mut self, at: Spot, cx: &mut Context<Self>) {
        self.commit(cx);
        self.workspace.update(cx, |workspace, cx| {
            let text = workspace
                .active_board()
                .and_then(|board| board.card(at))
                .map(|card| card.text.clone());
            let (Some(text), Some(entry)) = (text, workspace.preferred_agent()) else {
                return;
            };
            let id = workspace.new_session(entry, Some(text), cx);
            if let Some(card) = workspace
                .active_board_mut()
                .and_then(|board| board.card_mut(at))
            {
                card.session = id;
            }
        });
        cx.notify();
    }

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

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

    /// The lanes. Same frame as [`Cydonia::transcript`]: the body of the
    /// content card, with the composer stack still pinned under it.
    pub fn board(&self, cx: &mut Context<Self>) -> AnyElement {
        let Some(board) = self.workspace.read(cx).active_board() else {
            return div().flex_1().into_any_element();
        };
        let count = board.columns.len();
        let columns: Vec<AnyElement> = (0..count).map(|ix| self.column(ix, cx)).collect();
        div()
            .flex_1()
            .min_h_0()
            .on_action(cx.listener(Self::commit_card))
            .on_action(cx.listener(Self::dismiss_card))
            .child(
                div()
                    .id("board")
                    .size_full()
                    .overflow_x_scroll()
                    .flex()
                    .flex_row()
                    .gap(px(10.))
                    .px(px(16.))
                    .py(px(16.))
                    .children(columns),
            )
            .into_any_element()
    }

    fn column(&self, ix: usize, cx: &mut Context<Self>) -> AnyElement {
        let theme = Theme::of(cx).clone();
        let Some((name, count)) = self
            .workspace
            .read(cx)
            .active_board()
            .and_then(|board| board.columns.get(ix))
            .map(|column| (column.name.clone(), column.cards.len()))
        else {
            return div().into_any_element();
        };
        let mut cards: Vec<AnyElement> = (0..count)
            .map(|n| self.card(Spot::new(ix, n), cx))
            .collect();
        if self.editing == Some(Editing::New(ix)) {
            cards.push(self.card_editor(cx));
        }

        div()
            .flex_none()
            .w(px(COLUMN_WIDTH))
            .h_full()
            .flex()
            .flex_col()
            .gap(px(8.))
            .child(
                div()
                    .flex_none()
                    .px(px(4.))
                    .flex()
                    .flex_row()
                    .items_center()
                    .gap(px(6.))
                    .text_style(TextStyle::Subheadline)
                    .child(
                        div()
                            .font_weight(FontWeight::MEDIUM)
                            .text_color(theme.text_muted)
                            .child(name),
                    )
                    .child(div().text_color(theme.text_faint).child(count.to_string())),
            )
            .child(
                div()
                    .id(("column", ix))
                    .flex_1()
                    .min_h_0()
                    .overflow_y_scroll()
                    .flex()
                    .flex_col()
                    .gap(px(8.))
                    .children(cards)
                    .child(
                        theme
                            .ghost(("add-card", ix))
                            .flex_none()
                            .px(px(8.))
                            .py(px(6.))
                            .gap(px(6.))
                            .child(
                                icons::icon(icons::system::PLUS)
                                    .size(px(12.))
                                    .text_color(theme.text_faint),
                            )
                            .child(
                                div()
                                    .text_style(TextStyle::Callout)
                                    .text_color(theme.text_faint)
                                    .child("Add a card"),
                            )
                            .on_click(cx.listener(move |this, _, window, cx| {
                                this.edit(Editing::New(ix), window, cx);
                            })),
                    ),
            )
            .into_any_element()
    }

    fn card(&self, at: Spot, cx: &mut Context<Self>) -> AnyElement {
        if self.editing == Some(Editing::Card(at)) {
            return self.card_editor(cx);
        }
        let theme = Theme::of(cx).clone();
        let painter = Painter::of(cx);
        let Some(card) = self
            .workspace
            .read(cx)
            .active_board()
            .and_then(|board| board.card(at))
        else {
            return div().into_any_element();
        };
        let text = card.text.clone();
        let chat = self.card_session(card, cx);
        let live = chat.map(|chat| chat.id);
        let sessions = self.workspace.read(cx).settings.features.sessions;
        // The same reading as the sidebar's session row: the card and the row are
        // reporting the same process.
        let running = chat.is_some_and(|chat| chat.streaming);
        let orb = running.then(|| {
            loaders::orb(
                loaders::Orb::Cluster,
                SharedString::from(format!("card-orb-{}-{}", at.column, at.card)),
                12.,
                &theme,
                painter,
                cx,
            )
            .into_any_element()
        });
        div()
            .id(SharedString::from(format!(
                "card-{}-{}",
                at.column, at.card
            )))
            .group("card")
            .flex_none()
            .p(px(10.))
            .rounded(px(Theme::control_radius()))
            .border_1()
            .border_color(theme.border)
            .bg(theme.surface_raised)
            .cursor_pointer()
            .hover(|el| el.border_color(theme.text_faint))
            .flex()
            .flex_col()
            .gap(px(6.))
            .child(
                div()
                    .max_h(px(140.))
                    .overflow_hidden()
                    .text_style(TextStyle::Callout)
                    .text_color(theme.text)
                    .child(text),
            )
            .child(
                div()
                    .flex()
                    .flex_row()
                    .items_center()
                    .gap(px(2.))
                    // On show, not behind a hover — a card's run is what you
                    // look at the board to see, and hiding it would mean
                    // hunting for the one that is working.
                    .children(orb)
                    .child(div().flex_1())
                    .child(
                        div()
                            .invisible()
                            .group_hover("card", |el| el.visible())
                            .flex()
                            .flex_row()
                            .items_center()
                            .gap(px(2.))
                            .children((at.column > 0).then(|| {
                                self.card_action("left", at, icons::arrows::ALT_ARROW_LEFT, cx)
                                    .on_click(cx.listener(move |this, _, _, cx| {
                                        cx.stop_propagation();
                                        this.move_card(at, -1, cx);
                                    }))
                            }))
                            .children((!self.last_column(at, cx)).then(|| {
                                self.card_action("right", at, icons::arrows::ALT_ARROW_RIGHT, cx)
                                    .on_click(cx.listener(move |this, _, _, cx| {
                                        cx.stop_propagation();
                                        this.move_card(at, 1, cx);
                                    }))
                            }))
                            // Handing a card to an agent is opening a session,
                            // so the control goes with them: with sessions off
                            // the play would start nothing, and the card is
                            // still a card without it.
                            .children(sessions.then(|| {
                                match live {
                                    Some(id) => self
                                        .card_action("open", at, icons::system::CHAT_ROUND_LINE, cx)
                                        .on_click(cx.listener(move |this, _, _, cx| {
                                            cx.stop_propagation();
                                            this.select_session(id, cx);
                                            this.show_pane(Pane::Chat, cx);
                                        })),
                                    None => self.card_action("run", at, icons::media::PLAY, cx).on_click(
                                        cx.listener(move |this, _, _, cx| {
                                            cx.stop_propagation();
                                            this.dispatch_card(at, cx);
                                        }),
                                    ),
                                }
                            }))
                            .child(
                                self.card_action("delete", at, icons::files::TRASH_BIN_MINIMALISTIC, cx)
                                    .on_click(cx.listener(move |this, _, _, cx| {
                                        cx.stop_propagation();
                                        this.delete_card(at, cx);
                                    })),
                            ),
                    ),
            )
            .on_click(cx.listener(move |this, _, window, cx| {
                this.edit(Editing::Card(at), window, cx);
            }))
            .into_any_element()
    }

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

    /// Whether `at` sits in the rightmost column — nowhere further to carry it.
    fn last_column(&self, at: Spot, cx: &App) -> bool {
        self.workspace
            .read(cx)
            .active_board()
            .is_none_or(|board| at.column + 1 >= board.columns.len())
    }

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