strop-engine 0.35.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
//! Picker glue: workers post onto the editor event loop, every stream
//! owned by an exact ticket (R9): registration precedes launch, every
//! request settles exactly once, and stale streams die at the handler
//! instead of against the model (0020 §2).

use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::mpsc::{channel, Receiver};

use strop_core::worker::{CancelHandle, CancelReason, Load, Ticket, WorkerId};
use strop_picker::{Item, Kind, Payload, Picker, PickerMsg};

use super::{Editor, Key};

mod accept;
mod drain;
mod keys;
#[cfg(test)]
mod lifecycle_traces;
mod open;
mod preview;
mod query;
#[cfg(test)]
mod query_tests;
pub(crate) mod ranking;
mod replace;
pub(crate) mod status;
pub use replace::checked_hit_range;
pub use replace::ReplacementHit;
pub(crate) mod search;
pub use search::SearchScope;
#[cfg(test)]
mod search_tests;
#[cfg(test)]
mod tests;

/// One picker instance's identity, allocated from the editor's worker
/// id pool when the picker opens. Every streaming request and preview
/// read binds to it — closing the picker invalidates them all at once.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
#[serde(transparent)]
pub struct PickerId(pub WorkerId);

/// What one streaming picker request owns: which instance, against
/// which working directory.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct PickerKey {
    pub picker: PickerId,
    #[serde(with = "strop_core::path_serde")]
    pub cwd: PathBuf,
}

/// A worker message stamped with the request that produced it. Both
/// the TUI's forwarded events and the headless drain deliver these;
/// only the owning ticket may touch the model.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct PickerEvent {
    pub ticket: Ticket<PickerKey>,
    pub msg: PickerMsg,
}

/// One supervised preview read: the picker instance it serves and the
/// namespace-qualified resource being read.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct PreviewKey {
    pub picker: PickerId,
    pub path: strop_workspace::ResourceLocation,
}

/// The terminal result of a preview request.
pub type PreviewResult = strop_core::worker::Completion<PreviewKey, preview::PreparedPreview>;

pub(crate) use status::ProjectStatus;

pub struct PickerGlue {
    pub picker: Picker,
    /// Normal-mode key sequences on the picker fields: counts, pending
    /// operators, motion text (the vim grammar, 0003 §2).
    pub(crate) field_keys: super::field::FieldMachine,
    pub id: PickerId,
    /// The request owning the stream: set at launch, cleared by its
    /// terminal Finished event or by cancellation.
    pub(crate) active: Option<Ticket<PickerKey>>,
    /// Headless only: the active request's raw stream (the TUI gets a
    /// ticket-stamping bridge at launch instead).
    pub(crate) rx: Option<(Ticket<PickerKey>, Receiver<PickerMsg>)>,
    pub(crate) worker: Option<CancelHandle>,
    pub(crate) lsp_context: Option<strop_lsp::ReplyContext>,
    pub(crate) rank_worker: Option<strop_picker::RankingWorker<ranking::Key>>,
    pub rank_pending: Option<Ticket<ranking::Key>>,
    /// Coalesce catalog/query changes while one rank snapshot is in flight.
    pub(crate) rank_dirty: bool,
    pub(crate) ranked_query: Option<String>,
    pub(crate) rank_alive: bool,
    pub(crate) accept_when_ranked: bool,
    /// The manual query-suggestion list (0051 R02): ctrl-space opens
    /// it; it owns accept/cancel keys until dismissed.
    pub suggestions: Option<SuggestionList>,
    pub query_highlights: Vec<strop_picker::query::HighlightSpan>,
    pub query_summary: String,
    pub(crate) query: Option<std::sync::Arc<strop_picker::query::SearchQuery>>,
    file_scope: Option<std::sync::Arc<strop_picker::query::SearchQuery>>,
    pub(crate) indent_target: Option<strop_core::id::DocumentId>,
    pub(crate) search: Option<search::SearchContext>,
    preview_witness: Option<preview::WitnessCheck>,
    /// Workspace-symbols ownership (0063 §2): bumped on every query
    /// change; only the live generation's replies merge.
    pub(crate) wsymbols_generation: u64,
    /// Per-project warm-attach outcomes (0063 §2), keyed by project
    /// root: the source of truth behind the picker's pinned status rows.
    /// Recorded at every warm-up decision point; lives and dies with
    /// the workspace-symbols surface that owns it.
    pub(crate) project_statuses: Vec<(PathBuf, ProjectStatus)>,
    /// The document-symbols reply, retained whole (0063 §3):
    /// `textDocument/documentSymbol` carries no query, so Boolean and
    /// `kind:` narrowing re-filters these candidates locally as the
    /// picker's query changes.
    pub(crate) symbols_candidates: Vec<strop_lsp::ProtoSymbol>,
}

/// The visible suggestion list: static candidates from the query's own
/// parse position — never an LSP or a filesystem scan.
pub struct SuggestionList {
    pub items: Vec<strop_picker::query::suggest::Suggestion>,
    pub selected: usize,
}

impl PickerGlue {
    /// A picker with no request yet: `Editor::set_picker` allocates the
    /// instance identity before the glue is installed; Files/grep
    /// requests are launched afterwards by `Editor::open_picker` and
    /// `picker_input_changed`. (LSP location lists never launch one.)
    pub fn diagnostics(picker: Picker) -> Self {
        Self {
            picker,
            field_keys: super::field::FieldMachine::default(),
            id: PickerId(WorkerId::new(0)), // replaced on install
            active: None,
            rx: None,
            worker: None,
            lsp_context: None,
            rank_worker: None,
            rank_pending: None,
            rank_dirty: false,
            ranked_query: None,
            rank_alive: false,
            accept_when_ranked: false,
            suggestions: None,
            query_highlights: Vec::new(),
            query_summary: String::new(),
            project_statuses: Vec::new(),
            file_scope: None,
            query: None,
            indent_target: None,
            search: None,
            preview_witness: None,
            symbols_candidates: Vec::new(),
            wsymbols_generation: 0,
        }
    }

    /// Revoke the active request without touching the model: cancel
    /// the worker (a queued terminal event is rejected later — it
    /// cannot regain authority) and drop the raw stream.
    fn revoke(&mut self, reason: CancelReason) {
        self.rx = None;
        if self.active.take().is_some() {
            if let Some(worker) = self.worker.take() {
                worker.cancel(reason);
            }
        }
    }
}

impl Editor {
    /// Install a picker: tears down any previous instance (revoking
    /// its streams and previews) and allocates a fresh identity from
    /// the worker id pool.
    pub(crate) fn set_picker(&mut self, mut glue: PickerGlue) {
        // Warm-up is on demand (0063 §2): another surface installing
        // ends the queue — servers never start for a closed picker.
        if glue.picker.kind != Kind::WorkspaceSymbols {
            self.lsp_state.attach.warm_queue.clear();
            self.lsp_state.attach.warm_attempts.clear();
        }
        self.cancel_pending();
        self.close_picker();
        let id = match self.worker_ids.allocate() {
            Ok(id) => id,
            Err(error) => {
                self.message = error.message;
                return;
            }
        };
        glue.preview_witness = None;
        glue.id = PickerId(id);
        if glue.picker.kind == Kind::Search && glue.search.is_none() {
            match self.new_search_context(SearchScope {
                root: strop_workspace::ResourceLocation::local(self.cwd.clone()),
            }) {
                Ok(context) => glue.search = Some(context),
                Err(error) => {
                    self.message = error;
                    return;
                }
            }
        }
        strop_trace::record_with(strop_trace::EventKind::JobStarted, || {
            serde_json::json!({
                "service":"picker","id":id.get(),
                "kind":glue.picker.kind.title().trim(),"streaming":glue.picker.streaming,
            })
        });
        self.picker = Some(glue);
        if self
            .picker
            .as_ref()
            .is_some_and(|glue| glue.picker.kind != Kind::RemoteAddress)
        {
            self.start_picker_ranking();
        }
    }

    /// Register headless delivery before launch, or stamp directly onto the live
    /// app queue. Source restarts never allocate per-request bridge threads.
    fn picker_source_sink(&mut self, ticket: Ticket<PickerKey>) -> strop_picker::SourceSink {
        if let Some(app_tx) = self.app_tx.clone() {
            return strop_picker::SourceSink::new(move |msg| {
                app_tx
                    .send(super::events::AppEvent::Picker(PickerEvent {
                        ticket: ticket.clone(),
                        msg,
                    }))
                    .is_ok()
            });
        }
        let (tx, rx) = channel();
        if let Some(glue) = self.picker.as_mut() {
            glue.rx = Some((ticket, rx));
        }
        tx.into()
    }

    /// Connect-time: hand any already-registered headless stream to
    /// the app channel (normally requests attach at launch).
    pub(crate) fn connect_picker_stream(&mut self, tx: &super::events::EventSender) {
        if let Some(glue) = &mut self.picker {
            if let Some((ticket, rx)) = glue.rx.take() {
                if let Err(error) = drain::forward_picker_stream(rx, ticket.clone(), tx.clone()) {
                    let _ = tx.send(super::events::AppEvent::Picker(PickerEvent {
                        ticket,
                        msg: PickerMsg::Finished(strop_core::worker::Outcome::failed(
                            strop_core::worker::FailureKind::ThreadStart,
                            format!("picker bridge: {error}"),
                        )),
                    }));
                }
            }
        }
    }

    /// Close the picker: revoke its active request, stop its worker,
    /// and cancel/forget the previews it owns (failed reads become
    /// retryable on reopen; retained successful bytes must be revalidated).
    pub fn close_picker(&mut self) {
        let Some(mut glue) = self.picker.take() else {
            return;
        };
        glue.revoke(CancelReason::OwnerClosed);
        self.revoke_remote_chooser(glue.id);
        self.revoke_filesystem_actions(glue.id);
        self.revoke_picker_previews(glue.id);
        if glue.rank_alive {
            self.picker_ranking.retiring.insert(glue.id);
        }
        if glue.picker.kind == Kind::Search {
            drop(glue.rank_worker.take());
            self.retain_search(glue);
        } else if let Some(worker) = glue.rank_worker.take() {
            if let Err(error) = worker.retire(glue.picker) {
                self.message = format!("picker cleanup failed: {error}");
            }
        }
    }

    pub fn picker_open(&self) -> bool {
        self.picker.is_some()
    }

    /// Cancel/forget every preview this picker instance owns. Running
    /// requests are cancelled; Failed/Cancelled loads and their blank
    /// cache entries are removed so an explicit reopen retries; Ready
    /// bytes stay within the cache bound but are not current in a new picker.
    fn revoke_picker_previews(&mut self, picker: PickerId) {
        let mut cancelled = Vec::new();
        let mut forgotten = Vec::new();
        self.preview_loads.retain(|path, load| match load {
            Load::Running(ticket) if ticket.key.picker == picker => {
                cancelled.push(ticket.request);
                false
            }
            Load::Failed { key, .. } | Load::Cancelled { key, .. } if key.picker == picker => {
                forgotten.push(path.clone());
                false
            }
            _ => true,
        });
        for request in cancelled {
            if let Some(handle) = self.worker_handles.remove(&request) {
                handle.cancel(CancelReason::OwnerClosed);
            }
        }
        for path in forgotten {
            self.previews.remove(&path);
            self.analysis
                .forget(super::analysis::AnalysisTarget::Preview(path));
        }
    }

    pub(crate) fn accept_current_picker(&mut self) {
        if self
            .picker
            .as_ref()
            .is_some_and(|glue| glue.picker.kind == Kind::RemoteAddress)
        {
            self.accept_remote_address();
            return;
        }
        let Some(glue) = self.picker.as_mut() else {
            return;
        };
        if matches!(glue.picker.kind, Kind::Files | Kind::Search) {
            if let Some(error) = &glue.picker.error {
                self.message = error.clone();
                return;
            }
        }
        let replacing = glue.picker.kind == Kind::Search
            && glue.picker.replacement_visible
            && glue.picker.field == strop_picker::Field::Replace;
        if glue.rank_pending.is_some()
            || ((replacing || glue.picker.current().is_none()) && glue.picker.streaming)
        {
            glue.accept_when_ranked = true;
            return;
        }
        glue.accept_when_ranked = false;
        if replacing {
            self.prepare_search_review();
            return;
        }
        let payload = glue.picker.current().map(|item| item.payload.clone());
        // RemoteHosts: the pinned "Add a host…" row keeps one meaning —
        // open the address box. Typed filter text comes along as the
        // draft, so a hostname that matched no listed destination isn't
        // lost (0.21.0 field report), and typing "Add" can't connect to
        // a host literally named "add".
        if glue.picker.kind == Kind::RemoteHosts && matches!(payload, Some(Payload::RemoteConnect))
        {
            let draft = {
                let text = glue.picker.input.text().trim();
                // Filter text that matches the pinned row's own label was
                // aimed AT the row ("Add"); only text that matched
                // nothing — a bare hostname — becomes the address draft.
                let aimed_at_row = glue
                    .picker
                    .current()
                    .is_some_and(|item| strop_picker::fuzzy_score(text, &item.text).is_some());
                (!aimed_at_row).then(|| text.to_string())
            };
            self.close_picker();
            self.open_remote_address();
            if let Some(draft) = draft.filter(|draft| !draft.is_empty()) {
                if let Some(glue) = self.picker.as_mut() {
                    glue.picker.paste(&draft);
                }
            }
            return;
        }
        // TabSize: every row is an IndentChoice; the typed filter text
        // rides along so the pinned custom row can validate it as a
        // width (the RemoteHosts draft pattern, 0.21.0).
        if glue.picker.kind == Kind::TabSize {
            let draft = glue.picker.input.text().trim().to_string();
            let Some(Payload::IndentChoice(choice)) = payload else {
                self.message = "no matching entries".into();
                return;
            };
            let Some(document) = glue.indent_target else {
                self.message = "indentation selector lost its source — reopen :tab-size".into();
                return;
            };
            self.close_picker();
            self.accept_indent_choice(document, choice, &draft);
            return;
        }
        if glue.picker.kind == Kind::FilesystemActions {
            let Some(Payload::FilesystemAction(index)) = payload else {
                self.message = "no matching filesystem action".into();
                return;
            };
            let picker = glue.id;
            self.accept_filesystem_action(picker, index);
            return;
        }
        let Some(payload) = payload else {
            self.message = "no matching entries".into();
            return;
        };
        if glue.picker.kind == Kind::Search {
            self.open_search_hit(payload);
            return;
        }
        let context = glue.lsp_context;
        self.close_picker();
        self.accept_picker(payload, context);
    }

    pub(crate) fn finish_pending_picker_accept(&mut self) {
        if self.picker.as_ref().is_some_and(|glue| {
            glue.accept_when_ranked
                && glue.rank_pending.is_none()
                && (!(glue.picker.kind == Kind::Search
                    && glue.picker.replacement_visible
                    && glue.picker.field == strop_picker::Field::Replace)
                    || !glue.picker.streaming)
        }) {
            self.accept_current_picker();
        }
    }
}

pub struct PreviewEntry {
    pub rope: ropey::Rope,
}

pub enum PreviewSource {
    Buffer(strop_core::id::DocumentId),
    Cached(strop_workspace::ResourceLocation),
    Loading,
    Failed(String),
    Cancelled(CancelReason),
}

pub type Previews = HashMap<strop_workspace::ResourceLocation, PreviewEntry>;