strop-engine 0.36.0

strop editor engine: documents, grammar, services and sessions — no frontend UI dependencies
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
use super::*;
use std::time::{Duration, Instant};

use crate::editor::{Document, DocumentSource, Key, Mode};
use strop_core::Buffer;
use strop_terminal::model::{Color, Style, Update};

fn retained_terminal(editor: &mut Editor) -> DocumentId {
    editor.terminal_fixture(
        &[("safe", Style::default())],
        Phase::Exited {
            code: Some(0),
            signal: None,
        },
    )
}

/// Drive the real service loop (worker PTY over the in-process codec)
/// until `condition` holds; failure to converge is a test failure with
/// the editor state attached, never a hang.
fn drain_until(editor: &mut Editor, condition: impl Fn(&Editor) -> bool, what: &str) {
    let deadline = Instant::now() + Duration::from_secs(10);
    while Instant::now() < deadline {
        editor.drain_terminals();
        if condition(editor) {
            return;
        }
        std::thread::sleep(Duration::from_millis(10));
    }
    assert!(
        condition(editor),
        "terminal never reached {what}: {}",
        editor.message
    );
}

fn live_text(editor: &Editor, document: DocumentId) -> String {
    editor
        .terminal_frame(document, true)
        .map(|frame| frame.projection.to_string())
        .unwrap_or_default()
}

/// 0058 WK12: the modal terminal's lifecycle rides the namespace's
/// worker end to end — spawn with geometry, fed input, bounded output,
/// an ordered resize the child's own `stty` attests, and a truthful
/// exit — with emulation and presentation still engine-owned.
#[test]
fn terminal_journey_runs_through_the_namespace_worker() {
    use strop_core::frontend_input::Input;

    let directory = tempfile::tempdir().unwrap();
    let mut editor = Editor::new_in(Buffer::from_text("origin"), directory.path().to_owned());
    editor.feed_text(":terminal\r");
    let document = editor.current();
    assert!(matches!(
        editor.doc(document).source,
        DocumentSource::Terminal(_)
    ));
    drain_until(
        &mut editor,
        |editor| matches!(editor.terminal_phase(document), Some(Phase::Running)),
        "the worker-admitted shell",
    );
    editor.feed_terminal(Input::Text("printf 'HI:%s\\n' x\n".into()));
    drain_until(
        &mut editor,
        |editor| live_text(editor, document).contains("HI:x"),
        "the fed command's output",
    );
    // The ordered resize boundary: after it, the child itself reports
    // the new winsize, and the projection keeps parsing truthfully.
    editor.prepare_terminal_geometry(document, 100, 30);
    drain_until(
        &mut editor,
        |editor| {
            editor
                .terminal_frame(document, true)
                .is_some_and(|frame| frame.geometry.columns == 100 && frame.geometry.rows == 30)
        },
        "the applied resize",
    );
    editor.feed_terminal(Input::Text("stty size\n".into()));
    drain_until(
        &mut editor,
        |editor| live_text(editor, document).contains("30 100"),
        "the child's attestation of the new geometry",
    );
    editor.feed_terminal(Input::Text("exit 3\n".into()));
    drain_until(
        &mut editor,
        |editor| {
            matches!(
                editor.terminal_phase(document),
                Some(Phase::Exited {
                    code: Some(3),
                    signal: None
                })
            )
        },
        "the truthful exit status",
    );
}

/// 0058 WK12 regression: a tiny-write flood (`yes` writes 2 bytes per
/// syscall) coalesces at the worker's pump instead of drowning the
/// bounded stream in per-write chunks — the tail always lands.
#[test]
fn terminal_flood_coalesces_without_losing_the_tail() {
    let directory = tempfile::tempdir().unwrap();
    let mut editor = Editor::new_in(Buffer::from_text("origin"), directory.path().to_owned());
    editor.feed_text(":terminal yes | head -c 16384; printf 'FLOOD-DONE\\n'; exit 0\r");
    let document = editor.current();
    drain_until(
        &mut editor,
        |editor| live_text(editor, document).contains("FLOOD-DONE"),
        "the flood completing",
    );
    drain_until(
        &mut editor,
        |editor| {
            matches!(
                editor.terminal_phase(document),
                Some(Phase::Exited { code: Some(0), .. })
            )
        },
        "exit",
    );
}

/// 0058 WK12: a one-shot command through the worker pins its final
/// frame into the terminal document with its exit status.
#[test]
fn terminal_command_exit_pins_the_final_frame() {
    let directory = tempfile::tempdir().unwrap();
    let mut editor = Editor::new_in(Buffer::from_text("origin"), directory.path().to_owned());
    editor.feed_text(":terminal printf 'DONE\\n'; exit 5\r");
    let document = editor.current();
    drain_until(
        &mut editor,
        |editor| {
            matches!(
                editor.terminal_phase(document),
                Some(Phase::Exited {
                    code: Some(5),
                    signal: None
                })
            )
        },
        "the command's exit",
    );
    drain_until(
        &mut editor,
        |editor| live_text(editor, document).contains("DONE"),
        "the final published frame",
    );
    // The exited terminal is a snapshot, never relaunchable.
    assert!(!editor.terminal_input_active());
}

#[test]
fn unsupported_remote_terminal_never_retargets_the_document_to_local_execution() {
    let directory = tempfile::tempdir().unwrap();
    let mut editor = Editor::new_in(Buffer::from_text("origin"), directory.path().to_owned());
    let location = strop_workspace::ResourceLocation::remote(
        strop_workspace::RemoteEndpoint::parse("ssh://fixture").unwrap(),
        "/workspace".into(),
    );
    let source = crate::editor::Directory::new(strop_workspace::DirectorySnapshot {
        location: location.clone(),
        entries: Arc::from([]),
        state: strop_workspace::ListingState::Complete,
    });
    let id = editor
        .docs
        .try_insert(Document::directory(
            Buffer::from_text(&source.text()),
            source,
        ))
        .unwrap();
    editor.switch_to(id);
    editor.feed_text(":terminal touch should-not-execute\r");
    assert_eq!(editor.current(), id);
    assert_eq!(editor.directory().unwrap().location, location);
    assert!(editor.terminals.entries.is_empty());
    assert!(editor.message.contains(":terminal-local"));
    assert!(!directory.path().join("should-not-execute").exists());
}

#[test]
fn terminal_snapshot_cannot_be_made_writable_saved_or_implicitly_relaunched() {
    let directory = tempfile::tempdir().unwrap();
    let mut editor = Editor::new_in(Buffer::from_text("origin"), directory.path().to_owned());
    let id = retained_terminal(&mut editor);
    editor.feed_text(":set noro\rdd:w! exported.txt\r");
    assert!(editor.buf().readonly);
    assert_eq!(editor.buf().text().to_string(), "safe\n");
    assert!(!directory.path().join("exported.txt").exists());
    assert!(matches!(editor.doc(id).source, DocumentSource::Terminal(_)));
    editor.feed(Key::Char('i'));
    assert!(!editor.terminal_input_active());
    assert_eq!(editor.terminals.entries.len(), 1);
    assert!(matches!(
        editor.terminal_phase(id),
        Some(Phase::Exited { code: Some(0), .. })
    ));
}

#[test]
fn terminal_window_prefix_moves_panes_without_reaching_the_child() {
    use strop_core::frontend_input::{Input, KeyCode, KeyEvent};

    let directory = tempfile::tempdir().unwrap();
    let mut editor = Editor::new_in(Buffer::from_text("left"), directory.path().to_owned());
    let id = retained_terminal(&mut editor);
    assert!(editor.enter_terminal_input());
    editor.split_pub('v');
    assert_eq!(editor.panes.len(), 2);
    let terminal_pane = editor.active_pane;

    let ctrl = |code: KeyCode| {
        Input::Key(KeyEvent {
            code,
            modifiers: strop_core::frontend_input::Modifiers {
                control: true,
                ..Default::default()
            },
            ..KeyEvent::press(code)
        })
    };
    // Ctrl-W opens the prefix; the follow-up moves focus off the terminal
    // pane without a single byte reaching the (service-less) child — the
    // message stays clear, proving no failed send was attempted.
    editor.feed_terminal(ctrl(KeyCode::Char('w')));
    editor.message.clear();
    editor.feed_terminal(Input::Key(KeyEvent::press(KeyCode::Char('l'))));
    assert_ne!(editor.active_pane, terminal_pane);
    assert!(editor.message.is_empty(), "{}", editor.message);
    assert!(editor.terminals.prefix.is_none());

    // the same prefix grammar escapes into pinned-snapshot inspection
    let mut other = Editor::new_in(Buffer::from_text("origin"), directory.path().to_owned());
    retained_terminal(&mut other);
    other.feed_terminal(ctrl(KeyCode::Char('w')));
    other.feed_terminal(Input::Key(KeyEvent::press(KeyCode::Char('N'))));
    assert_eq!(other.mode, crate::editor::Mode::Normal);
    assert!(other.message.contains("snapshot"), "{}", other.message);
    // the exited session was never relaunched by any of it
    assert!(matches!(
        editor.terminal_phase(id),
        Some(Phase::Exited { code: Some(0), .. })
    ));
}

/// 0065 S2 (invariant): focus loss cancels a pending escape prefix — a
/// later Ctrl-N goes to the child, never silently completes the escape.
#[test]
fn focus_loss_cancels_a_pending_terminal_escape_prefix() {
    use strop_core::frontend_input::{Input, KeyCode, KeyEvent, Modifiers};
    let mut editor = Editor::new(Buffer::from_text("origin"));
    editor.terminal_fixture(&[("safe", Style::default())], Phase::Running);
    editor.feed(Key::Char('i'));
    assert!(editor.terminal_input_active());
    let ctrl = |code: KeyCode| {
        Input::Key(KeyEvent {
            code,
            modifiers: Modifiers {
                control: true,
                ..Default::default()
            },
            ..KeyEvent::press(code)
        })
    };
    editor.feed_terminal(ctrl(KeyCode::Char('\\')));
    assert!(editor.terminals.prefix.is_some());
    editor.terminal_focus_changed(false);
    assert!(editor.terminals.prefix.is_none());
    editor.terminal_focus_changed(true);
    editor.feed_terminal(ctrl(KeyCode::Char('n')));
    assert!(editor.terminal_input_active());
    assert_eq!(editor.message, "terminal service unavailable");
}

#[test]
fn buffers_list_shows_terminals_with_their_live_phase() {
    let directory = tempfile::tempdir().unwrap();
    let mut editor = Editor::new_in(Buffer::from_text("origin"), directory.path().to_owned());
    retained_terminal(&mut editor);
    editor.open_picker(strop_picker::Kind::Buffers);
    let glue = editor.picker.as_ref().unwrap();
    let terminal_item = glue
        .picker
        .items
        .iter()
        .find(|item| item.text.starts_with("terminal #"))
        .expect("terminal listed in buffers");
    assert_eq!(terminal_item.badge.as_deref(), Some("!"));
    assert!(
        terminal_item.text.contains("exited 0"),
        "{}",
        terminal_item.text
    );
}

#[test]
fn private_terminal_command_paste_is_classified_before_action_capture() {
    use crate::editor::trace::drive::Action;
    use strop_core::frontend_input::Input;
    let mut editor = Editor::new_in(Buffer::from_text(""), "/workspace".into());
    let tape = std::rc::Rc::new(strop_trace::replay::Tape::fixture(|_, _| {
        Err(std::io::Error::other("unexpected native observation"))
    }));
    editor.tape = tape.clone();
    editor.feed_text(":termi");
    editor
        .recorded_action(
            Action::Event(crate::editor::events::AppEvent::Input(Input::Paste(
                "nal printf PRIVATE-COMMAND".into(),
            ))),
            tape.now(),
        )
        .unwrap();
    assert_eq!(editor.pending.text(), ":terminal printf PRIVATE-COMMAND");
    assert!(tape.content_omitted());
    assert!(!serde_json::to_string(&tape.fixture_nodes())
        .unwrap()
        .contains("PRIVATE-COMMAND"));
}

/// 0065 S0: the baseline modal journey as one deterministic spine —
/// enter input, child-bound keys, both escapes to inspection, motions,
/// yank, pinned output, explicit refresh, return to input.
#[test]
fn modal_terminal_baseline_journey() {
    use strop_core::frontend_input::{Input, KeyCode, KeyEvent, Modifiers};
    let directory = tempfile::tempdir().unwrap();
    let mut editor = Editor::new_in(Buffer::from_text("origin"), directory.path().to_owned());
    let id = editor.terminal_fixture(
        &[
            ("first", Style::default()),
            ("second", Style::default()),
            ("third", Style::default()),
        ],
        Phase::Running,
    );
    // i enters terminal-input: owner, view state and the honest message agree.
    editor.feed(Key::Char('i'));
    assert!(editor.terminal_input_active());
    assert_eq!(editor.input_owner(), crate::editor::InputOwner::Terminal);
    assert!(
        editor.message.contains("Ctrl-\\ Ctrl-N"),
        "{}",
        editor.message
    );
    // A raw key routes to the terminal path, never the grammar: the
    // cursor stays put and the (service-less) send reports its own
    // failure instead of moving like a Normal-mode j.
    let head = editor.head();
    editor.feed_terminal(Input::Key(KeyEvent::press(KeyCode::Char('j'))));
    assert_eq!(editor.head(), head);
    assert!(editor.terminal_input_active());
    assert_eq!(editor.message, "terminal service unavailable");
    // Ctrl-\ Ctrl-N leaves to pinned inspection.
    let ctrl = |code: KeyCode| {
        Input::Key(KeyEvent {
            code,
            modifiers: Modifiers {
                control: true,
                ..Default::default()
            },
            ..KeyEvent::press(code)
        })
    };
    editor.feed_terminal(ctrl(KeyCode::Char('\\')));
    editor.feed_terminal(ctrl(KeyCode::Char('n')));
    assert!(!editor.terminal_input_active());
    assert_eq!(editor.mode, Mode::Normal);
    assert!(editor.message.contains("snapshot"), "{}", editor.message);
    // Motions and yank operate on the projected text.
    editor.feed_text("j");
    assert_eq!(editor.buf().line_of(editor.head()), 1);
    editor.feed_text("yy");
    assert_eq!(editor.register(None).text, "second\n");
    // Output arriving under inspection stays pinned; the statusline
    // signal flips, the buffer does not.
    let session = editor.terminal_document(id).unwrap().session;
    let updated = fixture_frame(
        session,
        &[
            ("first", Style::default()),
            ("second", Style::default()),
            ("THIRD!", Style::default()),
        ],
        2,
        0,
    );
    editor.apply_terminal_update(Update {
        session,
        phase: Phase::Running,
        frame: Some(updated),
        effects: Vec::new(),
        acknowledged_input: 0,
        warning: None,
    });
    assert!(editor.terminal_has_new_output(id));
    assert!(!editor.buf().text().to_string().contains("THIRD!"));
    // The explicit refresh reinstalls the latest frame; positions map by
    // stream byte, so the same-width revision keeps the line-1 cursor.
    editor.feed_text(":terminal-refresh\r");
    assert!(editor.buf().text().to_string().contains("THIRD!"));
    assert!(!editor.terminal_has_new_output(id));
    assert!(editor.message.contains("refreshed"), "{}", editor.message);
    assert_eq!(editor.buf().line_of(editor.head()), 1);
    // i returns to live input, following the child's cursor.
    editor.feed(Key::Char('i'));
    assert!(editor.terminal_input_active());
}

/// 0065 S4: the refresh remap carries cursor and saved anchors across a
/// scrollback-shifted frame — the same content stays addressed.
#[test]
fn terminal_refresh_remaps_anchors_across_scrollback_drops() {
    let directory = tempfile::tempdir().unwrap();
    let mut editor = Editor::new_in(Buffer::from_text("origin"), directory.path().to_owned());
    let id = editor.terminal_fixture(
        &[
            ("dropped", Style::default()),
            ("kept-one", Style::default()),
            ("kept-two", Style::default()),
        ],
        Phase::Running,
    );
    // Cursor and mark a sit on "kept-one" (line 1, stream byte 9: the
    // padded "dropped " row plus its newline occupy 0..9).
    editor.feed_text("j0ma");
    assert_eq!(editor.head(), 9);
    // The child scrolled one row out: the new frame's stream origin moved
    // past "dropped \n".
    let session = editor.terminal_document(id).unwrap().session;
    let updated = fixture_frame(
        session,
        &[
            ("kept-one", Style::default()),
            ("kept-two", Style::default()),
            ("fresh", Style::default()),
        ],
        2,
        9,
    );
    editor.apply_terminal_update(Update {
        session,
        phase: Phase::Running,
        frame: Some(updated),
        effects: Vec::new(),
        acknowledged_input: 0,
        warning: None,
    });
    assert!(editor.terminal_has_new_output(id));
    assert!(editor.buf().text().to_string().starts_with("dropped"));
    editor.feed_text(":terminal-refresh\r");
    assert!(editor.buf().text().to_string().starts_with("kept-one"));
    // Cursor remapped to the same content: byte 9 of the old stream is
    // byte 0 of the refreshed projection.
    assert_eq!(editor.head(), 0);
    assert_eq!(editor.buf().line_of(editor.head()), 0);
    // The mark followed the same correspondence.
    editor.feed_text("G'a");
    assert_eq!(editor.head(), 0);
    assert_eq!(editor.buf().line_of(editor.head()), 0);
}

/// 0065 S4: the full motion surface over the projection — j/k, gg/G,
/// Ctrl-D/U, / and ? with n/N, and visual yank — asserted, not assumed.
#[test]
fn terminal_projection_supports_the_full_motion_surface() {
    let directory = tempfile::tempdir().unwrap();
    let mut editor = Editor::new_in(Buffer::from_text("origin"), directory.path().to_owned());
    editor.view_rows = 20;
    let mut rows: Vec<(String, Style)> = (0..30)
        .map(|index| (format!("filler {index:02}"), Style::default()))
        .collect();
    rows[5] = ("needle one".into(), Style::default());
    rows[20] = ("needle two".into(), Style::default());
    let refs: Vec<(&str, Style)> = rows.iter().map(|(t, s)| (t.as_str(), *s)).collect();
    editor.terminal_fixture(&refs, Phase::Running);
    // Ctrl-W N (vim's t_CTRL-W inspection) — the journey used Ctrl-\ Ctrl-N.
    editor.enter_terminal_input();
    editor.feed_terminal(strop_core::frontend_input::Input::Key(
        strop_core::frontend_input::KeyEvent {
            code: strop_core::frontend_input::KeyCode::Char('w'),
            modifiers: strop_core::frontend_input::Modifiers {
                control: true,
                ..Default::default()
            },
            ..strop_core::frontend_input::KeyEvent::press(
                strop_core::frontend_input::KeyCode::Char('w'),
            )
        },
    ));
    editor.feed_terminal(strop_core::frontend_input::Input::Key(
        strop_core::frontend_input::KeyEvent::press(strop_core::frontend_input::KeyCode::Char('N')),
    ));
    assert!(!editor.terminal_input_active());
    assert!(editor.message.contains("snapshot"));
    let line = |editor: &Editor| editor.buf().line_of(editor.head());
    editor.feed_text("G");
    assert_eq!(line(&editor), 29);
    editor.feed_text("gg");
    assert_eq!(line(&editor), 0);
    editor.feed_text("j");
    assert_eq!(line(&editor), 1);
    editor.feed_text("k");
    assert_eq!(line(&editor), 0);
    editor.feed(Key::CtrlD);
    assert_eq!(line(&editor), 10, "ctrl-d is a half page of 20 rows");
    editor.feed(Key::CtrlU);
    assert_eq!(line(&editor), 0);
    editor.feed_text("/needle\r");
    assert_eq!(line(&editor), 5);
    editor.feed_text("n");
    assert_eq!(line(&editor), 20);
    editor.feed_text("N");
    assert_eq!(line(&editor), 5);
    editor.feed_text("?needle\r");
    assert_eq!(line(&editor), 20, "? wraps to the previous hit");
    editor.feed_text("ggVGy");
    assert!(editor.register(None).text.contains("needle one"));
    assert!(editor.register(None).text.contains("filler 29"));
}

/// 0065 S4: wide/CJK cells keep their cell↔byte correspondence — motions
/// never land mid-cluster and styling resolves every byte of a wide
/// cluster to the same cell.
#[test]
fn wide_cells_keep_byte_mapping_and_motion_boundaries() {
    let wide = Style {
        foreground: Color::Indexed(2),
        ..Style::default()
    };
    let mut editor = Editor::new(Buffer::from_text("origin"));
    let id = editor.terminal_fixture(
        &[("ab東京cd", wide), ("plain", Style::default())],
        Phase::Exited {
            code: Some(0),
            signal: None,
        },
    );
    // Bytes: a=0 b=1 東=2..5 京=5..8 c=8 d=9. Motions land on cluster
    // starts only — never byte 3 or 4 inside 東.
    editor.feed_text("ll");
    assert_eq!(editor.head(), 2);
    editor.feed_text("l");
    assert_eq!(editor.head(), 5);
    editor.feed_text("l");
    assert_eq!(editor.head(), 8);
    // Every byte of a wide cluster resolves to that cluster's cell style.
    let at = |byte| {
        editor
            .terminal_style_at(id, byte)
            .map(|(style, _)| style.foreground)
    };
    assert_eq!(at(2), Some(Color::Indexed(2)));
    assert_eq!(at(3), Some(Color::Indexed(2)));
    assert_eq!(at(4), Some(Color::Indexed(2)));
    // A visual yank across the cluster boundary takes whole clusters.
    editor.feed_text("0vll");
    editor.feed_text("y");
    assert_eq!(editor.register(None).text, "ab東");
}