link-assistant-router 1.2.1

Link.Assistant.Router — Claude MAX OAuth proxy and token gateway for Anthropic APIs
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
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
//! Tests for the temporary launcher's directories, isolation and settings.
//!
//! Split from `with_command.rs` to keep that file within the repository's
//! 1000-line limit.

use super::*;
/// Gemini CLI resolves settings as `<home>/.gemini/settings.json`, where
/// `<home>` is `GEMINI_CLI_HOME` if set and `$HOME` otherwise. Pointing
/// `GEMINI_CLI_HOME` at the `.gemini` directory made it look one level too
/// deep, fall back to the user's personal settings, and refuse the run
/// (issue #227). Both variables must therefore name the root.
#[test]
fn the_gemini_client_is_pointed_at_the_isolated_home() {
    let root = tempfile::tempdir().expect("isolated root");
    let manager = ClientManager::isolated(root.path());
    let mut command = Command::new("gemini");
    configure_isolation(
        &mut command,
        &manager,
        root.path(),
        ClientKind::GeminiCli,
        true,
    )
    .expect("configure gemini isolation");

    let environment: std::collections::HashMap<_, _> = command
        .get_envs()
        .filter_map(|(key, value)| Some((key.to_string_lossy().into_owned(), value?)))
        .collect();

    for name in ["HOME", "GEMINI_CLI_HOME"] {
        assert_eq!(
            environment.get(name).map(|value| value.to_string_lossy()),
            Some(root.path().to_string_lossy()),
            "{name} must name the isolated root, not the .gemini directory \
             inside it — the CLI appends `.gemini` itself"
        );
    }
    // The file the CLI actually reads lives under that home.
    assert_eq!(
        manager.config_path(ClientKind::GeminiCli),
        root.path().join(".gemini/settings.json")
    );
    // The trusted-directory prompt cannot be answered non-interactively.
    assert_eq!(
        environment
            .get("GEMINI_CLI_TRUST_WORKSPACE")
            .map(|value| value.to_string_lossy()),
        Some(std::borrow::Cow::Borrowed("true"))
    );
}

/// End to end: after preparing the client, the file Gemini CLI actually
/// reads must exist and select the API-key flow. The router previously
/// wrote a correct file the CLI never opened (issue #227).
/// By default the client keeps its own configuration directory, so sessions
/// started outside the router remain visible and a conversation can be
/// resumed through it (issue #233), and an interactive user does not land in
/// first-run onboarding (issue #277).
#[test]
fn the_users_configuration_is_kept_by_default() {
    let models = [RouterModel {
        id: "test-model".to_string(),
        owned_by: "test".to_string(),
        ..RouterModel::default()
    }];
    let extended = TemporaryClient::prepare(&Preparation {
        client: ClientKind::ClaudeCode,
        base_url: "http://router.test",
        token: "task-token",
        model_override: None,
        models: &models,
        isolated_config: false,
        one_shot: true,
        profile_root: None,
        codex_reasoning_effort: None,
    })
    .expect("prepare with the default configuration handling");
    let names: Vec<String> = extended
        .command
        .get_envs()
        .map(|(name, _)| name.to_string_lossy().into_owned())
        .collect();
    assert!(
        !names.iter().any(|name| name == "CLAUDE_CONFIG_DIR"),
        "the user's configuration directory must not be repointed: {names:?}"
    );
    // The router's actual contribution is still applied.
    for required in ["ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_BASE_URL"] {
        assert!(
            names.iter().any(|name| name == required),
            "{required} missing: {names:?}"
        );
    }
    let environment = extended
        .command
        .get_envs()
        .filter_map(|(name, value)| {
            Some((
                name.to_string_lossy().into_owned(),
                value?.to_string_lossy().into_owned(),
            ))
        })
        .collect::<std::collections::HashMap<_, _>>();
    assert_eq!(
        environment.get("ANTHROPIC_BASE_URL").map(String::as_str),
        Some("http://router.test/api/services/anthropic")
    );
    assert_eq!(
        environment
            .get("CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY")
            .map(String::as_str),
        Some("1")
    );
    assert_eq!(
        environment
            .get("CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC")
            .map(String::as_str),
        Some("0")
    );
    assert_eq!(
        environment.get("ANTHROPIC_API_KEY").map(String::as_str),
        Some("")
    );
    for untouched in [
        "ANTHROPIC_MODEL",
        "ANTHROPIC_DEFAULT_OPUS_MODEL",
        "ANTHROPIC_DEFAULT_SONNET_MODEL",
        "ANTHROPIC_DEFAULT_HAIKU_MODEL",
        "CLAUDE_CODE_SUBAGENT_MODEL",
    ] {
        assert!(!environment.contains_key(untouched), "{untouched}");
    }

    // Asking for isolation still repoints the directory.
    let isolated = TemporaryClient::prepare(&Preparation {
        client: ClientKind::ClaudeCode,
        base_url: "http://router.test",
        token: "task-token",
        model_override: None,
        models: &models,
        isolated_config: true,
        one_shot: true,
        profile_root: None,
        codex_reasoning_effort: None,
    })
    .expect("prepare isolated");
    assert!(
        isolated
            .command
            .get_envs()
            .any(|(name, _)| name == "CLAUDE_CONFIG_DIR"),
        "--isolated-config must still give the client its own directory"
    );
}

#[test]
fn zai_only_claude_launch_pins_only_main_and_subagent() {
    let models = [
        RouterModel {
            id: "future-first-2099".to_string(),
            owned_by: crate::clients::ZAI_MODEL_OWNER.to_string(),
            ..RouterModel::default()
        },
        RouterModel {
            id: "future-explicit-2099".to_string(),
            owned_by: crate::clients::ZAI_MODEL_OWNER.to_string(),
            ..RouterModel::default()
        },
    ];
    let resumed = TemporaryClient::prepare(&Preparation {
        client: ClientKind::ClaudeCode,
        base_url: "http://router.test",
        token: "task-token",
        model_override: None,
        models: &models,
        isolated_config: false,
        one_shot: false,
        profile_root: None,
        codex_reasoning_effort: None,
    })
    .expect("prepare a resumed z.ai-only Claude session");
    let resumed_env = resumed
        .command
        .get_envs()
        .filter_map(|(key, value)| {
            Some((
                key.to_string_lossy().into_owned(),
                value?.to_string_lossy().into_owned(),
            ))
        })
        .collect::<std::collections::HashMap<_, _>>();
    for key in crate::clients::CLAUDE_GATEWAY_TARGET_ENV {
        assert_eq!(
            resumed_env.get(key).map(String::as_str),
            Some("future-first-2099"),
            "{key}"
        );
    }
    for key in crate::clients::CLAUDE_MODEL_ENV {
        if !crate::clients::CLAUDE_GATEWAY_TARGET_ENV.contains(&key) {
            assert!(!resumed_env.contains_key(key), "{key}");
        }
    }

    let explicit = TemporaryClient::prepare(&Preparation {
        client: ClientKind::ClaudeCode,
        base_url: "http://router.test",
        token: "task-token",
        model_override: Some("future-explicit-2099"),
        models: &models,
        isolated_config: false,
        one_shot: true,
        profile_root: None,
        codex_reasoning_effort: None,
    })
    .expect("prepare an explicit z.ai Claude model");
    let explicit_env = explicit
        .command
        .get_envs()
        .filter_map(|(key, value)| {
            Some((
                key.to_string_lossy().into_owned(),
                value?.to_string_lossy().into_owned(),
            ))
        })
        .collect::<std::collections::HashMap<_, _>>();
    for key in crate::clients::CLAUDE_GATEWAY_TARGET_ENV {
        assert_eq!(
            explicit_env.get(key).map(String::as_str),
            Some("future-explicit-2099"),
            "explicit model must win for {key}"
        );
    }
    for key in crate::clients::CLAUDE_MODEL_ENV {
        if !crate::clients::CLAUDE_GATEWAY_TARGET_ENV.contains(&key) {
            assert!(!explicit_env.contains_key(key), "{key}");
        }
    }
}

/// Issue #379: Codex supports repeatable global `-c` overlays, so routing does
/// not require replacing `HOME` or `CODEX_HOME`. The overlay must precede the
/// user's subcommand and arguments; `launch` appends those after preparation.
#[test]
fn codex_overlays_routing_without_repointing_user_configuration() {
    let models = [RouterModel {
        id: "gpt-5.6-sol".to_string(),
        owned_by: "codex".to_string(),
        default_reasoning_level: Some("high".to_string()),
        supported_reasoning_levels: Some(vec![crate::clients::RouterReasoningLevel {
            effort: "high".to_string(),
            description: "Deep reasoning".to_string(),
        }]),
    }];
    assert!(
        extends_user_configuration(ClientKind::Codex, false),
        "ordinary Codex runs can layer routing through CLI configuration"
    );
    assert!(
        !extends_user_configuration(ClientKind::Codex, true),
        "explicit isolation must still replace the client configuration"
    );

    let prepared = TemporaryClient::prepare(&Preparation {
        client: ClientKind::Codex,
        base_url: "http://router.test/path?tenant=one",
        token: "task-token",
        model_override: None,
        models: &models,
        isolated_config: false,
        one_shot: true,
        profile_root: None,
        codex_reasoning_effort: None,
    })
    .expect("prepare Codex overlay");

    let environment = prepared
        .command
        .get_envs()
        .map(|(name, value)| (name.to_string_lossy().into_owned(), value))
        .collect::<std::collections::HashMap<_, _>>();
    assert!(!environment.contains_key("HOME"), "{environment:?}");
    assert!(!environment.contains_key("CODEX_HOME"), "{environment:?}");
    assert_eq!(
        environment
            .get("LINK_ASSISTANT_TOKEN")
            .and_then(|value| *value)
            .map(|value| value.to_string_lossy()),
        Some(std::borrow::Cow::Borrowed("task-token"))
    );

    let arguments = prepared
        .command
        .get_args()
        .map(|argument| argument.to_string_lossy().into_owned())
        .collect::<Vec<_>>();
    assert_eq!(
        arguments[0..3],
        ["-c", "model_provider=\"link-assistant\"", "-c"]
    );
    let catalog_path = arguments[3]
        .strip_prefix("model_catalog_json=")
        .and_then(|value| serde_json::from_str::<String>(value).ok())
        .expect("process-local model catalog argument");
    assert!(Path::new(&catalog_path).starts_with(prepared.directory.path()));
    let catalog: serde_json::Value = serde_json::from_slice(
        &std::fs::read(&catalog_path).expect("read process-local model catalog"),
    )
    .expect("parse process-local model catalog");
    assert_eq!(catalog["models"][0]["slug"], "gpt-5.6-sol");
    assert_eq!(catalog["models"][0]["default_reasoning_level"], "high");
    assert_eq!(
        catalog["models"][0]["supported_reasoning_levels"],
        json!([{"effort": "high", "description": "Deep reasoning"}])
    );
    assert_eq!(catalog["models"].as_array().unwrap().len(), 1);
    assert_eq!(
        arguments[4..],
        [
            "-c",
            "model_providers.link-assistant.name=\"Link.Assistant.Router\"",
            "-c",
            "model_providers.link-assistant.base_url=\"http://router.test/path?tenant=one/api/services/codex/v1\"",
            "-c",
            "model_providers.link-assistant.env_key=\"LINK_ASSISTANT_TOKEN\"",
            "-c",
            "model_providers.link-assistant.wire_api=\"responses\"",
        ]
    );

    let isolated = TemporaryClient::prepare(&Preparation {
        client: ClientKind::Codex,
        base_url: "http://router.test",
        token: "task-token",
        model_override: None,
        models: &models,
        isolated_config: true,
        one_shot: true,
        profile_root: None,
        codex_reasoning_effort: None,
    })
    .expect("prepare isolated Codex");
    let isolated_home = isolated
        .command
        .get_envs()
        .find_map(|(name, value)| (name == "HOME").then_some(value?))
        .expect("isolated Codex sets HOME");
    assert_eq!(Path::new(isolated_home), isolated.directory.path());
    assert!(
        isolated
            .command
            .get_envs()
            .any(|(name, value)| name == "CODEX_HOME" && value.is_none()),
        "isolation must prevent an inherited CODEX_HOME from escaping"
    );
    assert!(isolated.command.get_args().next().is_none());
    assert!(
        isolated
            .directory
            .path()
            .join(".codex/config.toml")
            .is_file()
    );
}

/// Issue #423: the disposable catalog is a projection of the live Codex
/// catalog, not a model capability table maintained by Router. Different live
/// entries must therefore keep their different defaults and supported levels.
#[test]
fn codex_catalog_preserves_per_model_live_reasoning_metadata() {
    let root = tempfile::tempdir().expect("temporary catalog directory");
    let models = [
        RouterModel {
            id: "future-reasoning-a".to_string(),
            owned_by: "openai".to_string(),
            default_reasoning_level: Some("medium".to_string()),
            supported_reasoning_levels: Some(vec![
                crate::clients::RouterReasoningLevel {
                    effort: "low".to_string(),
                    description: "Faster answers".to_string(),
                },
                crate::clients::RouterReasoningLevel {
                    effort: "medium".to_string(),
                    description: "Balanced reasoning".to_string(),
                },
                crate::clients::RouterReasoningLevel {
                    effort: "xhigh".to_string(),
                    description: "Deepest reasoning".to_string(),
                },
            ]),
        },
        RouterModel {
            id: "future-reasoning-b".to_string(),
            owned_by: "openai".to_string(),
            default_reasoning_level: Some("xhigh".to_string()),
            supported_reasoning_levels: Some(vec![crate::clients::RouterReasoningLevel {
                effort: "xhigh".to_string(),
                description: "Only supported level".to_string(),
            }]),
        },
    ];

    let path =
        write_codex_model_catalog(root.path(), &models, None, None).expect("write live catalog");
    let catalog: serde_json::Value =
        serde_json::from_slice(&std::fs::read(path).expect("read generated catalog"))
            .expect("parse generated catalog");

    assert_eq!(
        catalog["models"][0]["supported_reasoning_levels"],
        json!([
            {"effort": "low", "description": "Faster answers"},
            {"effort": "medium", "description": "Balanced reasoning"},
            {"effort": "xhigh", "description": "Deepest reasoning"}
        ])
    );
    assert_eq!(
        catalog["models"][1]["supported_reasoning_levels"],
        json!([{"effort": "xhigh", "description": "Only supported level"}])
    );
    assert_eq!(catalog["models"][0]["default_reasoning_level"], "medium");
    assert_eq!(catalog["models"][1]["default_reasoning_level"], "xhigh");
}

/// Missing capability metadata is different from an authoritative empty list:
/// launching with unknown metadata would make Codex silently discard an
/// explicit user effort after `/model`, so Router must stop with a useful error.
#[test]
fn codex_catalog_rejects_unknown_reasoning_metadata() {
    let root = tempfile::tempdir().expect("temporary catalog directory");
    let models = [RouterModel {
        id: "future-reasoning-unknown".to_string(),
        owned_by: "openai".to_string(),
        default_reasoning_level: None,
        supported_reasoning_levels: None,
    }];

    let error = write_codex_model_catalog(root.path(), &models, None, None)
        .expect_err("unknown reasoning metadata must not silently reset the user's setting")
        .to_string();
    assert!(error.contains("future-reasoning-unknown"), "{error}");
    assert!(error.contains("reasoning metadata"), "{error}");
}

#[test]
fn codex_catalog_never_offers_a_model_that_would_reset_an_explicit_effort() {
    let root = tempfile::tempdir().expect("temporary catalog directory");
    let models = [
        RouterModel {
            id: "future-supports-xhigh".to_string(),
            owned_by: "openai".to_string(),
            default_reasoning_level: Some("medium".to_string()),
            supported_reasoning_levels: Some(vec![
                crate::clients::RouterReasoningLevel {
                    effort: "medium".to_string(),
                    description: "Balanced reasoning".to_string(),
                },
                crate::clients::RouterReasoningLevel {
                    effort: "xhigh".to_string(),
                    description: "Deepest reasoning".to_string(),
                },
            ]),
        },
        RouterModel {
            id: "future-medium-only".to_string(),
            owned_by: "openai".to_string(),
            default_reasoning_level: Some("medium".to_string()),
            supported_reasoning_levels: Some(vec![crate::clients::RouterReasoningLevel {
                effort: "medium".to_string(),
                description: "Only supported level".to_string(),
            }]),
        },
    ];

    let path = write_codex_model_catalog(root.path(), &models, Some("xhigh"), None)
        .expect("write compatibility catalog");
    let catalog: serde_json::Value =
        serde_json::from_slice(&std::fs::read(path).expect("read generated catalog"))
            .expect("parse generated catalog");
    let slugs = catalog["models"]
        .as_array()
        .expect("models array")
        .iter()
        .filter_map(|model| model["slug"].as_str())
        .collect::<Vec<_>>();
    assert_eq!(slugs, ["future-supports-xhigh"]);

    let error = write_codex_model_catalog(
        root.path(),
        &models,
        Some("xhigh"),
        Some("future-medium-only"),
    )
    .expect_err("an explicit unsupported model must be rejected")
    .to_string();
    assert!(error.contains("future-medium-only"), "{error}");
    assert!(error.contains("xhigh"), "{error}");
}

/// A client configured through a file is isolated even though extending is
/// the default, because there is nothing to layer short of rewriting that
/// file.
///
/// A fallback rather than an error: the user did not ask for isolation, they
/// asked to run a client, and this is the only way it can be run. Refusing
/// was right while extending was opt-in — the flag could not be honoured —
/// but as a default it would make `with opencode` fail outright (issue
/// #277).
#[test]
fn a_file_configured_client_is_isolated_even_by_default() {
    let models = [RouterModel {
        id: "test-model".to_string(),
        owned_by: "test".to_string(),
        ..RouterModel::default()
    }];
    assert!(
        !extends_user_configuration(ClientKind::Opencode, false),
        "opencode sets no base-url variable, so there is nothing to layer"
    );
    assert!(
        extends_user_configuration(ClientKind::ClaudeCode, false),
        "claude code sets both variables, so the default extends"
    );
    assert!(
        !extends_user_configuration(ClientKind::ClaudeCode, true),
        "--isolated-config wins over the default"
    );

    // And it still prepares rather than failing.
    let profiles = tempfile::tempdir().expect("profile root");
    TemporaryClient::prepare(&Preparation {
        client: ClientKind::Opencode,
        base_url: "http://router.test",
        token: "task-token",
        model_override: None,
        models: &models,
        isolated_config: false,
        one_shot: true,
        profile_root: Some(profiles.path()),
        codex_reasoning_effort: None,
    })
    .expect("a file-configured client must still run");
}

/// Gemini CLI sets both connection variables and still cannot be extended.
///
/// It is pointed at the router by a `settings.json` it resolves from `HOME`,
/// so extending — which leaves `HOME` alone — would write that file where
/// the client never looks and let the user's own settings decide the run
/// (issue #227). Having both variables is therefore not enough to layer
/// onto, and the default must not assume it is.
#[test]
fn a_client_needing_a_written_file_is_isolated_despite_its_variables() {
    let integration = ClientKind::GeminiCli.integration();
    assert!(
        integration.token_env.is_some() && integration.base_url_env.is_some(),
        "the variables alone would otherwise qualify it for extending"
    );
    assert!(
        !extends_user_configuration(ClientKind::GeminiCli, false),
        "routing depends on a file only isolation makes reachable"
    );
}

#[test]
fn a_prepared_gemini_run_leaves_settings_where_the_cli_reads_them() {
    let models = [RouterModel {
        id: "test-model".to_string(),
        owned_by: "test".to_string(),
        ..RouterModel::default()
    }];
    let profiles = tempfile::tempdir().expect("profile root");
    let temporary = TemporaryClient::prepare(&Preparation {
        client: ClientKind::GeminiCli,
        base_url: "http://router.test",
        token: "task-token",
        model_override: None,
        models: &models,
        isolated_config: false,
        one_shot: true,
        profile_root: Some(profiles.path()),
        codex_reasoning_effort: None,
    })
    .expect("prepare gemini");
    let root = temporary.directory.path();
    let home = temporary
        .command
        .get_envs()
        .find_map(|(name, value)| (name == "HOME").then_some(value?))
        .expect("gemini run sets HOME");
    // The CLI resolves its settings from HOME; the file must be there.
    let settings = Path::new(home).join(".gemini/settings.json");
    assert!(
        settings.is_file(),
        "no settings at {}, which is where the CLI looks",
        settings.display()
    );
    let written = fs::read_to_string(&settings).expect("read settings");
    assert!(written.contains("gemini-api-key"), "{written}");
    assert!(Path::new(home).starts_with(root), "HOME escaped the root");
}

/// An isolated run must be governed by the settings the router wrote. The
/// previous `create_new` silently deferred to whatever was already there,
/// which with the `HOME` fix would let an inherited `oauth-personal`
/// survive and fail the run.
#[test]
fn written_gemini_settings_replace_an_existing_file() {
    let root = tempfile::tempdir().expect("isolated root");
    let path = root.path().join(".gemini/settings.json");
    fs::create_dir_all(path.parent().expect("parent")).expect("create directory");
    fs::write(
        &path,
        r#"{"security":{"auth":{"selectedType":"oauth-personal"}}}"#,
    )
    .expect("seed a conflicting file");

    write_gemini_settings(&path).expect("write settings");

    let written = fs::read_to_string(&path).expect("read settings");
    assert!(written.contains("gemini-api-key"), "{written}");
    assert!(
        !written.contains("oauth-personal"),
        "the inherited value survived: {written}"
    );
}

/// The value itself is the one the CLI accepts; a wrong spelling is what
/// produced the original error, so it is pinned rather than assumed.
#[test]
fn gemini_settings_select_the_api_key_flow() {
    let root = tempfile::tempdir().expect("isolated root");
    let path = root.path().join(".gemini/settings.json");
    write_gemini_settings(&path).expect("write settings");
    let written: serde_json::Value =
        serde_json::from_str(&fs::read_to_string(&path).expect("read")).expect("valid JSON");
    assert_eq!(
        written["security"]["auth"]["selectedType"],
        "gemini-api-key"
    );
}

/// Every client prepares under a root the router owns, and only the ones
/// that were meant to be thrown away are.
///
/// A client routed through a file the router writes *lives* in that
/// directory. Discarding it after every run made every launch a first
/// launch — no session history, so nothing to resume, and onboarding
/// answered again from scratch (issue #298).
#[test]
fn a_client_that_cannot_be_extended_keeps_its_profile() {
    let models = [RouterModel {
        id: "test-model".to_string(),
        owned_by: "test".to_string(),
        default_reasoning_level: Some("medium".to_string()),
        supported_reasoning_levels: Some(vec![crate::clients::RouterReasoningLevel {
            effort: "medium".to_string(),
            description: "Test reasoning".to_string(),
        }]),
    }];
    let profiles = tempfile::tempdir().expect("profile root");
    for client in ClientKind::ALL {
        if client == ClientKind::Cursor {
            assert!(
                TemporaryClient::prepare(&Preparation {
                    client,
                    base_url: "http://router.test",
                    token: "task-token",
                    model_override: None,
                    models: &models,
                    isolated_config: false,
                    one_shot: true,
                    profile_root: Some(profiles.path()),
                    codex_reasoning_effort: None,
                })
                .is_err()
            );
            continue;
        }
        let temporary = TemporaryClient::prepare(&Preparation {
            client,
            base_url: "http://router.test",
            token: "task-token",
            model_override: None,
            models: &models,
            isolated_config: false,
            one_shot: true,
            profile_root: Some(profiles.path()),
            codex_reasoning_effort: None,
        })
        .unwrap_or_else(|error| panic!("{client} failed setup: {error}"));
        let root = temporary.directory.path().to_path_buf();
        assert_eq!(temporary.command.get_program(), client.command());
        let environment = temporary
            .command
            .get_envs()
            .filter_map(|(name, value)| value.map(|value| (name, value)))
            .collect::<std::collections::HashMap<_, _>>();
        if let Some(token_env) = client.token_env() {
            assert_eq!(
                environment.get(std::ffi::OsStr::new(token_env)).copied(),
                Some(std::ffi::OsStr::new("task-token")),
                "{client} did not receive its token environment"
            );
        }
        for name in [
            "HOME",
            "CLAUDE_CONFIG_DIR",
            "GEMINI_CLI_HOME",
            "OPENCODE_CONFIG",
            "OPENCODE_CONFIG_DIR",
        ] {
            if let Some(value) = environment.get(std::ffi::OsStr::new(name)) {
                assert!(
                    Path::new(value).starts_with(&root),
                    "{client} {name} escaped its root"
                );
            }
        }
        let keeps_a_profile = !extends_user_configuration(client, false);
        drop(temporary);
        assert_eq!(
            root.exists(),
            keeps_a_profile,
            "{client}: a client routed through a written file must keep its profile, and \
             one that only needs two environment variables must not leave a directory behind"
        );
        if keeps_a_profile {
            assert!(
                root.starts_with(profiles.path()),
                "{client} profile must live under the router's own directory, not TMPDIR: \
                 {}",
                root.display()
            );
        }
    }
}

/// The same client twice gets the same directory, which is what makes a
/// session resumable through the router.
#[test]
fn two_runs_of_the_same_client_share_one_profile() {
    let profiles = tempfile::tempdir().expect("profile root");
    let root = Some(profiles.path());
    let first = persistent_profile(ClientKind::Codex, root).expect("first profile");
    let second = persistent_profile(ClientKind::Codex, root).expect("second profile");
    assert_eq!(first, second);
    assert!(first.is_dir());
    assert_ne!(
        first,
        persistent_profile(ClientKind::GeminiCli, root).expect("another client")
    );
}

#[test]
fn registry_order_matches_client_discriminants() {
    for client in ClientKind::ALL {
        assert_eq!(client.integration().kind, client);
    }
}

/// The default label names the client and a run, never the directory the
/// command was run in — a deployment was accumulating a list of every project
/// its users work in, visible to anyone who can list tokens (issue #316).
#[test]
fn the_default_label_carries_no_directory_name() {
    let label = format!("with-{}-{}", ClientKind::ClaudeCode, super::run_suffix());

    assert!(label.starts_with("with-claude-"), "{label}");
    // Whatever the working directory is called, it is not in the label.
    let cwd = std::env::current_dir().expect("cwd");
    let name = cwd
        .file_name()
        .expect("directory name")
        .to_string_lossy()
        .into_owned();
    assert!(
        !label.contains(&name),
        "the working directory's name must not reach the router: {label} contains {name}"
    );
    // The suffix distinguishes concurrent runs without describing them.
    assert_eq!(super::run_suffix().len(), 4, "a fixed-width run suffix");
    assert_eq!(
        super::run_suffix(),
        super::run_suffix(),
        "stable within one process, so one run has one label"
    );
}