rho-coding-agent 3.6.0

A fast Rust agent harness with a small footprint and opinionated defaults
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
//! The daemon's settings as the TUI shows them (#1720).
//!
//! Once it attaches, a followed session registers the `tui` client's
//! settings, then reads the agent schema and both namespaces' values
//! (`daemon_settings_read`), and again on the new connection after the
//! daemon restarts; `rho/config/changed` keeps them current. It reads the
//! models a model setting may take there too, which `rho/model/changed`
//! keeps current. [`DaemonSettings`] is that cache, and maps it to
//! `/config` rows; `settings_screen` owns the pages and what choosing a row
//! does.

use std::collections::BTreeMap;

use rho_protocol::{
    Applies, ClientName, ConfigChangedParams, ConfigError, ConfigGetResponse, ConfigNamespace,
    ConfigRevision, ConfigSchema, IntegerUnit, ModelChoice, ModelList, ModelRuntime,
    ModelSelection, SettingEntry, SettingKey, SettingKind, SettingSpec, SettingValue,
};

use super::{
    config_row::ConfigRow, picker::PickerDetail, PickerBadge, PickerBadgeTone, PickerItem,
};

/// The `tui` client's namespace name.
const TUI_CLIENT: &str = "tui";

/// The agent setting `/config` leaves out: the daemon changes the
/// credential store only through `rho/auth/choose_store`, which checks the
/// store can be reached, so `rho credential-store set` and the login
/// question own it.
const CREDENTIAL_STORE_KEY: &str = "behavior.credential_store";

/// The settings namespaces the TUI reads.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub(super) enum SettingsNamespace {
    /// `config.toml`, described by the daemon's schema.
    Agent,
    /// `clients/tui.toml`, described by the TUI's own registry.
    Tui,
}

impl SettingsNamespace {
    pub(super) fn wire(self) -> ConfigNamespace {
        match self {
            Self::Agent => ConfigNamespace::Agent,
            Self::Tui => ConfigNamespace::Client { name: tui_client() },
        }
    }

    fn of(namespace: &ConfigNamespace) -> Option<Self> {
        match namespace {
            ConfigNamespace::Agent => Some(Self::Agent),
            ConfigNamespace::Client { name } if name.as_str() == TUI_CLIENT => Some(Self::Tui),
            _ => None,
        }
    }
}

pub(crate) fn tui_client() -> ClientName {
    ClientName::new(TUI_CLIENT).expect("`tui` is a valid client name")
}

/// One namespace's values, as the daemon last sent them.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct NamespaceValues {
    pub(super) revision: ConfigRevision,
    pub(super) values: BTreeMap<SettingKey, SettingEntry>,
    /// Problems in the file; the daemon keeps its last good values.
    pub(super) errors: Vec<ConfigError>,
}

impl From<ConfigGetResponse> for NamespaceValues {
    fn from(response: ConfigGetResponse) -> Self {
        Self {
            revision: response.revision,
            values: response.values,
            errors: response.errors,
        }
    }
}

/// What one `rho/config/changed` did to the cache.
#[derive(Debug, PartialEq)]
pub(super) struct Applied {
    pub(super) namespace: SettingsNamespace,
    /// Only the entries that changed, so a live setting the TUI changed
    /// for itself, such as Alt+S streaming, survives another's change.
    pub(super) changed: BTreeMap<SettingKey, SettingEntry>,
    /// The namespace's problems, when they changed; empty otherwise, or
    /// once the file is fixed.
    pub(super) new_problems: Vec<ConfigError>,
}

/// What the TUI knows of the daemon's settings.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct DaemonSettings {
    schema: ConfigSchema,
    tui_specs: Vec<SettingSpec>,
    agent: NamespaceValues,
    tui: NamespaceValues,
    /// The models a model setting may take, as `rho/model/list` answered
    /// this process.
    models: ListedModels,
}

/// The models a model setting may take, as the daemon listed them.
#[derive(Clone, Debug, PartialEq)]
pub(crate) enum ListedModels {
    Listed(ModelList),
    /// The daemon could not list them, and said why: a build older than
    /// `rho/model/list`, or a config file that does not load. The other
    /// settings still show; a model setting offers no models until the
    /// settings are read again.
    Unlisted(String),
}

impl DaemonSettings {
    pub(crate) fn new(
        mut schema: ConfigSchema,
        tui_specs: Vec<SettingSpec>,
        agent: NamespaceValues,
        tui: NamespaceValues,
        models: ListedModels,
    ) -> Self {
        schema
            .settings
            .retain(|spec| spec.key.as_str() != CREDENTIAL_STORE_KEY);
        Self {
            schema,
            tui_specs,
            agent,
            tui,
            models,
        }
    }

    /// The models rho runs that a model setting may take.
    pub(super) fn models(&self) -> &[ModelChoice] {
        self.listed().map_or(&[], |list| &list.models)
    }

    /// Why the daemon could not list the models, when it could not.
    pub(super) fn unlisted_models(&self) -> Option<&str> {
        match &self.models {
            ListedModels::Listed(_) => None,
            ListedModels::Unlisted(error) => Some(error),
        }
    }

    fn listed(&self) -> Option<&ModelList> {
        match &self.models {
            ListedModels::Listed(list) => Some(list),
            ListedModels::Unlisted(_) => None,
        }
    }

    /// Takes in a `rho/model/changed`.
    pub(super) fn set_models(&mut self, models: ModelList) {
        self.models = ListedModels::Listed(models);
    }

    /// Takes in a `rho/config/changed`; `None` for a namespace the TUI
    /// never read.
    pub(super) fn apply(&mut self, changed: ConfigChangedParams) -> Option<Applied> {
        let namespace = SettingsNamespace::of(&changed.namespace)?;
        let current = self.values_mut(namespace);
        current.revision = changed.revision;
        current.values.extend(changed.values.clone());
        let new_problems = if current.errors == changed.errors {
            Vec::new()
        } else {
            changed.errors.clone()
        };
        current.errors = changed.errors;
        Some(Applied {
            namespace,
            changed: changed.values,
            new_problems,
        })
    }

    /// Every problem in the files, as when the settings were first read.
    pub(super) fn problems(&self) -> Vec<ConfigError> {
        [&self.agent, &self.tui]
            .into_iter()
            .flat_map(|values| values.errors.iter().cloned())
            .collect()
    }

    pub(super) fn values(&self, namespace: SettingsNamespace) -> &NamespaceValues {
        match namespace {
            SettingsNamespace::Agent => &self.agent,
            SettingsNamespace::Tui => &self.tui,
        }
    }

    fn values_mut(&mut self, namespace: SettingsNamespace) -> &mut NamespaceValues {
        match namespace {
            SettingsNamespace::Agent => &mut self.agent,
            SettingsNamespace::Tui => &mut self.tui,
        }
    }

    fn specs(&self, namespace: SettingsNamespace) -> &[SettingSpec] {
        match namespace {
            SettingsNamespace::Agent => &self.schema.settings,
            SettingsNamespace::Tui => &self.tui_specs,
        }
    }

    pub(super) fn spec(
        &self,
        namespace: SettingsNamespace,
        key: &SettingKey,
    ) -> Option<&SettingSpec> {
        self.specs(namespace).iter().find(|spec| &spec.key == key)
    }

    /// The value `key` has now; `None` for an unset optional setting.
    pub(super) fn value(
        &self,
        namespace: SettingsNamespace,
        key: &SettingKey,
    ) -> Option<&SettingValue> {
        self.values(namespace).values.get(key)?.value.as_ref()
    }

    /// The root page's category rows: the agent's, in schema order, then
    /// the `tui` client's. A category without settings is left out.
    pub(super) fn category_rows(&self) -> Vec<PickerItem> {
        let agent = self.schema.categories.iter().map(|category| {
            (
                SettingsNamespace::Agent,
                category.id.clone(),
                category.label.clone(),
            )
        });
        let mut tui_categories: Vec<String> = Vec::new();
        for spec in &self.tui_specs {
            if !tui_categories.contains(&spec.category) {
                tui_categories.push(spec.category.clone());
            }
        }
        let tui = tui_categories
            .into_iter()
            .map(|id| (SettingsNamespace::Tui, id.clone(), capitalized(&id)));
        agent
            .chain(tui)
            .filter_map(|(namespace, id, label)| {
                let specs: Vec<_> = self
                    .specs(namespace)
                    .iter()
                    .filter(|spec| spec.category == id)
                    .collect();
                if specs.is_empty() {
                    return None;
                }
                let detail = specs
                    .iter()
                    .map(|spec| spec.label.as_str())
                    .collect::<Vec<_>>()
                    .join(", ");
                Some(PickerItem {
                    section: Some("Settings".into()),
                    detail: Some(PickerDetail::Text(format!("{detail}."))),
                    ..PickerItem::new(label, ConfigRow::Category { namespace, id }.encode())
                })
            })
            .collect()
    }

    /// The label a category page shows as its title.
    pub(super) fn category_label(&self, namespace: SettingsNamespace, id: &str) -> String {
        match namespace {
            SettingsNamespace::Agent => self
                .schema
                .categories
                .iter()
                .find(|category| category.id == id)
                .map_or_else(|| capitalized(id), |category| category.label.clone()),
            SettingsNamespace::Tui => capitalized(id),
        }
    }

    /// Category `id`'s setting rows, in registry order, under their
    /// sections. A row's badge is its value; its detail is the help, when
    /// the change applies, and the file's problem with it, if any.
    pub(super) fn setting_rows(&self, namespace: SettingsNamespace, id: &str) -> Vec<PickerItem> {
        let current = self.values(namespace);
        self.specs(namespace)
            .iter()
            .filter(|spec| spec.category == id)
            .map(|spec| {
                let value = current
                    .values
                    .get(&spec.key)
                    .and_then(|entry| entry.value.as_ref());
                let mut detail = spec.help.clone();
                if let Some(when) = applies_suffix(spec.applies) {
                    detail.push(' ');
                    detail.push_str(when);
                }
                for error in current
                    .errors
                    .iter()
                    .filter(|error| error.key.as_ref() == Some(&spec.key))
                {
                    detail.push_str(&format!(
                        "\n\nThe file's value is not used: {}",
                        error.message
                    ));
                }
                PickerItem {
                    section: spec.section.clone(),
                    detail: Some(PickerDetail::Text(detail)),
                    badge: Some(selected_badge(self.display_value(spec, value))),
                    selection_verb: Some(match spec.kind {
                        SettingKind::Bool => "toggle",
                        _ => "change",
                    }),
                    space_confirms: matches!(spec.kind, SettingKind::Bool),
                    ..PickerItem::new(
                        spec.label.clone(),
                        ConfigRow::Setting {
                            namespace,
                            key: spec.key.clone(),
                        }
                        .encode(),
                    )
                }
            })
            .collect()
    }

    /// The child page of a choice or model setting: one row per value it
    /// takes, the current one badged, then a reset row once the file sets
    /// it. `None` for other kinds, which change without a page.
    pub(super) fn value_rows(
        &self,
        namespace: SettingsNamespace,
        key: &SettingKey,
    ) -> Option<Vec<PickerItem>> {
        let spec = self.spec(namespace, key)?;
        let current = self.value(namespace, key);
        let set = |value: SettingValue| ConfigRow::Set {
            namespace,
            key: key.clone(),
            value,
        };
        let mut rows: Vec<PickerItem> = match &spec.kind {
            SettingKind::Choice { choices } => choices
                .iter()
                .map(|choice| {
                    let value = SettingValue::Text(choice.value.clone());
                    PickerItem {
                        detail: choice.help.clone().map(PickerDetail::Text),
                        badge: (current == Some(&value)).then(|| selected_badge("current")),
                        ..PickerItem::new(choice.label.clone(), set(value).encode())
                    }
                })
                .collect(),
            SettingKind::Model { runtimes } => {
                let mut rows = Vec::new();
                if runtimes.contains(&ModelRuntime::Rho) {
                    rows.extend(self.models().iter().map(|choice| {
                        let value = SettingValue::Model(ModelSelection::Rho {
                            provider: choice.model.provider.clone(),
                            model: choice.model.model.clone(),
                        });
                        PickerItem {
                            detail: Some(PickerDetail::Text(format!(
                                "{}/{}",
                                choice.model.provider, choice.model.model
                            ))),
                            badge: (current == Some(&value)).then(|| selected_badge("current")),
                            ..PickerItem::new(choice.label.clone(), set(value).encode())
                        }
                    }));
                }
                if runtimes.contains(&ModelRuntime::ClaudeCli) {
                    rows.extend(self.claude_code_rows(current).into_iter().map(
                        |(label, detail, model)| {
                            let value = SettingValue::Model(ModelSelection::ClaudeCli { model });
                            PickerItem {
                                detail: Some(PickerDetail::Text(detail)),
                                badge: (current == Some(&value)).then(|| selected_badge("current")),
                                ..PickerItem::new(label, set(value).encode())
                            }
                        },
                    ));
                }
                rows
            }
            // Bool, integer, and text change in place; `Unknown` cannot.
            _ => return None,
        };
        let from_file = self
            .values(namespace)
            .values
            .get(key)
            .is_some_and(|entry| entry.source == rho_protocol::ValueSource::Global);
        if from_file {
            let default = self.display_value(spec, spec.default.as_ref());
            rows.push(PickerItem {
                detail: Some(PickerDetail::Text(
                    "Remove the setting from the file, so its default applies.".into(),
                )),
                ..PickerItem::new(
                    format!("Default ({default})"),
                    ConfigRow::Reset {
                        namespace,
                        key: key.clone(),
                    }
                    .encode(),
                )
            });
        }
        Some(rows)
    }

    /// Claude Code's model rows as `(label, detail, model)`: the daemon's
    /// list, its own default first, then `current`'s model when the list
    /// does not name it.
    fn claude_code_rows(
        &self,
        current: Option<&SettingValue>,
    ) -> Vec<(String, String, Option<String>)> {
        let offered = self.listed().map_or(&[][..], |list| &list.claude_cli);
        let mut rows: Vec<_> = offered
            .iter()
            .map(|model| {
                (
                    model.label.clone(),
                    model.detail.clone(),
                    model.model.clone(),
                )
            })
            .collect();
        if let Some(SettingValue::Model(ModelSelection::ClaudeCli { model: Some(model) })) = current
        {
            if !offered
                .iter()
                .any(|offered| offered.model.as_ref() == Some(model))
            {
                rows.push((
                    rho_providers::provider::model_reference(
                        crate::claude_runtime::models::CLAUDE_CODE_SOURCE_LABEL,
                        model,
                    ),
                    "Runs on Claude Code.".to_owned(),
                    Some(model.clone()),
                ));
            }
        }
        rows
    }

    /// `value` as a row's badge says it.
    pub(super) fn display_value(&self, spec: &SettingSpec, value: Option<&SettingValue>) -> String {
        let Some(value) = value else {
            return "not set".into();
        };
        match (&spec.kind, value) {
            (SettingKind::Bool, SettingValue::Bool(on)) => if *on { "on" } else { "off" }.into(),
            (SettingKind::Choice { choices }, SettingValue::Text(text)) => choices
                .iter()
                .find(|choice| &choice.value == text)
                .map_or_else(|| text.clone(), |choice| choice.label.clone()),
            (SettingKind::Integer { unit, .. }, SettingValue::Integer(number)) => match unit {
                Some(IntegerUnit::Percent) => format!("{number}%"),
                Some(IntegerUnit::Seconds) => format!("{number}s"),
                Some(IntegerUnit::Lines) => format!("{number} lines"),
                Some(IntegerUnit::Bytes) => format!("{number} bytes"),
                // `Unknown`, or a unit a newer daemon sends.
                _ => number.to_string(),
            },
            (_, SettingValue::Model(ModelSelection::Rho { provider, model })) => self
                .models()
                .iter()
                .find(|choice| &choice.model.provider == provider && &choice.model.model == model)
                .map_or_else(
                    || format!("{provider}/{model}"),
                    |choice| choice.label.clone(),
                ),
            (_, SettingValue::Model(ModelSelection::ClaudeCli { model })) => {
                format!("claude-code/{}", model.as_deref().unwrap_or("default"))
            }
            (_, SettingValue::Text(text)) => text.clone(),
            (_, SettingValue::Integer(number)) => number.to_string(),
            (_, SettingValue::Bool(on)) => on.to_string(),
        }
    }
}

/// When a change takes effect, as a row's detail ends.
fn applies_suffix(applies: Applies) -> Option<&'static str> {
    match applies {
        Applies::Immediately => None,
        Applies::NextTurn => Some("Applies from the next turn."),
        Applies::NextSession => Some("Applies to new sessions."),
        Applies::Restart => Some("Applies once rho restarts."),
        _ => None,
    }
}

fn selected_badge(text: impl Into<String>) -> PickerBadge {
    PickerBadge {
        text: text.into(),
        tone: PickerBadgeTone::Selected,
    }
}

fn capitalized(id: &str) -> String {
    let mut chars = id.chars();
    match chars.next() {
        Some(first) => first.to_uppercase().chain(chars).collect(),
        None => String::new(),
    }
}

#[cfg(test)]
#[path = "daemon_settings_tests.rs"]
pub(super) mod tests;