mahbot 0.11.3

An autonomous agentic engineering system that manages software development through role separation, subagents, and deterministic diagnostics.
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
//! Workspaces dashboard page.

use crate::Workspace;
use crate::workspace::truncate_workspace_notes;

use iced::Task;
use iced::widget::markdown;

use std::collections::HashMap;

use super::common::SingleLineEditorState;
use super::editor_widget::EditorAction;

#[derive(Debug, Clone)]
#[expect(private_interfaces)] // ContextKind is deliberately pub(crate) (see gui/mod.rs Message)
pub enum WorkspacesMessage {
    DeleteWorkspace(String),
    ConfirmDelete(String),
    CancelDelete,
    DeleteResult(Result<(String, Option<String>), String>),
    Reanalyze(String),
    ReanalyzeResult(Result<(), String>),

    /// User clicked a role icon to view per-agent context (read-only markdown).
    ViewContext(String, String), // workspace_name, role

    /// User clicked the general-context icon to view the workspace's non-role context (read-only
    /// markdown).
    ViewGeneralContext(String), // workspace_name

    ContextViewed(String, ContextKind, Result<Option<String>, String>), // ws_name, kind, result

    LinkClicked(String),

    ShowDiagnostics(String),

    DiagnosticsFieldEdited(String, usize, EditorAction),
    SaveDiagnostics(String),
    DiagnosticsSaved(String, Result<(), String>),
    RediscoverDiagnostics(String),
    RediscoverDiagnosticsResult(String, Result<(), String>),

    Escape,

    Toast(super::ToastMessage),

    /// Open the rules popup for a workspace. The popup's backdrop covers the page, so it is the
    /// only surface reachable until it closes.
    OpenRules(String),
    RulesEdited(super::editor_widget::EditorAction),
    SaveRules,
    RulesSaved(String, Result<(), String>),
    RulesDiscard,
    /// Escape or a click outside the popup: close it only when nothing is unsaved.
    RulesDismiss,
    ContextsClose,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum ContextKind {
    Role(String),
    General,
}

pub struct WorkspacesState {
    pub(crate) workspaces: Vec<Workspace>,
    pub(crate) load_state: super::common::AsyncLoadState,
    pub(crate) delete_target: Option<String>,

    /// Read-only context view modal: (workspace_name, context kind, parsed_markdown_items). `None`
    /// while the modal is not open, `Some` with `None` items while loading.
    pub(crate) context_view: Option<(String, ContextKind, Option<Vec<markdown::Item>>)>,
    pub(crate) context_view_error: Option<String>,

    pub(crate) diagnostics_modal: Option<String>,
    pub(crate) diagnostics_edit_buffers:
        HashMap<String, [SingleLineEditorState; crate::DiagnosticsCommands::COMMAND_COUNT]>,
    pub(crate) diagnostics_busy: bool,
    pub(crate) diagnostics_error: Option<String>,

    /// The open rules popup, or nothing — one at a time, so its buffer and undo stack live here
    /// rather than in a per-workspace map.
    pub(crate) rules_editor: Option<RulesEditor>,
}

pub(crate) const RULES_EDITOR_ID: &str = "workspace_rules";

pub(crate) struct RulesEditor {
    pub(crate) workspace: String,
    saved: String,
    pub(crate) buffer: super::editor_widget::EditorBuffer,
    pub(crate) undo: super::common::UndoStack,
    pub(crate) error: Option<String>,
}

impl RulesEditor {
    fn new(workspace: String, saved: String) -> Self {
        let buffer = super::editor_widget::EditorBuffer::with_text(
            &saved,
            Some(super::highlight::HighlightLanguage::Markdown),
        );
        // Opened over existing rules to add to them: the caret goes to the end so the first
        // keystroke appends instead of rewriting the first line.
        buffer.move_to_end();
        Self {
            workspace,
            saved,
            buffer,
            undo: super::common::UndoStack::new(),
            error: None,
        }
    }

    fn is_dirty(&self) -> bool {
        self.buffer.text() != self.saved
    }
}

impl WorkspacesState {
    #[must_use]
    pub fn new() -> Self {
        Self {
            workspaces: Vec::new(),
            load_state: super::common::AsyncLoadState::new(),
            delete_target: None,
            context_view: None,
            context_view_error: None,
            diagnostics_modal: None,
            diagnostics_edit_buffers: HashMap::new(),
            diagnostics_busy: false,
            diagnostics_error: None,
            rules_editor: None,
        }
    }

    #[expect(clippy::too_many_lines)]
    pub fn update(&mut self, msg: WorkspacesMessage) -> Task<WorkspacesMessage> {
        // Allow match_same_arms: separate error variants that happen to share the same
        // error-handling body after initial processing (e.g. logging variant info). Narrowing
        // per-arm would duplicate the handler across variants.
        #[expect(clippy::match_same_arms)]
        match msg {
            WorkspacesMessage::DeleteWorkspace(name) => {
                self.delete_target = Some(name);
                Task::none()
            }
            WorkspacesMessage::ConfirmDelete(name) => {
                self.delete_target = None;
                Task::perform(
                    async move {
                        crate::workspace::store()
                            .delete(&name)
                            .await
                            .map(|moved_to| (name, moved_to))
                            .map_err(|e| e.to_string())
                    },
                    WorkspacesMessage::DeleteResult,
                )
            }
            WorkspacesMessage::CancelDelete => {
                self.delete_target = None;
                Task::none()
            }
            WorkspacesMessage::DeleteResult(Ok(_)) => {
                self.load_state.clear_error();
                Task::none()
            }
            WorkspacesMessage::DeleteResult(Err(e)) => {
                self.load_state.fail(e.clone());
                Task::done(WorkspacesMessage::Toast(super::ToastMessage::Error(e)))
            }
            WorkspacesMessage::Reanalyze(name) => Task::perform(
                async move {
                    crate::workspace::store()
                        .rediscover(&name)
                        .await
                        .map_err(|e| e.to_string())
                },
                WorkspacesMessage::ReanalyzeResult,
            ),
            WorkspacesMessage::ReanalyzeResult(Ok(())) => Task::none(),
            WorkspacesMessage::ReanalyzeResult(Err(e)) => {
                self.load_state.fail(e.clone());
                Task::done(WorkspacesMessage::Toast(super::ToastMessage::Error(e)))
            }
            WorkspacesMessage::ViewContext(ws_name, role) => {
                self.context_view = Some((ws_name.clone(), ContextKind::Role(role.clone()), None));
                self.context_view_error = None;
                let ws_name2 = ws_name.clone();
                let role2 = role.clone();
                Task::perform(
                    async move {
                        let content = crate::workspace::store()
                            .get_context(&ws_name, &role)
                            .await
                            .map_err(|e| e.to_string())?;
                        Ok::<_, String>((ws_name, role, content))
                    },
                    move |res| match res {
                        Ok((name, role, content)) => WorkspacesMessage::ContextViewed(
                            name,
                            ContextKind::Role(role),
                            Ok(content),
                        ),
                        Err(e) => WorkspacesMessage::ContextViewed(
                            ws_name2,
                            ContextKind::Role(role2),
                            Err(e),
                        ),
                    },
                )
            }
            WorkspacesMessage::ViewGeneralContext(ws_name) => {
                self.context_view = Some((ws_name.clone(), ContextKind::General, None));
                self.context_view_error = None;
                let ws_name2 = ws_name.clone();
                Task::perform(
                    async move {
                        let content = crate::workspace::store()
                            .get_general_context(&ws_name)
                            .await
                            .map_err(|e| e.to_string())?;
                        Ok::<_, String>((ws_name, content))
                    },
                    move |res| match res {
                        Ok((name, content)) => WorkspacesMessage::ContextViewed(
                            name,
                            ContextKind::General,
                            Ok(content),
                        ),
                        Err(e) => {
                            WorkspacesMessage::ContextViewed(ws_name2, ContextKind::General, Err(e))
                        }
                    },
                )
            }
            WorkspacesMessage::ContextViewed(ws_name, kind, result) => {
                // A fetch that lands after the popup was dismissed has nowhere to go: reopening it
                // would undo the dismissal.
                if self.context_view.is_none() {
                    return Task::none();
                }
                let items = match &result {
                    Ok(Some(content)) => markdown::parse(content).collect(),
                    Ok(None) | Err(_) => Vec::new(),
                };
                self.context_view_error = result.err();
                self.context_view = Some((ws_name, kind, Some(items)));
                Task::none()
            }
            WorkspacesMessage::LinkClicked(_url) => {
                // Handled by the Dashboard (mod.rs) which intercepts this variant to call
                // open_url() before forwarding to update().
                Task::none()
            }
            WorkspacesMessage::ShowDiagnostics(name) => {
                self.diagnostics_modal = Some(name.clone());
                self.diagnostics_busy = false;
                self.diagnostics_error = None;

                // Populate edit buffers from current diagnostics. An absent or empty blob is
                // legitimately empty; a non-empty blob that fails to parse must surface instead of
                // rendering as the "(skipped)" placeholders.
                let raw = self
                    .workspaces
                    .iter()
                    .find(|w| w.name == name)
                    .and_then(|w| w.diagnostics.clone());
                let commands = match raw.as_deref().filter(|json| !json.trim().is_empty()) {
                    Some(json) => match serde_json::from_str::<crate::DiagnosticsCommands>(json) {
                        Ok(cmds) => Some(cmds),
                        Err(e) => {
                            self.diagnostics_error =
                                Some(format!("failed to parse saved diagnostics: {e}"));
                            None
                        }
                    },
                    None => None,
                };
                let fields = commands.map_or(
                    std::array::from_fn(|_| SingleLineEditorState::new("")),
                    |cmds| {
                        std::array::from_fn(|i| {
                            cmds.commands()[i].1.map_or_else(
                                || SingleLineEditorState::new(""),
                                SingleLineEditorState::new,
                            )
                        })
                    },
                );
                self.diagnostics_edit_buffers.insert(name, fields);
                Task::none()
            }
            WorkspacesMessage::DiagnosticsFieldEdited(name, idx, action) => {
                if let Some(task) = super::common::focus_navigation_task(&action) {
                    return task;
                }
                if let Some(buffers) = self.diagnostics_edit_buffers.get_mut(&name) {
                    if idx < crate::DiagnosticsCommands::COMMAND_COUNT {
                        buffers[idx].apply_action(action);
                    }
                }
                Task::none()
            }
            WorkspacesMessage::SaveDiagnostics(name) => {
                self.diagnostics_busy = true;
                self.diagnostics_error = None;

                let buffers: [String; crate::DiagnosticsCommands::COMMAND_COUNT] = match self
                    .diagnostics_edit_buffers
                    .get(&name)
                {
                    Some(buffers) => std::array::from_fn(|i| buffers[i].text()),
                    None => [const { String::new() }; crate::DiagnosticsCommands::COMMAND_COUNT],
                };

                let cmds = crate::DiagnosticsCommands::from_buffers(&buffers);

                let name_clone = name.clone();
                Task::perform(
                    async move {
                        crate::workspace::store()
                            .set_diagnostics(&name_clone, &cmds)
                            .await
                            .map_err(|e| e.to_string())
                    },
                    move |result| WorkspacesMessage::DiagnosticsSaved(name, result),
                )
            }
            WorkspacesMessage::DiagnosticsSaved(name, Ok(())) => {
                self.diagnostics_busy = false;
                self.diagnostics_edit_buffers.remove(&name);
                self.diagnostics_modal = None;
                Task::none()
            }
            WorkspacesMessage::DiagnosticsSaved(_name, Err(e)) => {
                self.diagnostics_busy = false;
                self.diagnostics_error = Some(e.clone());
                Task::done(WorkspacesMessage::Toast(super::ToastMessage::Error(e)))
            }
            WorkspacesMessage::RediscoverDiagnostics(name) => {
                self.diagnostics_busy = true;
                self.diagnostics_error = None;
                let name_for_task = name.clone();
                Task::perform(
                    async move {
                        crate::workspace::store()
                            .rediscover_diagnostics(&name_for_task)
                            .await
                            .map_err(|e| e.to_string())
                    },
                    move |result| WorkspacesMessage::RediscoverDiagnosticsResult(name, result),
                )
            }
            WorkspacesMessage::RediscoverDiagnosticsResult(name, Ok(())) => {
                self.diagnostics_busy = false;
                self.diagnostics_modal = None;
                self.diagnostics_edit_buffers.remove(&name);
                Task::none()
            }
            WorkspacesMessage::RediscoverDiagnosticsResult(_name, Err(e)) => {
                self.diagnostics_busy = false;
                self.diagnostics_error = Some(e.clone());
                Task::done(WorkspacesMessage::Toast(super::ToastMessage::Error(e)))
            }

            WorkspacesMessage::OpenRules(workspace) => {
                let saved = self
                    .workspaces
                    .iter()
                    .find(|w| w.name == workspace)
                    .map_or_else(String::new, |w| w.notes.clone());
                self.rules_editor = Some(RulesEditor::new(workspace, saved));
                iced::widget::operation::focus(iced::widget::Id::from(RULES_EDITOR_ID))
            }
            WorkspacesMessage::RulesEdited(action) => {
                let Some(rules) = self.rules_editor.as_mut() else {
                    return Task::none();
                };
                super::common::apply_editor_action(&mut rules.buffer, &mut rules.undo, action);
                // The store cuts at the cap; the buffer must not grow past it, or the counter would
                // promise what a save throws away.
                let current = rules.buffer.text();
                let truncated = truncate_workspace_notes(&current);
                if truncated.len() < current.len() {
                    rules.buffer.set_text(&truncated);
                    rules.buffer.move_to_end();
                }
                Task::none()
            }
            WorkspacesMessage::SaveRules => {
                let Some(rules) = self.rules_editor.as_mut() else {
                    return Task::none();
                };
                rules.error = None;
                let name = rules.workspace.clone();
                let text = rules.buffer.text();
                let name_clone = name.clone();
                Task::perform(
                    async move {
                        crate::workspace::store()
                            .set_notes(&name_clone, &text)
                            .await
                            .map_err(|e| e.to_string())
                    },
                    move |result| WorkspacesMessage::RulesSaved(name, result),
                )
            }
            WorkspacesMessage::RulesSaved(workspace, Ok(())) => {
                if self
                    .rules_editor
                    .as_ref()
                    .is_some_and(|rules| rules.workspace == workspace)
                {
                    self.rules_editor = None;
                }
                Task::none()
            }
            WorkspacesMessage::RulesSaved(workspace, Err(e)) => {
                if let Some(rules) = self.rules_editor.as_mut()
                    && rules.workspace == workspace
                {
                    rules.error = Some(e);
                }
                Task::none()
            }
            WorkspacesMessage::RulesDiscard => {
                self.rules_editor = None;
                Task::none()
            }
            // Escape and a click outside are not ways out of unsaved text: only Save and the corner
            // cross are.
            WorkspacesMessage::RulesDismiss => self.dismiss_rules(),
            WorkspacesMessage::ContextsClose => {
                self.context_view = None;
                self.context_view_error = None;
                Task::none()
            }

            // One dismissal closes one surface — the topmost that is open — and leaves the others
            // alone. Unsaved rules survive it.
            WorkspacesMessage::Escape => {
                if self.rules_editor.is_some() {
                    self.dismiss_rules()
                } else if self.context_view.is_some() {
                    self.context_view = None;
                    self.context_view_error = None;
                    Task::none()
                } else if self.diagnostics_modal.is_some() {
                    self.diagnostics_modal = None;
                    self.diagnostics_edit_buffers.clear();
                    self.diagnostics_busy = false;
                    self.diagnostics_error = None;
                    Task::none()
                } else {
                    self.delete_target = None;
                    Task::none()
                }
            }
            WorkspacesMessage::Toast(_) => Task::none(),
        }
    }

    /// Close the rules popup unless it holds unsaved text — the one place that decides what
    /// "unsaved" means for a dismissal. A refused dismissal puts the focus back in the editor: a
    /// click outside has just taken it away.
    fn dismiss_rules(&mut self) -> Task<WorkspacesMessage> {
        let Some(rules) = self.rules_editor.as_ref() else {
            return Task::none();
        };
        if rules.is_dirty() {
            iced::widget::operation::focus(iced::widget::Id::from(RULES_EDITOR_ID))
        } else {
            self.rules_editor = None;
            Task::none()
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn state_with_diagnostics(diagnostics: Option<String>) -> WorkspacesState {
        let mut state = WorkspacesState::new();
        state.workspaces.push(Workspace {
            name: "ws".to_string(),
            diagnostics,
            ..Workspace::default()
        });
        state
    }

    #[test]
    fn unsaved_rules_survive_escape_and_only_discard_drops_them() {
        let mut state = state_with_diagnostics(None);
        state.workspaces[0].notes = "stored rules".to_string();

        let _ = state.update(WorkspacesMessage::OpenRules("ws".to_string()));
        let _ = state.update(WorkspacesMessage::RulesEdited(EditorAction::Insert('!')));

        let _ = state.update(WorkspacesMessage::Escape);
        assert!(
            state.rules_editor.is_some(),
            "escape must not throw unsaved rules away"
        );
        let _ = state.update(WorkspacesMessage::RulesDismiss);
        assert!(
            state.rules_editor.is_some(),
            "a click outside must not throw unsaved rules away"
        );

        let _ = state.update(WorkspacesMessage::RulesDiscard);
        assert!(state.rules_editor.is_none(), "discard is the way out");

        // A popup the user has not touched closes on the same dismissals.
        let _ = state.update(WorkspacesMessage::OpenRules("ws".to_string()));
        let _ = state.update(WorkspacesMessage::Escape);
        assert!(
            state.rules_editor.is_none(),
            "a clean popup closes on escape"
        );
    }
}