knotra 0.34.0

knotra: multi-project VCS dashboard and bulk-operation tool.
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
//! Application state — single source of truth.

pub mod changelog;
pub mod conflict_ops;
pub mod context;
pub mod dashboard;
pub mod detail_panel;
pub mod focus;
pub mod freezer;
pub mod layer;
pub mod palette;
pub mod sync;
pub mod topology;
pub mod workspace_mgr;

use std::collections::HashSet;

use knotra_ui::KnotraTheme;
use knotra_ui::i18n::Catalog;
use knotra_vcs::{
    OperationId, WorkspaceStatus,
    model::{
        operation::{OperationLog, ProjectOperationResult, RetryExclusionReason},
        project::ProjectId,
        workspace::Workspace,
    },
};

use crate::{
    config::{AppConfig, AppPaths},
    message::{FilterMessage, StatusFilter},
    view::dashboard::WidthMode,
};

// ---------------------------------------------------------------------------
// Window size
// ---------------------------------------------------------------------------

/// The window size `main.rs` configures at startup. A single named constant
/// so `main.rs`'s `window::Settings` and `AppState`'s initial `width_mode`
/// (no resize event fires before the first frame) can never silently drift
/// apart (RFC-035 R8/Handoff 029 §2.2).
pub const INITIAL_WINDOW_SIZE: iced::Size = iced::Size::new(1100.0, 720.0);

// ---------------------------------------------------------------------------
// Screen
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Screen {
    Dashboard,
    History,
    Settings,
}

// ---------------------------------------------------------------------------
// Filter state
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Default)]
pub struct FilterState {
    pub search_text: String,
    pub active_group: Option<String>,
    pub status_filters: Vec<StatusFilter>,
}

impl FilterState {
    pub fn is_active(&self) -> bool {
        !self.search_text.is_empty()
            || self.active_group.is_some()
            || !self.status_filters.is_empty()
    }
    pub fn has_status_filter(&self, sf: &StatusFilter) -> bool {
        self.status_filters.contains(sf)
    }
}

// ---------------------------------------------------------------------------
// Dialog states
// ---------------------------------------------------------------------------

/// Which step of the 2-step Add Project flow is active.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub enum AddProjectStep {
    /// Step 1: choose a project folder.
    #[default]
    ChooseFolder,
    /// Step 2: give it a display name.
    NameProject,
}

#[derive(Debug, Clone, Default)]
pub struct AddProjectDialog {
    pub step: AddProjectStep,
    pub name: String,
    pub path: String,
    pub error: Option<String>,
}

#[derive(Debug, Clone)]
pub struct ConfirmRemoveDialog {
    pub project_id: ProjectId,
    pub project_name: String,
}

/// A recently removed project that can be undone before the snackbar expires.
#[derive(Debug, Clone)]
pub struct UndoableRemoval {
    pub project: knotra_vcs::Project,
    /// Project status snapshot so re-adding restores display immediately.
    pub status_snapshot: Option<knotra_vcs::ProjectStatus>,
}

// ---------------------------------------------------------------------------
// Load phase
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum LoadPhase {
    Startup,
    Refreshing,
    Ready,
}

// ---------------------------------------------------------------------------
// Settings edit buffer
// ---------------------------------------------------------------------------

/// Temporary edit buffer for the Settings screen.
/// Mirrors `AppConfig` but stores text fields as raw Strings for input widgets.
///
/// RFC-073 D12: `refresh_interval_secs`/`max_concurrent_reads`/
/// `max_log_entries`/`fs_debounce_secs` are gone from here — each is a
/// select now, drawn straight from `state.config`'s own value (the same
/// way `zoom_percent`/`theme`/`locale` already were), with no typed text
/// to buffer or validate.
#[derive(Debug, Clone)]
pub struct SettingsEdit {
    pub external_editor: String,
    pub external_merge_tool: String,
}

impl SettingsEdit {
    pub fn from_config(cfg: &AppConfig) -> Self {
        SettingsEdit {
            external_editor: cfg.external_editor.clone().unwrap_or_default(),
            external_merge_tool: cfg.external_merge_tool.clone().unwrap_or_default(),
        }
    }
}

// ---------------------------------------------------------------------------
// Tag push pending state
// ---------------------------------------------------------------------------

/// Tracks a pending offer to push freeze tags to the remote after success.
#[derive(Debug, Clone)]
pub struct PendingTagPush {
    pub freeze_name: String,
    pub project_ids: Vec<knotra_vcs::ProjectId>,
    pub is_pushing: bool,
}

// ---------------------------------------------------------------------------
// RFC-0009 — Selection model
// ---------------------------------------------------------------------------

/// Which projects the user has selected (checkboxes).
/// Drives the selection bar and bulk-action modals.
#[derive(Debug, Clone, Default)]
pub struct SelectionState {
    pub selected_ids: HashSet<knotra_vcs::ProjectId>,
    /// Last card clicked without Shift — for range-select anchor.
    pub anchor_id: Option<knotra_vcs::ProjectId>,
}

impl SelectionState {
    pub fn toggle(&mut self, id: knotra_vcs::ProjectId) {
        if self.selected_ids.contains(&id) {
            self.selected_ids.remove(&id);
            if self.selected_ids.is_empty() {
                self.anchor_id = None;
            } else if self.anchor_id.as_ref() == Some(&id) {
                self.anchor_id = self.selected_ids.iter().next().cloned();
            }
        } else {
            self.selected_ids.insert(id.clone());
            self.anchor_id = Some(id);
        }
    }

    pub fn clear(&mut self) {
        self.selected_ids.clear();
        self.anchor_id = None;
    }
    pub fn contains(&self, id: &knotra_vcs::ProjectId) -> bool {
        self.selected_ids.contains(id)
    }

    /// Select all projects.
    pub fn select_all(&mut self, ids: &[knotra_vcs::ProjectId]) {
        for id in ids {
            self.selected_ids.insert(id.clone());
        }
        if self.anchor_id.is_none() {
            self.anchor_id = ids.first().cloned();
        }
    }

    pub fn retain_ids(&mut self, ids: &HashSet<knotra_vcs::ProjectId>) {
        self.selected_ids.retain(|id| ids.contains(id));
        if self
            .anchor_id
            .as_ref()
            .is_some_and(|anchor| !self.selected_ids.contains(anchor))
        {
            self.anchor_id = self.selected_ids.iter().next().cloned();
        }
        if self.selected_ids.is_empty() {
            self.anchor_id = None;
        }
    }
}

#[derive(Debug, Clone, Default)]
pub struct SelectionSummary {
    pub selected_count: usize,
    pub selected_ids: Vec<knotra_vcs::ProjectId>,
    pub visible_ids: Vec<knotra_vcs::ProjectId>,
    pub fetchable_ids: Vec<knotra_vcs::ProjectId>,
    pub has_upstream: bool,
}

// ---------------------------------------------------------------------------
// RFC-0011 — Activity strip
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Default)]
pub enum LatestOpState {
    #[default]
    Idle,
    Running {
        operation_id: OperationId,
        label: String,
        done: usize,
        total: usize,
    },
    Completed {
        log: OperationLog,
        retry: RetryAvailability,
    },
}

#[derive(Debug, Clone)]
pub enum ActivityRetryAction {
    FetchFailed {
        source_operation_id: OperationId,
        project_ids: Vec<ProjectId>,
    },
    ReviewSmartPull {
        source_operation_id: OperationId,
        project_ids: Vec<ProjectId>,
    },
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RetryUnavailableReason {
    NoEligibleTargets,
    ContextSwitch,
    Freeze,
    FreezeRollback,
    StatusRefresh,
}

impl RetryUnavailableReason {
    pub fn i18n_key(self) -> &'static str {
        match self {
            Self::NoEligibleTargets => "plain.activity.none_available",
            Self::ContextSwitch => "plain.activity.retry_context_again",
            Self::Freeze | Self::FreezeRollback => "plain.activity.retry_freeze_again",
            Self::StatusRefresh => "plain.activity.retry_refresh_again",
        }
    }
}

#[derive(Debug, Clone)]
pub enum RetryAvailability {
    Available(ActivityRetryAction),
    Unavailable(RetryUnavailableReason),
    NotApplicable,
}

#[derive(Debug, Clone)]
pub struct RetryExclusion {
    pub project_id: ProjectId,
    pub reason: RetryExclusionReason,
}

#[derive(Debug, Clone)]
pub struct FetchRetryRun {
    pub operation_id: OperationId,
    pub lease_id: OperationLeaseId,
    pub started_at: jiff::Timestamp,
    pub total: usize,
    pub completed: Vec<ProjectOperationResult>,
    pub exclusions: Vec<RetryExclusion>,
}

#[derive(Debug, Clone, Default)]
pub struct ActivityStripState {
    pub latest: LatestOpState,
    /// Seconds since the last operation completed (for auto-fade).
    pub completed_secs: u32,
    pub fetch_retry: Option<FetchRetryRun>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct OperationLeaseId(pub u64);

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OperationOwner {
    SingleFetch,
    BulkFetch,
    SmartPullPreparation,
    SmartPullExecution,
    ContextSwitch,
    FreezeValidation,
    FreezeExecution,
    ConflictMutation,
    TagPush,
    ActivityFetchRetry,
    ActivitySmartPullPreparation,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct OperationLease {
    pub id: OperationLeaseId,
    pub owner: OperationOwner,
}

#[derive(Debug, Default)]
pub struct OperationInterlock {
    active: Option<OperationLease>,
    next_id: u64,
}

impl OperationInterlock {
    pub fn try_acquire(&mut self, owner: OperationOwner) -> Option<OperationLeaseId> {
        if self.active.is_some() {
            return None;
        }
        self.next_id = self.next_id.checked_add(1)?;
        let id = OperationLeaseId(self.next_id);
        self.active = Some(OperationLease { id, owner });
        Some(id)
    }

    pub fn release_if_matches(&mut self, id: OperationLeaseId) -> bool {
        if self.active.is_some_and(|lease| lease.id == id) {
            self.active = None;
            true
        } else {
            false
        }
    }

    pub fn is_busy(&self) -> bool {
        self.active.is_some()
    }
}

// ---------------------------------------------------------------------------
// RFC-0012 — Command palette
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PaletteEntryKind {
    Project,
    Workspace,
    Action,
}

#[derive(Debug, Clone)]
pub struct PaletteEntry {
    pub kind: PaletteEntryKind,
    pub label: String,
    /// Machine-readable id for dispatching (e.g. project id, action key).
    pub payload: String,
    /// i18n key for why this row cannot currently run.
    pub disabled_reason_key: Option<&'static str>,
}

#[derive(Debug, Clone, Default)]
pub struct PaletteState {
    pub open: bool,
    pub query: String,
    pub results: Vec<PaletteEntry>,
    /// Last disabled/no-op reason shown in the palette.
    pub notice_key: Option<&'static str>,
}

impl PaletteState {
    pub fn open_palette(&mut self) {
        self.open = true;
        self.query.clear();
        self.notice_key = None;
    }
    pub fn close(&mut self) {
        self.open = false;
        self.notice_key = None;
    }
}

// ---------------------------------------------------------------------------
// RFC-0013 — Active modal discriminant
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub enum ActiveModal {
    #[default]
    None,
    Pull,
    Tag,
    Switch,
    Resolve(knotra_vcs::ProjectId),
    Changelog,
}

/// Whether the keyboard cheat-sheet overlay is open.
#[derive(Debug, Clone, Default)]
pub struct KeyboardState {
    pub cheat_sheet_open: bool,
}

// ---------------------------------------------------------------------------
// AppState
// ---------------------------------------------------------------------------

pub struct AppState {
    pub screen: Screen,
    pub config: AppConfig,
    /// Filesystem paths used for config, workspace, and history persistence.
    pub paths: AppPaths,
    pub catalog: Catalog,
    pub theme: KnotraTheme,
    pub workspace: Option<Workspace>,
    pub workspace_status: Option<WorkspaceStatus>,
    pub load_phase: LoadPhase,
    pub filter: FilterState,
    pub operation_logs: Vec<OperationLog>,
    /// RFC-047 D2: entries `load_recent_logs` could not read or parse,
    /// within the most-recent-`max_log_entries` window loaded at startup.
    /// Deliberately not folded into `operation_logs` — this is a startup
    /// fact about the history directory, not a property of the in-memory
    /// list, and five other sites read `operation_logs` (including
    /// `background/mod.rs`, which appends to it at runtime as operations
    /// complete) without needing to know or preserve this count.
    pub history_unreadable_count: usize,
    /// RFC-047 D3: the history directory itself could not be read, distinct
    /// from a directory that has simply never been created (genuinely "no
    /// history yet" — see `persistence::LoadedLogs`'s own doc comment).
    pub history_directory_unreadable: bool,
    pub history_search: String,
    pub status_bar: Option<String>,
    pub add_project_dialog: Option<AddProjectDialog>,
    pub confirm_remove_dialog: Option<ConfirmRemoveDialog>,
    pub fetching_projects: HashSet<ProjectId>,
    pub is_refreshing: bool,
    /// History: which log entry IDs are currently expanded.
    pub history_expanded: std::collections::HashSet<knotra_vcs::OperationId>,
    /// Settings: in-progress edit buffer (mirrors config until saved).
    pub settings_edit: SettingsEdit,
    /// Settings: last save result message.
    pub settings_save_msg: Option<String>,
    /// Sync Center state.
    pub sync: sync::SyncCenterState,
    /// Context Operations state.
    pub context_ops: context::ContextOpsState,
    /// Freezer state.
    pub freezer: freezer::FreezerState,
    /// Conflict resolution state.
    pub conflict_ops: conflict_ops::ConflictOpsState,
    /// Changelog aggregation state.
    pub changelog: changelog::ChangelogState,
    /// Dependency topology state.
    pub topology: topology::TopologyState,
    /// All loaded workspaces (active index = active_workspace_idx).
    pub all_workspaces: Vec<knotra_vcs::Workspace>,
    /// Index into `all_workspaces` for the currently active workspace.
    pub active_workspace_idx: usize,
    /// Workspace management dialog state.
    pub workspace_mgr: workspace_mgr::WorkspaceMgrState,
    /// Missing-path projects detected at last refresh.
    pub missing_projects: std::collections::HashSet<knotra_vcs::ProjectId>,
    /// Post-freeze: offer to push tags to remote.
    pub pending_tag_push: Option<PendingTagPush>,
    /// Global ownership guard for VCS launch paths.
    pub operation_interlock: OperationInterlock,
    /// File-system change poller (used by the FS-watch Subscription).
    pub fs_poller: knotra_vcs::FsPoller,
    // ------------------------------------------------------------------
    // RFC-0009 selection model
    // ------------------------------------------------------------------
    pub selection: SelectionState,
    // ------------------------------------------------------------------
    // RFC-0011 activity strip
    // ------------------------------------------------------------------
    pub activity: ActivityStripState,
    // ------------------------------------------------------------------
    // RFC-0012 command palette
    // ------------------------------------------------------------------
    pub palette: PaletteState,
    // RFC-0016 keyboard state
    // ------------------------------------------------------------------
    pub keyboard: KeyboardState,
    // ------------------------------------------------------------------
    // RFC-0014 project detail panel
    // ------------------------------------------------------------------
    pub detail_panel: detail_panel::DetailPanelState,
    // ------------------------------------------------------------------
    // RFC-0013 active modal
    // ------------------------------------------------------------------
    pub active_modal: ActiveModal,
    /// True = selection mode active (checkboxes visible, selection bar shown).
    /// Off by default — cards are clean until the user explicitly selects.
    pub selection_mode: bool,
    /// Whether to show technical command details in modal result views.
    /// Toggled by the "Show details" / "Hide details" button in result screens.
    pub show_op_details: bool,
    /// RFC-035 R8/Handoff 028 Ruling 6.1, renamed by RFC-073 D2: whether the
    /// "Arrange" disclosure holding the grouping/sorting selects is open.
    /// RFC-073 Amendment A6 §1 removed the toolbar's only other such flag
    /// (the compact chip overflow, `⋯`) — Compact now shares this same
    /// control and this same flag with Standard/Wide. Not cleared on
    /// resize (a stale `true` while the panel happens to be hidden is
    /// harmless).
    pub dashboard_arrange_open: bool,
    /// RFC-073 D11: whether Settings' "Advanced" disclosure is open.
    /// **Not saved** — `app.rs`'s `Message::Navigate` resets this to
    /// `false` every time Settings is entered, so it is always closed on
    /// a fresh visit, the same as this field's own default.
    pub settings_advanced_open: bool,
    /// A recently removed project eligible for undo (cleared by next action or timeout).
    pub recent_removal: Option<UndoableRemoval>,
    // ------------------------------------------------------------------
    // RFC-036 keyboard focus traversal
    // ------------------------------------------------------------------
    /// Current knotra-focus target for the dashboard/shell context.
    /// Presentation state only — not persisted, not in `AppConfig`.
    pub dashboard_focus: Option<focus::FocusTarget>,
    /// Current knotra-focus target while an overlay is open. Kept separate
    /// from `dashboard_focus` because R5 confines Tab/Shift-Tab to the
    /// overlay while it is open, and R7 needs `dashboard_focus` untouched
    /// underneath so focus can return to it when the overlay closes.
    pub overlay_focus: Option<focus::FocusTarget>,
    /// RFC-066 D4: whether the focus outline should be drawn right now.
    /// `true` from Tab/Shift-Tab/an arrow key/`j`/`k`; `false` from a mouse
    /// button press — the browser's `:focus-visible` behaviour. Focus
    /// itself (`dashboard_focus`/`overlay_focus`) is never cleared by
    /// either; only whether its ring is drawn changes.
    pub focus_visible: bool,
    // ------------------------------------------------------------------
    // RFC-035 R8 responsive mode
    // ------------------------------------------------------------------
    /// The dashboard's width-derived presentation mode (RFC-035 R8).
    /// **Reversed from a `responsive`-computed, `AppState`-excluded value
    /// (RFC-035's original Internal Design §Responsive strategy) to a real
    /// state field, fed by `Message::WindowResized`** (Handoff 028's
    /// finding, Handoff 029): `focus_order` runs inside `update()`, where
    /// no `responsive` closure's `Size` is reachable, so keyboard order and
    /// rendering could not derive from the same value under the original
    /// mechanism. See `width_mode.rs`'s module doc for the full history.
    pub width_mode: WidthMode,
    /// The window's current width in logical pixels (RFC-051 D1) — kept
    /// alongside `width_mode` rather than only the derived band, so overlay
    /// sizing (`OverlayWidth::pixels`) can scale continuously with the
    /// window instead of only in `WidthMode`'s coarse steps. Set on the same
    /// line as `width_mode` in `Message::WindowResized`'s handler, and
    /// seeded here from the same `INITIAL_WINDOW_SIZE` — the two must never
    /// be set independently, which is what R2's pairing test checks.
    pub window_width: f32,
}

impl AppState {
    #[cfg(test)]
    pub fn new(config: AppConfig) -> Self {
        Self::new_with_paths(config, AppPaths::resolve().0)
    }

    pub fn new_with_paths(config: AppConfig, paths: AppPaths) -> Self {
        let locale = config.locale;
        AppState {
            screen: Screen::Dashboard,
            catalog: Catalog::for_locale(locale),
            theme: KnotraTheme::from_choice(config.theme),
            workspace: None,
            workspace_status: None,
            load_phase: LoadPhase::Startup,
            filter: FilterState::default(),
            operation_logs: Vec::new(),
            history_unreadable_count: 0,
            history_directory_unreadable: false,
            history_search: String::new(),
            status_bar: None,
            add_project_dialog: None,
            confirm_remove_dialog: None,
            fetching_projects: HashSet::new(),
            is_refreshing: false,
            history_expanded: std::collections::HashSet::new(),
            settings_edit: SettingsEdit::from_config(&config),
            settings_save_msg: None,
            sync: sync::SyncCenterState::default(),
            context_ops: context::ContextOpsState::default(),
            freezer: freezer::FreezerState::default(),
            conflict_ops: conflict_ops::ConflictOpsState::default(),
            changelog: changelog::ChangelogState::default(),
            topology: topology::TopologyState::default(),
            all_workspaces: Vec::new(),
            active_workspace_idx: 0,
            workspace_mgr: workspace_mgr::WorkspaceMgrState::default(),
            missing_projects: std::collections::HashSet::new(),
            pending_tag_push: None,
            operation_interlock: OperationInterlock::default(),
            fs_poller: knotra_vcs::FsPoller::default(),
            selection: SelectionState::default(),
            activity: ActivityStripState::default(),
            palette: PaletteState::default(),
            keyboard: KeyboardState::default(),
            detail_panel: detail_panel::DetailPanelState::default(),
            active_modal: ActiveModal::default(),
            selection_mode: false,
            show_op_details: false,
            dashboard_arrange_open: false,
            settings_advanced_open: false,
            recent_removal: None,
            dashboard_focus: None,
            overlay_focus: None,
            focus_visible: false,
            width_mode: WidthMode::from_width(INITIAL_WINDOW_SIZE.width),
            window_width: INITIAL_WINDOW_SIZE.width,
            paths,
            config,
        }
    }

    pub fn t(&self, key: &'static str) -> &'static str {
        self.catalog.t(key)
    }

    pub fn apply_filter(&mut self, msg: FilterMessage) {
        match msg {
            FilterMessage::SearchChanged(s) => self.filter.search_text = s,
            FilterMessage::StatusFilterToggled(sf) => {
                if let Some(pos) = self.filter.status_filters.iter().position(|f| f == &sf) {
                    self.filter.status_filters.remove(pos);
                } else {
                    self.filter.status_filters.push(sf);
                }
            }
            FilterMessage::AllFiltersCleared => self.filter = FilterState::default(),
        }
    }

    pub fn visible_project_ids(&self) -> Vec<knotra_vcs::ProjectId> {
        self.dashboard_display().ordered_selectable_ids
    }

    /// RFC-035 R15/Handoff 030 §4.1, extended by RFC-073 D16 W3: the one
    /// catalog key explaining why no project is currently selectable,
    /// shared by every surface that needs that reason — the toolbar's
    /// Select control (`view/dashboard/toolbar.rs::select_mode_reason`)
    /// and the command palette's own "Enter selection" entry
    /// (`state/palette.rs::visible_projects_available`) both showed "No
    /// projects match this view" for the exact same underlying state
    /// before this method existed, which W3 would otherwise have fixed in
    /// one of the two and not the other. `None` when at least one project
    /// is currently selectable.
    pub fn visible_projects_unavailable_reason(&self) -> Option<&'static str> {
        if !self.visible_project_ids().is_empty() {
            return None;
        }
        let no_projects_registered = self
            .workspace
            .as_ref()
            .is_none_or(|workspace| workspace.projects.is_empty());
        if no_projects_registered {
            return Some(self.t("plain.selection.no_projects_registered"));
        }
        let display = self.dashboard_display();
        let all_in_closed_groups = !display.sections.is_empty()
            && display.sections.iter().all(|section| section.collapsed);
        Some(if all_in_closed_groups {
            self.t("plain.selection.all_in_closed_groups")
        } else {
            self.t("plain.selection.no_visible_projects")
        })
    }

    /// Task 103: a project's *current* name, looked up by id across every
    /// registered workspace — not only the active one, since a logged
    /// operation can name a project that now lives in a different
    /// workspace, or that was moved since. Used both to fill
    /// `ProjectOperationResult.project_name` at construction time, for a
    /// site that starts with only an id (`app/background/mod.rs`'s
    /// `skipped_retry_result`), and as the "current name" branch of
    /// History's own three-way resolver (`view/history.rs`'s
    /// `resolve_project_name`).
    pub fn find_project_name(&self, id: &knotra_vcs::ProjectId) -> Option<String> {
        self.all_workspaces
            .iter()
            .flat_map(|ws| &ws.projects)
            .find(|p| &p.id == id)
            .map(|p| p.name.clone())
    }

    /// RFC-071 D5: a status filter chip's own count.
    pub fn status_filter_count(&self, filter: &StatusFilter) -> usize {
        let projects = self
            .workspace
            .as_ref()
            .map(|ws| ws.projects.as_slice())
            .unwrap_or(&[]);
        dashboard::count_for_filter(
            projects,
            self.workspace_status.as_ref(),
            &self.missing_projects,
            filter,
        )
    }

    pub fn dashboard_display(&self) -> dashboard::DashboardDisplay<'_> {
        let projects = self
            .workspace
            .as_ref()
            .map(|ws| ws.projects.as_slice())
            .unwrap_or(&[]);
        dashboard::build_dashboard_display(
            projects,
            self.workspace_status.as_ref(),
            &self.missing_projects,
            &self.filter,
            dashboard::DashboardDisplayOptions {
                grouping: self.config.dashboard_grouping,
                sort: self.config.dashboard_sort,
                in_progress_collapsed: self.config.dashboard_in_progress_collapsed,
                all_set_collapsed: self.config.dashboard_all_set_collapsed,
            },
        )
    }

    pub fn selection_summary(&self) -> SelectionSummary {
        let visible_ids = self.visible_project_ids();
        let selected_ids: Vec<_> = visible_ids
            .iter()
            .filter(|id| self.selection.selected_ids.contains(*id))
            .cloned()
            .collect();

        let fetchable_ids: Vec<_> = selected_ids
            .iter()
            .filter(|id| !self.missing_projects.contains(*id))
            .cloned()
            .collect();

        let has_upstream = self.workspace_status.as_ref().is_some_and(|status| {
            status.projects.iter().any(|project_status| {
                selected_ids.contains(&project_status.project_id)
                    && project_status.remote.upstream.is_some()
                    && !self.missing_projects.contains(&project_status.project_id)
            })
        });

        SelectionSummary {
            selected_count: selected_ids.len(),
            selected_ids,
            visible_ids,
            fetchable_ids,
            has_upstream,
        }
    }

    pub fn reconcile_selection_with_display(&mut self) {
        let visible_ids: HashSet<_> = self.visible_project_ids().into_iter().collect();
        self.selection.retain_ids(&visible_ids);
    }

    pub fn clear_selection_mode(&mut self) {
        self.selection.clear();
        self.selection_mode = false;
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// RFC-035 R8/Handoff 029 §2.2: the initial `width_mode` must be
    /// *derived* from `INITIAL_WINDOW_SIZE`, not a hardcoded default that
    /// happens to match today's configured size by accident of enum
    /// ordering — this would silently go wrong if `INITIAL_WINDOW_SIZE`
    /// (or `main.rs`'s `window::Settings`, which reads the same constant)
    /// ever changed without this staying in sync.
    #[test]
    fn initial_width_mode_is_derived_from_initial_window_size() {
        let state = AppState::new(AppConfig::default());
        assert_eq!(
            state.width_mode,
            WidthMode::from_width(INITIAL_WINDOW_SIZE.width)
        );
    }
}