swapdex 0.167.16

Switch between multiple Claude Code, Codex, Gemini, and Antigravity login accounts, locally and safely.
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
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
//! Renewing a lapsed access token, end to end.
//!
//! The failure paths are covered by unit tests and were seen against the real
//! endpoint; the SUCCESS path had never been executed, because it needs an
//! account that is idle AND holds a refresh token the server still honours, and
//! there was not one to spare. This runs the whole path against a token endpoint
//! of our own: the request swapdex builds, the answer it merges, and the
//! credential it writes back.

use std::process::Command;
use std::sync::{Arc, Mutex};

fn bin() -> &'static str {
    env!("CARGO_BIN_EXE_swapdex")
}

/// A token endpoint that records what it was asked and answers with new tokens.
fn fake_oauth(sink: Arc<Mutex<Vec<String>>>, response: &'static str) -> String {
    let server = tiny_http::Server::http("127.0.0.1:0").unwrap();
    let port = server.server_addr().to_ip().unwrap().port();
    std::thread::spawn(move || {
        for mut rq in server.incoming_requests() {
            let mut body = String::new();
            std::io::Read::read_to_string(rq.as_reader(), &mut body).ok();
            sink.lock().unwrap().push(body);
            let _ = rq.respond(tiny_http::Response::from_string(response));
        }
    });
    format!("http://127.0.0.1:{port}/v1/oauth/token")
}

/// A login server that refuses every refresh with `status`.
fn refusing_oauth(sink: Arc<Mutex<Vec<String>>>, status: u16, body: &'static str) -> String {
    let server = tiny_http::Server::http("127.0.0.1:0").unwrap();
    let port = server.server_addr().to_ip().unwrap().port();
    std::thread::spawn(move || {
        for mut rq in server.incoming_requests() {
            let mut seen = String::new();
            std::io::Read::read_to_string(rq.as_reader(), &mut seen).ok();
            sink.lock().unwrap().push(seen);
            let _ = rq.respond(tiny_http::Response::from_string(body).with_status_code(status));
        }
    });
    format!("http://127.0.0.1:{port}/v1/oauth/token")
}

/// A Claude account whose access token lapsed an hour ago and whose refresh
/// token is still good - the state every idle account reaches.
fn seed_lapsed_account(root: &std::path::Path, name: &str, id: &str) -> std::path::PathBuf {
    let store = root.join(".local/share/swapdex");
    let slot = store.join("slots").join(id);
    std::fs::create_dir_all(&slot).unwrap();
    let now_ms = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap()
        .as_millis() as i64;
    std::fs::write(
        slot.join(".credentials.json"),
        format!(
            r#"{{"claudeAiOauth":{{"accessToken":"OLD-AT","refreshToken":"OLD-RT",
               "expiresAt":{},"refreshTokenExpiresAt":{},"subscriptionType":"max",
               "scopes":["user:inference"]}},"mcpOAuth":{{"keep":"me"}}}}"#,
            now_ms - 3_600_000,
            now_ms + 30 * 86_400_000
        ),
    )
    .unwrap();
    std::fs::write(
        slot.join(".claude.json"),
        format!(r#"{{"oauthAccount":{{"accountUuid":"u-{name}","emailAddress":"{name}@x.com"}}}}"#),
    )
    .unwrap();
    std::fs::write(
        store.join("slots.json"),
        serde_json::to_vec(&serde_json::json!([{
            "name": name, "id": id, "config_dir": slot, "adopted": false,
            "tool": "claude-code"
        }]))
        .unwrap(),
    )
    .unwrap();
    slot
}

fn credential(slot: &std::path::Path) -> serde_json::Value {
    let bytes = std::fs::read(slot.join(".credentials.json")).unwrap();
    serde_json::from_slice(&bytes).unwrap()
}

#[test]
fn a_lapsed_account_is_renewed_in_place() {
    let root = tempfile::tempdir().unwrap();
    let slot = seed_lapsed_account(root.path(), "work", "aaaa1111");
    let asked = Arc::new(Mutex::new(Vec::new()));
    let url = fake_oauth(
        asked.clone(),
        r#"{"access_token":"NEW-AT","refresh_token":"NEW-RT","expires_in":3600}"#,
    );

    let out = Command::new(bin())
        .args(["refresh", "work"])
        .env("SWAPDEX_ROOT", root.path())
        .env("SWAPDEX_OAUTH_URL", &url)
        .env("HOME", root.path())
        .output()
        .unwrap();
    let said =
        String::from_utf8_lossy(&out.stdout).into_owned() + &String::from_utf8_lossy(&out.stderr);
    assert!(said.contains("work renewed"), "reported success: {said}");

    // What swapdex asked for.
    let body = asked.lock().unwrap().first().cloned().expect("one request");
    let req: serde_json::Value = serde_json::from_str(&body).expect("json body");
    assert_eq!(req["grant_type"], "refresh_token");
    assert_eq!(req["refresh_token"], "OLD-RT", "the token it held");
    assert!(req["client_id"].is_string(), "the client is named: {body}");

    // What it wrote back. The new refresh token REPLACES the old one: the server
    // retires what it just spent, and keeping it would leave the account unable
    // to renew the time after this.
    let c = credential(&slot);
    let o = &c["claudeAiOauth"];
    assert_eq!(o["accessToken"], "NEW-AT");
    assert_eq!(o["refreshToken"], "NEW-RT");
    assert_eq!(o["subscriptionType"], "max", "untouched fields survive");
    assert_eq!(
        c["mcpOAuth"]["keep"], "me",
        "and so does the rest of the file"
    );

    // The expiry is an absolute moment in the future, not the seconds it was sent.
    let now_ms = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap()
        .as_millis() as i64;
    let exp = o["expiresAt"].as_i64().expect("an expiry");
    assert!(
        exp > now_ms && exp <= now_ms + 3_600_000,
        "an hour ahead, not 3600: {exp}"
    );

    // And the account now reads as current rather than expired.
    let after = Command::new(bin())
        .args(["refresh", "work"])
        .env("SWAPDEX_ROOT", root.path())
        .env("SWAPDEX_OAUTH_URL", &url)
        .env("HOME", root.path())
        .output()
        .unwrap();
    assert!(
        String::from_utf8_lossy(&after.stdout).contains("already current"),
        "a renewed account is not renewed again: {:?}",
        String::from_utf8_lossy(&after.stdout)
    );
    assert_eq!(
        asked.lock().unwrap().len(),
        1,
        "and no second request was made"
    );
}

// A server that renews the access token without issuing a new refresh token:
// dropping the old one would leave the account unable to renew ever again.
#[test]
fn a_renewal_without_a_new_refresh_token_keeps_the_old_one() {
    let root = tempfile::tempdir().unwrap();
    let slot = seed_lapsed_account(root.path(), "work", "bbbb2222");
    let asked = Arc::new(Mutex::new(Vec::new()));
    let url = fake_oauth(
        asked.clone(),
        r#"{"access_token":"NEW-AT","expires_in":3600}"#,
    );

    let out = Command::new(bin())
        .args(["refresh", "work"])
        .env("SWAPDEX_ROOT", root.path())
        .env("SWAPDEX_OAUTH_URL", &url)
        .env("HOME", root.path())
        .output()
        .unwrap();
    assert!(String::from_utf8_lossy(&out.stdout).contains("renewed"));
    let o = credential(&slot);
    assert_eq!(o["claudeAiOauth"]["accessToken"], "NEW-AT");
    assert_eq!(o["claudeAiOauth"]["refreshToken"], "OLD-RT");
}

// A refusal must leave the credential exactly as it was: half-writing one is how
// an account becomes unusable without anybody touching it.
#[test]
fn a_refused_renewal_changes_nothing() {
    let root = tempfile::tempdir().unwrap();
    let slot = seed_lapsed_account(root.path(), "work", "cccc3333");
    let before = std::fs::read(slot.join(".credentials.json")).unwrap();
    let asked = Arc::new(Mutex::new(Vec::new()));
    let url = fake_oauth(asked.clone(), r#"{"error":"invalid_grant"}"#);

    let out = Command::new(bin())
        .args(["refresh", "work"])
        .env("SWAPDEX_ROOT", root.path())
        .env("SWAPDEX_OAUTH_URL", &url)
        .env("HOME", root.path())
        .output()
        .unwrap();
    let said = String::from_utf8_lossy(&out.stdout).into_owned();
    assert_eq!(
        out.status.code(),
        Some(4),
        "failed renewal must fail the command: {said}"
    );
    assert!(
        said.contains("could not be renewed"),
        "the refusal is reported: {said}"
    );
    assert_eq!(
        std::fs::read(slot.join(".credentials.json")).unwrap(),
        before,
        "the credential is untouched"
    );
}

/// The keep-alive sweep is the answer to accounts that die of neglect. An OAuth
/// refresh token rotates when it is used; leave an account alone long enough and
/// only a browser sign-in brings it back. Three accounts on the machine this was
/// written for died exactly that way and stayed dead for a week.
///
/// So the sweep renews AHEAD of the refresh token's end, and it must reach an
/// account nobody is using, which is the one at risk. It does NOT renew because
/// the ACCESS token is about to lapse: every renewal rotates the refresh token,
/// and one renewed two hours after the last - which that rule did to
/// eight-hour tokens - was stranded by a login server that processed it and
/// answered 503.
#[test]
fn keep_alive_renews_by_the_refresh_tokens_end_not_the_access_tokens() {
    let root = tempfile::tempdir().unwrap();
    let slot = seed_lapsed_account(root.path(), "idle", "aaaa1111");
    // Still VALID, a couple of hours from expiry: the state `swapdex refresh`
    // leaves alone. What decides a keep-alive is the refresh token's end.
    let now_ms = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap()
        .as_millis() as i64;
    let write = |refresh_end: i64| {
        std::fs::write(
            slot.join(".credentials.json"),
            format!(
                r#"{{"claudeAiOauth":{{"accessToken":"OLD-AT","refreshToken":"OLD-RT",
                   "expiresAt":{},"refreshTokenExpiresAt":{}}}}}"#,
                now_ms + 2 * 3_600_000,
                refresh_end
            ),
        )
        .unwrap();
    };

    let asked = Arc::new(Mutex::new(Vec::new()));
    let url = fake_oauth(
        asked.clone(),
        r#"{"access_token":"NEW-AT","refresh_token":"NEW-RT","expires_in":3600}"#,
    );
    let sweep = || {
        let out = Command::new(bin())
            .args(["refresh", "--keep-alive"])
            .env("SWAPDEX_ROOT", root.path())
            .env("SWAPDEX_OAUTH_URL", &url)
            .output()
            .unwrap();
        format!(
            "{}{}",
            String::from_utf8_lossy(&out.stdout),
            String::from_utf8_lossy(&out.stderr)
        )
    };

    // Two hours of access left, weeks of refresh token: nothing to renew.
    write(now_ms + 30 * 86_400_000);
    let said = sweep();
    assert_eq!(
        asked.lock().unwrap().len(),
        0,
        "a refresh token weeks from its end was rotated anyway: {said}"
    );
    // Two days from the refresh token's end: renewed, once.
    write(now_ms + 2 * 86_400_000);
    let said = sweep();
    assert_eq!(
        asked.lock().unwrap().len(),
        1,
        "a refresh token near its end was not renewed: {said}"
    );
    let after = std::fs::read_to_string(slot.join(".credentials.json")).unwrap();
    assert!(
        after.contains("NEW-AT"),
        "the renewed token was written: {after}"
    );
    assert!(
        after.contains("NEW-RT"),
        "and the rotated refresh token replaced the spent one: {after}"
    );
    assert!(
        said.contains("idle"),
        "it says which account it renewed: {said}"
    );
}

/// A Codex slot whose access token lapsed and whose refresh token is still good.
///
/// Measured on two real machines: a slot's access token expires exactly ten days
/// after its last renewal, Codex only renews when Codex RUNS, and four of eight
/// slots were already dead. Nothing in swapdex could renew one - `refresh_slot`
/// reads Claude's credential shape, so it answered "no credential" and did
/// nothing, silently.
fn seed_lapsed_codex(root: &std::path::Path, name: &str, id: &str) -> std::path::PathBuf {
    let store = root.join(".local/share/swapdex");
    let slot = store.join("slots").join(id);
    std::fs::create_dir_all(&slot).unwrap();
    // A JWT that expired an hour ago: header.payload.sig, payload carrying `exp`.
    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap()
        .as_secs() as i64;
    let b64 = |s: &str| {
        use base64::Engine;
        base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(s)
    };
    let lapsed = format!(
        "{}.{}.sig",
        b64(r#"{"alg":"none"}"#),
        b64(&format!(r#"{{"exp":{}}}"#, now - 3_600))
    );
    std::fs::write(
        slot.join("auth.json"),
        serde_json::to_vec_pretty(&serde_json::json!({
            "auth_mode": "chatgpt",
            "OPENAI_API_KEY": serde_json::Value::Null,
            "tokens": {
                "id_token": "OLD-ID", "access_token": lapsed,
                "refresh_token": "OLD-RT", "account_id": "acct-1"
            },
            "last_refresh": "2026-08-19T07:41:56Z"
        }))
        .unwrap(),
    )
    .unwrap();
    std::fs::write(
        store.join("slots.json"),
        serde_json::to_vec(&serde_json::json!([{
            "name": name, "id": id, "config_dir": slot, "adopted": false, "tool": "codex"
        }]))
        .unwrap(),
    )
    .unwrap();
    slot
}

fn codex_auth(slot: &std::path::Path) -> serde_json::Value {
    serde_json::from_slice(&std::fs::read(slot.join("auth.json")).unwrap()).unwrap()
}

#[cfg(target_os = "linux")]
struct ReapedChild(std::process::Child);

#[cfg(target_os = "linux")]
impl Drop for ReapedChild {
    fn drop(&mut self) {
        let _ = self.0.kill();
        let _ = self.0.wait();
    }
}

/// Run a harmless process whose name and config environment look exactly like
/// one tool session. Its config lives under the test root, so refresh safety
/// can inspect a fake identity without ever following `/proc` into a real auth
/// file.
#[cfg(target_os = "linux")]
fn running_tool(root: &std::path::Path, tool: &str, config_dir: &std::path::Path) -> ReapedChild {
    let bin = root.join(format!("fake-{tool}")).join(tool);
    std::fs::create_dir_all(bin.parent().unwrap()).unwrap();
    // exec preserves this link's basename as the process name. Reusing the
    // system executable avoids ETXTBSY from executing a just-copied fixture
    // while other test threads are spawning children.
    let sleep = if std::path::Path::new("/bin/sleep").exists() {
        "/bin/sleep"
    } else {
        "/usr/bin/sleep"
    };
    std::os::unix::fs::symlink(sleep, &bin).unwrap();

    let config_var = if tool == "claude" {
        "CLAUDE_CONFIG_DIR"
    } else {
        "CODEX_HOME"
    };
    let mut child = std::process::Command::new(&bin)
        .arg("30")
        .env("HOME", root)
        .env(config_var, config_dir)
        .spawn()
        .unwrap();
    let environ = format!("/proc/{}/environ", child.id());
    for _ in 0..300 {
        if std::fs::read(&environ).is_ok_and(|b| {
            String::from_utf8_lossy(&b)
                .contains(&format!("{config_var}={}", config_dir.to_string_lossy()))
        }) {
            return ReapedChild(child);
        }
        std::thread::sleep(std::time::Duration::from_millis(10));
    }
    let _ = child.kill();
    let _ = child.wait();
    panic!("the fake {tool} process never exposed its isolated environment");
}

#[cfg(target_os = "linux")]
fn seed_external_identity(dir: &std::path::Path, tool: &str, account: &str) {
    std::fs::create_dir_all(dir).unwrap();
    if tool == "claude" {
        std::fs::write(
            dir.join(".claude.json"),
            serde_json::to_vec(&serde_json::json!({
                "oauthAccount": {"accountUuid": account}
            }))
            .unwrap(),
        )
        .unwrap();
    } else {
        std::fs::write(
            dir.join("auth.json"),
            serde_json::to_vec(&serde_json::json!({
                "tokens": {"account_id": account}
            }))
            .unwrap(),
        )
        .unwrap();
    }
}

#[cfg(target_os = "linux")]
fn fake_refresh_curl(root: &std::path::Path, answer: &str) -> std::path::PathBuf {
    use std::os::unix::fs::PermissionsExt;
    let path = root.join("fake-refresh-curl");
    std::fs::write(
        &path,
        format!(
            "#!/bin/sh\ncat > /dev/null\nprintf x >> \"$SWAPDEX_TEST_REFRESH_COUNT\"\nprintf '{answer}\\n200'\n"
        ),
    )
    .unwrap();
    std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
    path
}

#[cfg(target_os = "linux")]
fn refresh_calls(root: &std::path::Path) -> usize {
    std::fs::read(root.join("refresh-count"))
        .map(|b| b.len())
        .unwrap_or(0)
}

/// A process can hold the same provider account from a second config directory.
/// Refreshing either copy retires the token held by the other, so the active
/// twin must protect the candidate even though their paths differ. An unrelated
/// known account must not block it.
#[cfg(target_os = "linux")]
fn check_explicit_active_twin(tool: &str, candidate_account: &str, url_var: &str) {
    for (running_account, should_refresh) in [(candidate_account, false), ("someone-else", true)] {
        let root = tempfile::tempdir().unwrap();
        let candidate = if tool == "claude" {
            seed_lapsed_account(root.path(), "work", "candidate")
        } else {
            seed_lapsed_codex(root.path(), "work", "candidate")
        };
        let external = root.path().join(format!(".{tool}-external"));
        seed_external_identity(&external, tool, running_account);
        let _running = running_tool(root.path(), tool, &external);
        let answer = if tool == "claude" {
            r#"{"access_token":"NEW-AT","refresh_token":"NEW-RT","expires_in":3600}"#
        } else {
            r#"{"access_token":"NEW-AT","refresh_token":"NEW-RT","id_token":"NEW-ID"}"#
        };
        let curl = fake_refresh_curl(root.path(), answer);

        let out = Command::new(bin())
            .args(["refresh", "work"])
            .env("SWAPDEX_ROOT", root.path())
            .env("SWAPDEX_CURL", curl)
            .env(
                "SWAPDEX_TEST_REFRESH_COUNT",
                root.path().join("refresh-count"),
            )
            .env(url_var, "http://127.0.0.1:1/fake-oauth")
            .output()
            .unwrap();
        let said = String::from_utf8_lossy(&out.stdout).into_owned()
            + &String::from_utf8_lossy(&out.stderr);
        assert_eq!(
            refresh_calls(root.path()),
            usize::from(should_refresh),
            "{tool}: active account {running_account:?} gave the wrong refresh verdict:\n{said}"
        );
        assert_eq!(
            out.status.code(),
            Some(if should_refresh { 0 } else { 4 }),
            "{tool}: {said}"
        );
        if should_refresh {
            assert!(said.contains("work renewed"), "{tool}: {said}");
        } else {
            assert!(
                !said.contains("work renewed"),
                "{tool}: refreshed a twin held by a live process:\n{said}"
            );
            let unchanged = if tool == "claude" {
                credential(&candidate)["claudeAiOauth"]["accessToken"] == "OLD-AT"
            } else {
                codex_auth(&candidate)["tokens"]["access_token"] != "NEW-AT"
            };
            assert!(unchanged, "{tool}: the protected credential changed");
        }
    }
}

#[cfg(target_os = "linux")]
#[test]
fn explicit_refresh_protects_an_active_claude_twin_but_not_an_unrelated_account() {
    check_explicit_active_twin("claude", "u-work", "SWAPDEX_OAUTH_URL");
}

#[cfg(target_os = "linux")]
#[test]
fn explicit_refresh_protects_an_active_codex_twin_but_not_an_unrelated_account() {
    check_explicit_active_twin("codex", "acct-1", "SWAPDEX_CODEX_OAUTH_URL");
}

/// The unattended sweep reaches the same refresh entry point as an explicit
/// command. It must stand down for an active twin too, for both providers.
#[cfg(target_os = "linux")]
fn check_keep_alive_active_twin(tool: &str, account: &str, url_var: &str) {
    let root = tempfile::tempdir().unwrap();
    if tool == "claude" {
        seed_lapsed_account(root.path(), "idle", "candidate");
    } else {
        seed_lapsed_codex(root.path(), "idle", "candidate");
    }
    let external = root.path().join(format!(".{tool}-external"));
    seed_external_identity(&external, tool, account);
    let _running = running_tool(root.path(), tool, &external);
    let answer = if tool == "claude" {
        r#"{"access_token":"NEW-AT","refresh_token":"NEW-RT","expires_in":3600}"#
    } else {
        r#"{"access_token":"NEW-AT","refresh_token":"NEW-RT","id_token":"NEW-ID"}"#
    };
    let curl = fake_refresh_curl(root.path(), answer);

    let out = Command::new(bin())
        .args(["refresh", "--keep-alive"])
        .env("SWAPDEX_ROOT", root.path())
        .env("SWAPDEX_CURL", curl)
        .env(
            "SWAPDEX_TEST_REFRESH_COUNT",
            root.path().join("refresh-count"),
        )
        .env(url_var, "http://127.0.0.1:1/fake-oauth")
        .output()
        .unwrap();
    let said =
        String::from_utf8_lossy(&out.stdout).into_owned() + &String::from_utf8_lossy(&out.stderr);
    assert_eq!(
        refresh_calls(root.path()),
        0,
        "{tool}: keep-alive refreshed an account held through a twin:\n{said}"
    );
}

#[cfg(target_os = "linux")]
#[test]
fn keep_alive_sweep_protects_an_active_claude_twin() {
    check_keep_alive_active_twin("claude", "u-idle", "SWAPDEX_OAUTH_URL");
}

#[cfg(target_os = "linux")]
#[test]
fn keep_alive_sweep_protects_an_active_codex_twin() {
    check_keep_alive_active_twin("codex", "acct-1", "SWAPDEX_CODEX_OAUTH_URL");
}

#[test]
fn a_lapsed_codex_account_is_renewed_in_place() {
    let t = tempfile::tempdir().unwrap();
    let root = t.path();
    let slot = seed_lapsed_codex(root, "work", "codex-1");
    let asked = Arc::new(Mutex::new(Vec::new()));
    let url = fake_oauth(
        asked.clone(),
        r#"{"access_token":"NEW-AT","refresh_token":"NEW-RT","id_token":"NEW-ID"}"#,
    );

    let out = Command::new(bin())
        .args(["refresh", "work"])
        .env("SWAPDEX_ROOT", root)
        .env("SWAPDEX_CODEX_OAUTH_URL", &url)
        .output()
        .unwrap();
    let text = String::from_utf8_lossy(&out.stdout).into_owned();
    assert!(text.contains("work renewed"), "stdout was:\n{text}");

    // The request is the one the working implementation sends: form-encoded,
    // the account's own refresh token, Codex's public client id.
    let body = asked.lock().unwrap().first().cloned().unwrap_or_default();
    assert!(body.contains("grant_type=refresh_token"), "body: {body}");
    assert!(body.contains("refresh_token=OLD-RT"), "body: {body}");
    assert!(
        body.contains("client_id=app_EMoamEEZ73f0CkXaXp7hrann"),
        "body: {body}"
    );

    // And the answer landed in the file Codex reads, keeping its other fields.
    let a = codex_auth(&slot);
    assert_eq!(a["tokens"]["access_token"], "NEW-AT");
    assert_eq!(
        a["tokens"]["refresh_token"], "NEW-RT",
        "the ROTATED token must be written, or the slot holds one the server retired"
    );
    assert_eq!(a["tokens"]["id_token"], "NEW-ID");
    assert_eq!(
        a["tokens"]["account_id"], "acct-1",
        "untouched fields survive"
    );
    assert_eq!(a["auth_mode"], "chatgpt");
    assert_ne!(a["last_refresh"], "2026-08-19T07:41:56Z", "stamped anew");
}

#[test]
fn a_codex_renewal_the_server_refuses_changes_nothing() {
    let t = tempfile::tempdir().unwrap();
    let root = t.path();
    let slot = seed_lapsed_codex(root, "work", "codex-1");
    let before = codex_auth(&slot);
    let url = fake_oauth(
        Arc::new(Mutex::new(Vec::new())),
        r#"{"error":"invalid_grant"}"#,
    );
    // tiny_http answers 200 by default, so a refusal is modelled as a body with
    // no access token - the other half of the same guard.
    let out = Command::new(bin())
        .args(["refresh", "work"])
        .env("SWAPDEX_ROOT", root)
        .env("SWAPDEX_CODEX_OAUTH_URL", &url)
        .output()
        .unwrap();
    assert_eq!(out.status.code(), Some(4));
    assert_eq!(
        codex_auth(&slot),
        before,
        "an answer with no access token must leave the credential alone"
    );
}

/// An OAuth server that retires a refresh token when it is spent, the way the
/// real one does. The first request carrying OLD-RT is answered; every later
/// one is refused, because by then the server has retired it.
fn rotating_oauth(sink: Arc<Mutex<Vec<String>>>) -> String {
    let server = tiny_http::Server::http("127.0.0.1:0").unwrap();
    let port = server.server_addr().to_ip().unwrap().port();
    std::thread::spawn(move || {
        let mut spent = false;
        for mut rq in server.incoming_requests() {
            let mut body = String::new();
            std::io::Read::read_to_string(rq.as_reader(), &mut body).ok();
            let holds_retired = body.contains("OLD-RT");
            sink.lock().unwrap().push(body);
            let resp = if holds_retired && !spent {
                spent = true;
                tiny_http::Response::from_string(
                    r#"{"access_token":"NEW-AT","refresh_token":"NEW-RT","expires_in":3600}"#,
                )
                .with_status_code(200)
            } else {
                tiny_http::Response::from_string(r#"{"error":"invalid_grant"}"#)
                    .with_status_code(400)
            };
            let _ = rq.respond(resp);
        }
    });
    format!("http://127.0.0.1:{port}/v1/oauth/token")
}

/// Several lapsed Claude slots that all hold the SAME account - two directories
/// for one login, which `doctor` already reports as a thing people do.
fn seed_lapsed_twins(root: &std::path::Path, slots: &[(&str, &str, &str)]) {
    let store = root.join(".local/share/swapdex");
    let now_ms = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap()
        .as_millis() as i64;
    let mut reg = Vec::new();
    for (name, id, uuid) in slots {
        let slot = store.join("slots").join(id);
        std::fs::create_dir_all(&slot).unwrap();
        std::fs::write(
            slot.join(".credentials.json"),
            format!(
                r#"{{"claudeAiOauth":{{"accessToken":"OLD-AT","refreshToken":"OLD-RT",
                   "expiresAt":{},"refreshTokenExpiresAt":{},"subscriptionType":"max",
                   "scopes":["user:inference"]}}}}"#,
                now_ms - 3_600_000,
                now_ms + 30 * 86_400_000
            ),
        )
        .unwrap();
        std::fs::write(
            slot.join(".claude.json"),
            format!(
                r#"{{"oauthAccount":{{"accountUuid":"{uuid}","emailAddress":"shared@x.com"}}}}"#
            ),
        )
        .unwrap();
        reg.push(serde_json::json!({
            "name": name, "id": id, "config_dir": slot,
            "adopted": false, "tool": "claude-code"
        }));
    }
    std::fs::write(store.join("slots.json"), serde_json::to_vec(&reg).unwrap()).unwrap();
}

/// Two slots holding ONE account must be renewed once, not twice.
///
/// swapdex states the rule itself, in the remedy for a slot already being
/// renewed: "spending its refresh token twice is what logs an account out".
/// That guard is per DIRECTORY. Two directories holding one login are the same
/// double-spend and were not guarded, so `swapdex refresh` renewed the first,
/// the server retired the token both were holding, and the loop then spent the
/// retired one on behalf of the second - which the server refused, and the
/// second was reported as having been idle too long with a fresh sign-in as the
/// cure, seconds after its account had in fact been renewed.
#[test]
fn two_slots_on_one_account_are_renewed_once() {
    let root = tempfile::tempdir().unwrap();
    seed_lapsed_twins(
        root.path(),
        &[
            ("work", "aaaa1111", "u-shared"),
            ("work-copy", "bbbb2222", "u-shared"),
        ],
    );
    let asked = Arc::new(Mutex::new(Vec::new()));
    let url = rotating_oauth(asked.clone());

    let out = Command::new(bin())
        .args(["refresh"])
        .env("SWAPDEX_ROOT", root.path())
        .env("SWAPDEX_OAUTH_URL", &url)
        .env("HOME", root.path())
        .output()
        .unwrap();
    let said =
        String::from_utf8_lossy(&out.stdout).into_owned() + &String::from_utf8_lossy(&out.stderr);

    let bodies = asked.lock().unwrap().clone();
    let spends = bodies.iter().filter(|b| b.contains("OLD-RT")).count();
    assert_eq!(
        spends, 1,
        "the retired refresh token was spent {spends} times:\n{said}\nrequests: {bodies:?}"
    );
    assert!(
        !said.contains("idle too long"),
        "the twin was blamed for being idle when its account had just been renewed:\n{said}"
    );
}

/// Distinct accounts are each renewed; the guard is about one login, not two.
///
/// Skipping the second slot whenever anything was renewed would turn a fleet
/// refresh into a single refresh, which is the ordinary case this command
/// exists for. The check has to compare accounts, not count renewals.
#[test]
fn slots_on_different_accounts_are_each_renewed() {
    let root = tempfile::tempdir().unwrap();
    seed_lapsed_twins(
        root.path(),
        &[("one", "aaaa1111", "u-one"), ("two", "bbbb2222", "u-two")],
    );
    let asked = Arc::new(Mutex::new(Vec::new()));
    let url = fake_oauth(
        asked.clone(),
        r#"{"access_token":"NEW-AT","refresh_token":"NEW-RT","expires_in":3600}"#,
    );

    let out = Command::new(bin())
        .args(["refresh"])
        .env("SWAPDEX_ROOT", root.path())
        .env("SWAPDEX_OAUTH_URL", &url)
        .env("HOME", root.path())
        .output()
        .unwrap();
    let said =
        String::from_utf8_lossy(&out.stdout).into_owned() + &String::from_utf8_lossy(&out.stderr);

    assert!(
        said.contains("one renewed"),
        "'one' was not renewed:\n{said}"
    );
    assert!(
        said.contains("two renewed"),
        "'two' was not renewed:\n{said}"
    );
    assert_eq!(
        asked.lock().unwrap().len(),
        2,
        "two accounts, two renewals:\n{said}"
    );
}

/// The keep-alive sweep must renew an account once, however many directories
/// hold it.
///
/// The account guard was added to the `refresh` command's own loop, and this
/// sweep reaches `refresh_slot` by another road - the same mistake the gate's
/// note in refresh.rs records: "a rule enforced at one caller is a rule the
/// next caller does not know exists". Two slots on one login, and the sweep
/// spent the token the first renewal had already retired.
#[test]
fn the_keep_alive_sweep_renews_an_account_once() {
    let root = tempfile::tempdir().unwrap();
    seed_lapsed_twins(
        root.path(),
        &[
            ("work", "aaaa1111", "u-shared"),
            ("work-copy", "bbbb2222", "u-shared"),
        ],
    );
    // Due by the refresh token's end, which is what a sweep renews on.
    let now_ms = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap()
        .as_millis() as i64;
    for id in ["aaaa1111", "bbbb2222"] {
        let path = root
            .path()
            .join(".local/share/swapdex/slots")
            .join(id)
            .join(".credentials.json");
        let mut v: serde_json::Value =
            serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
        v["claudeAiOauth"]["refreshTokenExpiresAt"] = (now_ms + 2 * 86_400_000).into();
        std::fs::write(&path, serde_json::to_vec(&v).unwrap()).unwrap();
    }
    let asked = Arc::new(Mutex::new(Vec::new()));
    let url = rotating_oauth(asked.clone());

    let out = Command::new(bin())
        .args(["refresh", "--keep-alive"])
        .env("SWAPDEX_ROOT", root.path())
        .env("SWAPDEX_OAUTH_URL", &url)
        .env("HOME", root.path())
        .output()
        .unwrap();
    let said =
        String::from_utf8_lossy(&out.stdout).into_owned() + &String::from_utf8_lossy(&out.stderr);

    let bodies = asked.lock().unwrap().clone();
    let spends = bodies.iter().filter(|b| b.contains("OLD-RT")).count();
    assert_eq!(
        spends, 1,
        "the sweep spent the retired refresh token {spends} times:\n{said}\nrequests: {bodies:?}"
    );
}

/// Two slots whose identity cannot be read are not one account.
///
/// The claim key falls back to the path when a slot's login cannot be
/// identified. Collapsing unknowns onto one key instead would let the first
/// unreadable slot claim the renewal for every other unreadable slot, and a
/// fleet where identity files are missing would renew exactly one account.
#[test]
fn slots_with_unreadable_identity_are_each_renewed() {
    let root = tempfile::tempdir().unwrap();
    seed_lapsed_twins(
        root.path(),
        &[("one", "aaaa1111", "u-one"), ("two", "bbbb2222", "u-two")],
    );
    // Take the identity away from both: only the credential is left.
    for id in ["aaaa1111", "bbbb2222"] {
        std::fs::remove_file(
            root.path()
                .join(".local/share/swapdex/slots")
                .join(id)
                .join(".claude.json"),
        )
        .unwrap();
    }
    let asked = Arc::new(Mutex::new(Vec::new()));
    let url = fake_oauth(
        asked.clone(),
        r#"{"access_token":"NEW-AT","refresh_token":"NEW-RT","expires_in":3600}"#,
    );

    let out = Command::new(bin())
        .args(["refresh"])
        .env("SWAPDEX_ROOT", root.path())
        .env("SWAPDEX_OAUTH_URL", &url)
        .env("HOME", root.path())
        .output()
        .unwrap();
    let said =
        String::from_utf8_lossy(&out.stdout).into_owned() + &String::from_utf8_lossy(&out.stderr);
    assert_eq!(
        asked.lock().unwrap().len(),
        2,
        "two unidentifiable slots were treated as one account:\n{said}"
    );
}

/// `restore` must say when the login it is putting back was retired.
///
/// It applies a backup without either check `use` performs: no word that the
/// snapshot is old, and nothing about a refresh token some other holder has
/// since rotated away. These tokens are single-use, so a backup taken before a
/// renewal elsewhere is dead - and restoring it replaces a working login with
/// one that cannot renew, reported as a success. `restore` is the escape hatch,
/// so it still restores; it must not do it silently.
#[test]
fn restore_says_when_the_backup_it_puts_back_was_retired() {
    let root = tempfile::tempdir().unwrap();
    let store = root.path().join(".local/share/swapdex");
    std::fs::create_dir_all(store.join("slots/live")).unwrap();
    std::fs::write(store.join("onboarded"), b"1").unwrap();

    // A live slot holding the account, with the token the last rotation minted.
    let slot = store.join("slots/live");
    std::fs::write(
        slot.join(".credentials.json"),
        br#"{"claudeAiOauth":{"accessToken":"AT","refreshToken":"RT-NEW","expiresAt":9999999999999,"subscriptionType":"max"}}"#,
    )
    .unwrap();
    std::fs::write(
        slot.join(".claude.json"),
        br#"{"oauthAccount":{"accountUuid":"u-shared","emailAddress":"shared@example.com"}}"#,
    )
    .unwrap();
    std::fs::write(
        store.join("slots.json"),
        format!(
            r#"[{{"name":"live","id":"live","config_dir":"{}","adopted":false,"tool":"claude-code"}}]"#,
            slot.display()
        ),
    )
    .unwrap();

    // A backup of the SAME account carrying the token that rotation retired.
    let backup = store.join("backups/claude-code/1");
    std::fs::create_dir_all(&backup).unwrap();
    std::fs::write(
        backup.join("credentials"),
        br#"{"claudeAiOauth":{"accessToken":"AT-OLD","refreshToken":"RT-OLD"}}"#,
    )
    .unwrap();
    std::fs::write(
        backup.join("oauth_account"),
        br#"{"accountUuid":"u-shared","emailAddress":"shared@example.com"}"#,
    )
    .unwrap();

    let out = Command::new(bin())
        .args(["restore", "--tool", "claude"])
        .env("SWAPDEX_ROOT", root.path())
        .env("HOME", root.path())
        .output()
        .unwrap();
    let said =
        String::from_utf8_lossy(&out.stdout).into_owned() + &String::from_utf8_lossy(&out.stderr);
    assert!(
        said.contains("retired") || said.contains("rotated") || said.contains("renew"),
        "restore put back a retired login without a word:\n{said}"
    );
}

/// A refresh token the login server refused has settled the account: only a
/// sign-in helps. The sweep logged the refusal and tried again every pass, and
/// `ls`, reading only the access token, could not tell a refused account from
/// an idle one. The refusal is now recorded and shown, the sweep stops
/// retrying it, and asking by name still re-checks it.
#[test]
fn a_refused_claude_refresh_is_recorded_shown_and_not_swept_again() {
    let root = tempfile::tempdir().unwrap();
    let slot = seed_lapsed_account(root.path(), "gone", "cccc3333");
    let path = slot.join(".credentials.json");
    let mut v: serde_json::Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
    let now_ms = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap()
        .as_millis() as i64;
    v["claudeAiOauth"]["refreshTokenExpiresAt"] = (now_ms + 86_400_000).into();
    std::fs::write(&path, serde_json::to_vec(&v).unwrap()).unwrap();

    let asked = Arc::new(Mutex::new(Vec::new()));
    let url = refusing_oauth(
        asked.clone(),
        400,
        r#"{"error":"invalid_grant","error_description":"Refresh token not found or invalid"}"#,
    );
    let swapdex = |args: &[&str]| {
        let out = Command::new(bin())
            .args(args)
            .env("SWAPDEX_ROOT", root.path())
            .env("SWAPDEX_OAUTH_URL", &url)
            .output()
            .unwrap();
        String::from_utf8_lossy(&out.stdout).into_owned() + &String::from_utf8_lossy(&out.stderr)
    };

    let said = swapdex(&["refresh", "--keep-alive"]);
    assert_eq!(asked.lock().unwrap().len(), 1, "{said}");
    let listing = swapdex(&["ls"]);
    assert!(
        listing.contains("claude-code refresh rejected (invalid_grant) - re-login required"),
        "the refusal and its reason are not shown:\n{listing}"
    );
    let said = swapdex(&["refresh", "--keep-alive"]);
    assert_eq!(
        asked.lock().unwrap().len(),
        1,
        "the sweep spent another request on a refused token: {said}"
    );
    let said = swapdex(&["refresh", "gone"]);
    assert_eq!(
        asked.lock().unwrap().len(),
        2,
        "asking by name did not re-check the refused token: {said}"
    );
}

/// The token endpoint answers a request it cannot parse with the same 400 it
/// gives a dead token; only `invalid_grant` is the verdict on the login.
/// Recording any 400 made the sweep stop renewing a login that was fine.
#[test]
fn a_claude_400_without_invalid_grant_is_not_recorded_as_a_refusal() {
    let root = tempfile::tempdir().unwrap();
    let slot = seed_lapsed_account(root.path(), "odd", "dddd4444");
    let path = slot.join(".credentials.json");
    let mut v: serde_json::Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
    let now_ms = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap()
        .as_millis() as i64;
    v["claudeAiOauth"]["refreshTokenExpiresAt"] = (now_ms + 86_400_000).into();
    std::fs::write(&path, serde_json::to_vec(&v).unwrap()).unwrap();
    let asked = Arc::new(Mutex::new(Vec::new()));
    let url = refusing_oauth(
        asked.clone(),
        400,
        r#"{"error":"invalid_request","error_description":"malformed"}"#,
    );
    let sweep = || {
        let out = Command::new(bin())
            .args(["refresh", "--keep-alive"])
            .env("SWAPDEX_ROOT", root.path())
            .env("SWAPDEX_OAUTH_URL", &url)
            .output()
            .unwrap();
        String::from_utf8_lossy(&out.stdout).into_owned() + &String::from_utf8_lossy(&out.stderr)
    };
    sweep();
    assert!(
        !slot.join(".swapdex-claude-refresh-status.json").exists(),
        "a 400 without invalid_grant was recorded as a refusal"
    );
    let said = sweep();
    assert_eq!(
        asked.lock().unwrap().len(),
        2,
        "the sweep stopped renewing after a 400 that was no verdict: {said}"
    );
}

/// The login server answered with a new refresh token - and retired the old
/// one - but saving it failed. The new token was dropped, the old one was
/// already spent, and the account was signed out. The answer is now kept
/// outside the slot and adopted on the next renewal, without asking the
/// server again.
#[cfg(unix)]
#[test]
fn a_renewal_that_could_not_be_saved_is_kept_and_adopted_next_time() {
    use std::os::unix::fs::PermissionsExt;
    let root = tempfile::tempdir().unwrap();
    let slot = seed_lapsed_account(root.path(), "keep", "eeee5555");
    let asked = Arc::new(Mutex::new(Vec::new()));
    let server = tiny_http::Server::http("127.0.0.1:0").unwrap();
    let port = server.server_addr().to_ip().unwrap().port();
    let (sink, locked) = (asked.clone(), slot.clone());
    std::thread::spawn(move || {
        for mut rq in server.incoming_requests() {
            let mut seen = String::new();
            std::io::Read::read_to_string(rq.as_reader(), &mut seen).ok();
            sink.lock().unwrap().push(seen);
            // The server has rotated the token; now the save will fail.
            std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o500)).unwrap();
            let _ = rq.respond(tiny_http::Response::from_string(
                r#"{"access_token":"NEW-AT","refresh_token":"NEW-RT","expires_in":28800}"#,
            ));
        }
    });
    let url = format!("http://127.0.0.1:{port}/v1/oauth/token");
    let refresh = || {
        let out = Command::new(bin())
            .args(["refresh", "keep"])
            .env("SWAPDEX_ROOT", root.path())
            .env("SWAPDEX_OAUTH_URL", &url)
            .output()
            .unwrap();
        String::from_utf8_lossy(&out.stdout).into_owned() + &String::from_utf8_lossy(&out.stderr)
    };

    let first = refresh();
    std::fs::set_permissions(&slot, std::fs::Permissions::from_mode(0o700)).unwrap();
    // The read-only slot that failed the save also kept the refresh lock from
    // being released; a real failed save (a locked keychain, a full disk)
    // releases it as usual.
    let _ = std::fs::remove_dir(slot.join(".oauth_refresh.lock"));
    assert_eq!(asked.lock().unwrap().len(), 1, "{first}");
    let saved = std::fs::read_to_string(slot.join(".credentials.json")).unwrap();
    assert!(
        saved.contains("OLD-RT"),
        "the failed save changed the file: {first}"
    );

    let second = refresh();
    let saved = std::fs::read_to_string(slot.join(".credentials.json")).unwrap();
    assert!(
        saved.contains("NEW-RT"),
        "the renewal the server already made was lost:\n{first}\n{second}"
    );
    assert_eq!(
        asked.lock().unwrap().len(),
        1,
        "the spent token was sent again instead of adopting the kept answer: {second}"
    );
}

/// The over-correction: a kept answer belongs to the token it renewed. After
/// a new sign-in it is obsolete and must not overwrite the new login.
#[cfg(unix)]
#[test]
fn a_kept_renewal_never_overwrites_a_newer_sign_in() {
    use std::os::unix::fs::PermissionsExt;
    let root = tempfile::tempdir().unwrap();
    let slot = seed_lapsed_account(root.path(), "relog", "ffff6666");
    let asked = Arc::new(Mutex::new(Vec::new()));
    let server = tiny_http::Server::http("127.0.0.1:0").unwrap();
    let port = server.server_addr().to_ip().unwrap().port();
    let (sink, locked) = (asked.clone(), slot.clone());
    std::thread::spawn(move || {
        for mut rq in server.incoming_requests() {
            let mut seen = String::new();
            std::io::Read::read_to_string(rq.as_reader(), &mut seen).ok();
            let first = {
                let mut sink = sink.lock().unwrap();
                sink.push(seen);
                sink.len() == 1
            };
            if first {
                std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o500)).unwrap();
            }
            let body = if first {
                r#"{"access_token":"KEPT-AT","refresh_token":"KEPT-RT","expires_in":28800}"#
            } else {
                r#"{"access_token":"FRESH-AT","refresh_token":"FRESH-RT","expires_in":28800}"#
            };
            let _ = rq.respond(tiny_http::Response::from_string(body));
        }
    });
    let url = format!("http://127.0.0.1:{port}/v1/oauth/token");
    let refresh = || {
        let out = Command::new(bin())
            .args(["refresh", "relog"])
            .env("SWAPDEX_ROOT", root.path())
            .env("SWAPDEX_OAUTH_URL", &url)
            .output()
            .unwrap();
        String::from_utf8_lossy(&out.stdout).into_owned() + &String::from_utf8_lossy(&out.stderr)
    };
    refresh();
    std::fs::set_permissions(&slot, std::fs::Permissions::from_mode(0o700)).unwrap();
    let _ = std::fs::remove_dir(slot.join(".oauth_refresh.lock"));

    // A new sign-in replaces the spent token before the next renewal.
    let path = slot.join(".credentials.json");
    let relogged = std::fs::read_to_string(&path)
        .unwrap()
        .replace("OLD-RT", "SIGNED-IN-RT");
    std::fs::write(&path, relogged).unwrap();

    let second = refresh();
    let saved = std::fs::read_to_string(&path).unwrap();
    assert!(
        !saved.contains("KEPT-RT"),
        "an obsolete kept renewal overwrote a newer sign-in: {second}"
    );
    let asked = asked.lock().unwrap();
    assert!(
        asked.len() == 2 && asked[1].contains("SIGNED-IN-RT"),
        "the new sign-in was not renewed with its own token: {second}"
    );
}