croft-software 0.2.3

VSCode-style TUI written in Rust
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
use assert_cmd::Command;

#[test]
fn help_flag_prints_usage_and_exits_zero() {
    let out = Command::cargo_bin("croft").unwrap().arg("--help").assert();
    let out = out.success();
    let stdout = String::from_utf8(out.get_output().stdout.clone()).unwrap();
    assert!(stdout.contains("Usage:"), "stdout was: {stdout}");
    assert!(stdout.contains("setup-terminal"));
}

#[test]
fn version_flag_prints_version() {
    let out = Command::cargo_bin("croft")
        .unwrap()
        .arg("--version")
        .assert();
    let out = out.success();
    let stdout = String::from_utf8(out.get_output().stdout.clone()).unwrap();
    assert!(stdout.contains("croft"));
}

/// #282 end to end, against the real binary: `--version` is a bare `x.y.z`
/// and the provenance is reachable behind `--build-info`. The unit test pins
/// the constants and clap's rendering; this pins that the `--build-info`
/// handler actually runs and prints the verbose form.
#[test]
fn build_info_carries_provenance_and_version_does_not() {
    let out = Command::cargo_bin("croft")
        .unwrap()
        .arg("--build-info")
        .assert();
    let out = out.success();
    let build_info = String::from_utf8(out.get_output().stdout.clone()).unwrap();
    assert!(
        build_info.contains(env!("CARGO_PKG_VERSION")) && build_info.contains("built "),
        "--build-info carries version and build time: {build_info}"
    );

    let out = Command::cargo_bin("croft")
        .unwrap()
        .arg("--version")
        .assert();
    let out = out.success();
    let version = String::from_utf8(out.get_output().stdout.clone()).unwrap();
    assert_eq!(
        version.trim(),
        format!("croft {}", env!("CARGO_PKG_VERSION")),
        "--version stays bare"
    );
}

#[test]
fn setup_terminal_help_works() {
    Command::cargo_bin("croft")
        .unwrap()
        .args(["setup-terminal", "--help"])
        .assert()
        .success();
}

/// The remote launch script runs `croft session-host --probe` (and the
/// collab-relay twin) over SSH on every connect as a pure liveness check.
/// A remote macOS host hands SSH sessions the stripped launchd PATH, so if
/// the GUI-PATH repair ran before the probe early-out, every attach would
/// stall on a login-shell probe — against the "remote attach never waits"
/// invariant. The probe subcommands must answer without consulting a shell.
#[test]
fn probe_subcommands_answer_instantly_even_with_a_stripped_path() {
    let dir = tempfile::tempdir().unwrap();
    let slow_shell = dir.path().join("slow-shell");
    std::fs::write(&slow_shell, "#!/bin/sh\nsleep 30\n").unwrap();
    let mut perm = std::fs::metadata(&slow_shell).unwrap().permissions();
    std::os::unix::fs::PermissionsExt::set_mode(&mut perm, 0o755);
    std::fs::set_permissions(&slow_shell, perm).unwrap();
    for sub in ["session-host", "collab-relay"] {
        let start = std::time::Instant::now();
        Command::cargo_bin("croft")
            .unwrap()
            .args([sub, "--probe"])
            .env("PATH", "/usr/bin:/bin:/usr/sbin:/sbin")
            .env("SHELL", &slow_shell)
            .assert()
            .success();
        // The discriminant is the 30s sleeping shell: a probe that runs the
        // PATH repair blocks on it, one that early-outs answers in well
        // under a second. The measured span also covers the cargo_bin
        // spawn, which a suite-saturated box once pushed past a 5s ceiling
        // (#50) — half the sleep keeps the failure mode unreachable while
        // giving load an order of magnitude more headroom.
        assert!(
            start.elapsed() < std::time::Duration::from_secs(15),
            "{sub} --probe took {:?} with a stripped PATH",
            start.elapsed()
        );
    }
}

#[test]
fn nonexistent_path_fails_cleanly() {
    Command::cargo_bin("croft")
        .unwrap()
        .arg("/nonexistent/path/that/does/not/exist/abc123")
        .assert()
        .failure();
}

/// The persisted pair record is the baseline for every `croft pair`
/// invocation: `--off` (with or without provider flags) and a plain
/// re-activation must both keep a custom ollama endpoint. Resolving bare
/// flags in isolation used to clobber the custom URL with the default and
/// silently converted a disabled ollama record into a cloud claude seat.
#[test]
fn pair_off_and_reactivation_keep_the_recorded_backend() {
    // A SHORT home: the activation path binds a relay socket under
    // $HOME/.cache/croft/sessions, and the default tempdir base pushes the
    // path past the AF_UNIX 104-byte limit.
    let home = tempfile::Builder::new()
        .prefix("h")
        .tempdir_in("/tmp")
        .unwrap();
    let ws = tempfile::tempdir().unwrap();
    let run = |args: &[&str]| {
        Command::cargo_bin("croft")
            .unwrap()
            .args(args)
            .arg("--workspace")
            .arg(ws.path())
            .env("HOME", home.path())
            .assert()
            .success();
    };
    run(&[
        "pair",
        "--provider",
        "ollama",
        "--model",
        "qwen3-coder:30b",
        "--base-url",
        "http://localhost:9999",
    ]);
    let record_path = || {
        let dir = home.path().join(".cache/croft/sessions");
        std::fs::read_dir(&dir)
            .unwrap()
            .filter_map(|e| e.ok())
            .map(|e| e.path())
            .find(|p| p.to_string_lossy().ends_with(".pair.json"))
            .expect("a pair record exists")
    };
    let read = || std::fs::read_to_string(record_path()).unwrap();
    assert!(read().contains("http://localhost:9999"));
    // Deactivate with provider flags but no URL: the custom URL survives.
    run(&["pair", "--provider", "ollama", "--off"]);
    let r = read();
    assert!(r.contains("\"enabled\":false"), "{r}");
    assert!(
        r.contains("http://localhost:9999"),
        "the default endpoint must not clobber the custom one: {r}"
    );
    // Plain re-activation: the whole recorded backend comes back.
    run(&["pair"]);
    let r = read();
    assert!(r.contains("\"enabled\":true"), "{r}");
    assert!(r.contains("\"provider\":\"ollama\""), "{r}");
    assert!(r.contains("http://localhost:9999"), "{r}");
    assert!(r.contains("qwen3-coder:30b"), "{r}");
    // An explicit provider SWITCH starts fresh: the other backend's
    // endpoint and model must not ride along into the claude record.
    run(&["pair", "--provider", "claude"]);
    let r = read();
    assert!(r.contains("\"provider\":\"claude\""), "{r}");
    assert!(
        !r.contains("http://localhost:9999"),
        "the ollama endpoint must not survive a provider switch: {r}"
    );
    assert!(!r.contains("qwen3-coder:30b"), "{r}");
    // Activation detached a relay for the workspace; reap it so test runs
    // do not accumulate idle processes.
    let sessions = home.path().join(".cache/croft/sessions");
    if let Ok(entries) = std::fs::read_dir(&sessions) {
        for e in entries.filter_map(|e| e.ok()) {
            let p = e.path();
            if p.to_string_lossy().ends_with(".collab.sock") {
                let _ = std::process::Command::new("pkill")
                    .args(["-f", &p.to_string_lossy()])
                    .status();
            }
        }
    }
}

/// #362 acceptance criterion 3, against the real binary: outside croft the
/// command exits 1 with a one-line explanation rather than trying to render.
///
/// `env_remove` rather than a bare run: this test suite is itself often
/// launched from a croft pane, where `CROFT_VIEW_SOCK` is set and inherited,
/// and the test would then quietly exercise the connected path instead.
#[test]
fn view_outside_croft_exits_one_with_an_explanation() {
    let out = Command::cargo_bin("croft")
        .unwrap()
        .env_remove("CROFT_VIEW_SOCK")
        .args(["view", "Cargo.toml"])
        .assert();
    let out = out.failure().code(1);
    let stderr = String::from_utf8(out.get_output().stderr.clone()).unwrap();
    assert!(
        stderr.contains("croft view needs a croft"),
        "stderr must say why, was: {stderr}"
    );
    assert_eq!(
        stderr.lines().filter(|l| !l.trim().is_empty()).count(),
        1,
        "one line, not a backtrace: {stderr}"
    );
}

/// An empty `CROFT_VIEW_SOCK` must read as absent, not as a socket at "".
#[test]
fn view_treats_an_empty_socket_variable_as_no_croft_at_all() {
    let out = Command::cargo_bin("croft")
        .unwrap()
        .env("CROFT_VIEW_SOCK", "")
        .args(["view", "Cargo.toml"])
        .assert();
    let out = out.failure().code(1);
    let stderr = String::from_utf8(out.get_output().stderr.clone()).unwrap();
    assert!(
        stderr.contains("croft view needs a croft"),
        "stderr was: {stderr}"
    );
}

/// A stale socket path (the croft that set it has exited) must name that
/// situation rather than surfacing a raw connect error.
#[test]
fn view_against_a_vanished_croft_says_the_croft_is_gone() {
    let tmp = tempfile::tempdir().unwrap();
    let out = Command::cargo_bin("croft")
        .unwrap()
        .env("CROFT_VIEW_SOCK", tmp.path().join("nobody.sock"))
        .args(["view", "Cargo.toml"])
        .assert();
    let out = out.failure().code(1);
    let stderr = String::from_utf8(out.get_output().stderr.clone()).unwrap();
    assert!(
        stderr.contains("is gone"),
        "stderr must name the situation, was: {stderr}"
    );
}

/// #362 end to end against the REAL binary: `croft view <file>` connects to
/// the socket named by the environment, sends the resolved path, and exits 0
/// on an ok reply.
///
/// The unit tests drive the client and server halves in one process, where
/// they can agree with each other. This stands up a socket the binary knows
/// nothing about and makes the shipped `croft view` talk to it.
#[test]
fn view_sends_the_resolved_path_to_the_socket_and_exits_zero() {
    use std::io::{BufRead, BufReader, Write};
    let tmp = tempfile::tempdir().unwrap();
    let sock = tmp.path().join("v.sock");
    let target = tmp.path().join("report.txt");
    std::fs::write(&target, b"hello").unwrap();
    let listener = std::os::unix::net::UnixListener::bind(&sock).unwrap();

    let server = std::thread::spawn(move || {
        let (mut stream, _) = listener.accept().unwrap();
        let mut line = String::new();
        BufReader::new(&stream).read_line(&mut line).unwrap();
        stream.write_all(b"{\"status\":\"ok\"}\n").unwrap();
        line
    });

    // Run from a DIFFERENT directory with a RELATIVE argument: the client is
    // the side that resolves, and running from the file's own directory
    // would pass even if it did not.
    Command::cargo_bin("croft")
        .unwrap()
        .env("CROFT_VIEW_SOCK", &sock)
        .current_dir(tmp.path())
        .args(["view", "report.txt"])
        .assert()
        .success();

    // The wire carries the path as raw bytes (a filename is bytes, not
    // UTF-8), so decode rather than substring-match: asserting on the text
    // form would pass only for paths that happen to be valid UTF-8, which is
    // the case the byte encoding exists to stop relying on.
    let request = server.join().unwrap();
    let bytes: Vec<u8> = request
        .trim()
        .trim_start_matches("{\"path\":[")
        .trim_end_matches("]}")
        .split(',')
        .map(|n| n.trim().parse::<u8>().expect("the wire is a byte array"))
        .collect();
    // Canonicalised on both sides: macOS hands a process a cwd under
    // `/private/var` for a `/var` tempdir, so the client resolves against a
    // path that is the same directory by a different name and a raw compare
    // fails there while passing on Linux.
    let received = std::path::PathBuf::from(String::from_utf8(bytes).unwrap());
    assert_eq!(
        received.canonicalize().unwrap_or(received),
        target.canonicalize().unwrap_or(target.clone()),
        "the server must receive the path resolved against the client's cwd"
    );
}

/// A file that does not exist is refused by the client, before any croft is
/// asked to open it: the message can then name the path as the user typed it,
/// resolved against the cwd they typed it in.
#[test]
fn view_refuses_a_missing_file_without_bothering_the_socket() {
    let tmp = tempfile::tempdir().unwrap();
    let sock = tmp.path().join("v.sock");
    let _listener = std::os::unix::net::UnixListener::bind(&sock).unwrap();
    let out = Command::cargo_bin("croft")
        .unwrap()
        .env("CROFT_VIEW_SOCK", &sock)
        .current_dir(tmp.path())
        .args(["view", "nope.pdf"])
        .assert();
    let out = out.failure().code(1);
    let stderr = String::from_utf8(out.get_output().stderr.clone()).unwrap();
    assert!(
        stderr.contains("no such file") && stderr.contains("nope.pdf"),
        "stderr must name the missing path, was: {stderr}"
    );
}

/// The wire carries a path as raw bytes so a filename that is not UTF-8
/// survives. That is only true if the CLI takes the argument as an
/// `OsString`: a `String` parameter throws the bytes away one call before
/// the encoding that preserves them, which is where this started.
///
/// Not on macOS: APFS rejects a filename that is not valid UTF-8, so the
/// fixture cannot be created there and the test would fail for a reason
/// that has nothing to do with the wire.
#[cfg(all(unix, not(target_os = "macos")))]
#[test]
fn view_transmits_a_non_utf8_filename_byte_for_byte() {
    use std::ffi::OsStr;
    use std::io::{BufRead, BufReader, Write};
    use std::os::unix::ffi::OsStrExt;

    let tmp = tempfile::tempdir().unwrap();
    let sock = tmp.path().join("v.sock");
    let name = OsStr::from_bytes(b"od\xffd.txt");
    let target = tmp.path().join(name);
    std::fs::write(&target, b"x").unwrap();
    assert!(
        target.to_str().is_none(),
        "fixture must be invalid UTF-8, or this test proves nothing"
    );
    let listener = std::os::unix::net::UnixListener::bind(&sock).unwrap();

    let server = std::thread::spawn(move || {
        let (mut stream, _) = listener.accept().unwrap();
        let mut line = String::new();
        BufReader::new(&stream).read_line(&mut line).unwrap();
        stream.write_all(b"{\"status\":\"ok\"}\n").unwrap();
        line
    });

    Command::cargo_bin("croft")
        .unwrap()
        .env("CROFT_VIEW_SOCK", &sock)
        .current_dir(tmp.path())
        .arg("view")
        .arg(name)
        .assert()
        .success();

    let request = server.join().unwrap();
    let bytes: Vec<u8> = request
        .trim()
        .trim_start_matches("{\"path\":[")
        .trim_end_matches("]}")
        .split(',')
        .map(|n| n.trim().parse::<u8>().expect("the wire is a byte array"))
        .collect();
    assert!(
        bytes.contains(&0xff),
        "the 0xff byte must reach the server intact, got {bytes:?}"
    );
    assert_eq!(std::path::PathBuf::from(OsStr::from_bytes(&bytes)), target);
}

/// An `--as` value that cannot become a filename is refused, not ignored:
/// falling back to the sniff would stage the bytes under a name the user did
/// not ask for and still report success.
#[test]
fn view_refuses_an_as_flag_that_cannot_be_a_file_extension() {
    let tmp = tempfile::tempdir().unwrap();
    let sock = tmp.path().join("v.sock");
    let _listener = std::os::unix::net::UnixListener::bind(&sock).unwrap();
    let home = tmp.path().join("home");
    std::fs::create_dir(&home).unwrap();
    let out = Command::cargo_bin("croft")
        .unwrap()
        .env("CROFT_VIEW_SOCK", &sock)
        .env("HOME", &home)
        .current_dir(tmp.path())
        .write_stdin("a,b\n1,2\n")
        .args(["view", "-", "--as", "../x"])
        .assert();
    let out = out.failure().code(1);
    let stderr = String::from_utf8(out.get_output().stderr.clone()).unwrap();
    assert!(
        stderr.contains("--as"),
        "the message must name the flag, was: {stderr}"
    );
    // And it refuses without leaving anything behind. `stage_stdin` used to
    // create `view-stdin/` before it validated the hint, so this refusal
    // built a directory in the user's real cache dir on its way out. HOME is
    // redirected here precisely so that is observable rather than invisible.
    assert!(
        !home.join(".cache/croft/view-stdin").exists(),
        "a refused --as must not create the staging directory"
    );
}

/// `croft view -` end to end against the shipped binary (#362).
///
/// The rejection test above never reaches the staging write, so nothing
/// covered the success path at the binary level: the file appearing on disk
/// under a sniffed extension the editor routes on, at 0600, with THAT path
/// being what the server is told to open. HOME is redirected so the staging
/// lands in a tempdir rather than the developer's own cache.
#[test]
fn view_from_a_pipe_stages_an_owner_only_file_and_sends_its_path() {
    use std::io::{BufRead, BufReader, Write};
    use std::os::unix::fs::PermissionsExt;
    let tmp = tempfile::tempdir().unwrap();
    let home = tmp.path().join("home");
    std::fs::create_dir(&home).unwrap();
    let sock = tmp.path().join("v.sock");
    let listener = std::os::unix::net::UnixListener::bind(&sock).unwrap();

    let server = std::thread::spawn(move || {
        let (mut stream, _) = listener.accept().unwrap();
        let mut line = String::new();
        BufReader::new(&stream).read_line(&mut line).unwrap();
        stream.write_all(b"{\"status\":\"ok\"}\n").unwrap();
        line
    });

    Command::cargo_bin("croft")
        .unwrap()
        .env("CROFT_VIEW_SOCK", &sock)
        .env("HOME", &home)
        .current_dir(tmp.path())
        .write_stdin("a,b\n1,2\n")
        .args(["view", "-"])
        .assert()
        .success();

    // Same byte-array decode as the on-disk case: the wire carries a filename
    // as bytes, and a substring match would only work for UTF-8 paths.
    let request = server.join().unwrap();
    let bytes: Vec<u8> = request
        .trim()
        .trim_start_matches("{\"path\":[")
        .trim_end_matches("]}")
        .split(',')
        .map(|n| n.trim().parse::<u8>().expect("the wire is a byte array"))
        .collect();
    let staged = std::path::PathBuf::from(String::from_utf8(bytes).unwrap());

    assert_eq!(
        staged.extension().and_then(|e| e.to_str()),
        Some("csv"),
        "delimited text must be staged under the extension the sheet viewer \
         routes on, or it arrives as plain text: {staged:?}"
    );
    assert!(
        staged.starts_with(home.join(".cache").join("croft")),
        "the staged file belongs under the cache dir, not beside the user's \
         own files: {staged:?}"
    );
    let meta = std::fs::metadata(&staged)
        .expect("the staged file must exist by the time the server is told about it");
    assert_eq!(
        meta.permissions().mode() & 0o777,
        0o600,
        "piped content is owner-only: `vault read ... | croft view -` is the \
         case this command invites"
    );
    assert_eq!(
        std::fs::read(&staged).unwrap(),
        b"a,b\n1,2\n",
        "and it is the bytes that came down the pipe, unaltered"
    );
}

/// `--as` on a NAMED file is refused, not ignored (#362).
///
/// The flag only ever reached `stage_stdin`, which only runs for `-`, so
/// `croft view data.log --as csv` opened a text tab and exited 0. The only
/// signal that the flag did nothing was the file opening in the viewer the
/// user was trying to override, which is precisely the reasoning the module
/// already gives for refusing an unusable `--as` value rather than sniffing
/// past it.
#[test]
fn view_refuses_an_as_flag_on_a_named_file_rather_than_ignoring_it() {
    let tmp = tempfile::tempdir().unwrap();
    let sock = tmp.path().join("v.sock");
    let target = tmp.path().join("data.log");
    std::fs::write(&target, b"a,b\n1,2\n").unwrap();
    // A listener that would ACCEPT, so a pass here cannot come from the
    // socket being unreachable.
    let _listener = std::os::unix::net::UnixListener::bind(&sock).unwrap();
    let out = Command::cargo_bin("croft")
        .unwrap()
        .env("CROFT_VIEW_SOCK", &sock)
        .current_dir(tmp.path())
        .args(["view", "data.log", "--as", "csv"])
        .assert();
    let out = out.failure().code(1);
    let stderr = String::from_utf8(out.get_output().stderr.clone()).unwrap();
    assert!(
        stderr.contains("--as"),
        "the message must name the flag that was refused, was: {stderr}"
    );
    assert!(
        stderr.contains("piped"),
        "and say what it applies to, or the user cannot tell what to do \
         instead, was: {stderr}"
    );
}

/// An empty pipe is refused by name, and stages nothing (#362).
#[test]
fn view_from_an_empty_pipe_says_nothing_arrived() {
    let tmp = tempfile::tempdir().unwrap();
    let home = tmp.path().join("home");
    std::fs::create_dir(&home).unwrap();
    let sock = tmp.path().join("v.sock");
    let _listener = std::os::unix::net::UnixListener::bind(&sock).unwrap();
    let out = Command::cargo_bin("croft")
        .unwrap()
        .env("CROFT_VIEW_SOCK", &sock)
        .env("HOME", &home)
        .current_dir(tmp.path())
        .write_stdin("")
        .args(["view", "-"])
        .assert();
    let out = out.failure().code(1);
    let stderr = String::from_utf8(out.get_output().stderr.clone()).unwrap();
    assert!(
        stderr.contains("nothing arrived on stdin"),
        "an empty pipe must say so rather than staging a zero-byte file and \
         reporting success, was: {stderr}"
    );
    assert!(
        !home.join(".cache/croft/view-stdin").exists(),
        "and it must not create the staging directory either"
    );
}

/// #682 end to end: croft over a pty with an image protocol on (iTerm2's,
/// forced) must not stream images on every keystroke. Before the fix, 20
/// keystrokes in a file cost about 175 KB of escape output (the minimap and
/// chrome images re-sent each frame); now they cost a few KB. The budget
/// sits between the two so a regression fails loudly without being flaky.
#[cfg(unix)]
#[test]
fn typing_with_images_on_does_not_stream_images_per_keystroke() {
    use std::io::Read;
    use std::os::fd::{FromRawFd, OwnedFd};
    use std::os::unix::process::CommandExt;
    use std::time::{Duration, Instant};

    let home = tempfile::tempdir().unwrap();
    let file = home.path().join("a.rs");
    std::fs::write(&file, "fn main() {\n    println!(\"hi\");\n}\n".repeat(300)).unwrap();

    let (mut master, mut slave) = (0, 0);
    let ws = libc::winsize {
        ws_row: 50,
        ws_col: 160,
        ws_xpixel: 160 * 9,
        ws_ypixel: 50 * 18,
    };
    assert_eq!(
        unsafe {
            libc::openpty(
                &mut master,
                &mut slave,
                std::ptr::null_mut(),
                std::ptr::null(),
                &ws,
            )
        },
        0
    );
    let slave = unsafe { OwnedFd::from_raw_fd(slave) };
    let bin = assert_cmd::cargo::cargo_bin("croft");
    let mut cmd = std::process::Command::new(bin);
    cmd.arg("a.rs")
        .current_dir(home.path())
        .env("HOME", home.path())
        .env("TERM", "xterm-256color")
        .env("TERM_PROGRAM", "iTerm.app")
        .env("CROFT_FORCE_INLINE_IMAGES", "1")
        .stdin(slave.try_clone().unwrap())
        .stdout(slave.try_clone().unwrap())
        .stderr(slave.try_clone().unwrap());
    unsafe {
        cmd.pre_exec(|| {
            libc::setsid();
            libc::ioctl(0, libc::TIOCSCTTY as _, 0);
            Ok(())
        });
    }
    let mut child = cmd.spawn().unwrap();
    drop(slave);
    unsafe {
        let flags = libc::fcntl(master, libc::F_GETFL);
        libc::fcntl(master, libc::F_SETFL, flags | libc::O_NONBLOCK);
    }
    let mut pty = unsafe { std::fs::File::from_raw_fd(master) };
    let mut tty = pty.try_clone().unwrap();
    let mut drain = |for_: Duration| {
        let mut n = 0usize;
        let mut buf = [0u8; 1 << 16];
        let end = Instant::now() + for_;
        while Instant::now() < end {
            match pty.read(&mut buf) {
                Ok(0) => break,
                Ok(k) => n += k,
                Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
                    std::thread::sleep(Duration::from_millis(10))
                }
                Err(_) => break,
            }
        }
        n
    };
    // Let it start, then dismiss any first-run popup and let that settle.
    let started = drain(Duration::from_secs(8));
    assert!(started > 1000, "croft drew nothing ({started} bytes)");
    use std::io::Write;
    tty.write_all(b"\x1b").unwrap();
    drain(Duration::from_secs(2));
    let mut typed = 0;
    for _ in 0..20 {
        tty.write_all(b"x").unwrap();
        typed += drain(Duration::from_millis(80));
    }
    typed += drain(Duration::from_secs(1));
    let _ = child.kill();
    let _ = child.wait();
    assert!(
        typed < 30_000,
        "20 keystrokes wrote {typed} bytes: images are being re-sent per frame"
    );
}

/// #621: a locale as `$LANG` spells it (`de_DE.UTF-8`) seeds the template
/// from the German catalog and names the file croft will load.
#[test]
fn locale_template_accepts_a_full_locale() {
    let out = Command::cargo_bin("croft")
        .unwrap()
        .args(["locale-template", "de_DE.UTF-8"])
        .assert()
        .success();
    let stdout = String::from_utf8(out.get_output().stdout.clone()).unwrap();
    let stderr = String::from_utf8(out.get_output().stderr.clone()).unwrap();
    let catalog: serde_json::Value = serde_json::from_str(&stdout).unwrap();
    let filled = catalog
        .as_object()
        .unwrap()
        .values()
        .filter(|v| v.as_str().is_some_and(|s| !s.is_empty()))
        .count();
    assert!(filled > 0, "the built-in German entries seed it");
    assert!(stderr.contains("locales/de.json"), "{stderr}");
}