argonauts-app 0.1.0

Argonauts Code's app controller and run host: the conversation, routing, choosing Captain or crew, and the run host each run has.
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
use argonauts_core::api::UsagePeriod;
use argonauts_core::app::{AppEvent, UiCommand, ViewData, ViewRequest};
use argonauts_core::input::{SlashCommand, ViewAction};

use crate::controller::test_support::{CliOptions, TestDriver};

/// A folder without git, as someone's Downloads folder is.
async fn no_git() -> TestDriver {
    TestDriver::start_with(CliOptions {
        prepare: Some(Box::new(|repo| {
            std::fs::remove_dir_all(repo.root().join(".git")).expect("the repo's .git removed");
        })),
        ..CliOptions::default()
    })
    .await
}

fn is_answer(event: &AppEvent) -> bool {
    matches!(event, AppEvent::View { .. })
}

/// What each tab asks for as it opens and as it stays open.
fn every_tab() -> Vec<UiCommand> {
    let mut asks = vec![ViewRequest::StatusTab, ViewRequest::Context];
    asks.extend(
        [
            UsagePeriod::Today,
            UsagePeriod::Week,
            UsagePeriod::Month,
            UsagePeriod::All,
        ]
        .map(|period| ViewRequest::Usage { period }),
    );
    // The Usage tab reads every CLI again as it opens, and the Overview asks for its numbers.
    asks.push(ViewRequest::ReadPlanUsage);
    asks.push(ViewRequest::Overview {
        period: argonauts_core::overview::OverviewPeriod::All,
        import: None,
    });
    let mut commands: Vec<UiCommand> = asks
        .into_iter()
        .map(|view| UiCommand::Request { view })
        .collect();
    // `/status` typed opens the same tab.
    commands.push(UiCommand::Slash {
        command: SlashCommand::Status {
            action: ViewAction::Open,
        },
    });
    commands
}

#[tokio::test]
async fn opening_every_tab_with_nothing_to_show_writes_nothing_into_the_conversation() {
    let mut driver = no_git().await;
    // Whatever the opening says is said by the time its first answer comes.
    driver
        .send(UiCommand::Request {
            view: ViewRequest::StatusTab,
        })
        .await;
    driver.until(is_answer).await;
    let opened = driver.seen().len();
    // Twice over, as the tabs ask again while they stay open.
    for command in every_tab().into_iter().chain(every_tab()) {
        // A live read answers later, through the next numbers the tab asks for.
        let answers = !matches!(
            command,
            UiCommand::Request {
                view: ViewRequest::ReadPlanUsage
            }
        );
        driver.send(command).await;
        if answers {
            driver.until(is_answer).await;
        }
    }
    let after: Vec<AppEvent> = driver.seen()[opened..].to_vec();
    let spoke: Vec<&AppEvent> = after
        .iter()
        .filter(|event| !matches!(event, AppEvent::View { .. } | AppEvent::Status { .. }))
        .collect();
    assert!(
        spoke.is_empty(),
        "the tabs wrote into the conversation: {spoke:#?}"
    );
    let status_tab = after
        .iter()
        .filter(|event| {
            matches!(event, AppEvent::View { data }
                if matches!(data.as_ref(), ViewData::StatusTab { .. }))
        })
        .count();
    assert_eq!(status_tab, 4, "the tab's own read and /status, twice");
    driver.exit().await;
}

#[tokio::test]
async fn the_status_tab_answers_with_no_run_and_no_git() {
    let mut driver = no_git().await;
    driver
        .send(UiCommand::Request {
            view: ViewRequest::StatusTab,
        })
        .await;
    let AppEvent::View { data } = driver.until(is_answer).await else {
        unreachable!()
    };
    let ViewData::StatusTab { view } = *data else {
        panic!("{data:?}")
    };
    assert!(view.runs.is_empty() && view.run.is_none());
    assert!(!view.folder.git);
    assert_eq!(view.version, env!("CARGO_PKG_VERSION"));
    driver.exit().await;
}

#[test]
fn claude_codes_auth_status_names_the_account_and_the_plan() {
    let printed = r#"{
      "loggedIn": true,
      "authMethod": "claude.ai",
      "email": "you@example.com",
      "subscriptionType": "max"
    }"#;
    assert_eq!(
        super::sign_in_from(printed),
        super::SignIn {
            account: Some("you@example.com".to_owned()),
            plan: Some("Max".to_owned()),
            ..super::SignIn::default()
        }
    );
    // Codex's says only how it is signed in.
    assert_eq!(
        super::sign_in_from("Logged in using ChatGPT\n"),
        super::SignIn::default()
    );
    // Claude Code's says when no one is.
    let out = super::sign_in_from(r#"{"loggedIn": false, "authMethod": "none"}"#);
    assert!(out.signed_out && out.account.is_none(), "{out:?}");
}

/// A login check that fails, as `codex login status` does with no one signed in, means
/// signed out, never "signed in".
#[tokio::test]
async fn a_login_check_that_fails_means_signed_out() {
    let dir = tempfile::tempdir().unwrap();
    let check = dir.path().join("login-check");
    argonauts_testkit::write_script(&check, "#!/bin/sh\necho 'Not logged in'\nexit 1\n").unwrap();
    let out = super::sign_in(&check, &[]).await.unwrap();
    assert!(out.signed_out && out.account.is_none(), "{out:?}");
}

fn check(
    id: &str,
    name: &str,
    status: argonauts_conductor::AgentStatus,
) -> argonauts_conductor::AgentCheck {
    argonauts_conductor::AgentCheck {
        id: id.to_owned(),
        display_name: name.to_owned(),
        binary: id.to_owned(),
        path: None,
        version: Some("1.0.0".to_owned()),
        status,
        tested_versions: Vec::new(),
        cheapest_model: String::new(),
        cheapest_effort: None,
        problem: None,
        enabled: true,
    }
}

/// One answer holds how each CLI stands and how each of its models does. The CLIs are the
/// ones Doctor checked, each with what was made of its version, and those that are installed
/// have a row of health a model, where the one that is out says so.
#[tokio::test]
async fn one_answer_holds_each_clis_standing_and_each_models_health() {
    use argonauts_conductor::{AgentStatus, DoctorReport, GitCheck};
    use argonauts_core::limits::{ModelState, Trouble};
    use argonauts_core::names::ModelRef;
    use argonauts_core::status_tab::{Standing, VersionStanding};

    use crate::controller::conversation::ConversationState;
    use crate::controller::runs::RunsState;
    use crate::controller::test_support::TestCtx;

    let (mut parts, _opening) = TestCtx::new(CliOptions::default());
    parts.ctx.cli_facts.checked(DoctorReport {
        agents: vec![
            check("claude-code", "Claude Code", AgentStatus::Tested),
            check("opencode", "OpenCode", AgentStatus::NotInstalled),
        ],
        git: GitCheck {
            version: None,
            problem: None,
        },
    });
    let opus: ModelRef = "claude-code/claude-opus-5-5".parse().unwrap();
    parts
        .health
        .set_model(&opus, ModelState::Out, Some(Trouble::Overload));
    let conversation = ConversationState::new(&parts.ctx).unwrap();
    let mut runs = RunsState::new(&parts.ctx);
    let view = super::read(&mut parts.ctx, &mut runs, &conversation).await;

    let listed: Vec<&str> = view.clis.iter().map(|cli| cli.id.as_str()).collect();
    assert_eq!(listed, ["claude-code", "opencode"]);
    let claude = &view.clis[0];
    assert!(claude.installed && claude.main, "{claude:?}");
    assert_eq!(claude.version.as_deref(), Some("1.0.0"));
    assert_ne!(claude.check.standing, VersionStanding::Unknown);

    let health: Vec<&str> = view.health.clis.iter().map(|cli| cli.id.as_str()).collect();
    assert_eq!(health, listed, "a row of health for each CLI listed");
    let models = &view.health.clis[0].models;
    let out: Vec<&str> = models
        .iter()
        .filter(|model| model.state == Standing::Overloaded)
        .map(|model| model.name.as_str())
        .collect();
    assert_eq!(out, ["Opus 5.5"], "{models:#?}");
    // The main agent names no model and runs Opus 5.5: that model has one row, which says
    // what the main agent meets, and no row beside it speaks of a default.
    let named: Vec<&str> = models.iter().map(|model| model.name.as_str()).collect();
    assert!(!named.contains(&"its default"), "{named:?}");
    let opus_rows = named.iter().filter(|name| **name == "Opus 5.5").count();
    assert_eq!(opus_rows, 1, "{named:?}");
    assert!(
        view.health.clis[1].models.is_empty(),
        "nothing runs on a CLI that isn't here"
    );
}

#[test]
fn every_cli_doctor_checked_is_listed_the_main_sessions_first() {
    use argonauts_conductor::{AgentStatus, DoctorReport, GitCheck};

    let report = DoctorReport {
        agents: vec![
            check("codex", "Codex", AgentStatus::Tested),
            check("claude-code", "Claude Code", AgentStatus::Newer),
            check("opencode", "OpenCode", AgentStatus::NotInstalled),
            check("opencode-acp", "OpenCode (ACP)", AgentStatus::Untested),
        ],
        git: GitCheck {
            version: None,
            problem: None,
        },
    };
    let mut sign_ins = std::collections::BTreeMap::new();
    sign_ins.insert(
        "claude-code".to_owned(),
        super::SignIn {
            account: Some("you@example.com".to_owned()),
            plan: Some("Max".to_owned()),
            ..super::SignIn::default()
        },
    );
    // OpenCode names no account: it was asked what it can use.
    sign_ins.insert(
        "opencode-acp".to_owned(),
        super::SignIn {
            providers: Some(Vec::new()),
            ..super::SignIn::default()
        },
    );
    // Codex's login check names no account; its live plan reading does.
    let plan_usage = argonauts_testkit::services::MemoryPlanUsageBoard::default();
    let mut live = argonauts_core::plan_usage::LiveUsage::new(
        argonauts_core::names::AgentId("codex".to_owned()),
        argonauts_core::limits::PlanUsageSource::AppServer,
        time::OffsetDateTime::now_utc(),
    );
    live.account = Some("me@work.example".to_owned());
    live.plan = Some("Plus".to_owned());
    argonauts_core::limits::PlanUsageBoard::observe_live(&plan_usage, live);
    use argonauts_core::status_tab::{CliVersionCheck, VersionStanding};
    let checks = std::collections::BTreeMap::from([(
        "claude-code".to_owned(),
        CliVersionCheck {
            standing: VersionStanding::Newer,
            works: true,
            ..CliVersionCheck::default()
        },
    )]);
    let none = std::collections::BTreeSet::new();
    let clis = super::clis(
        &report,
        "claude-code",
        &sign_ins,
        &plan_usage,
        &checks,
        &none,
    );
    let names: Vec<&str> = clis.iter().map(|cli| cli.name.as_str()).collect();
    assert_eq!(
        names,
        ["Claude Code", "Codex", "OpenCode", "OpenCode (ACP)"]
    );
    assert_eq!(clis[0].command, "claude-code");
    assert_eq!(clis[3].providers.as_deref(), Some(&[][..]));
    assert!(clis[0].main);
    assert_eq!(clis[0].account.as_deref(), Some("you@example.com"));
    assert_eq!(clis[1].account.as_deref(), Some("me@work.example"));
    assert_eq!(clis[1].plan.as_deref(), Some("Plus"));
    assert_eq!(clis[0].check.state(), "newer than checked · works");
    assert_eq!(clis[1].check.state(), "unknown version");
    assert!(!clis[2].installed);
    assert_eq!(clis[2].version, None);
}

#[test]
fn only_other_servers_count_as_the_main_sessions_mcp_servers() {
    let tools = [
        "Bash",
        "mcp__github__create_issue",
        "mcp__argonauts__argonauts_status",
        "mcp__argonauts_status__approve",
        "mcp__linear__list",
        "mcp__github__comment",
    ]
    .map(str::to_owned);
    assert_eq!(
        crate::controller::conversation::own_mcp_servers(&tools),
        ["github", "linear"]
    );
}

#[tokio::test]
async fn the_status_tab_counts_each_settings_file_and_says_how_the_folder_is_set_up() {
    let mut driver = TestDriver::start_with(CliOptions {
        prepare: Some(Box::new(|repo| {
            std::fs::create_dir_all(repo.home()).unwrap();
            std::fs::write(repo.global_config(), "workflow_size = \"large\"\n").unwrap();
        })),
        ..CliOptions::default()
    })
    .await;
    driver
        .send(UiCommand::Request {
            view: ViewRequest::StatusTab,
        })
        .await;
    let AppEvent::View { data } = driver.until(is_answer).await else {
        unreachable!()
    };
    let ViewData::StatusTab { view } = *data else {
        panic!("{data:?}")
    };
    assert!(view.folder.git);
    assert_eq!(view.workflow.size, "large");
    assert!(!view.mode.is_empty());
    let global = view
        .settings
        .files
        .iter()
        .find(|file| file.layer == "global")
        .unwrap_or_else(|| panic!("{:#?}", view.settings));
    // The key the test wrote, and the workflow a setup names.
    assert_eq!(global.keys, 2);
    assert!(global.path.ends_with("config.toml"), "{}", global.path);
    assert!(
        view.settings
            .keys
            .iter()
            .any(|entry| entry.key == "workflow_size" && entry.layer == "global")
    );
    assert!(view.settings.mods_built_in > 0);
    assert_eq!(view.main.as_ref().unwrap().worker.agent, "claude-code");
    // Doctor never ran here, so no CLI is listed and none was asked who it's signed in as.
    assert!(view.clis.is_empty());
    driver.exit().await;
}

/// Doctor says why a CLI's address isn't shown, by what was asked of it.
/// A CLI that keeps providers of its own never reads as an account whose address isn't
/// shown: until it answers nothing is said of it to Doctor, and an answer that couldn't be
/// read says so on the tab and to Doctor alike.
#[test]
fn a_cli_with_providers_of_its_own_is_never_an_unnamed_account() {
    use std::collections::{BTreeMap, BTreeSet};

    use argonauts_conductor::{AgentStatus, DoctorReport, GitCheck};

    let report = DoctorReport {
        agents: vec![check("opencode", "OpenCode", AgentStatus::Tested)],
        git: GitCheck {
            version: None,
            problem: None,
        },
    };
    let board = argonauts_testkit::services::FakeServices::new().plan_usage;
    let listing = BTreeSet::from(["opencode".to_owned()]);
    let row = |sign_ins: &BTreeMap<String, super::SignIn>| {
        super::clis(
            &report,
            "claude-code",
            sign_ins,
            board.as_ref(),
            &BTreeMap::new(),
            &listing,
        )
        .remove(0)
    };

    let asking = row(&BTreeMap::new());
    assert!(asking.lists_providers && !asking.providers_unread);
    assert_eq!(asking.providers, None);

    let unread = super::SignIn {
        providers_unread: true,
        ..super::SignIn::default()
    };
    let unread = row(&BTreeMap::from([("opencode".to_owned(), unread)]));
    assert!(unread.lists_providers && unread.providers_unread);
    assert_eq!(
        argonauts_core::status_tab::providers_unread(&unread.command),
        "couldn't list its providers · opencode auth list shows them"
    );
}

#[test]
fn each_unnamed_account_says_why() {
    assert!(super::unnamed_why("codex", true).starts_with("its login check doesn't print"));
    assert_eq!(
        super::unnamed_why("antigravity-cli", true),
        "its start-up screen was read and showed no address"
    );
    assert_eq!(
        super::unnamed_why("opencode", false),
        "it has no check that names the account"
    );
}

/// What agy's start-up screen said is kept as the tab shows it: the account, signed out, or a
/// folder it hasn't trusted. A screen that never said is one that was read all the same.
#[test]
fn each_thing_agys_screen_says_is_kept_apart() {
    use argonauts_core::adapter::BannerAccount;

    let signed_in = super::sign_in_shown(Some(BannerAccount::SignedIn {
        account: "you@example.com".to_owned(),
        plan: Some("Google AI Pro".to_owned()),
    }));
    assert_eq!(signed_in.account.as_deref(), Some("you@example.com"));
    assert_eq!(signed_in.plan.as_deref(), Some("Google AI Pro"));
    assert!(super::sign_in_shown(Some(BannerAccount::SignedOut)).signed_out);
    let untrusted = super::sign_in_shown(Some(BannerAccount::UntrustedFolder));
    assert!(untrusted.untrusted_folder && !untrusted.signed_out);
    assert_eq!(super::sign_in_shown(None), super::SignIn::default());
}

/// OpenCode is asked what it can use by its own commands, here a fake one that answers each
/// with the made-up lists, and its credentials file is never touched.
#[tokio::test]
async fn opencode_is_asked_for_its_providers_by_its_own_commands() {
    use argonauts_core::status_tab::ProviderBilling;

    let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("../adapters/opencode/fixtures")
        .canonicalize()
        .unwrap();
    let dir = tempfile::tempdir().unwrap();
    let opencode = dir.path().join("opencode");
    let script = format!(
        "#!/bin/sh\necho \"$*\" >> '{asked}'\ncase \"$*\" in\n  'auth list --standalone --format json') \
         cat '{f}/providers_2_auth_list.stdout.json' ;;\n  'models --standalone') cat \
         '{f}/providers_models.stdout.txt' ;;\n  'debug config') cat \
         '{f}/providers_config.stdout.json' ;;\n  *) exit 2 ;;\nesac\n",
        asked = dir.path().join("asked").display(),
        f = fixtures.display(),
    );
    argonauts_testkit::write_script(&opencode, &script).unwrap();
    let adapter: std::sync::Arc<dyn argonauts_core::Adapter> =
        std::sync::Arc::new(argonauts_adapter_opencode::OpenCodeAdapter::new());
    let asked = super::Asked {
        program: opencode.clone(),
        cwd: dir.path().to_owned(),
        confine: std::sync::Arc::new(argonauts_core::confine::Unconfined),
    };
    let found = super::providers(&asked, std::sync::Arc::clone(&adapter))
        .await
        .unwrap();
    let providers = found.providers.unwrap();
    let listed: Vec<(&str, ProviderBilling)> = providers
        .iter()
        .map(|provider| (provider.name.as_str(), provider.billing))
        .collect();
    assert_eq!(
        listed,
        [
            ("OpenRouter", ProviderBilling::ApiKey),
            ("Ollama", ProviderBilling::Local)
        ]
    );
    assert_eq!(found.default_model.as_deref(), Some("GLM 5 on OpenRouter"));
    assert!(found.account.is_none() && !found.signed_out);
    let asked_for = std::fs::read_to_string(dir.path().join("asked")).unwrap();
    // Each on a private server, never OpenCode 2's shared service.
    assert_eq!(
        asked_for,
        "auth list --standalone --format json\nmodels --standalone\ndebug config\n"
    );

    // A sandbox that can't start runs none of them, and the tab says so.
    let refused = super::Asked {
        confine: std::sync::Arc::new(Refusing),
        ..asked
    };
    let found = super::providers(&refused, adapter).await.unwrap();
    assert!(found.providers_unread && found.providers.is_none());
    let asked_for = std::fs::read_to_string(dir.path().join("asked")).unwrap();
    assert_eq!(asked_for.lines().count(), 3);
}

/// A sandbox that can't start here.
#[derive(Debug)]
struct Refusing;

impl argonauts_core::confine::Confine for Refusing {
    fn confine<'a>(
        &'a self,
        _cli: &'a str,
        _command: argonauts_core::CommandSpec,
    ) -> argonauts_core::future::BoxFuture<'a, Result<argonauts_core::CommandSpec, String>> {
        Box::pin(async { Err("no working sandbox: sandbox-exec is missing".to_owned()) })
    }
}