mobius-cli 0.15.8

The terminal client for a möbius gateway
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
use mobius::protocol::{
    FrontendAction, FrontendActionListItem, FrontendBlock, FrontendBlockFormat, FrontendBlockRole,
    FrontendBlockState, FrontendBlockUpdate, FrontendEvent, FrontendListItemState,
    FrontendPickerOption, FrontendSlot, FrontendSymbol, FrontendTone, FrontendWidget,
    FrontendWidgetContent, Op, SessionContext, TokenUsage,
};
use std::collections::BTreeMap;

use mobius::middleware::session_files::session_file_limits;
use mobius_gateway::wire::{
    DailyUsage, ReadyPayload, ServerMessage, SessionActivity, SessionActivityState, SessionRecord,
};
use ratatui::Terminal;
use ratatui::backend::TestBackend;
use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use ratatui::widgets::ListState;

use super::runtime::{
    activate_overlay, handle_action_input_key, handle_frame, moved_index, ordered_sessions,
    prepare_overlay_operation,
};
use super::state::{CapabilityOverlay, DashboardFocus};
use super::view::{render_action_list, token_total_for_day};

#[test]
fn daily_usage_sums_all_providers_on_the_same_day() {
    let usage = [
        DailyUsage {
            unix_day: 7,
            provider: "openai_socket".into(),
            usage: TokenUsage {
                total_tokens: 11,
                ..TokenUsage::default()
            },
        },
        DailyUsage {
            unix_day: 7,
            provider: "kimi".into(),
            usage: TokenUsage {
                total_tokens: 13,
                ..TokenUsage::default()
            },
        },
        DailyUsage {
            unix_day: 8,
            provider: "responses".into(),
            usage: TokenUsage {
                total_tokens: 17,
                ..TokenUsage::default()
            },
        },
    ];

    assert_eq!(token_total_for_day(&usage, 7), 24);
}

#[test]
fn superseded_profile_rejection_does_not_set_dashboard_error() {
    let mut state = dashboard_state();

    handle_frame(
        &mut state,
        ServerMessage::Rejected {
            request_id: "profile-1".into(),
            code: "profile_superseded".into(),
            message: "profile request superseded".into(),
            fatal: false,
        },
    )
    .expect("benign superseded profile rejection");

    assert_eq!(state.error, None);
}

#[test]
fn moved_index_clamps_scroll_to_the_history() {
    assert_eq!(
        (
            moved_index(Some(1), 3, -5),
            moved_index(Some(1), 3, 5),
            moved_index(None, 0, 1),
        ),
        (Some(0), Some(2), None)
    );
}

#[test]
fn dashboard_focus_cycles_through_bots() {
    assert_eq!(
        (
            DashboardFocus::Devices.next(),
            DashboardFocus::Chats.next(),
            DashboardFocus::Bots.next(),
        ),
        (
            DashboardFocus::Chats,
            DashboardFocus::Bots,
            DashboardFocus::Devices,
        )
    );
}

#[test]
fn session_identity_survives_activity_sorting() {
    let mut sessions = vec![
        session("selected", SessionActivityState::Idle),
        session("other", SessionActivityState::Running),
    ];
    assert_eq!(
        ordered_sessions(&sessions)
            .iter()
            .position(|session| session.session_id == "selected"),
        Some(1)
    );

    sessions[0].activity.state = SessionActivityState::Running;
    sessions[1].activity.state = SessionActivityState::Idle;
    assert_eq!(
        ordered_sessions(&sessions)
            .iter()
            .position(|session| session.session_id == "selected"),
        Some(0)
    );
}

#[test]
fn open_widget_tracks_updates_and_submits_the_advertised_operation() {
    let key: (String, String) = ("capability-a".into(), "view".into());
    let mut overlay = CapabilityOverlay {
        title: "Chat capabilities · session-1".into(),
        session_id: "session-1".into(),
        slots: vec![FrontendSlot::Navigation],
        widgets: vec![(key.clone(), widget(blocks("Initial")))],
        widget_list: ListState::default(),
        open: Some(key.clone()),
        option_list: ListState::default(),
        action_index: 0,
        input: None,
    };
    overlay.sync_selection();
    let op = Op::ResumeSession {
        session_id: "session-2".into(),
    };
    overlay.apply(FrontendEvent::Widget {
        capability: key.0.clone(),
        item: widget(FrontendWidgetContent::Picker {
            title: "Updated".into(),
            options: vec![FrontendPickerOption {
                label: "Apply".into(),
                description: "Apply the advertised operation".into(),
                detail: String::new(),
                symbol: None,
                shows_detail: false,
                op: op.clone(),
            }],
        }),
    });

    assert!(matches!(
        overlay.open_widget().and_then(|widget| widget.content.as_ref()),
        Some(FrontendWidgetContent::Picker { title, .. }) if title == "Updated"
    ));
    assert_eq!(activate_overlay(&mut overlay), Some(op));

    overlay.apply(FrontendEvent::RemoveWidget {
        capability: key.0,
        id: key.1,
    });
    assert!(overlay.open.is_none());
}

#[test]
fn opening_widget_submits_its_advertised_refresh() {
    let key: (String, String) = ("capability-a".into(), "view".into());
    let op = Op::CapabilityCommand {
        capability: key.0.clone(),
        command: "refresh".into(),
        arguments: String::new(),
        input: None,
        target: None,
    };
    let mut item = widget(blocks("Initial"));
    item.action = Some(op.clone());
    let mut overlay = CapabilityOverlay {
        title: "Chat capabilities · session-1".into(),
        session_id: "session-1".into(),
        slots: vec![FrontendSlot::Navigation],
        widgets: vec![(key.clone(), item)],
        widget_list: ListState::default().with_selected(Some(0)),
        open: None,
        option_list: ListState::default(),
        action_index: 0,
        input: None,
    };

    assert_eq!(activate_overlay(&mut overlay), Some(op));
    assert_eq!(overlay.open, Some(key));
}

#[test]
fn action_list_renders_one_row_with_declared_actions_and_runs_the_selected_one() {
    let edit = capability_op("edit", Some("Remember this"));
    let delete = capability_op("delete", None);
    let content = action_list(edit.clone(), delete.clone());
    let key: (String, String) = ("capability-a".into(), "view".into());
    let mut overlay = CapabilityOverlay {
        title: "Chat capabilities · session-1".into(),
        session_id: "session-1".into(),
        slots: vec![FrontendSlot::Navigation],
        widgets: vec![(key.clone(), widget(content.clone()))],
        widget_list: ListState::default(),
        open: Some(key),
        option_list: ListState::default().with_selected(Some(0)),
        action_index: 1,
        input: None,
    };
    let FrontendWidgetContent::ActionList { title, items, .. } = content else {
        unreachable!();
    };
    let mut terminal = Terminal::new(TestBackend::new(72, 5)).expect("terminal");

    terminal
        .draw(|frame| {
            render_action_list(
                frame,
                frame.area(),
                &title,
                &items,
                &mut overlay.option_list,
                overlay.action_index,
            );
        })
        .expect("action list draw");

    let rendered = terminal.backend().to_string();
    let row = rendered
        .lines()
        .find(|line| line.contains("Remember this"))
        .expect("note row");
    let note_position = row.find("Remember this").expect("note text");
    let edit_position = row.find("[Edit]").expect("edit action");
    let delete_position = row.find("[Delete]").expect("delete action");
    assert!(note_position < edit_position && edit_position < delete_position);
    assert!(row.len().saturating_sub(delete_position + "[Delete]".len()) <= 1);
    assert_eq!(activate_overlay(&mut overlay), Some(delete));
}

#[test]
fn editable_action_replaces_its_advertised_input_before_submission() {
    let key: (String, String) = ("capability-a".into(), "view".into());
    let mut overlay = CapabilityOverlay {
        title: "Chat capabilities · session-1".into(),
        session_id: "session-1".into(),
        slots: vec![FrontendSlot::Navigation],
        widgets: vec![(key.clone(), widget(blocks("Initial")))],
        widget_list: ListState::default(),
        open: Some(key),
        option_list: ListState::default(),
        action_index: 0,
        input: None,
    };

    assert!(
        prepare_overlay_operation(&mut overlay, capability_op("edit", Some("Before"))).is_none()
    );
    handle_action_input_key(
        &mut overlay,
        KeyEvent::new(KeyCode::Char('!'), KeyModifiers::NONE),
    );
    let submitted = handle_action_input_key(
        &mut overlay,
        KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE),
    )
    .expect("submitted operation");

    assert!(matches!(
        submitted,
        Op::CapabilityCommand { input: Some(value), .. } if value == "Before!"
    ));
}

fn session(id: &str, state: SessionActivityState) -> SessionRecord {
    SessionRecord {
        session_id: id.into(),
        session_context: SessionContext::default(),
        parent_session_id: None,
        parent_sequence: None,
        sequence: 0,
        first_user_message: None,
        execution_stats: Default::default(),
        title: None,
        pinned: false,
        activity: SessionActivity {
            state,
            ..SessionActivity::default()
        },
        created_at: 0,
        updated_at: 0,
    }
}

fn dashboard_state() -> super::state::DashboardState {
    super::state::DashboardState {
        endpoint: String::new(),
        gateway: ReadyPayload {
            machine_name: String::new(),
            bots: Vec::new(),
            sessions: Vec::new(),
            background_approvals: Vec::new(),
            swarm_attentions: Vec::new(),
            swarms: Vec::new(),
            providers: Vec::new(),
            provider_instances: Vec::new(),
            bot_defaults: None,
            models: Vec::new(),
            model_providers: BTreeMap::new(),
            middleware_features: Vec::new(),
            extensions: Vec::new(),
            contributions: Vec::new(),
            max_active_sessions: 0,
            session_file_limits: session_file_limits(),
        },
        clients: Vec::new(),
        current_client_id: None,
        selected_client_id: None,
        selected_session_id: None,
        selected_bot_id: None,
        device_list: ListState::default(),
        chat_list: ListState::default(),
        bot_list: ListState::default(),
        focus: DashboardFocus::Devices,
        pending_unpair: None,
        profile: None,
        pending_open: None,
        overlay: None,
        error: None,
    }
}

fn blocks(text: &str) -> FrontendWidgetContent {
    FrontendWidgetContent::Blocks {
        title: "View".into(),
        blocks: vec![FrontendBlock {
            id: None,
            group: None,
            update: FrontendBlockUpdate::Replace,
            state: FrontendBlockState::Complete,
            role: FrontendBlockRole::Notice,
            title: String::new(),
            text: text.into(),
            symbol: None,
            format: FrontendBlockFormat::PlainText,
            tone: FrontendTone::Neutral,
            files: Vec::new(),
        }],
    }
}

fn action_list(edit: Op, delete: Op) -> FrontendWidgetContent {
    FrontendWidgetContent::ActionList {
        actions: Vec::new(),
        title: "Notes".into(),
        items: vec![FrontendActionListItem {
            id: "note-1".into(),
            text: "Remember this".into(),
            state: FrontendListItemState::Plain,
            actions: vec![
                FrontendAction {
                    editor: None,
                    id: "edit".into(),
                    label: "Edit".into(),
                    symbol: FrontendSymbol::Edit,
                    tone: FrontendTone::Neutral,
                    op: edit,
                },
                FrontendAction {
                    editor: None,
                    id: "delete".into(),
                    label: "Delete".into(),
                    symbol: FrontendSymbol::Delete,
                    tone: FrontendTone::Error,
                    op: delete,
                },
            ],
        }],
    }
}

fn capability_op(command: &str, input: Option<&str>) -> Op {
    Op::CapabilityCommand {
        capability: "capability-a".into(),
        command: command.into(),
        arguments: "note-1".into(),
        input: input.map(str::to_owned),
        target: None,
    }
}

fn widget(content: FrontendWidgetContent) -> FrontendWidget {
    FrontendWidget {
        id: "view".into(),
        slot: FrontendSlot::Navigation,
        text: "Capability view".into(),
        tone: FrontendTone::Neutral,
        symbol: None,
        icon_only: false,
        progress: None,
        content: Some(content),
        action: None,
    }
}