quinjet 0.0.74

A fast, live, keyboard-first Git source-control interface for the terminal
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
use std::time::Duration;

use ratatui::Terminal;
use ratatui::backend::TestBackend;

use super::*;
use crate::git::diff::ImageSide;
use crate::theme::{Appearance, Theme, ThemeName};
use crate::ui::image_diff::tests::{image_line, preview};
use crate::ui::image_diff::{ImageDrawState, PreparationFrame, Rect, draw_image_line};

struct ControlledEncoder {
    requests: Receiver<Vec<PreparationRequest>>,
    completed: Sender<PreparationResult>,
}

impl ControlledEncoder {
    fn install() -> Self {
        let (requests, queued) = bounded(1);
        let (completed, results) = bounded(MAX_PENDING_IMAGES);
        IMAGE_PREPARATION.with(|preparation| {
            *preparation.borrow_mut() = ImagePreparation {
                encoded: Vec::new(),
                wanted: Vec::new(),
                pending: Vec::new(),
                encoder: Some(Encoder {
                    requests,
                    queued: queued.clone(),
                    completed: results,
                }),
                unavailable: false,
            };
        });
        Self {
            requests: queued,
            completed,
        }
    }

    fn finish(&self, request: PreparationRequest) {
        let display = prepare_native(&request.key);
        self.completed
            .send(PreparationResult { request, display })
            .expect("test completion");
    }
}

#[test]
fn pending_images_render_halfblocks_before_native_completion_and_request_repaint() {
    for (protocol, marker) in [
        (ImageProtocol::Kitty, "\x1b_G"),
        (ImageProtocol::Iterm2, "]1337;File=inline=1"),
        (ImageProtocol::Sixel, "\x1bP"),
    ] {
        let encoder = ControlledEncoder::install();
        let mut terminal = Terminal::new(TestBackend::new(32, 4)).expect("test terminal");
        let image = preview(ImageSide::New);
        let mut last_row = image.clone();
        last_row.row = 1;
        let rows = [image_line(image), image_line(last_row)];
        let theme = Theme::new(ThemeName::Quinjet, Appearance::Dark);
        let render = |frame: &mut ratatui::Frame<'_>| {
            let _images = PreparationFrame::begin();
            let mut state = ImageDrawState::new(true);
            for (row, line) in rows.iter().enumerate() {
                let row = u16::try_from(row).expect("test row");
                draw_image_line(
                    frame,
                    Rect::new(0, row, 32, 1),
                    line,
                    4 - row,
                    &theme,
                    protocol,
                    &mut state,
                );
            }
        };
        let _frame = terminal.draw(render).expect("pending frame");
        assert_eq!(
            terminal
                .backend()
                .buffer()
                .cell((0, 1))
                .expect("fallback row")
                .symbol(),
            "â–€"
        );
        assert!(
            terminal
                .backend()
                .buffer()
                .content()
                .iter()
                .all(|cell| !cell.symbol().contains('\x1b')),
            "pending {protocol:?} must render without native payloads"
        );
        assert!(
            !image_preparation_ready(),
            "pending image has no completion"
        );
        let requests = encoder.requests.try_recv().expect("pending requests");
        assert_eq!(requests.len(), 1, "one request per raster and size");
        for request in requests {
            encoder.finish(request);
        }
        assert!(
            image_preparation_ready(),
            "native completion requests repaint"
        );
        assert!(
            !image_preparation_ready(),
            "completion requests one repaint"
        );
        let _frame = terminal.draw(render).expect("native frame");
        assert!(
            terminal
                .backend()
                .buffer()
                .cell((0, 0))
                .expect("native row")
                .symbol()
                .contains(marker),
            "completed {protocol:?} renders its native payload"
        );
        assert!(
            encoder.requests.is_empty(),
            "cached frames do not enqueue another encoding"
        );
    }
}

#[test]
fn resize_raster_and_protocol_churn_coalesces_and_rejects_old_generation() {
    let encoder = ControlledEncoder::install();
    let first = key(5, ImageProtocol::Kitty);
    request_frame(std::slice::from_ref(&first));
    let original = encoder
        .requests
        .try_recv()
        .expect("first request")
        .remove(0);
    let replacement = key(4, ImageProtocol::Iterm2);
    let alternate = key(3, ImageProtocol::Sixel);
    for pass in 0..1_000_u16 {
        let protocol = match pass % 3 {
            0 => ImageProtocol::Kitty,
            1 => ImageProtocol::Iterm2,
            _ => ImageProtocol::Sixel,
        };
        let mut next = replacement.clone();
        next.raster = Arc::clone(if pass % 2 == 0 {
            &replacement.raster
        } else {
            &alternate.raster
        });
        next.width = pass % 10 + 1;
        next.height = pass % 5 + 1;
        next.protocol = protocol;
        request_frame(&[next]);
        IMAGE_PREPARATION.with(|preparation| {
            let preparation = preparation.borrow();
            assert_eq!(
                preparation.pending.len(),
                1,
                "only the current dimensions remain pending"
            );
            assert_eq!(
                preparation.wanted.len(),
                1,
                "only the current raster remains desired"
            );
            assert!(
                preparation.encoded.len() <= preparation.wanted.len() + MAX_OFFSCREEN_IMAGES,
                "encoded cache is bounded by the viewport and offscreen allowance"
            );
            assert_eq!(
                preparation.encoder.as_ref().expect("encoder").queued.len(),
                1,
                "one coalesced batch is queued"
            );
        });
    }
    request_frame(std::slice::from_ref(&first));
    encoder.finish(original);
    assert!(
        !image_preparation_ready(),
        "an obsolete ticket cannot fill an identical newer request"
    );
    IMAGE_PREPARATION.with(|preparation| {
        assert!(
            preparation.borrow().encoded.is_empty(),
            "stale results do not enter the cache"
        );
    });
    let current = encoder.requests.try_recv().expect("current request");
    for request in current {
        encoder.finish(request);
    }
    assert!(
        image_preparation_ready(),
        "the current generation becomes ready"
    );
    IMAGE_PREPARATION.with(|preparation| {
        let preparation = preparation.borrow();
        assert_eq!(
            preparation.encoded.len(),
            1,
            "only the current generation is cached"
        );
        assert!(
            preparation
                .encoded
                .first()
                .expect("current image")
                .key
                .matches(&first),
            "raster identity, protocol, and dimensions match"
        );
    });
}

#[test]
fn images_leaving_the_frame_cancel_pending_completions() {
    let encoder = ControlledEncoder::install();
    request_frame(&[key(5, ImageProtocol::Kitty)]);
    let request = encoder
        .requests
        .try_recv()
        .expect("pending request")
        .remove(0);
    request_frame(&[]);
    assert!(
        !request.ticket.valid(),
        "leaving the viewport cancels the ticket"
    );
    encoder.finish(request);
    assert!(
        !image_preparation_ready(),
        "offscreen completion does not request a repaint"
    );
    IMAGE_PREPARATION.with(|preparation| {
        let preparation = preparation.borrow();
        assert!(
            preparation.pending.is_empty(),
            "offscreen requests are removed"
        );
        assert!(
            preparation.encoded.is_empty(),
            "offscreen results are rejected"
        );
    });
}

#[test]
fn failed_preparation_keeps_fallback_without_repeating_work() {
    let encoder = ControlledEncoder::install();
    let invalid = ImageKey {
        raster: Arc::new(ImageRaster {
            width: 2,
            height: 2,
            rgba: vec![255; 3],
        }),
        protocol: ImageProtocol::Kitty,
        width: 5,
        height: 2,
    };
    request_frame(std::slice::from_ref(&invalid));
    let request = encoder
        .requests
        .try_recv()
        .expect("invalid request")
        .remove(0);
    encoder.finish(request);
    assert!(
        image_preparation_ready(),
        "failed encoding completes its slot and lets other visible images prepare"
    );
    request_frame(std::slice::from_ref(&invalid));
    assert!(
        encoder.requests.is_empty(),
        "failed identities are not encoded repeatedly"
    );
    IMAGE_PREPARATION.with(|preparation| {
        let preparation = preparation.borrow();
        assert!(preparation.pending.is_empty(), "failed work is removed");
        assert!(
            preparation
                .encoded
                .first()
                .expect("failed cache entry")
                .display
                .is_none(),
            "failed encoding remains a halfblock fallback"
        );
    });
}

#[test]
fn every_visible_image_prepares_in_bounded_batches_and_remains_cached() {
    let encoder = ControlledEncoder::install();
    let images = (1..=6)
        .map(|width| key(width, ImageProtocol::Kitty))
        .collect::<Vec<_>>();
    for expected in [MAX_PENDING_IMAGES, 2] {
        request_frame(&images);
        let requests = encoder.requests.try_recv().expect("bounded requests");
        assert_eq!(requests.len(), expected, "one bounded preparation batch");
        for request in requests {
            encoder.finish(request);
        }
        assert!(image_preparation_ready(), "current images complete");
    }
    request_frame(&images);
    assert!(encoder.requests.is_empty(), "every visible image is cached");
    IMAGE_PREPARATION.with(|preparation| {
        let mut preparation = preparation.borrow_mut();
        assert_eq!(preparation.encoded.len(), images.len());
        assert_eq!(preparation.wanted.len(), images.len());
        assert!(preparation.pending.is_empty(), "completed work is removed");
        for image in &images {
            assert!(
                preparation
                    .display(image.clone())
                    .expect("cached image")
                    .display
                    .is_some(),
                "the fifth and later visible images retain native output"
            );
        }
    });
    request_frame(&[]);
    IMAGE_PREPARATION.with(|preparation| {
        assert_eq!(
            preparation.borrow().encoded.len(),
            MAX_OFFSCREEN_IMAGES,
            "only four offscreen encodings remain"
        );
    });
}

#[test]
fn failed_first_batch_does_not_starve_a_later_visible_image() {
    let encoder = ControlledEncoder::install();
    let images = (1..=5)
        .map(|width| key(width, ImageProtocol::Kitty))
        .collect::<Vec<_>>();
    request_frame(&images);
    for request in encoder.requests.try_recv().expect("first batch") {
        encoder
            .completed
            .send(PreparationResult {
                request,
                display: None,
            })
            .expect("failed result");
    }
    assert!(
        image_preparation_ready(),
        "completed slots request a repaint"
    );
    request_frame(&images);
    let requests = encoder.requests.try_recv().expect("remaining batch");
    assert_eq!(requests.len(), 1);
    for request in requests {
        encoder.finish(request);
    }
    assert!(image_preparation_ready(), "the fifth image becomes ready");
    request_frame(&images);
    assert!(encoder.requests.is_empty(), "failed keys are not retried");
}

#[test]
fn a_single_encoder_keeps_only_the_latest_batch_while_a_job_is_in_flight() {
    let (started, starts) = bounded(1);
    let (release, releases) = bounded(1);
    let encoder = Encoder::start(move |key| {
        started
            .send((key.clone(), thread::current().id()))
            .expect("encoding started");
        releases
            .recv_timeout(Duration::from_secs(10))
            .expect("encoding released");
        prepare_native(key)
    })
    .expect("test encoder thread");
    IMAGE_PREPARATION.with(|preparation| {
        *preparation.borrow_mut() = ImagePreparation {
            encoded: Vec::new(),
            wanted: Vec::new(),
            pending: Vec::new(),
            encoder: Some(encoder),
            unavailable: false,
        };
    });
    let initial = key(5, ImageProtocol::Kitty);
    request_frame(&[initial]);
    let (_, encoder_thread) = starts
        .recv_timeout(Duration::from_secs(10))
        .expect("initial encoding");
    assert_ne!(
        encoder_thread,
        thread::current().id(),
        "encoding runs off the rendering thread"
    );
    let mut latest = key(3, ImageProtocol::Iterm2);
    for pass in 0..1_000_u16 {
        latest.width = pass % 10 + 1;
        latest.protocol = if pass % 2 == 0 {
            ImageProtocol::Kitty
        } else {
            ImageProtocol::Iterm2
        };
        request_frame(std::slice::from_ref(&latest));
    }
    release.send(()).expect("release stale encoding");
    let (started_key, next_thread) = starts
        .recv_timeout(Duration::from_secs(10))
        .expect("latest encoding");
    assert!(
        started_key.matches(&latest),
        "the encoder skips superseded batches"
    );
    assert_eq!(
        encoder_thread, next_thread,
        "one worker services every request"
    );
    release.send(()).expect("release current encoding");
    IMAGE_PREPARATION.with(|preparation| {
        let mut preparation = preparation.borrow_mut();
        let completed = preparation
            .encoder
            .as_ref()
            .expect("encoder")
            .completed
            .recv_timeout(Duration::from_secs(10))
            .expect("current completion");
        assert!(
            preparation.accept(completed),
            "only the current image is published"
        );
        assert_eq!(
            preparation.encoded.len(),
            1,
            "the obsolete in-flight image was dropped"
        );
        assert!(
            preparation
                .encoded
                .first()
                .expect("current image")
                .key
                .matches(&latest),
            "the current identity is cached"
        );
        assert!(
            preparation
                .encoder
                .as_ref()
                .expect("encoder")
                .completed
                .is_empty(),
            "stale encodings do not publish results"
        );
        *preparation = ImagePreparation::default();
    });
}

fn key(width: u16, protocol: ImageProtocol) -> ImageKey {
    ImageKey {
        raster: Arc::new(ImageRaster {
            width: 2,
            height: 2,
            rgba: vec![255; 16],
        }),
        protocol,
        width,
        height: 2,
    }
}

fn request_frame(images: &[ImageKey]) {
    let _frame = PreparationFrame::begin();
    IMAGE_PREPARATION.with(|preparation| {
        let mut preparation = preparation.borrow_mut();
        for image in images {
            let _display = preparation.display(image.clone());
        }
    });
}