trusty-common 0.23.3

Shared utilities and provider-agnostic streaming chat (ChatProvider, OllamaProvider, OpenRouter, tool-use) for trusty-* projects
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
//! Tests for the `update` module.
//!
//! Why: Kept in a sibling file to respect the 500-line cap on `mod.rs`
//! while still using `#[cfg(test)]` so the test helpers are compiled only
//! in test mode.

use super::*;
use std::sync::Mutex;
use std::sync::atomic::{AtomicU64, Ordering};

/// Serialize tests that mutate environment variables to prevent races when
/// `cargo test` runs them on parallel threads.
static ENV_LOCK: Mutex<()> = Mutex::new(());

/// Monotonic counter guaranteeing every `unique_crate` name generated by
/// [`run_cache_freshness_test`] is actually unique.
///
/// Why (issue #2460): the previous generator combined the process id with a
/// nanosecond timestamp, but two test threads scheduled close enough
/// together can observe the *same* `SystemTime::now()` value on platforms
/// where the wall clock does not have true nanosecond resolution — the two
/// cache-freshness tests would then race on the identical cache file. A
/// process-wide atomic counter is deterministic by construction and cannot
/// collide, independent of clock granularity or thread scheduling.
/// What: `fetch_add`'d once per call; the returned value is folded into the
/// generated crate name.
/// Test: covered indirectly — `cache_fresh_returns_some_when_newer` and
/// `cache_fresh_returns_none_when_current` no longer flake under
/// `--test-threads` > 1 (see the repro loop in the PR description).
static UNIQUE_CRATE_COUNTER: AtomicU64 = AtomicU64::new(0);

// ── semver helpers ──────────────────────────────────────────────────────

#[test]
fn semver_newer_returns_true() {
    assert!(is_newer("0.20.0", "0.19.0"));
    assert!(is_newer("1.0.0", "0.99.99"));
    assert!(is_newer("0.19.1", "0.19.0"));
}

#[test]
fn semver_equal_returns_false() {
    assert!(!is_newer("0.19.0", "0.19.0"));
}

#[test]
fn semver_older_returns_false() {
    assert!(!is_newer("0.18.0", "0.19.0"));
    assert!(!is_newer("0.19.0", "1.0.0"));
}

#[test]
fn semver_prerelease_stripped() {
    // Pre-release suffixes are stripped before comparison.
    assert!(!is_newer("0.19.0-beta.1", "0.19.0"));
    assert!(is_newer("0.20.0-alpha.1", "0.19.0"));
}

#[test]
fn semver_parse_strips_prerelease() {
    assert_eq!(parse_version("1.2.3-beta.1"), Some((1, 2, 3)));
    assert_eq!(parse_version("1.2.3+build.42"), Some((1, 2, 3)));
    assert_eq!(parse_version("1.2.3-rc.1+sha.abc"), Some((1, 2, 3)));
}

#[test]
fn semver_parse_handles_missing_patch() {
    assert_eq!(parse_version("1.2"), Some((1, 2, 0)));
    assert_eq!(parse_version("1"), Some((1, 0, 0)));
}

#[test]
fn semver_parse_rejects_garbage() {
    assert_eq!(parse_version("not-a-version"), None);
    assert_eq!(parse_version(""), None);
}

// ── notice formatting ───────────────────────────────────────────────────

#[test]
fn notice_formats_correctly() {
    let info = UpdateInfo {
        crate_name: "trusty-search".to_owned(),
        current: "0.19.0".to_owned(),
        latest: "0.20.0".to_owned(),
    };
    let n = notice(&info);
    assert!(n.contains("trusty-search"), "crate name missing: {n}");
    assert!(n.contains("0.20.0"), "latest version missing: {n}");
    assert!(n.contains("0.19.0"), "current version missing: {n}");
    assert!(n.contains("cargo install"), "install command missing: {n}");
    assert!(n.contains("--locked"), "--locked flag missing: {n}");
}

// ── opt-out env var ────────────────────────────────────────────────────

#[tokio::test]
async fn check_throttled_skips_when_no_update_check_set() {
    // Set the env var while holding the lock, then drop the lock before
    // the await so clippy::await-holding-lock is satisfied.
    {
        let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        // Safety: env mutation is serialized by ENV_LOCK; guard dropped
        // before the async call below.
        unsafe { std::env::set_var(NO_UPDATE_CHECK_ENV, "1") };
    }
    let result = check_throttled("trusty-search", "0.19.0").await;
    {
        let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        unsafe { std::env::remove_var(NO_UPDATE_CHECK_ENV) };
    }
    assert!(
        result.is_none(),
        "expected None when {NO_UPDATE_CHECK_ENV} is set"
    );
}

#[tokio::test]
async fn check_throttled_skips_when_ci_set() {
    {
        let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        unsafe { std::env::set_var(CI_ENV, "true") };
    }
    let result = check_throttled("trusty-search", "0.19.0").await;
    {
        let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        unsafe { std::env::remove_var(CI_ENV) };
    }
    assert!(result.is_none(), "expected None when CI is set");
}

// ── cache freshness logic (uses a temp cache dir) ────────────────────────

/// Write a cache entry with the given `last_check_unix` timestamp and
/// `latest_version`, then call `check_throttled` and verify the result
/// matches `expected_is_some`. No real network is used because a fresh
/// cache entry suppresses the network call.
async fn run_cache_freshness_test(
    last_check_unix: u64,
    latest_version: &str,
    current_version: &str,
    expected_is_some: bool,
) {
    // Use a unique crate name to avoid cross-test cache pollution. The
    // atomic counter (not just pid + nanosecond timestamp) guarantees
    // uniqueness by construction — see `UNIQUE_CRATE_COUNTER` (issue #2460).
    let unique_crate = format!(
        "test-crate-{}-{}",
        std::process::id(),
        UNIQUE_CRATE_COUNTER.fetch_add(1, Ordering::Relaxed)
    );

    let entry = CacheEntry {
        last_check_unix,
        latest_version: latest_version.to_owned(),
    };
    write_cache(&unique_crate, &entry);

    // The cache is fresh, so check_throttled returns the cached result
    // without any network call.
    let result = check_throttled(&unique_crate, current_version).await;
    assert_eq!(
        result.is_some(),
        expected_is_some,
        "freshness={expected_is_some}: latest={latest_version} current={current_version}"
    );

    // Clean up.
    let _ = std::fs::remove_file(cache_path(&unique_crate));
}

#[tokio::test]
async fn cache_fresh_returns_some_when_newer() {
    // Cache written 1 h ago (well within 24 h) with a newer version.
    run_cache_freshness_test(now_unix_secs() - 3600, "1.0.0", "0.19.0", true).await;
}

#[tokio::test]
async fn cache_fresh_returns_none_when_current() {
    // Cache written 1 h ago with the same version — already up to date.
    run_cache_freshness_test(now_unix_secs() - 3600, "0.19.0", "0.19.0", false).await;
}

// ── corrupt / missing cache file ──────────────────────────────────────

#[test]
fn corrupt_cache_returns_none() {
    // Write garbage bytes to the cache file; read_cache must return None.
    let unique_crate = format!("corrupt-test-{}", std::process::id());
    let path = cache_path(&unique_crate);
    if let Some(parent) = path.parent() {
        let _ = std::fs::create_dir_all(parent);
    }
    let _ = std::fs::write(&path, b"this is not valid json {{{{");
    let result = read_cache(&unique_crate);
    let _ = std::fs::remove_file(&path);
    assert!(result.is_none(), "corrupt cache must yield None");
}

#[test]
fn missing_cache_returns_none() {
    let unique_crate = format!("missing-test-{}", std::process::id());
    // Ensure the file does not exist.
    let _ = std::fs::remove_file(cache_path(&unique_crate));
    let result = read_cache(&unique_crate);
    assert!(result.is_none(), "missing cache must yield None");
}

// ── cache round-trip ──────────────────────────────────────────────────

#[test]
fn cache_round_trip() {
    let unique_crate = format!("roundtrip-{}", std::process::id());
    let entry = CacheEntry {
        last_check_unix: 1_700_000_000,
        latest_version: "9.9.9".to_owned(),
    };
    write_cache(&unique_crate, &entry);
    let back = read_cache(&unique_crate);
    let _ = std::fs::remove_file(cache_path(&unique_crate));
    let back = back.expect("cache round-trip should succeed");
    assert_eq!(back.last_check_unix, 1_700_000_000);
    assert_eq!(back.latest_version, "9.9.9");
}

// ── upgrade primitive tests ────────────────────────────────────────────────

/// Verify the command constructed by `perform_upgrade` uses the right args.
///
/// Why: We can't actually run `cargo install` in a unit test without touching
/// the network and the filesystem. This test validates the command construction
/// logic by inspecting that `perform_upgrade` calls cargo with `install` and
/// `--locked` — validated by running it against a non-existent crate name and
/// checking that it fails with the right kind of error (cargo not found is
/// acceptable too, meaning the command was built).
/// Test: tagged #[ignore] because it shells out; run manually with
/// `cargo test -p trusty-common --features update-check -- --include-ignored`.
#[tokio::test]
#[ignore]
async fn perform_upgrade_fails_cleanly_on_nonexistent_crate() {
    let result = super::perform_upgrade("___trusty_test_crate_does_not_exist___").await;
    // Should be Err because cargo install would fail for a nonexistent crate.
    assert!(
        result.is_err(),
        "expected Err for nonexistent crate, got Ok"
    );
    let msg = result.unwrap_err().to_string();
    // The error message should mention cargo or the status.
    assert!(
        msg.contains("cargo install") || msg.contains("status") || msg.contains("exited"),
        "unexpected error message: {msg}"
    );
}

/// Verify that `verify_installed_binary` passes for `cargo`, which is always
/// on PATH for any developer machine.
///
/// Why: We need a real binary that is always present to test the happy path
/// without installing anything. `cargo --version` is a safe no-side-effect probe.
/// Test: tagged #[ignore] (shells out); run manually with `--include-ignored`.
#[tokio::test]
#[ignore]
async fn verify_installed_binary_passes_for_cargo() {
    let result = super::verify_installed_binary("cargo").await;
    assert!(
        result.is_ok(),
        "expected Ok for `cargo --version`, got: {:?}",
        result
    );
}

/// Verify that `verify_installed_binary` returns Err for a non-existent binary.
///
/// Why: Confirms the health gate catches missing binaries before a self-exit.
/// Test: sync test — no shell-out needed because `which` will quickly fail.
#[tokio::test]
async fn verify_installed_binary_fails_for_missing_binary() {
    let result = super::verify_installed_binary("___no_such_binary_xyz_999___").await;
    assert!(
        result.is_err(),
        "expected Err for non-existent binary, got Ok"
    );
}

// ── candidate_bin_dirs (pure path-resolution logic, issue #1771) ──────────

#[test]
fn candidate_bin_dirs_falls_back_to_dot_cargo() {
    let home = std::path::Path::new("/home/tester");
    let dirs = super::upgrade::candidate_bin_dirs(Some(home), None);
    assert_eq!(dirs[0], home.join(".cargo").join("bin"));
}

#[test]
fn candidate_bin_dirs_prefers_cargo_home_override() {
    let home = std::path::Path::new("/home/tester");
    let dirs = super::upgrade::candidate_bin_dirs(Some(home), Some("/opt/custom-cargo"));
    assert_eq!(
        dirs[0],
        std::path::PathBuf::from("/opt/custom-cargo").join("bin"),
        "CARGO_HOME override must take priority over ~/.cargo/bin"
    );
}

#[test]
fn candidate_bin_dirs_ignores_empty_cargo_home() {
    let home = std::path::Path::new("/home/tester");
    let dirs = super::upgrade::candidate_bin_dirs(Some(home), Some(""));
    assert_eq!(
        dirs[0],
        home.join(".cargo").join("bin"),
        "empty CARGO_HOME must fall back to ~/.cargo/bin, not be treated as a path"
    );
}

#[test]
fn candidate_bin_dirs_includes_local_bin() {
    let home = std::path::Path::new("/home/tester");
    let dirs = super::upgrade::candidate_bin_dirs(Some(home), None);
    assert!(
        dirs.contains(&home.join(".local").join("bin")),
        "~/.local/bin (the prebuilt installer's default) must be a candidate: {dirs:?}"
    );
    // ~/.local/bin must be checked after ~/.cargo/bin, not before.
    let local_idx = dirs
        .iter()
        .position(|d| d == &home.join(".local").join("bin"))
        .expect("local bin present");
    let cargo_idx = dirs
        .iter()
        .position(|d| d == &home.join(".cargo").join("bin"))
        .expect("cargo bin present");
    assert!(cargo_idx < local_idx, "cargo bin must be checked first");
}

#[test]
fn candidate_bin_dirs_empty_without_home_or_cargo_home() {
    let dirs = super::upgrade::candidate_bin_dirs(None, None);
    assert!(
        dirs.is_empty(),
        "no home and no CARGO_HOME override must yield zero candidates"
    );
}

// ── verify_installed_binary directory resolution (issue #1771) ────────────
//
// These write a tiny executable shell script that exits 0 on `--version` and
// point HOME at a tempdir so the real filesystem/env are never touched.

/// Write a minimal executable shell script at `path` that responds
/// successfully to `--version`, standing in for a real installed binary.
#[cfg(unix)]
fn write_fake_binary(path: &std::path::Path) {
    use std::os::unix::fs::PermissionsExt;
    std::fs::write(path, b"#!/bin/sh\necho fake 1.0.0\nexit 0\n").expect("write fake binary");
    let mut perms = std::fs::metadata(path)
        .expect("stat fake binary")
        .permissions();
    perms.set_mode(0o755);
    std::fs::set_permissions(path, perms).expect("chmod fake binary");
}

/// Snapshot of the env vars mutated by the `verify_installed_binary_*`
/// directory-resolution tests, captured so they can be restored verbatim.
#[cfg(unix)]
struct EnvSnapshot {
    home: Option<String>,
    cargo_home: Option<String>,
    path: Option<String>,
}

/// Set `HOME` (and clear `CARGO_HOME` unless `cargo_home` is given) and
/// return the prior values so the caller can restore them afterward.
///
/// Why: Split into non-async set/restore steps (rather than wrapping an
/// awaited closure) so the `ENV_LOCK` guard is only ever held across the
/// synchronous mutation, never across an `.await` point
/// (`clippy::await_holding_lock`).
#[cfg(unix)]
fn set_home_env(home: &std::path::Path, cargo_home: Option<&str>) -> EnvSnapshot {
    let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
    let snapshot = EnvSnapshot {
        home: std::env::var("HOME").ok(),
        cargo_home: std::env::var("CARGO_HOME").ok(),
        path: std::env::var("PATH").ok(),
    };
    unsafe {
        std::env::set_var("HOME", home);
        match cargo_home {
            Some(v) => std::env::set_var("CARGO_HOME", v),
            None => std::env::remove_var("CARGO_HOME"),
        }
    }
    snapshot
}

/// Restore env vars captured by [`set_home_env`]. Must be called after the
/// awaited work under test has completed.
#[cfg(unix)]
fn restore_home_env(snapshot: EnvSnapshot) {
    let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
    unsafe {
        match snapshot.home {
            Some(h) => std::env::set_var("HOME", h),
            None => std::env::remove_var("HOME"),
        }
        match snapshot.cargo_home {
            Some(h) => std::env::set_var("CARGO_HOME", h),
            None => std::env::remove_var("CARGO_HOME"),
        }
        match snapshot.path {
            Some(p) => std::env::set_var("PATH", p),
            None => std::env::remove_var("PATH"),
        }
    }
}

#[cfg(unix)]
#[tokio::test]
async fn verify_installed_binary_finds_binary_in_cargo_bin() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let cargo_bin = tmp.path().join(".cargo").join("bin");
    std::fs::create_dir_all(&cargo_bin).expect("mkdir .cargo/bin");
    write_fake_binary(&cargo_bin.join("fake_trusty_bin_cargo"));

    let snapshot = set_home_env(tmp.path(), None);
    let result = super::verify_installed_binary("fake_trusty_bin_cargo").await;
    restore_home_env(snapshot);

    assert!(result.is_ok(), "expected Ok, got {result:?}");
}

#[cfg(unix)]
#[tokio::test]
async fn verify_installed_binary_finds_binary_in_local_bin() {
    let tmp = tempfile::tempdir().expect("tempdir");
    // Deliberately do NOT create ~/.cargo/bin — only ~/.local/bin has the
    // binary, mirroring a prebuilt-installer-only install (issue #1771/#1992).
    let local_bin = tmp.path().join(".local").join("bin");
    std::fs::create_dir_all(&local_bin).expect("mkdir .local/bin");
    write_fake_binary(&local_bin.join("fake_trusty_bin_local"));

    let snapshot = set_home_env(tmp.path(), None);
    let result = super::verify_installed_binary("fake_trusty_bin_local").await;
    restore_home_env(snapshot);

    assert!(
        result.is_ok(),
        "expected Ok when binary only exists in ~/.local/bin, got {result:?}"
    );
}

#[cfg(unix)]
#[tokio::test]
async fn verify_installed_binary_honours_cargo_home_override() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let custom_cargo_home = tmp.path().join("custom-cargo-home");
    let custom_bin = custom_cargo_home.join("bin");
    std::fs::create_dir_all(&custom_bin).expect("mkdir custom cargo bin");
    write_fake_binary(&custom_bin.join("fake_trusty_bin_cargo_home"));

    let home_dir = tmp.path().join("home");
    std::fs::create_dir_all(&home_dir).expect("mkdir home");

    let snapshot = set_home_env(
        &home_dir,
        Some(custom_cargo_home.to_str().expect("utf8 path")),
    );
    let result = super::verify_installed_binary("fake_trusty_bin_cargo_home").await;
    restore_home_env(snapshot);

    assert!(
        result.is_ok(),
        "expected Ok when binary is under $CARGO_HOME/bin, got {result:?}"
    );
}

#[cfg(unix)]
#[tokio::test]
async fn verify_installed_binary_finds_binary_via_path() {
    // HOME points at an empty tempdir with neither ~/.cargo/bin nor
    // ~/.local/bin containing the binary, forcing the PATH/`which` fallback.
    let home_tmp = tempfile::tempdir().expect("home tempdir");
    let path_tmp = tempfile::tempdir().expect("path tempdir");
    write_fake_binary(&path_tmp.path().join("fake_trusty_bin_path"));

    let snapshot = set_home_env(home_tmp.path(), None);
    let prev_path = std::env::var("PATH").unwrap_or_default();
    let new_path = format!("{}:{prev_path}", path_tmp.path().display());
    unsafe { std::env::set_var("PATH", &new_path) };

    let result = super::verify_installed_binary("fake_trusty_bin_path").await;
    restore_home_env(snapshot);

    assert!(
        result.is_ok(),
        "expected Ok via PATH fallback, got {result:?}"
    );
}

/// Verify that `is_launchd_supervised` returns `false` in a normal test env.
///
/// Why: Unit tests run in a developer terminal / CI, neither of which is a
/// launchd-managed job. This catches regressions where the heuristic fires
/// too eagerly.
/// Test: the test sets `TERM_PROGRAM` to a non-empty value (mimicking an
/// interactive terminal session) and clears `XPC_SERVICE_NAME` to ensure the
/// fast path returns false.
#[test]
fn is_launchd_supervised_returns_false_in_test_env() {
    // Env mutations must be serialised with the same lock used by the other
    // env-mutating tests.
    let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
    unsafe {
        std::env::set_var("TERM_PROGRAM", "TestRunner");
        std::env::remove_var("XPC_SERVICE_NAME");
    }
    let result = super::is_launchd_supervised();
    unsafe {
        std::env::remove_var("TERM_PROGRAM");
    }
    // In a terminal (TERM_PROGRAM set) the function must return false even
    // if XPC_SERVICE_NAME were somehow present.
    assert!(
        !result,
        "is_launchd_supervised returned true inside a test terminal env"
    );
}

// ── live crates.io integration test (requires network) ───────────────────────
// Tagged #[ignore] so it is skipped in normal CI runs.

#[tokio::test]
#[ignore]
async fn live_crates_io_with_old_version_returns_some() {
    // Deliberately old version — should show trusty-search is newer.
    let result = check_crates_io("trusty-search", "0.0.1").await;
    assert!(
        result.is_some(),
        "expected Some(UpdateInfo) for old version 0.0.1 — is network available?"
    );
    let info = result.unwrap();
    println!("crates.io returned: latest={}", info.latest);
    assert!(
        !info.latest.is_empty(),
        "latest version should not be empty"
    );
    // Verify the notice string renders correctly
    let n = notice(&info);
    println!("Notice: {n}");
    assert!(
        n.contains("cargo install trusty-search --locked"),
        "notice missing install cmd: {n}"
    );
    assert!(n.contains(&info.latest), "notice missing latest version");
    assert!(n.contains("0.0.1"), "notice missing current version");
}