strop-engine 0.29.0

strop editor engine: documents, grammar dispatch, services, sessions — no terminal
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
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
//! File I/O is owned work. Only matching completions may publish into a view.
mod codec;
pub(super) mod native;
mod remote;
#[cfg(test)]
mod remote_tests;
mod save;
use super::{Document, Editor};
use crate::files::FileTarget;
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::mpsc::{self, Receiver, Sender};
use strop_core::id::{BufferRevision, ByteColumn, DocumentId, LineIndex};
use strop_core::worker::{self, Completion, FailureKind, Outcome, Ticket, WorkerId};
use strop_core::{Buffer, SaveReceipt};

#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum OpenIntent {
    Switch {
        readonly: bool,
    },
    Split {
        vertical: bool,
    },
    AtLine {
        line: LineIndex,
    },
    Refresh,
    Browse,
    DirectoryParent {
        child: strop_workspace::RemoteFile,
    },
    RemoteDestination,
    RemoteView {
        view: super::remote::RemoteView,
        line: Option<LineIndex>,
    },
    Grep {
        line: LineIndex,
        column: ByteColumn,
    },
    LspLocation {
        context: strop_lsp::ReplyContext,
        position: strop_lsp::ServerPosition,
    },
    Replace {
        hits: Vec<(usize, usize, usize, String)>,
        replacement: String,
        /// The pending replace review this open feeds (0051 §6 R04);
        /// a stale generation merges nowhere.
        review: usize,
    },
    /// Open without focus (0044 v2): collection builds load sources in
    /// the background; the picker keeps focus and focus never moves.
    CollectionSource {
        owner: WorkerId,
    },
}
impl OpenIntent {
    fn requires_file(&self) -> bool {
        match self {
            Self::AtLine { .. } | Self::Grep { .. } | Self::LspLocation { .. } => true,
            Self::RemoteView { view, line } => {
                line.is_some() || *view != super::remote::RemoteView::default()
            }
            _ => false,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct OpenKey {
    pub path: FileTarget,
    pub origin: DocumentId,
    pub revision: BufferRevision,
    pub focus: u64,
    pub intent: OpenIntent,
    pub selection: strop_remote::ReadSelection,
}

pub struct Opened {
    pub document: Document,
    pub canonical: FileTarget,
}

#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct SaveKey {
    pub document: DocumentId,
    pub revision: BufferRevision,
    pub focus: u64,
    pub close: bool,
    #[serde(with = "strop_core::path_serde::option")]
    pub target: Option<PathBuf>,
    pub force: bool,
}

#[derive(serde::Serialize, serde::Deserialize)]
pub enum IoEvent {
    Open(Box<Completion<OpenKey, Opened>>),
    Save(Box<Completion<SaveKey, SaveReceipt>>),
    Native(Box<Completion<native::NativeKey, native::NativeResult>>),
    Remote(super::remote::RemoteEvent),
    Session {
        request: WorkerId,
        outcome: Outcome<()>,
    },
}

pub struct IoState {
    pub tx: Sender<IoEvent>,
    pub rx: Option<Receiver<IoEvent>>,
    pub open: HashMap<WorkerId, OpenKey>,
    navigation: Option<WorkerId>,
    saves: HashMap<DocumentId, Ticket<SaveKey>>,
    session: Option<WorkerId>,
    queued_session: Option<crate::session::SaveRequest>,
    native: HashMap<WorkerId, native::NativeKey>,
    pub session_error: Option<String>,
    pub(crate) format_warnings: HashMap<DocumentId, String>,
}

impl Default for IoState {
    fn default() -> Self {
        let (tx, rx) = mpsc::channel();
        Self {
            tx,
            rx: Some(rx),
            open: HashMap::new(),
            navigation: None,
            saves: HashMap::new(),
            session: None,
            queued_session: None,
            native: HashMap::new(),
            session_error: None,
            format_warnings: HashMap::new(),
        }
    }
}

impl Editor {
    pub fn request_open(&mut self, path: PathBuf, intent: OpenIntent) {
        self.request_target(FileTarget::Local(path), intent);
    }

    pub fn request_target(&mut self, target: FileTarget, intent: OpenIntent) {
        if matches!(intent, OpenIntent::Refresh) && self.remote_write_blocks_refresh(self.current())
        {
            self.message =
                "remote save pending or unconfirmed; settle or :remote verify before refresh"
                    .into();
            return;
        }
        let selection = match &intent {
            OpenIntent::RemoteView { view, .. } => view.selection(),
            OpenIntent::Refresh => self
                .cur()
                .remote_metadata()
                .map_or(strop_remote::ReadSelection::Full, |source| source.selection),
            _ => strop_remote::ReadSelection::Full,
        };
        let requires_file = intent.requires_file();
        let browse = matches!(
            intent,
            OpenIntent::Browse | OpenIntent::DirectoryParent { .. }
        );
        if matches!(target, FileTarget::Local(_))
            && (browse
                || matches!(
                    intent,
                    OpenIntent::RemoteView { .. } | OpenIntent::RemoteDestination
                ))
        {
            self.message = "range/tail/follow views require a remote target".into();
            return;
        }
        let path = match target {
            FileTarget::Local(path) => FileTarget::Local(self.cwd.join(path)),
            remote => remote,
        };
        if !matches!(intent, OpenIntent::Replace { .. }) {
            self.cancel_open(worker::CancelReason::Superseded);
        }
        let existing = self.docs.iter().find_map(|(id, document)| {
            (document.matches_target(&path)
                && document
                    .remote_metadata()
                    .is_none_or(|source| source.selection == selection))
            .then_some(id)
        });
        if let Some(id) = existing.filter(|&id| {
            !matches!(intent, OpenIntent::Refresh)
                && (!matches!(intent, OpenIntent::Browse | OpenIntent::RemoteDestination)
                    || self.doc(id).directory_metadata_ref().is_none())
        }) {
            if (requires_file && self.doc(id).directory_metadata_ref().is_some())
                || (browse && self.doc(id).directory_metadata_ref().is_none())
            {
                self.message = if browse {
                    "browse requires a directory"
                } else {
                    "this view requires a regular file"
                }
                .into();
                return;
            }
            self.finish_open(id, intent);
            return;
        }
        let request = match self.worker_ids.allocate() {
            Ok(request) => request,
            Err(error) => {
                self.message = error.message;
                return;
            }
        };
        let key = OpenKey {
            path: path.clone(),
            origin: self.current(),
            revision: self.buf().revision(),
            focus: self.focus_epoch,
            intent,
            selection,
        };
        if !matches!(
            key.intent,
            OpenIntent::Replace { .. } | OpenIntent::CollectionSource { .. }
        ) {
            self.io.navigation = Some(request);
        }
        self.io.open.insert(request, key.clone());
        self.message = format!("loading {path}");
        let tx = self.io.tx.clone();
        let ticket = Ticket { request, key };
        match self.tape.request("io.open", &ticket) {
            Ok(false) => return,
            Ok(true) => {}
            Err(error) => {
                self.handle_io(IoEvent::Open(Box::new(Completion {
                    ticket,
                    outcome: Outcome::failed(FailureKind::Protocol, error.to_string()),
                })));
                return;
            }
        }
        let client = self.remote_client();
        let handle = worker::spawn(
            "strop-open",
            move |outcome| {
                let _ = tx.send(IoEvent::Open(Box::new(Completion { ticket, outcome })));
            },
            move |cancel| match path {
                FileTarget::Local(path) => match Buffer::open(&path) {
                    Ok(buffer) => {
                        let canonical = buffer
                            .file_identity()
                            .map_or_else(|| path.clone(), ToOwned::to_owned);
                        Outcome::Success(Opened {
                            document: Document::new(buffer),
                            canonical: FileTarget::Local(canonical),
                        })
                    }
                    Err(error) => Outcome::failed(FailureKind::Io, error.to_string()),
                },
                // Container documents open through :containers owned jobs;
                // a container FileTarget never reads a local path.
                FileTarget::Container { .. } => Outcome::failed(
                    FailureKind::InvalidInput,
                    "container documents open through :containers".to_string(),
                ),
                FileTarget::Remote(location) => match if browse {
                    client
                        .list(&location, &cancel)
                        .map(strop_remote::RemoteResource::Directory)
                } else {
                    client.open(&location, selection, &cancel)
                } {
                    Ok(strop_remote::RemoteResource::File(snapshot)) => {
                        let canonical = FileTarget::Remote(snapshot.file.clone().into());
                        Outcome::Success(Opened {
                            document: Document::remote_snapshot(*snapshot, selection),
                            canonical,
                        })
                    }
                    Ok(strop_remote::RemoteResource::Directory(snapshot)) => {
                        if requires_file {
                            return Outcome::failed(
                                FailureKind::InvalidInput,
                                "range/tail/follow requires a regular file",
                            );
                        }
                        let canonical = FileTarget::Remote(snapshot.directory.clone().into());
                        Outcome::Success(Opened {
                            document: Document::remote_directory(snapshot),
                            canonical,
                        })
                    }
                    Err(error) if error.is_cancellation() => {
                        Outcome::Cancelled(worker::CancelReason::OwnerClosed)
                    }
                    Err(error) => Outcome::failed(FailureKind::Io, error.to_string()),
                },
            },
        );
        self.worker_handles.insert(request, handle);
    }

    fn open_fresh(&self, key: &OpenKey) -> bool {
        if self.finishing {
            return false;
        }
        // Background work owns its operation generation, not the current focus.
        match key.intent {
            OpenIntent::CollectionSource { owner } => {
                return !self.docs.is_empty()
                    && self
                        .collection_build
                        .as_ref()
                        .is_some_and(|build| build.owner == owner)
            }
            OpenIntent::Replace { review, .. } => {
                return !self.docs.is_empty()
                    && self
                        .review
                        .replace
                        .as_ref()
                        .is_some_and(|pending| pending.id == review)
            }
            _ => {}
        }
        if let OpenIntent::LspLocation { context, .. } = &key.intent {
            if !self.lsp_context_fresh(context) {
                return false;
            }
        }
        !self.docs.is_empty()
            && self.current() == key.origin
            && self.focus_epoch == key.focus
            && self.buf().revision() == key.revision
    }

    /// Re-resolve every open document (config lands after the startup
    /// buffer's construction in main).
    pub fn reresolve_indents(&mut self) {
        let ids: Vec<_> = self.docs.iter().map(|(id, _)| id).collect();
        for id in ids {
            self.resolve_indent_for(id);
        }
    }

    /// Indent resolution (0051 R08): manual override → confident
    /// detection → config, decided independently for style and width.
    /// Overrides live on the document, so reloads and config refreshes
    /// preserve them; a detected Tab style never dictates a width —
    /// display width falls through to the configured/manual width.
    pub(crate) fn resolve_indent_for(&mut self, document: DocumentId) {
        use super::document::{Detection, IndentSource};
        let detection = if self.config.indent_detect {
            self.docs.get(document).and_then(|doc| doc.detection)
        } else {
            None
        };
        let configured = super::document::Indent {
            style: self.config.indent_style,
            width: self.config.tab_size,
            style_source: IndentSource::Configured,
            width_source: IndentSource::Configured,
        };
        let Some(doc) = self.docs.get_mut(document) else {
            return;
        };
        let (style, style_source) = match (doc.indent_override.style, detection) {
            (Some(style), _) => (style, IndentSource::Manual),
            (None, Some(Detection::Tabs { .. })) => {
                (crate::config::IndentStyle::Tabs, IndentSource::Detected)
            }
            (None, Some(Detection::Spaces { .. })) => {
                (crate::config::IndentStyle::Spaces, IndentSource::Detected)
            }
            (None, _) => (configured.style, IndentSource::Configured),
        };
        let (width, width_source) = match (doc.indent_override.width, detection, style_source) {
            (Some(width), _, _) => (width, IndentSource::Manual),
            // A detected width is meaningful only with the detected
            // spaces style it was measured on.
            (None, Some(Detection::Spaces { width, .. }), IndentSource::Detected) => {
                (width, IndentSource::Detected)
            }
            (None, _, _) => (configured.width, IndentSource::Configured),
        };
        doc.indent = super::document::Indent {
            style,
            width,
            style_source,
            width_source,
        };
    }

    fn finish_open(&mut self, document: DocumentId, intent: OpenIntent) {
        self.resolve_indent_for(document);
        match intent {
            OpenIntent::LspLocation { context, position } => {
                self.finish_lsp_jump(document, position, context)
            }
            // 0051 §6 R04: the loaded target joins the pending review —
            // verified against its fresh text, never auto-applied and
            // never auto-saved.
            OpenIntent::Replace {
                hits,
                replacement,
                review,
            } => self.complete_replace_open(document, &hits, &replacement, review),
            OpenIntent::Split { vertical } => self.split_document(vertical, document),
            // Background opens never move focus; a pending collection
            // build counts down and assembles when its sources land.
            OpenIntent::CollectionSource { owner } => self.collection_source_ready(owner),
            intent => {
                self.switch_to(document);
                self.set_head(0);
                self.view_mut().view_top = 0;
                match intent {
                    OpenIntent::Switch { readonly: true } => self.buf_mut().readonly = true,
                    OpenIntent::DirectoryParent { child } => {
                        if let Some(line) = self
                            .remote_directory()
                            .and_then(|directory| directory.line_for(&child))
                        {
                            self.set_head(self.buf().line_start(line));
                        }
                    }
                    OpenIntent::AtLine { line } => {
                        self.set_head(
                            self.buf()
                                .line_start(line.get().min(self.buf().last_content_line())),
                        );
                        self.run_motion("^");
                    }
                    OpenIntent::RemoteView { view, line } => {
                        if let Some(line) = line {
                            self.set_head(
                                self.buf()
                                    .line_start(line.get().min(self.buf().last_content_line())),
                            );
                            self.run_motion("^");
                        } else if view.follow_limit().is_some() {
                            self.set_head(super::remote::follow::last_position(self.buf().text()));
                        }
                        if let Some(limit) = view.follow_limit() {
                            self.start_remote_follow(document, limit);
                        }
                    }
                    OpenIntent::Grep { line, column } => {
                        let line = line.get().min(self.buf().last_content_line());
                        let offset = self
                            .buf()
                            .line_start(line)
                            .saturating_add(column.get())
                            .min(self.buf().line_end(line));
                        self.set_head(self.buf().clamp_boundary(offset));
                        // grep/symbol landings use the 0051 §7
                        // placement: center unless comfortably visible
                        self.place_jump_target();
                    }
                    _ => {}
                }
                self.remember_remote_destination();
                self.discover_git();
                self.lsp_maybe_attach();
            }
        }
    }

    pub(crate) fn request_session_save(&mut self) {
        let Some(work) = crate::session::capture_save(self) else {
            return;
        };
        if self.io.session.is_some() {
            // Serialized writes; newest queued capture replaces an unwritten one.
            self.io.queued_session = Some(work);
        } else {
            self.start_session_save(work);
        }
    }

    fn start_session_save(&mut self, work: crate::session::SaveRequest) {
        let request = match self.worker_ids.allocate() {
            Ok(request) => request,
            Err(error) => {
                self.message = error.message;
                return;
            }
        };
        self.io.session = Some(request);
        match self.tape.request("io.session", &request) {
            Ok(false) => return,
            Ok(true) => {}
            Err(error) => {
                self.handle_io(IoEvent::Session {
                    request,
                    outcome: Outcome::failed(FailureKind::Protocol, error.to_string()),
                });
                return;
            }
        }
        let tx = self.io.tx.clone();
        let handle = worker::spawn(
            "strop-session",
            move |outcome| {
                let _ = tx.send(IoEvent::Session { request, outcome });
            },
            move |_| match work.persist() {
                Ok(()) => Outcome::Success(()),
                Err(error) => Outcome::failed(FailureKind::Io, error.to_string()),
            },
        );
        self.worker_handles.insert(request, handle);
    }

    pub fn handle_io(&mut self, event: IoEvent) {
        super::trace::services::io(&event);
        match event {
            IoEvent::Native(completion) => self.handle_native(*completion),
            IoEvent::Remote(event) => self.handle_remote_event(event),
            IoEvent::Open(completion) => {
                let request = completion.ticket.request;
                if self.io.open.get(&request) != Some(&completion.ticket.key) {
                    return;
                }
                let Some(key) = self.io.open.remove(&request) else {
                    return;
                };
                self.worker_handles.remove(&request);
                if self.io.navigation == Some(request) {
                    self.io.navigation = None;
                }
                if !self.open_fresh(&key) {
                    return;
                }
                match completion.outcome {
                    Outcome::Success(mut opened) => {
                        if matches!(key.intent, OpenIntent::Refresh) {
                            self.revoke_remote_write(key.origin);
                            self.finish_remote_refresh(key.origin, opened.document);
                            return;
                        }
                        opened.document.set_return_point(self.jump_record());
                        let existing = self.docs.iter().find_map(|(id, document)| {
                            (document.matches_target(&opened.canonical)
                                && document
                                    .remote_metadata()
                                    .is_none_or(|source| source.selection == key.selection))
                            .then_some(id)
                        });
                        let id = if let Some(id) = existing {
                            if matches!(
                                key.intent,
                                OpenIntent::Browse | OpenIntent::RemoteDestination
                            ) && self.doc(id).directory_metadata_ref().is_some()
                            {
                                if let Err(error) =
                                    self.publish_remote_snapshot(id, opened.document, false)
                                {
                                    self.message = error.to_string();
                                    return;
                                }
                            }
                            id
                        } else {
                            // Background loads never steal the view: the
                            // pristine scratch stays until a foreground
                            // open or the built collection replaces it.
                            let takes_focus = !matches!(
                                key.intent,
                                OpenIntent::CollectionSource { .. } | OpenIntent::Replace { .. }
                            );
                            // A first open on an endpoint binds its workspace
                            // context (0042 slice 2); rebinds are idempotent.
                            let endpoint = opened
                                .document
                                .remote_metadata()
                                .map(|source| source.file.endpoint().clone())
                                .or_else(|| {
                                    opened
                                        .document
                                        .directory_metadata_ref()
                                        .map(|directory| directory.directory.endpoint().clone())
                                });
                            if let Some(endpoint) = endpoint {
                                self.workspaces
                                    .bind(strop_workspace::Filesystem::Remote(endpoint), None);
                            }
                            let id = self.docs.insert(opened.document);
                            if takes_focus {
                                self.drop_stale_scratch(id);
                            }
                            self.generation += 1;
                            self.mru.push(id);
                            id
                        };
                        self.message.clear();
                        self.finish_open(id, key.intent);
                    }
                    Outcome::Failed { failure, .. } => {
                        if let OpenIntent::CollectionSource { owner } = key.intent {
                            self.collection_source_ready(owner);
                        }
                        // 0051 §6 R04: a failed replace target is a named
                        // refusal in the pending review, never a silent drop.
                        if let OpenIntent::Replace { review, .. } = &key.intent {
                            let path = match &key.path {
                                FileTarget::Local(path) => path.clone(),
                                other => PathBuf::from(other.to_string()),
                            };
                            self.refuse_replace_open(
                                &path,
                                format!("open failed: {}", failure.message),
                                *review,
                            );
                        } else {
                            self.message = format!("open {}: {}", key.path, failure.message);
                        }
                    }
                    Outcome::Cancelled(_) => {}
                }
            }
            IoEvent::Save(completion) => {
                let request = completion.ticket.request;
                if self.io.saves.get(&completion.ticket.key.document) != Some(&completion.ticket) {
                    return;
                }
                let key = completion.ticket.key;
                self.io.saves.remove(&key.document);
                self.worker_handles.remove(&request);
                match completion.outcome {
                    Outcome::Success(receipt) => {
                        let Some(document) = self.docs.get_mut(key.document) else {
                            self.message = "snapshot written; source buffer closed".into();
                            self.finish_save_feedback(key.document);
                            self.collection_save_progress(key.document, false);
                            return;
                        };
                        let previous_path = document.buf.path.clone();
                        let saved = document.buf.accept_save(receipt);
                        let renamed = previous_path != document.buf.path;
                        if renamed {
                            self.lsp_close_document(key.document);
                            if !self.docs.is_empty() && self.current() == key.document {
                                self.lsp_maybe_attach();
                            }
                        }
                        self.message = if saved {
                            "written"
                        } else {
                            "snapshot written; newer edits remain unsaved"
                        }
                        .into();
                        self.request_session_save();
                        self.collection_save_progress(key.document, saved);
                        if saved
                            && key.close
                            && !self.docs.is_empty()
                            && self.current() == key.document
                            && self.focus_epoch == key.focus
                        {
                            self.close_pane_or_buffer(false);
                        }
                    }
                    Outcome::Failed { failure, .. } => {
                        self.collection_save_progress(key.document, false);
                        self.message = format!("write failed: {}", failure.message)
                    }
                    Outcome::Cancelled(_) => {
                        self.collection_save_progress(key.document, false);
                        self.message = "write cancelled".into();
                    }
                }
                self.finish_save_feedback(key.document);
            }
            IoEvent::Session { request, outcome } => {
                if self.io.session != Some(request) {
                    return;
                }
                self.io.session = None;
                self.worker_handles.remove(&request);
                if let Outcome::Failed { failure, .. } = outcome {
                    self.message = format!("session save failed: {}", failure.message);
                    self.io.session_error = Some(self.message.clone());
                }
                if let Some(work) = self.io.queued_session.take() {
                    self.start_session_save(work);
                }
            }
        }
    }

    pub fn io_pending(&self) -> bool {
        !self.io.open.is_empty()
            || !self.io.saves.is_empty()
            || self.io.session.is_some()
            || !self.io.native.is_empty()
            || self.remote_work_pending()
    }
}

impl Editor {
    pub(crate) fn io_write_pending(&self, request: WorkerId) -> bool {
        self.io.session == Some(request)
            || self.remote_write_pending(request)
            || self.destination_write_pending(request)
            || self
                .io
                .saves
                .values()
                .any(|ticket| ticket.request == request)
            || self.io.native.get(&request).is_some_and(|key| {
                matches!(
                    key.operation,
                    native::Operation::Trust { .. } | native::Operation::TrustRemote { .. }
                )
            })
    }
    pub fn io_status(&self) -> Option<&'static str> {
        if let Some(status) = self.remote_write_status() {
            return Some(status);
        }
        if !self.io.saves.is_empty() {
            Some("saving")
        } else if !self.io.open.is_empty() {
            Some("loading")
        } else {
            None
        }
    }

    pub(crate) fn remote_refresh_pending(&self, document: DocumentId) -> bool {
        self.io
            .open
            .values()
            .any(|key| key.origin == document && matches!(key.intent, OpenIntent::Refresh))
    }
}

impl IoState {
    /// In-flight native tickets — tests answer a tape-suppressed
    /// launch by feeding `handle_io` a crafted completion.
    #[cfg(test)]
    pub(crate) fn native_tickets(&self) -> Vec<Ticket<native::NativeKey>> {
        self.native
            .iter()
            .map(|(request, key)| Ticket {
                request: *request,
                key: key.clone(),
            })
            .collect()
    }
}