fresh-editor 0.4.0

A lightweight, fast terminal-based text editor with LSP support and TypeScript plugins
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
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
//! Editor methods for window lifecycle (create, switch, close).
//!
//! Windows are introduced in
//! `docs/internal/orchestrator-sessions-design.md`. After Step 0b each
//! window owns its file tree, file mod-times, LSP set, panel-id
//! map, and split layout outright. `set_active_window` is therefore
//! a pointer write (plus seed-buffer allocation when diving into a
//! never-activated window) — there are no warm-swap stashes left to
//! shuffle. Plugins that listen for `active_window_changed` see the
//! same hook sequence as before.

use crate::app::window::Window;
use crate::app::window_resources::WindowResources;
use crate::services::plugins::hooks::HookArgs;
use crate::view::split::{SplitManager, SplitViewState};
use fresh_core::WindowId;
use std::collections::HashMap;
use std::path::PathBuf;

impl crate::app::Editor {
    /// Snapshot the editor-global resources every new `Window` needs.
    /// All fields are cheap clones (`Arc` increments or `Clone`-by-value
    /// where the inner type already holds `Arc`s, like `Authority`).
    /// Called by `create_window_at` and by the first-dive seed path in
    /// `set_active_window`; also by `editor_init` for the base window.
    pub(crate) fn window_resources(&self) -> WindowResources {
        WindowResources {
            config: std::sync::Arc::clone(&self.config),
            grammar_registry: std::sync::Arc::clone(&self.grammar_registry),
            theme_registry: std::sync::Arc::clone(&self.theme_registry),
            theme_cache: std::sync::Arc::clone(&self.theme_cache),
            keybindings: std::sync::Arc::clone(&self.keybindings),
            command_registry: std::sync::Arc::clone(&self.command_registry),
            // Derive the window's fs_manager from the *same* authority we hand
            // it below, so directory listings (the file explorer) ride the
            // window's filesystem — local or remote — instead of a stale,
            // boot-time local one. A born-attached SSH/k8s window otherwise
            // showed the local machine in the explorer while its terminal ran
            // remote, because the cached fs_manager never tracked the authority.
            // Default to a host fs_manager; callers that build a window with a
            // non-local authority re-derive it from that authority's
            // filesystem. The window's `authority` is set on the `Window`
            // itself (not here in the `Clone`-fanned resources).
            fs_manager: std::sync::Arc::new(crate::services::fs::FsManager::new(
                std::sync::Arc::new(crate::model::filesystem::StdFileSystem),
            )),
            local_filesystem: std::sync::Arc::clone(&self.local_filesystem),
            buffer_id_alloc: self.buffer_id_alloc.clone(),
            time_source: std::sync::Arc::clone(&self.time_source),
            dir_context: self.dir_context.clone(),
            tokio_runtime: self.tokio_runtime.clone(),
            async_bridge: self.async_bridge.clone(),
            plugin_manager: std::sync::Arc::clone(&self.plugin_manager),
            theme: std::sync::Arc::clone(&self.theme),
            event_broadcaster: self.event_broadcaster.clone(),
            recovery_service: std::sync::Arc::clone(&self.recovery_service),
        }
    }

    /// Allocate a session id, insert a new `Session`, fire
    /// `session_created`. Does not switch active.
    ///
    /// Caller is responsible for ensuring `root` is absolute. The
    /// `PluginCommand::CreateWindow` dispatcher rejects relative
    /// paths before reaching here.
    ///
    /// Find an existing window whose root resolves to the same
    /// canonical directory, if any. Backs the one-session-per-dir
    /// invariant: opening a directory that already has a window
    /// reuses it rather than creating a duplicate.
    pub(crate) fn find_window_by_root(&self, root: &std::path::Path) -> Option<WindowId> {
        let key = crate::app::orchestrator_persistence::canonical_key(root);
        self.windows
            .iter()
            .find(|(_, w)| crate::app::orchestrator_persistence::canonical_key(&w.root) == key)
            .map(|(id, _)| *id)
    }

    /// Open the window for `root`, creating it if absent. Enforces
    /// one-session-per-directory: if a window already exists at the
    /// same canonical root it is returned as-is and `label` is
    /// ignored (the existing window keeps its label) — no duplicate
    /// is created.
    ///
    /// Seeds a freshly created window with an empty scratch buffer +
    /// a minimal split layout up front (same shape as the first-dive
    /// seed path), so the window is renderable immediately. Without
    /// this, never-dived windows have `splits == None` and any
    /// cross-window render (e.g. the Orchestrator preview pane's
    /// `WindowEmbed`) draws blank.
    pub fn create_window_at(&mut self, root: PathBuf, label: String) -> WindowId {
        // One session per directory: reuse an existing window at this
        // root instead of spawning a colliding duplicate.
        if let Some(existing) = self.find_window_by_root(&root) {
            return existing;
        }
        let id = WindowId(self.next_window_id);
        self.next_window_id += 1;

        // A new window for `root` is its own local session with its **own**
        // per-session trust scoped to that root — not a clone of the active
        // session's authority/trust (which would leak a trust decision across
        // projects). Its `fs_manager` rides the same (host) filesystem.
        let local_authority = self.local_session_authority(&root);
        let mut resources = self.window_resources();
        resources.fs_manager = std::sync::Arc::new(crate::services::fs::FsManager::new(
            std::sync::Arc::clone(&local_authority.filesystem),
        ));
        let mut session = Window::new(id, label, root.clone(), local_authority, resources);
        session.terminal_width = self.terminal_width;
        session.terminal_height = self.terminal_height;
        let resolved_label = session.label.clone();
        self.windows.insert(id, session);

        // Same seed shape that `set_active_window` builds on
        // first dive — installed eagerly so the window is
        // immediately renderable from any code path that walks
        // the windows map (preview rendering, embedded session
        // panes, etc.).
        if let Some((buf, state, metadata, event_log, mgr, vs)) =
            self.build_fresh_layout_if_needed(id)
        {
            if let Some(s) = self.windows.get_mut(&id) {
                s.buffers.set_splits((mgr, vs));
                s.buffers.insert(buf, state);
                s.buffer_metadata.insert(buf, metadata);
                s.event_logs.insert(buf, event_log);
            }
        }

        self.plugin_manager.read().unwrap().run_hook(
            "window_created",
            HookArgs::WindowCreated {
                id: id.0,
                label: resolved_label,
                root: root.to_string_lossy().into_owned(),
            },
        );

        id
    }

    /// A fresh per-session execution scope (trust + env) for `root` — the one
    /// blessed factory. Each call mints handles owned by exactly one session,
    /// so a trust decision or env activation in one window can never leak into
    /// another. Every per-session window construction goes through this.
    pub(crate) fn session_scope_for(
        &self,
        root: &std::path::Path,
    ) -> crate::services::authority::SessionScope {
        crate::services::authority::SessionScope::for_root(
            root,
            &self.dir_context.project_state_dir(root),
        )
    }

    /// A fresh local authority for a brand-new session rooted at `root`, with
    /// its **own** per-session trust + env (not clones of the active
    /// session's) and a host filesystem. The canonical backend for the
    /// Orchestrator's "New Session (Local)" flow: callers pass this to
    /// [`Self::create_window_with_terminal`] so a new session for a different
    /// project is born under its own local backend, trust, and env.
    pub fn local_session_authority(
        &self,
        root: &std::path::Path,
    ) -> crate::services::authority::Authority {
        crate::services::authority::Authority::local_scoped(self.session_scope_for(root))
    }

    /// Atomic "create a new window seeded with an agent terminal"
    /// entry point. Used by Orchestrator's new-session flow.
    ///
    /// Unlike `create_window_at`, this path deliberately does NOT
    /// seed an empty `[No Name]` buffer up front — the terminal
    /// becomes the window's seed via `create_plugin_terminal`'s
    /// no-active-split branch, so the new window is born with a
    /// single tab (the terminal) instead of `[No Name] | <agent>`.
    ///
    /// The eager-seed invariant `create_window_at` upholds
    /// ("window is renderable immediately after returning") still
    /// holds here: the call to `create_plugin_terminal` runs
    /// synchronously on the same thread before this function
    /// yields, installing the terminal-rooted split layout before
    /// any other code can observe the window. The `window_created`
    /// hook is intentionally fired *after* the terminal is wired
    /// up so plugin handlers see the new window in its final
    /// shape, not the half-built intermediate state.
    ///
    /// `root` must be absolute; the plugin-command dispatcher
    /// validates this before reaching here.
    ///
    /// `authority` is the backend the new session is born under — passed
    /// explicitly so this primitive never guesses. The Orchestrator's "New
    /// Session (Local)" flow hands it [`Self::local_session_authority`] (a
    /// fresh local backend sharing the editor's trust + env handles), so a
    /// new session for a *different* project does not inherit the active
    /// window's container/SSH/k8s backend just because that window was
    /// focused when "+ New" was clicked. The born-attached remote-session
    /// path (`create_remote_session_window`) passes its already-connected
    /// backend so the new window's filesystem, LSP spawner, and terminal all
    /// act remotely from birth.
    ///
    /// The editor-wide authority cache is re-pointed at the new active
    /// window via [`Self::adopt_active_window_authority`] before returning,
    /// so the status bar, quick-open, and the 100+ `self.authority` call
    /// sites reflect the session the user just landed on rather than the one
    /// they left.
    ///
    /// `resume` is the agent-resume argv to re-run instead of `command` if
    /// this session is restored (Orchestrator agent-resume).
    #[allow(clippy::too_many_arguments)]
    pub fn create_window_with_terminal(
        &mut self,
        root: PathBuf,
        label: String,
        cwd: Option<PathBuf>,
        command: Option<Vec<String>>,
        title: Option<String>,
        window_authority: crate::services::authority::Authority,
        resume: Option<Vec<String>>,
    ) -> Result<(WindowId, fresh_core::TerminalId, fresh_core::BufferId), String> {
        let id = WindowId(self.next_window_id);
        self.next_window_id += 1;

        // The backend the editor was acting through before this new
        // session — captured so `adopt_active_window_authority` can tell
        // whether the active authority actually changed and skip the
        // hook/snapshot churn when it didn't.
        let previous_authority_label = self.authority().display_label.clone();

        let mut resources = self.window_resources();
        // Re-derive the window's `fs_manager` from *its* backend's filesystem
        // so the file explorer rides this session's backend, then build the
        // window owning `window_authority` outright.
        resources.fs_manager = std::sync::Arc::new(crate::services::fs::FsManager::new(
            std::sync::Arc::clone(&window_authority.filesystem),
        ));
        let mut session = Window::new(id, label, root.clone(), window_authority, resources);
        session.terminal_width = self.terminal_width;
        session.terminal_height = self.terminal_height;
        let resolved_label = session.label.clone();
        self.windows.insert(id, session);

        // Dive into the new window before spawning the terminal
        // so `Window::create_plugin_terminal` operates on a window
        // with `splits.is_none()` — that's the "no active_split"
        // branch which seeds the layout rooted at the terminal
        // buffer. We bypass `set_active_window`'s
        // `build_fresh_layout_if_needed` call (which would install
        // a `[No Name]` seed) by writing the active-window pointer
        // directly.
        let previous_id = self.active_window;
        self.active_window = id;

        // The argv to re-run if this session is restored. `None` (plain
        // shell) is recorded as an empty vec: a present entry — even empty —
        // marks this as a restorable *session* terminal (re-spawn it on
        // restore), distinct from a throwaway ephemeral build/exec shell.
        let restore_command = command.clone().unwrap_or_default();
        let spawn_result = {
            let target = self
                .windows
                .get_mut(&id)
                .expect("just-inserted window must be present");
            target.create_plugin_terminal(
                cwd.or_else(|| Some(root.clone())),
                None, // no split direction — let the no-layout branch seed
                None,
                true,  // focus — newly spawned terminal is the seed
                false, // ephemeral by default; orchestrator owns persistence
                command,
                title.filter(|t| !t.is_empty()),
            )
        };

        let (terminal_id, buffer_id, _split_id) = match spawn_result {
            Ok(triple) => triple,
            Err(e) => {
                // Roll back: tear down the half-built window and
                // restore the previous active pointer so the user
                // isn't stranded on an empty window when the PTY
                // spawn fails (missing binary, permission denied,
                // out of PTYs, ...).
                self.windows.remove(&id);
                self.active_window = previous_id;
                return Err(e);
            }
        };

        // Mark the freshly-spawned agent terminal restorable so workspace
        // capture persists it (with its command) and a later launch
        // re-runs it, instead of the session coming back as a blank pane.
        // An explicit `resume` argv (agent-resume) supersedes the launch
        // command on restore — see `restore_terminal_from_workspace`.
        if let Some(target) = self.windows.get_mut(&id) {
            target
                .terminal_commands
                .insert(terminal_id, restore_command);
            if let Some(resume_argv) = resume.filter(|a| !a.is_empty()) {
                target
                    .terminal_resume_commands
                    .insert(terminal_id, resume_argv);
            }
        }

        // The switch has now committed (the spawn succeeded and the active
        // pointer stays on the new window). This path wrote `active_window`
        // directly above, bypassing `set_active_window` — so mirror its
        // guard here, or a panel-scoped mode set on the window we switched
        // away from (e.g. the New-Session form's `orchestrator-new-form`,
        // still mounted during a born-attached SSH/K8s attach) is left
        // stranded and silently swallows all of that window's buffer input.
        // See #2237 / #2234 item 4.
        self.clear_panel_scoped_mode_on_switch_away(previous_id);

        // Adopt the new active window's authority into the editor-wide
        // caches (`self.authority`, quick-open, the `authority_changed`
        // hook). This path writes `active_window` directly and bypasses
        // `set_active_window`, so without this the status bar + the 100+
        // `self.authority` call sites keep reporting the *previous*
        // window's backend — e.g. a new local session created from a
        // devcontainer window would still show `Container:…` and route
        // file ops through the container. The window's own
        // `resources.authority` was already set above (local by default,
        // or the explicit remote backend for born-attached sessions).
        self.adopt_active_window_authority(&previous_authority_label);

        // Register the leader pid with the new window's
        // process_groups so window-level signal operations reach
        // the spawned group. Mirrors `create_plugin_terminal`'s
        // registration in the active-target path of
        // `handle_create_terminal`, but kept here because we
        // bypass that dispatcher.
        if let Some(pid) = self
            .windows
            .get(&id)
            .and_then(|w| w.terminal_manager.get(terminal_id))
            .and_then(|h| h.pid())
        {
            let pg_label = format!("terminal #{}", terminal_id.0);
            if let Some(win) = self.windows.get_mut(&id) {
                win.process_groups.register(pid, pg_label);
            }
        }

        // Size the newly-created window's PTYs (mirrors
        // `set_active_window`'s post-dive resize so the seeded terminal
        // renders into the right cell rect on its first frame). Route
        // through the funnel rather than `win.resize_visible_terminals()`
        // directly: a brand-new window's `dock_cols` cache is still 0, and
        // `relayout` pushes the current editor-global dock width into every
        // window before sizing, so the seeded terminal accounts for a dock
        // that's already showing.
        self.relayout();

        // Plugin lifecycle: fire `window_created` first, then
        // `active_window_changed`. Order mirrors the
        // `create_window_at` + `set_active_window` sequence the
        // orchestrator previously chained — plugin handlers that
        // care about either event see the same payload order.
        self.plugin_manager.read().unwrap().run_hook(
            "window_created",
            HookArgs::WindowCreated {
                id: id.0,
                label: resolved_label,
                root: root.to_string_lossy().into_owned(),
            },
        );
        if previous_id != id {
            self.plugin_manager.read().unwrap().run_hook(
                "active_window_changed",
                HookArgs::ActiveWindowChanged {
                    previous_id: Some(previous_id.0),
                    active_id: id.0,
                },
            );
        }
        #[cfg(feature = "plugins")]
        self.update_plugin_state_snapshot();
        #[cfg(feature = "plugins")]
        self.plugin_manager.read().unwrap().run_hook(
            "buffer_activated",
            crate::services::plugins::hooks::HookArgs::BufferActivated { buffer_id },
        );

        Ok((id, terminal_id, buffer_id))
    }

    /// Clear a floating-panel-scoped editor mode on the window we are
    /// switching *away* from.
    ///
    /// A plugin-defined editor mode (`editor.setEditorMode`) tied to a mounted
    /// floating widget panel — the Orchestrator picker (`orchestrator-open`) or
    /// new-session form (`orchestrator-new-form`) — is transient UI state that
    /// belongs to the *panel*, not to the window it was opened over.
    /// `setEditorMode` writes to whatever window is active when the plugin
    /// calls it, so a plugin that switches the active window while its panel is
    /// still mounted (the orchestrator "dive": `setActiveWindow(target)` first,
    /// then `closeOpenDialog()` / `closeForm()` which runs
    /// `setEditorMode(null)`) lands the clear on the *incoming* window and
    /// leaves the *outgoing* one stuck in the panel's mode. That stuck mode
    /// stays masked while the window sits in terminal mode, then silently
    /// swallows every printable key the moment the user leaves terminal mode
    /// (e.g. opens a file via quick-open) — the buffer ignores all keyboard
    /// input until the user switches sessions.
    ///
    /// Both window-switch paths must call this before moving the active
    /// pointer: the ordinary `set_active_window` dive *and* the born-attached
    /// remote session creation (`create_window_with_terminal`), which writes
    /// the active pointer directly and so never reaches `set_active_window`'s
    /// own guard. See #2237 / #2234 item 4.
    ///
    /// vi-mode and other persistent per-window modes are unaffected: they never
    /// have a floating panel mounted during a window switch.
    fn clear_panel_scoped_mode_on_switch_away(&mut self, previous_id: WindowId) {
        if self.floating_widget_panel.is_some() {
            if let Some(win) = self.windows.get_mut(&previous_id) {
                win.editor_mode = None;
            }
        }
    }

    /// Switch the active window to `id`.
    ///
    /// Pointer write: every per-window field
    /// (panel_ids / file_mod_times / file_explorer / lsp / splits)
    /// already lives on `Window`, so flipping `active_window` is the
    /// whole switch. Diving into a never-activated window seeds it
    /// with a fresh empty buffer + SplitManager so the renderer
    /// finds a populated `splits` field.
    ///
    /// No-op when `id` is already active. Logs and returns when
    /// `id` is unknown — the design treats unknown ids as a plugin
    /// bug (caller verifies with `listWindows`), not a recoverable
    /// error worth surfacing through the channel.
    pub fn set_active_window(&mut self, id: WindowId) {
        if self.active_window == id {
            return;
        }
        if !self.windows.contains_key(&id) {
            tracing::warn!("set_active_window: unknown window id {id}; active window unchanged");
            return;
        }

        let previous_id = self.active_window;
        // Capture the outgoing backend label so we can tell, after the
        // switch, whether the active *authority* actually changed (most
        // window switches are between same-authority local sessions, where
        // it doesn't). Only then do we re-point editor-wide caches + fire
        // the `authority_changed` hook.
        let previous_authority_label = self.authority().display_label.clone();

        // Clear any panel-scoped editor mode on the window we're leaving so
        // it can never outlive the switch (see
        // `clear_panel_scoped_mode_on_switch_away`).
        self.clear_panel_scoped_mode_on_switch_away(previous_id);

        // Lazy materialization: if this window's saved workspace hasn't
        // been restored yet, restore it now (before seeding) so the
        // dive lands on real content rather than an empty buffer.
        self.materialize_window(id);

        // For a never-activated incoming window, allocate a fresh
        // seed buffer + SplitManager rooted at it. The state is
        // installed into the incoming window's `buffers` map after
        // the active pointer moves. After a successful materialize the
        // window already has splits, so this is a no-op.
        let fresh_layout = self.build_fresh_layout_if_needed(id);

        // Pointer write — that's the whole switch. `working_dir()`
        // derives from the active window's root, so moving the pointer
        // is all it takes (no separate working_dir to sync).
        self.active_window = id;

        // For a never-activated incoming window, install the freshly
        // built layout into the window's `splits` field and attach
        // the seed buffer.
        if let Some((buf, state, metadata, event_log, mgr, vs)) = fresh_layout {
            if let Some(s) = self.windows.get_mut(&id) {
                s.buffers.set_splits((mgr, vs));
                s.buffers.insert(buf, state);
                s.buffer_metadata.insert(buf, metadata);
                s.event_logs.insert(buf, event_log);
            }
        }

        // Authority follows the active window. Each `Window` owns its
        // `resources.authority`; the editor-wide `self.authority` cache (read
        // by the 100+ filesystem/spawn/terminal call sites) must now reflect
        // the window we just switched to, or a per-session remote/cloud
        // backend would silently keep acting through the previous window's
        // authority. This is the switch-time counterpart to
        // `set_session_authority` (which mirrors on swap of the *active*
        // window) — see `AUTHORITY_DESIGN.md` §"Evolution: per-session
        // authority". Cheap for the common case: same-authority local windows
        // share `Arc`s and the label is unchanged, so the hook below is
        // skipped.
        self.adopt_active_window_authority(&previous_authority_label);

        // If we just switched to a remote session that came back from disk
        // dormant (backend spec known, live authority still the local
        // placeholder), start reconnecting its backend now — the per-window
        // activation the per-session design calls for. SSH/k8s reconnect from
        // core; the agent terminals re-run in the live backend once it lands.
        #[cfg(feature = "plugins")]
        self.reconnect_dormant_session_if_needed(id);

        // Refresh the plugin state snapshot so `getCwd()` (and every
        // other snapshot field) reflects the window we just switched
        // to *before* the `active_window_changed` hook runs. Without
        // this, plugins that read `editor.getCwd()` — Live Grep, file
        // finders, etc. — keep targeting the previous window's project
        // after a dive, surfacing the wrong project's files.
        #[cfg(feature = "plugins")]
        self.update_plugin_state_snapshot();

        self.plugin_manager.read().unwrap().run_hook(
            "active_window_changed",
            HookArgs::ActiveWindowChanged {
                previous_id: Some(previous_id.0),
                active_id: id.0,
            },
        );

        // Reflow the newly-active window's visible terminal PTYs to
        // match their dive-view split rects. Without this, a session
        // that was just previewed in the orchestrator picker
        // (`render_session_preview_into_rect` resizes PTYs to the
        // embed rect — typically ~half the terminal's height) keeps
        // drawing at that smaller size after the dive, leaving the
        // bottom of the dive view blank until something else triggers
        // a resize. Same applies for the inverse: dive away while a
        // session has a small split, dive back when the window is
        // bigger — the terminal needs the new dimensions. Route through
        // the funnel so the dive-target window also picks up the current
        // editor-global dock width (its `dock_cols` cache may be stale).
        self.relayout();
    }

    /// Switch the active window and play a directional wipe over the
    /// editor content as the incoming window appears. The editor
    /// content geometry is layout-driven (identical for any session),
    /// so the outgoing window's last content rect is the right area to
    /// animate. `capture_before_all` snapshots the previous frame (the
    /// outgoing window) and `SlideIn` slides the new content in over it.
    pub fn set_active_window_animated(&mut self, id: WindowId, from_edge: &str) {
        let animate = self.active_window != id
            && self.windows.contains_key(&id)
            && self.config().editor.animations;
        // Wipe the ENTIRE window — menu bar, explorer, tabs, splits, and
        // status bar — i.e. everything to the right of the dock. That's
        // the chrome area from the dock split, not just the buffer's
        // content rect. The dock column itself stays put.
        let full = ratatui::layout::Rect {
            x: 0,
            y: 0,
            width: self.terminal_width,
            height: self.terminal_height,
        };
        let (_dock, area) = self.compute_dock_split(full);
        self.set_active_window(id);
        if !animate {
            return;
        }
        if area.width == 0 || area.height == 0 {
            return;
        }
        use crate::view::animation::{AnimationKind, Edge};
        let from = match from_edge {
            "top" => Edge::Top,
            "bottom" => Edge::Bottom,
            "left" => Edge::Left,
            "right" => Edge::Right,
            _ => Edge::Bottom,
        };
        self.active_window_mut().animations.start(
            area,
            AnimationKind::SlideIn {
                from,
                duration: std::time::Duration::from_millis(180),
                delay: std::time::Duration::ZERO,
            },
        );
    }

    /// Cycle to the next open window in the workspace.
    ///
    /// Windows are ordered by their numeric `WindowId` (which is
    /// monotonically assigned by `create_window_at`), so "next"
    /// reads in creation order with wrap-around. No-op when only
    /// one window is open (issue #2031).
    pub fn next_window(&mut self) {
        self.cycle_active_window(1);
    }

    /// Cycle to the previous open window. See [`Self::next_window`]
    /// for ordering.
    pub fn prev_window(&mut self) {
        self.cycle_active_window(-1);
    }

    /// Step `delta` positions through the open windows (positive =
    /// forward, negative = backward), wrapping around at the ends.
    /// Centralises the cycle logic shared by `next_window` and
    /// `prev_window` so both directions stay in sync if the
    /// underlying ordering changes (e.g. user-controlled reorder).
    fn cycle_active_window(&mut self, delta: isize) {
        // A plugin (the orchestrator dock) may constrain cycling to a
        // specific ordered subset — the windows currently visible in its
        // session list — so Next/Prev Window walks exactly that list rather
        // than every open window. Ids no longer open are dropped, preserving
        // the given order. An empty result (or no override) falls back to the
        // default: every window, ordered by id.
        let override_ids: Option<Vec<WindowId>> = self
            .window_cycle_order
            .as_ref()
            .map(|order| {
                order
                    .iter()
                    .copied()
                    .filter(|id| self.windows.contains_key(id))
                    .collect::<Vec<_>>()
            })
            .filter(|kept| !kept.is_empty());
        let ids: Vec<WindowId> = match override_ids {
            Some(kept) => kept,
            None => {
                let mut all: Vec<WindowId> = self.windows.keys().copied().collect();
                all.sort_by_key(|id| id.0);
                all
            }
        };
        if ids.len() <= 1 {
            return;
        }
        let current_pos = match ids.iter().position(|id| *id == self.active_window) {
            Some(pos) => pos as isize,
            None => 0,
        };
        let len = ids.len() as isize;
        let next_pos = (((current_pos + delta) % len) + len) % len;
        let next_id = ids[next_pos as usize];
        self.set_active_window(next_id);
    }

    /// Build a fresh seed buffer + split layout for `id` if that
    /// window is missing either a split tree or any buffer to back
    /// it. Returns `None` when the window is unknown or already
    /// populated. The caller is responsible for installing the
    /// returned tuple into the window's fields.
    ///
    /// Both branches (no splits, or splits but empty buffer map)
    /// are pathological: render walks the active buffer and would
    /// panic at `expect("active buffer must be present")` when the
    /// split manager points at a buffer id that isn't in
    /// `window.buffers`.
    ///
    /// Factored out of `set_active_window` so other call sites that
    /// need to populate an inert window shell can share the same
    /// seed-construction logic.
    pub(crate) fn build_fresh_layout_if_needed(
        &mut self,
        id: WindowId,
    ) -> Option<(
        fresh_core::BufferId,
        crate::state::EditorState,
        crate::app::types::BufferMetadata,
        crate::model::event::EventLog,
        SplitManager,
        HashMap<crate::model::event::LeafId, SplitViewState>,
    )> {
        if !self
            .windows
            .get(&id)
            .is_some_and(|s| s.buffers.splits().is_none() || s.buffers.len() == 0)
        {
            return None;
        }
        let buf = self.alloc_buffer_id();
        let mut state = crate::state::EditorState::new(
            self.terminal_width,
            self.terminal_height,
            self.config.editor.large_file_threshold_bytes as usize,
            std::sync::Arc::clone(&self.authority().filesystem),
        );
        state
            .margins
            .configure_for_line_numbers(self.config.editor.line_numbers);
        state
            .buffer
            .set_default_line_ending(self.config.editor.default_line_ending.to_line_ending());
        let metadata = crate::app::types::BufferMetadata::new();
        let event_log = crate::model::event::EventLog::new();
        let manager = SplitManager::new(buf);
        let active_leaf = manager.active_split();
        let mut view_states = HashMap::new();
        view_states.insert(
            active_leaf,
            SplitViewState::with_buffer(self.terminal_width, self.terminal_height, buf),
        );
        Some((buf, state, metadata, event_log, manager, view_states))
    }

    /// Eagerly initialise an inactive session's per-session
    /// state without diving. Useful for plugins (Orchestrator) that
    /// want to pay the warm-up cost (file-tree walk, ignore
    /// matcher, etc.) ahead of the user's first dive.
    ///
    /// In the current build this is a placeholder — file
    /// explorer rebuilds and LSP boot still happen on first dive.
    /// The API exists so callers don't have to be rewritten when
    /// eager warm-up wires up later.
    pub fn prewarm_window(&mut self, id: WindowId) {
        if id == self.active_window {
            return;
        }
        if !self.windows.contains_key(&id) {
            tracing::warn!("prewarm_window: unknown session id {id}");
        }
        // Placeholder for eager warm-up of file_explorer / LSP.
    }

    /// Remove a buffer from whichever window holds it. Returns the
    /// removed `EditorState` if the buffer was found. Step 0c: each
    /// buffer lives in exactly one window, so this is at most one
    /// successful removal.
    pub(crate) fn detach_buffer_from_all_windows(
        &mut self,
        buffer_id: fresh_core::BufferId,
    ) -> Option<crate::state::EditorState> {
        for w in self.windows.values_mut() {
            if let Some(state) = w.buffers.remove(&buffer_id) {
                return Some(state);
            }
        }
        None
    }

    /// Close a session and drop its `Session` entry. Refuses to
    /// close the currently active session — the caller must switch
    /// to a different session first. Refuses to close the *last*
    /// remaining window — the editor must always host at least one.
    ///
    /// There is no special "base" window any more: id 1 is just the
    /// window the editor launched into, closable like any other once
    /// another window exists. The real invariant is "≥1 window", not
    /// "id 1 lives forever".
    ///
    /// Returns `true` on success, `false` on rejection.
    pub fn close_window(&mut self, id: WindowId) -> bool {
        if self.windows.len() <= 1 {
            tracing::warn!("close_window: refusing to close the last remaining window (id {id})");
            return false;
        }
        if id == self.active_window {
            tracing::warn!(
                "close_window: refusing to close the active session (id {id}); \
                 switch first via setActiveWindow"
            );
            return false;
        }
        if self.windows.remove(&id).is_none() {
            tracing::warn!("close_window: unknown session id {id}");
            return false;
        }
        // Tear down a born-attached remote session's connection (carrier +
        // reconnect/heartbeat + runtime) when its window closes. No-op for
        // local windows, which never have an entry.
        if self.session_keepalives.remove(&id).is_some() {
            tracing::info!("close_window: dropped remote session keepalive for window {id}");
        }

        self.plugin_manager
            .read()
            .unwrap()
            .run_hook("window_closed", HookArgs::WindowClosed { id: id.0 });

        true
    }

    /// Born-attached remote session: create a **new window** whose authority is
    /// the already-connected remote backend (Kubernetes / SSH / …), seed its
    /// terminal *inside* that backend, and park the connection `keepalive`
    /// keyed by the window so it outlives editor rebuilds and is torn down on
    /// close.
    ///
    /// Unlike the global `install_authority_with_keepalive` restart, existing
    /// windows are left untouched — the remote session coexists with them, and
    /// `set_active_window` (Gap A) retargets the active authority when the user
    /// switches. The new window is born under `authority` because it is passed
    /// straight to `create_window_with_terminal` as that window's backend, so
    /// its filesystem, LSP spawner, and terminal wrapper all act in the backend
    /// from birth (there are no stale local handles to invalidate — the caveat
    /// that gates hot-swapping an *existing* window's authority doesn't apply
    /// here). `create_window_with_terminal` adopts the new window's authority
    /// into the editor-wide caches before returning.
    pub(crate) fn create_remote_session_window(
        &mut self,
        authority: crate::services::authority::Authority,
        keepalive: Box<dyn std::any::Any + Send>,
        root: PathBuf,
        label: String,
        command: Option<Vec<String>>,
        spec: crate::services::authority::SessionAuthoritySpec,
    ) -> Result<WindowId, String> {
        match self.create_window_with_terminal(
            root.clone(),
            label,
            Some(root),
            command,
            None,
            authority,
            None,
        ) {
            Ok((window_id, _terminal, _buffer)) => {
                self.session_keepalives.insert(window_id, keepalive);
                // Persist how to reconnect this backend on the new session so
                // a restart / relaunch can bring it back rather than degrade
                // it to local.
                if let Some(w) = self.windows.get_mut(&window_id) {
                    w.authority_spec = spec;
                }
                Ok(window_id)
            }
            Err(e) => {
                // The connect succeeded but the window couldn't be seeded
                // (e.g. the backend has no python3 / the pod died):
                // `create_window_with_terminal` already rolled the active
                // pointer back to the previous window and left the
                // editor-wide authority untouched (it never installed the
                // remote one), so just drop the keepalive (tears down the
                // carrier).
                drop(keepalive);
                Err(e)
            }
        }
    }
}