trusty-common 0.52.0

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
use super::*;
use ratatui::{
    Terminal,
    backend::TestBackend,
    layout::{Constraint, Direction},
    style::Color,
};

/// A trusty-search payload with two indexes for rendering tests.
fn sample_search() -> SearchData {
    SearchData {
        version: "0.3.63".into(),
        uptime_secs: 7440,
        indexes: vec![
            IndexRow {
                id: "cto".into(),
                chunk_count: 1_200,
                root_path: "/tmp/cto".into(),
                ..Default::default()
            },
            IndexRow {
                id: "trusty".into(),
                chunk_count: 18_994,
                root_path: "/tmp/trusty".into(),
                ..Default::default()
            },
        ],
    }
}

/// A trusty-memory payload with two palaces for rendering tests.
fn sample_memory() -> MemoryData {
    MemoryData {
        version: "0.4.2".into(),
        palace_count: 2,
        total_drawers: 14,
        total_vectors: 8_400,
        total_kg_triples: 1_200,
        palaces: vec![
            PalaceRow {
                id: "default".into(),
                name: "default".into(),
                vector_count: 8_400,
                ..Default::default()
            },
            PalaceRow {
                id: "work".into(),
                name: "work".into(),
                vector_count: 0,
                ..Default::default()
            },
        ],
    }
}

#[test]
fn test_layout_wide() {
    // A terminal at or above the threshold splits the panels horizontally
    // into two equal halves.
    let (direction, constraints) = panel_layout(140);
    assert_eq!(direction, Direction::Horizontal);
    assert_eq!(
        constraints,
        [Constraint::Percentage(50), Constraint::Percentage(50)]
    );
    // Exactly at the boundary still counts as wide.
    assert_eq!(panel_layout(WIDE_LAYOUT_MIN_COLS).0, Direction::Horizontal);
}

#[test]
fn test_layout_narrow() {
    // Below the threshold the panels stack vertically.
    let (direction, constraints) = panel_layout(80);
    assert_eq!(direction, Direction::Vertical);
    assert_eq!(
        constraints,
        [Constraint::Percentage(50), Constraint::Percentage(50)]
    );
}

#[test]
fn test_offline_panel_renders() {
    // An offline panel must produce renderable lines (carrying the error)
    // and must not panic when fed to the frame renderer.
    let search: DaemonPanel<SearchData> = DaemonPanel {
        status: PanelStatus::Offline {
            last_error: "connection refused".into(),
        },
        base_url: "http://127.0.0.1:7878".into(),
    };
    let lines = search_panel_lines(&search);
    assert!(lines.iter().any(|l| l.contains("connection refused")));
    assert!(lines.iter().any(|l| l.contains("unreachable")));

    let memory: DaemonPanel<MemoryData> = DaemonPanel {
        status: PanelStatus::Offline {
            last_error: "timeout".into(),
        },
        base_url: "http://127.0.0.1:7070".into(),
    };
    let mlines = memory_panel_lines(&memory);
    assert!(mlines.iter().any(|l| l.contains("timeout")));

    // A whole-frame render with both panels offline must not panic.
    let state = DashboardState {
        search,
        memory,
        focus: Focus::Search,
        show_help: false,
        last_action: None,
    };
    let backend = TestBackend::new(130, 30);
    let mut terminal = Terminal::new(backend).expect("test terminal");
    terminal
        .draw(|f| render(f, &state))
        .expect("offline render must not panic");
}

#[test]
fn test_uptime_format() {
    assert_eq!(format_uptime(7440), "2h 4m");
    assert_eq!(format_uptime(0), "0h 0m");
    assert_eq!(format_uptime(59), "0h 0m");
    assert_eq!(format_uptime(3600), "1h 0m");
    assert_eq!(format_uptime(3661), "1h 1m");
}

#[test]
fn test_format_count() {
    // Small counts are comma-grouped and exact.
    assert_eq!(format_count(0), "0");
    assert_eq!(format_count(900), "900");
    assert_eq!(format_count(1_200), "1,200");
    assert_eq!(format_count(9_999), "9,999");
    // Counts at or above 10k are abbreviated with one decimal.
    assert_eq!(format_count(19_400), "19.4k");
    assert_eq!(format_count(10_000), "10.0k");
}

/// Why (issue #4682): the guard that stops the next caller printing a bare `0`
/// for a value nobody measured. `format_count` cannot express "unknown";
/// `format_opt_count` can, and every count renderer now goes through it.
/// What: asserts `None` renders as the shared placeholder and never as `"0"`,
/// while `Some(0)` — a genuinely empty palace — still renders as `"0"`.
/// Test: this test.
#[test]
fn test_format_opt_count() {
    assert_eq!(format_opt_count(None), UNKNOWN_COUNT);
    assert_ne!(format_opt_count(None), "0", "unknown must not read as zero");
    assert_eq!(format_opt_count(Some(0)), "0");
    assert_eq!(format_opt_count(Some(1_200)), "1,200");
    assert_eq!(format_opt_count(Some(19_400)), "19.4k");
}

/// Why (issue #4682): `PalaceRow`'s raw count fields hold `0` in both the
/// "genuinely empty" and the "daemon never loaded it" case. The accessors are
/// what let a renderer tell the two apart, so their contract is pinned here.
/// What: asserts a row flagged `counts_unknown` yields `None` from every
/// accessor even though the raw fields hold non-zero values, and that the
/// default (unflagged) row reports its counts.
/// Test: this test.
#[test]
fn palace_row_counts_are_unknown_when_not_cached() {
    // Non-zero raw fields prove the accessors read the flag, not the value.
    let cold = PalaceRow {
        id: "cold".into(),
        vector_count: 912,
        drawer_count: 38,
        kg_triple_count: 122,
        node_count: 9,
        edge_count: 8,
        counts_unknown: true,
        ..Default::default()
    };
    assert_eq!(cold.vectors(), None);
    assert_eq!(cold.drawers(), None);
    assert_eq!(cold.kg_triples(), None);
    assert_eq!(cold.nodes(), None);
    assert_eq!(cold.edges(), None);

    let warm = PalaceRow {
        id: "warm".into(),
        vector_count: 912,
        drawer_count: 38,
        ..Default::default()
    };
    assert!(
        !warm.counts_unknown,
        "a hand-built row defaults to reporting real counts"
    );
    assert_eq!(warm.vectors(), Some(912));
    assert_eq!(warm.drawers(), Some(38));
}

#[test]
fn test_search_total_chunks() {
    assert_eq!(sample_search().total_chunks(), 20_194);
    assert_eq!(SearchData::default().total_chunks(), 0);
}

#[test]
fn test_search_panel_renders() {
    let panel = DaemonPanel {
        status: PanelStatus::Online(sample_search()),
        base_url: "http://127.0.0.1:7878".into(),
    };
    let lines = search_panel_lines(&panel);
    assert!(
        lines
            .iter()
            .any(|l| l.contains("Uptime:") && l.contains("2h 4m"))
    );
    assert!(
        lines
            .iter()
            .any(|l| l.contains("Indexes:") && l.contains('2'))
    );
    assert!(
        lines
            .iter()
            .any(|l| l.contains("cto") && l.contains("1,200"))
    );
    assert!(
        lines
            .iter()
            .any(|l| l.contains("trusty") && l.contains("19.0k"))
    );
}

#[test]
fn test_memory_panel_renders() {
    let panel = DaemonPanel {
        status: PanelStatus::Online(sample_memory()),
        base_url: "http://127.0.0.1:7070".into(),
    };
    let lines = memory_panel_lines(&panel);
    assert!(
        lines
            .iter()
            .any(|l| l.contains("Palaces:") && l.contains('2'))
    );
    assert!(
        lines
            .iter()
            .any(|l| l.contains("Vectors:") && l.contains("8,400"))
    );
    assert!(
        lines
            .iter()
            .any(|l| l.contains("KG triples:") && l.contains("1,200"))
    );
    assert!(
        lines
            .iter()
            .any(|l| l.contains("default") && l.contains("8,400"))
    );
}

#[test]
fn test_toggle_focus() {
    let mut state = DashboardState::new("http://a", "http://b");
    assert_eq!(state.focus, Focus::Search);
    state.toggle_focus();
    assert_eq!(state.focus, Focus::Memory);
    state.toggle_focus();
    assert_eq!(state.focus, Focus::Search);
}

#[test]
fn test_new_state_starts_connecting() {
    let state = DashboardState::new("http://a", "http://b");
    assert!(matches!(state.search.status, PanelStatus::Connecting));
    assert!(matches!(state.memory.status, PanelStatus::Connecting));
    assert_eq!(state.search.base_url, "http://a");
    assert_eq!(state.memory.base_url, "http://b");
}

#[test]
fn test_panel_starts_connecting() {
    let panel: DaemonPanel<SearchData> = DaemonPanel::new("http://x");
    assert!(matches!(panel.status, PanelStatus::Connecting));
    assert_eq!(panel.base_url, "http://x");
}

#[test]
fn test_panel_status_is_online() {
    let online: PanelStatus<u32> = PanelStatus::Online(1);
    assert!(online.is_online());
    let offline: PanelStatus<u32> = PanelStatus::Offline {
        last_error: "x".into(),
    };
    assert!(!offline.is_online());
    let connecting: PanelStatus<u32> = PanelStatus::Connecting;
    assert!(!connecting.is_online());
}

#[test]
fn test_reindex_target() {
    let mut state = DashboardState::new("http://a", "http://b");
    // No target while connecting.
    assert_eq!(state.reindex_target(), None);
    // Online search panel, focused: first index id is the target.
    state.search.status = PanelStatus::Online(sample_search());
    assert_eq!(state.reindex_target(), Some("cto".to_string()));
    // Memory focus disables the reindex target.
    state.focus = Focus::Memory;
    assert_eq!(state.reindex_target(), None);
}

#[test]
fn test_status_badge() {
    let online: PanelStatus<u32> = PanelStatus::Online(0);
    assert_eq!(status_badge(&online), ('●', "ONLINE", Color::Green));
    let connecting: PanelStatus<u32> = PanelStatus::Connecting;
    assert_eq!(
        status_badge(&connecting),
        ('◌', "CONNECTING", Color::Yellow)
    );
    let offline: PanelStatus<u32> = PanelStatus::Offline {
        last_error: "x".into(),
    };
    assert_eq!(status_badge(&offline), ('○', "OFFLINE", Color::Red));
}

#[test]
fn test_truncate() {
    assert_eq!(truncate("short", 16), "short");
    assert_eq!(truncate("0123456789abcdefghij", 8), "0123456…");
    assert_eq!(truncate("exactlyeight", 12), "exactlyeight");
}

#[test]
fn test_palace_row_project() {
    // Auto-registered description → basename of the path.
    let row = PalaceRow {
        id: "trusty-search".into(),
        name: "trusty-search".into(),
        description: Some("Auto-registered from /Users/masa/Projects/trusty-search".into()),
        ..Default::default()
    };
    assert_eq!(row.project(), "trusty-search");

    // No description → falls back to the palace name.
    let bare = PalaceRow {
        id: "p1".into(),
        name: "notes".into(),
        ..Default::default()
    };
    assert_eq!(bare.project(), "notes");

    // Unexpected description shape → fall back to the name.
    let weird = PalaceRow {
        id: "p2".into(),
        name: "weird".into(),
        description: Some("hand-made palace".into()),
        ..Default::default()
    };
    assert_eq!(weird.project(), "weird");

    // Trailing slash should not yield an empty basename.
    let trailing = PalaceRow {
        id: "p3".into(),
        name: "fallback".into(),
        description: Some("Auto-registered from /tmp/".into()),
        ..Default::default()
    };
    assert_eq!(trailing.project(), "fallback");
}

#[test]
fn test_index_row_project() {
    // A populated root_path yields its basename.
    let row = IndexRow {
        id: "trusty".into(),
        root_path: "/Users/masa/Projects/trusty-tools".into(),
        ..Default::default()
    };
    assert_eq!(row.project(), "trusty-tools");

    // An empty root_path falls back to the index id.
    let bare = IndexRow {
        id: "p1".into(),
        ..Default::default()
    };
    assert_eq!(bare.project(), "p1");

    // A trailing-slash root should still resolve to the directory name.
    let trailing = IndexRow {
        id: "p2".into(),
        root_path: "/tmp/repo/".into(),
        ..Default::default()
    };
    assert_eq!(trailing.project(), "repo");
}

#[test]
fn test_help_text_lists_bindings() {
    let text = help_text();
    for token in ["Tab", "r ", "?", "Esc", "q "] {
        assert!(text.contains(token), "help text missing {token}");
    }
}

#[test]
fn test_render_smoke() {
    // A full render of a fully-online dashboard, wide and narrow, must not
    // panic and must exercise the help overlay path.
    let state = DashboardState {
        search: DaemonPanel {
            status: PanelStatus::Online(sample_search()),
            base_url: "http://127.0.0.1:7878".into(),
        },
        memory: DaemonPanel {
            status: PanelStatus::Online(sample_memory()),
            base_url: "http://127.0.0.1:7070".into(),
        },
        focus: Focus::Memory,
        show_help: true,
        last_action: Some("reindex queued".into()),
    };
    for (w, h) in [(140u16, 30u16), (90, 40)] {
        let backend = TestBackend::new(w, h);
        let mut terminal = Terminal::new(backend).expect("test terminal");
        terminal
            .draw(|f| render(f, &state))
            .expect("render must not panic");
    }
}