paperboy 0.5.5

A Rust TUI API tester
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
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
//! Persistence of the whole application state (tabs, collections, environments)
//! between sessions.

use std::fs;
use std::path::PathBuf;

use serde::{Deserialize, Serialize};

use crate::collection::Collection;
use crate::env_panel::EnvSource;
use crate::environment::{Environment, PendingSecret, parse_vars_pending};
use crate::git_remote::GitOrigin;
use crate::hurl::HurlEntry;
use crate::i18n::Language;
use crate::remote_flow::WorkspaceGitOrigin;
use crate::request::RequestView;

// ── Session state persistence ───────────────────────────────────────────────

/// One persisted tab: its display name plus the requests it holds.
/// A persisted environment: the variables' *source* form (provider references
/// like `{{ op://… }}`, or literals) — never resolved secret values — so it can
/// be reloaded and re-resolved on the next launch without writing secrets to disk.
/// Since environments are now global (shared across collections), this also
/// carries the source `.vars` path/git origin (moved here from `PersistedTab`).
#[derive(Serialize, Deserialize, Default, Clone)]
pub struct PersistedEnv {
    pub name: String,
    #[serde(default)]
    pub vars: Vec<PersistedVar>,
    /// Source `.vars` file this environment was loaded from (used by "Save
    /// Environment"). `None` for a hand-made environment until saved.
    #[serde(default)]
    pub path: Option<String>,
    /// Where the `.vars` file was loaded from in git, if it was.
    #[serde(default)]
    pub git_origin: Option<GitOrigin>,
}

#[derive(Serialize, Deserialize, Default, Clone)]
pub struct PersistedVar {
    pub key: String,
    /// The `.vars` source token (reference or literal), re-parsed on load.
    pub raw: String,
    #[serde(default)]
    pub user_added: bool,
}

impl PersistedEnv {
    pub fn from_environment(env: &Environment) -> Self {
        Self {
            name: env.name.clone(),
            vars: env
                .vars
                .iter()
                .map(|v| PersistedVar {
                    key: v.key.clone(),
                    raw: v.raw.clone(),
                    user_added: v.user_added,
                })
                .collect(),
            path: env.path.as_ref().map(|p| p.to_string_lossy().into_owned()),
            git_origin: env.git_origin.clone(),
        }
    }

    /// Rebuild the [`Environment`], leaving any provider references marked
    /// `loading` rather than resolving them immediately. Returns the
    /// environment and its list of pending secrets (if any) so the caller can
    /// gather several environments' pending secrets together and resolve them
    /// all in a single background batch (see [`crate::environment::spawn_resolution_many`]),
    /// instead of one authorization prompt per environment.
    pub fn restore(&self) -> (Environment, Vec<PendingSecret>) {
        let content = self
            .vars
            .iter()
            // A `.vars` line can't carry a newline, and JSON can, so a state
            // file written before values were flattened may still hold one.
            // Flatten on the way back in rather than letting the re-parse drop
            // everything after the first line.
            .map(|v| format!("{}={}", v.key, crate::environment::flatten_value(&v.raw)))
            .collect::<Vec<_>>()
            .join("\n");
        let (mut env, pending) = parse_vars_pending(self.name.clone(), &content);
        // Re-apply the hand-added marker (lost by re-parsing as a file).
        for pv in &self.vars {
            if pv.user_added
                && let Some(var) = env.vars.iter_mut().find(|x| x.key == pv.key)
            {
                var.user_added = true;
            }
        }
        env.path = self
            .path
            .clone()
            .filter(|s| !s.is_empty())
            .map(std::path::PathBuf::from)
            .map(crate::shared_utils::file_path);
        env.git_origin = self.git_origin.clone();
        (env, pending)
    }
}

#[derive(Serialize, Deserialize, Default)]
pub struct PersistedTab {
    pub name: String,
    #[serde(default)]
    pub entries: Vec<HurlEntry>,
    #[serde(default)]
    pub selected_entry: usize,
    /// Source `.hurl` path, so "Save Collection" still targets the right file
    /// after a restart.
    #[serde(default)]
    pub path: Option<String>,
    /// Where the `.hurl` file was loaded from in git, if it was, so the ⎇ icon
    /// and "Save Collection to Git…" defaults survive a restart.
    #[serde(default)]
    pub git_origin: Option<GitOrigin>,
    /// Index into `PersistedState.global_envs` of the Global Environment
    /// linked/"pinned" to this collection, if any. Remapped to a fresh
    /// `Environment` id on restore (ids aren't stable across restarts).
    #[serde(default)]
    pub linked_env_index: Option<usize>,
    /// Root folder this tab is bound to as a Workspace (see
    /// [`crate::workspace`]), if any. When set, `entries` is NOT a trusted
    /// snapshot — [`Self::into_collection`] re-reads `path` fresh from disk
    /// instead, since a Workspace is a live folder rather than a frozen file.
    #[serde(default)]
    pub workspace_root: Option<String>,
    /// Remembered `.hurl`/`.json` filter toggle for this tab's Workspace
    /// picker. Missing/`None` (older state files) defaults to `true`.
    #[serde(default)]
    pub workspace_filter_hurl_json: Option<bool>,
    /// Whether `workspace_root` is a throwaway folder downloaded from git
    /// rather than a folder the user picked themselves — carried across a
    /// restart so closing this tab later still offers to delete it (see
    /// [`Collection::workspace_downloaded_from_git`]).
    #[serde(default)]
    pub workspace_downloaded_from_git: bool,
    /// Where this tab's Workspace was downloaded from in git, if it was —
    /// carried across a restart so a vanished `workspace_root` (see
    /// [`Self::into_collection`]) can still be offered a redownload instead
    /// of just being reported as permanently missing.
    #[serde(default)]
    pub workspace_git_origin: Option<WorkspaceGitOrigin>,
    /// Expanded folder paths in the workspace file tree, stored as
    /// forward-slash-separated paths relative to `workspace_root`.  Absent in
    /// older state files (field defaults to empty), which means all folders
    /// start collapsed — a safe, backwards-compatible default.
    #[serde(default)]
    pub workspace_expanded_paths: Vec<String>,
    /// The workspace-tree node the user last selected, as a forward-slash path
    /// relative to `workspace_root` (see [`Collection::workspace_selected`]).
    /// Absent in older state files, which simply means the tab reopens on its
    /// loaded collection file as it always did.
    #[serde(default)]
    pub workspace_selected_path: Option<String>,
}

/// Enough information to offer redownloading a Workspace whose entire
/// `workspace_root` has vanished (see [`PersistedTab::into_collection`]) —
/// only produced when the vanished folder was originally downloaded from
/// git (an ordinary local folder that was simply moved/deleted has nothing
/// to redownload, so the tab is just reset with no prompt for it).
pub struct PendingWorkspaceReload {
    pub tab_name: String,
    pub origin: WorkspaceGitOrigin,
    /// The previously-selected file's path *relative to* the old (now dead)
    /// `workspace_root`, so it can be re-resolved against a freshly
    /// downloaded folder — which will have a different absolute temp path.
    pub relative_selected_path: Option<String>,
}

/// A path rendered as forward-slash-separated components, so relative paths in
/// `state.json` round-trip between platforms.
fn rel_slashes(rel: &std::path::Path) -> String {
    rel.components()
        .filter_map(|comp| comp.as_os_str().to_str())
        .collect::<Vec<_>>()
        .join("/")
}

impl PersistedTab {
    /// Snapshot a collection's persistable parts. `linked_env_index` is
    /// filled in by the caller (it needs the full global list to resolve the
    /// collection's `linked_env_id` to an index).
    pub fn from_collection(c: &Collection, linked_env_index: Option<usize>) -> Self {
        Self {
            name: c.name.clone(),
            // A Workspace-bound tab's entries are never a trusted snapshot —
            // its folder is re-scanned and the selected file re-read fresh
            // from disk on restore (see `into_collection`), so there's no
            // point (and some risk of staleness) in persisting them here.
            entries: if c.workspace_root.is_some() {
                Vec::new()
            } else {
                c.entries.clone()
            },
            selected_entry: c.selected_entry,
            path: c.path.as_ref().map(|p| p.to_string_lossy().into_owned()),
            git_origin: c.git_origin.clone(),
            linked_env_index,
            workspace_root: c
                .workspace_root
                .as_ref()
                .map(|p| p.to_string_lossy().into_owned()),
            workspace_filter_hurl_json: c
                .workspace_root
                .is_some()
                .then_some(c.workspace_filter_hurl_json),
            workspace_downloaded_from_git: c.workspace_downloaded_from_git,
            workspace_git_origin: c.workspace_git_origin.clone(),
            // Serialise expanded paths relative to workspace_root using
            // forward slashes so they survive cross-platform round-trips.
            workspace_expanded_paths: c
                .workspace_root
                .as_ref()
                .map(|root| {
                    let mut paths: Vec<String> = c
                        .workspace_expanded
                        .iter()
                        .filter_map(|abs| abs.strip_prefix(root).ok().map(rel_slashes))
                        .filter(|s| !s.is_empty())
                        .collect();
                    paths.sort(); // deterministic JSON
                    paths
                })
                .unwrap_or_default(),
            workspace_selected_path: match (&c.workspace_root, &c.workspace_selected) {
                (Some(root), Some(sel)) => sel.strip_prefix(root).ok().map(rel_slashes),
                _ => None,
            },
        }
    }

    /// Rebuild a collection from persisted data. `linked_env_id` is resolved
    /// by the caller from `linked_env_index` (see [`Self::from_collection`]),
    /// against the freshly-restored global environments' ids. Also returns
    /// a [`PendingWorkspaceReload`] whenever this tab's entire Workspace
    /// root has vanished *and* it's known to have come from git — the
    /// caller (`TuiApp::apply_persisted`) uses this to offer redownloading
    /// it instead of just reporting it as permanently gone.
    pub fn into_collection(
        self,
        linked_env_id: Option<u64>,
    ) -> (Collection, Option<PendingWorkspaceReload>) {
        let workspace_root = self
            .workspace_root
            .filter(|s| !s.is_empty())
            .map(std::path::PathBuf::from);
        let path = self
            .path
            .filter(|s| !s.is_empty())
            .map(std::path::PathBuf::from)
            // Repairs a path saved before it was cleaned on the way in: a
            // trailing separator makes the file unwritable and unreadable, and
            // the tab would go on failing to save for as long as the state
            // survived.
            .map(crate::shared_utils::file_path);

        // If the whole workspace root is gone (not just the last-selected
        // file) — e.g. it was a git-downloaded temp folder and the OS swept
        // /tmp since the last session — there's nothing left to re-read or
        // re-scan at all. Reset the tab back to an ordinary "no collection
        // chosen yet" tab (no folder/git icons, no phantom root) rather than
        // silently keeping a dead path around: an empty workspace picker
        // with no explanation would be far more confusing than a plain tab,
        // and `workspace_downloaded_from_git` would otherwise keep offering
        // a nonsensical "keep the (already-gone) folder?" choice on close.
        // The caller (`TuiApp::apply_persisted`) detects this by comparing
        // `workspace_root` before/after and surfaces a status message (or,
        // if `pending_reload` below is `Some`, a redownload prompt instead).
        let root_missing = workspace_root.as_ref().is_some_and(|r| !r.exists());

        // Captured *before* anything below is reset/moved away: if this was
        // a git download, remember enough to offer redownloading it — the
        // previously-selected file's path *relative to* the (now-dead) root,
        // so it can be re-resolved against a freshly downloaded folder,
        // which will have a different absolute temp path.
        let pending_reload = if root_missing {
            self.workspace_git_origin.clone().map(|origin| {
                let relative_selected_path = match (&path, &workspace_root) {
                    (Some(p), Some(root)) => p
                        .strip_prefix(root)
                        .ok()
                        .map(|rel| rel.to_string_lossy().into_owned()),
                    _ => None,
                };
                PendingWorkspaceReload {
                    tab_name: self.name.clone(),
                    origin,
                    relative_selected_path,
                }
            })
        } else {
            None
        };

        let workspace_root = if root_missing { None } else { workspace_root };

        // A Workspace tab is bound to a live folder, not a frozen file: on
        // restart, re-read whichever file was last selected straight from
        // disk. If the root (or just that one file) has vanished since, fall
        // back to the empty "no collection chosen yet" state instead of
        // showing stale content — the picker auto-opens to let the user pick
        // a replacement.
        // Whether the entries below came from the file or from the snapshot.
        // Only the snapshot can hold edits the file has never seen, and only it
        // therefore needs its recorded baselines kept rather than restamped.
        let mut restored_entries = false;
        let (entries, path) = if workspace_root.is_some() {
            match path
                .as_ref()
                .filter(|p| p.exists())
                .and_then(|p| std::fs::read_to_string(p).ok())
            {
                Some(content) => (crate::postman::parse_collection(&content), path),
                None => (Vec::new(), None),
            }
        } else if root_missing {
            (Vec::new(), None)
        } else {
            restored_entries = true;
            (self.entries, path)
        };

        // Captured before the collection is built, because building one treats
        // its entries as freshly agreed with the file and restamps them.
        let baselines: Vec<Option<String>> = restored_entries
            .then(|| entries.iter().map(|e| e.baseline.clone()).collect())
            .unwrap_or_default();
        let mut c = Collection::new(self.name, entries);
        if restored_entries {
            c.adopt_restored_entries(baselines);
        }
        c.selected_entry = self.selected_entry.min(c.entries.len().saturating_sub(1));
        c.path = path;
        // After the path, which is what the baselines are checked against.
        if restored_entries {
            c.repair_restored_baselines();
            // After the baselines, which is what the file's requests are
            // matched against to work out what the list still holds.
            c.rebuild_restored_structure_baseline();
        }
        c.git_origin = self.git_origin;
        c.linked_env_id = linked_env_id;
        c.workspace_root = workspace_root;
        c.workspace_filter_hurl_json = self.workspace_filter_hurl_json.unwrap_or(true);
        c.workspace_downloaded_from_git = self.workspace_downloaded_from_git && !root_missing;
        c.workspace_git_origin = if root_missing {
            None
        } else {
            self.workspace_git_origin
        };
        c.sync_folder_to_selected();
        // Restore expanded folders: convert relative slash-paths back to
        // absolute paths by prepending workspace_root.
        c.workspace_expanded = if let Some(root) = &c.workspace_root {
            self.workspace_expanded_paths
                .iter()
                .filter(|s| !s.is_empty())
                .map(|rel| root.join(rel))
                .collect()
        } else {
            std::collections::HashSet::new()
        };
        // Ensure the loaded file's ancestor folders are expanded so it is
        // immediately visible, then position the cursor on it.
        c.expand_ancestors_for_path();
        // Collections that were left expanded last session must list their
        // requests without having been opened yet this session — read their
        // names from disk into the cache.
        c.rebuild_expanded_titles();
        c.sync_ws_cursor();
        // Only remember a selection whose file is still there — a workspace is a
        // live folder, so the node may well have been deleted or renamed since,
        // and reopening on a path that no longer exists would just report an
        // error the user didn't ask for.
        c.workspace_selected = match (&c.workspace_root, &self.workspace_selected_path) {
            (Some(root), Some(rel)) if !rel.is_empty() => {
                Some(root.join(rel)).filter(|p| p.exists())
            }
            _ => None,
        };
        (c, pending_reload)
    }
}

/// One persisted report tab (see [`crate::report::Report`]). The `.trail`
/// *source text* is snapshotted (like [`PersistedTab`] snapshots collection
/// entries) so an unsaved scratch report survives a restart; `path`/`git_origin`
/// keep "Save" targeting the right place after a restart.
#[derive(Serialize, Deserialize, Default, Clone)]
pub struct PersistedReport {
    pub name: String,
    #[serde(default)]
    pub text: String,
    #[serde(default)]
    pub path: Option<String>,
    #[serde(default)]
    pub git_origin: Option<GitOrigin>,
    /// When this report was opened from a Workspace tree, the workspace root
    /// folder (absolute path) so it re-embeds in that Workspace collection tab's
    /// right pane on restart. `None` for an ordinary standalone report tab.
    #[serde(default)]
    pub workspace_root: Option<String>,
    /// For a Workspace-embedded report, whether it was the one *shown* in its
    /// Workspace tab's right pane (`true`) rather than merely retained while the
    /// tab showed its request/response view (`false`). Ignored for standalone
    /// reports. Older state files (no field) default to `true`, matching the
    /// "opened ⇒ shown" behaviour.
    #[serde(default = "default_true")]
    pub embedded_active: bool,
}

fn default_true() -> bool {
    true
}

/// One report's remembered parameter values (see
/// [`PersistedState::report_params`]).
#[derive(Serialize, Deserialize, Default, Clone, PartialEq, Eq)]
pub struct PersistedReportParams {
    /// [`crate::report::Report::param_key`] — path, git origin, or name.
    pub key: String,
    /// `NAME = value`, keyed by the parameter's raw name so relabelling a
    /// parameter never orphans what was chosen for it. A pair sorted by name,
    /// again so the file doesn't churn.
    pub values: Vec<(String, String)>,
}

impl PersistedReport {
    /// Snapshot a report's persistable parts.
    pub fn from_report(r: &crate::report::Report) -> Self {
        Self {
            name: r.name.clone(),
            text: r.text.clone(),
            path: r.path.as_ref().map(|p| p.to_string_lossy().into_owned()),
            git_origin: r.git_origin.clone(),
            // Workspace context lives on the TUI `ReportTab`, not the core
            // `Report`; the tui layer fills these in when snapshotting (see
            // `TuiApp::to_persisted`).
            workspace_root: None,
            embedded_active: true,
        }
    }

    /// Rebuild an in-memory report from persisted state. A restored report is
    /// not marked dirty (it matches what was last saved/persisted).
    pub fn into_report(self) -> crate::report::Report {
        crate::report::Report {
            id: crate::report::report::next_report_id(),
            name: self.name,
            text: self.text,
            path: self.path.map(PathBuf::from),
            git_origin: self.git_origin,
            dirty: false,
        }
    }
}

/// Which view the GUI's centre column was showing, so it reopens on the same
/// thing rather than always dropping the user back on the request editor.
///
/// A report opened from a Workspace file has no stable identity to persist (it
/// is addressed by an on-disk path that may have moved), so those record as
/// [`GuiView::Reports`] — the list is still the right place to land.
#[derive(Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Debug, Default)]
pub enum GuiView {
    /// The request editor (the default view).
    #[default]
    Requests,
    /// The reports list.
    Reports,
    /// The block editor open on the session report at this index.
    Report(usize),
}

/// Window and panel geometry for the graphical front-end.
///
/// The terminal UI's `list_width`/`response_pct` are measured in character
/// cells and percentages of a text grid, so they cannot describe a pixel layout
/// the user dragged with a mouse — rounding one into the other would creep the
/// panels every time the two front-ends were used in turn. The GUI therefore
/// records its own geometry here and the two leave each other's alone.
///
/// Every size is optional: `None` means "never adjusted", which is what lets
/// the GUI fall back to a layout derived from the terminal defaults on a fresh
/// profile.
#[derive(Serialize, Deserialize, Clone, Copy, PartialEq, Debug, Default)]
pub struct GuiLayout {
    /// Inner size of the window in logical points.
    #[serde(default)]
    pub window: Option<(f32, f32)>,
    /// Width of the left column (Requests + Global Environments).
    #[serde(default)]
    pub left_width: Option<f32>,
    /// Height of the Global Environments panel inside the left column.
    #[serde(default)]
    pub env_height: Option<f32>,
    /// Height of the Response panel under the request editor.
    #[serde(default)]
    pub response_height: Option<f32>,
    /// Height of the report editor's diagnostics panel.
    #[serde(default)]
    pub report_diag_height: Option<f32>,
    /// Width of the report editor's block palette column.
    #[serde(default)]
    pub report_palette_width: Option<f32>,
    /// Height of the results view's summary block (metrics, filters, matrices).
    #[serde(default)]
    pub report_summary_height: Option<f32>,
    /// Height of the row drill-down panel under the results grid.
    #[serde(default)]
    pub report_detail_height: Option<f32>,
    /// Which centre-column view was open.
    #[serde(default)]
    pub view: GuiView,
    /// Whether the open report editor was showing Blocks or Source. Stored as
    /// a flag rather than the full `EditorView` because the Results view has
    /// nothing to show until the report is run again.
    #[serde(default)]
    pub report_source_view: bool,
}

/// The full application state saved between sessions. Environments are stored
/// in *source* form only (references/literals) so resolved secrets are never
/// written to disk; they are re-resolved on load.
#[derive(Serialize, Deserialize)]
pub struct PersistedState {
    #[serde(default, deserialize_with = "lenient")]
    pub language: Language,
    #[serde(default)]
    pub base_url: String,
    #[serde(default)]
    pub tabs: Vec<PersistedTab>,
    /// Persisted report tabs (see [`PersistedReport`]). Restored after the
    /// collection tabs on launch.
    #[serde(default)]
    pub reports: Vec<PersistedReport>,
    /// The tab that was active when the app was last closed, so it reopens on
    /// the same tab.
    #[serde(default)]
    pub active_tab: usize,
    /// Last folder a file was chosen from in the TUI file browser, so it can
    /// reopen there next time.
    #[serde(default)]
    pub last_browse_dir: Option<String>,
    /// Last folder an *environment* file was loaded from, so the environment
    /// picker can reopen there independently of other file loads.
    #[serde(default)]
    pub last_env_dir: Option<String>,
    /// Last folder a Postman import was written into, so the next import
    /// suggests the same place and downloaded workspaces stay together.
    #[serde(default)]
    pub last_import_dir: Option<String>,
    /// Ask for confirmation before quitting the app.
    #[serde(default = "yes")]
    pub confirm_on_exit: bool,
    /// Ask for confirmation before closing all collections.
    #[serde(default = "yes")]
    pub confirm_on_clear: bool,
    /// Ask for confirmation before deleting a Global Environment.
    #[serde(default = "yes")]
    pub confirm_on_delete_env: bool,
    /// Ask for confirmation before deleting a request.
    #[serde(default = "yes")]
    pub confirm_on_delete_request: bool,
    /// When set, auto-pick "Save" on a Save/Discard/Cancel unsaved-changes
    /// prompt (Workspace collection switch or git push) instead of showing it.
    #[serde(default)]
    pub always_save_when_prompted: bool,
    /// Width (in columns) of the left column (Requests/Environment panels),
    /// user-adjustable with `<`/`>`.
    #[serde(default = "default_list_width")]
    pub list_width: u16,
    /// Height (as a percentage) of the Response/Environment panels, relative to
    /// their column, user-adjustable with `+`/`-`.
    #[serde(default = "default_response_pct")]
    pub response_pct: u16,
    /// Git URLs the user has loaded a collection/environment from, most recent
    /// first, offered as a pickable list in the "Load from Git" wizard.
    #[serde(default)]
    pub recent_git_urls: Vec<String>,
    /// Provider *references* the Postman API key has been read from, most
    /// recent first — `{{ op://… }}`, `{{ ssm:/… }}`, `{{ env:… }}`. Never a
    /// pasted key: a reference is an address, which is safe to keep, where the
    /// key itself is the credential and is never written to disk.
    #[serde(default)]
    pub recent_key_refs: Vec<String>,
    /// The parameter values each report was last run with, most recently used
    /// first. Keyed by the report's file path (or git origin, or name) rather
    /// than its process-unique id, so reopening tomorrow offers back what you
    /// chose today.
    ///
    /// A list rather than a map so `state.json` is written in a stable order:
    /// a serialized `HashMap` reshuffles between runs and turns every save
    /// into a diff. The report file itself is never touched — the default in
    /// the `.trail` is what the report *says*, this is only what this user
    /// last *did*.
    #[serde(default)]
    pub report_params: Vec<PersistedReportParams>,
    /// Which of JSON / Hurl text the Main (Request) panel shows by default for
    /// every request (Settings → Preferences → Default Request View).
    #[serde(default, deserialize_with = "lenient")]
    pub default_request_view: RequestView,
    /// Run "Run All" in batch mode (whole collection in one Hurl execution)
    /// rather than streaming per-entry. Off by default (streaming).
    #[serde(default)]
    pub run_all_batch_mode: bool,
    /// Let Esc throw away a request wizard's unsaved edits without asking
    /// (Settings → Preferences). Off by default, so the prompt is shown.
    #[serde(default)]
    pub discard_request_edits_on_esc: bool,
    /// User-created themes (Settings → Theme). Built-in presets are not stored.
    #[serde(default)]
    pub custom_themes: Vec<crate::tui::theme::ThemeSpec>,
    /// The explicitly-chosen theme name, or `None` to follow the language
    /// preset. Persisted so a manual theme choice survives restarts.
    #[serde(default)]
    pub active_theme: Option<String>,
    /// The global list of Environments (source form only — no resolved
    /// secrets), shared across all collections. Replaces the old per-tab
    /// `env` field.
    #[serde(default)]
    pub global_envs: Vec<PersistedEnv>,
    /// Index into `global_envs` of the currently-activated Global
    /// Environment, if any.
    #[serde(default)]
    pub active_global_env: Option<usize>,
    /// Which source(s) the Environments panel lists. Shared by both front-ends
    /// because they share the same row model and saved state file.
    #[serde(default, deserialize_with = "lenient")]
    pub env_source: EnvSource,
    /// GUI-only window/panel geometry and last-open view (see [`GuiLayout`]).
    /// Ignored by the terminal UI, which round-trips it untouched so using one
    /// front-end never discards the other's layout.
    #[serde(default, deserialize_with = "lenient")]
    pub gui: GuiLayout,
}

fn yes() -> bool {
    true
}

fn default_list_width() -> u16 {
    38
}

fn default_response_pct() -> u16 {
    42
}

impl Default for PersistedState {
    fn default() -> Self {
        Self {
            language: Language::default(),
            base_url: String::new(),
            tabs: Vec::new(),
            reports: Vec::new(),
            active_tab: 0,
            last_browse_dir: None,
            last_env_dir: None,
            last_import_dir: None,
            confirm_on_exit: true,
            confirm_on_clear: true,
            confirm_on_delete_env: true,
            confirm_on_delete_request: true,
            always_save_when_prompted: false,
            list_width: default_list_width(),
            response_pct: default_response_pct(),
            recent_git_urls: Vec::new(),
            recent_key_refs: Vec::new(),
            report_params: Vec::new(),
            default_request_view: RequestView::default(),
            run_all_batch_mode: false,
            discard_request_edits_on_esc: false,
            custom_themes: Vec::new(),
            active_theme: None,
            global_envs: Vec::new(),
            active_global_env: None,
            env_source: EnvSource::Both,
            gui: GuiLayout::default(),
        }
    }
}

/// Location of the saved state file. Honours `PAPERBOY_STATE_DIR` (used by
/// tests), else falls back to the platform config directory.
fn state_path() -> Option<PathBuf> {
    if let Some(dir) = std::env::var_os("PAPERBOY_STATE_DIR") {
        return Some(PathBuf::from(dir).join("state.json"));
    }
    let base = std::env::var_os("XDG_CONFIG_HOME")
        .map(PathBuf::from)
        .or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".config")))
        .or_else(|| std::env::var_os("APPDATA").map(PathBuf::from))?;
    Some(base.join("paperboy").join("state.json"))
}

/// Deserialize a field, falling back to its default rather than failing the
/// whole document when the value isn't one this build understands.
///
/// State is written by whichever version ran last, and a value a newer build
/// invented — a new `EnvSource`, a new form-field kind — used to abort the
/// entire parse, taking every tab, collection and environment with it. One
/// unrecognised setting is worth losing; a session is not.
///
/// **This has to be applied to every enum reachable from the saved state**, not
/// just the top-level settings: the enums nested inside a saved request
/// ([`FormFieldKind`](crate::hurl::entry::FormFieldKind),
/// [`CommentAnchor`](crate::hurl::entry::CommentAnchor)) are exactly the ones a
/// new feature is likely to extend, and an unknown value in any one of them
/// fails the document just as hard.
pub(crate) fn lenient<'de, D, T>(d: D) -> Result<T, D::Error>
where
    D: serde::Deserializer<'de>,
    T: serde::de::DeserializeOwned + Default,
{
    let value = serde_json::Value::deserialize(d)?;
    Ok(serde_json::from_value(value).unwrap_or_default())
}

/// Load the saved state, or `None` if there is no readable/parsable state file.
///
/// A file that exists but doesn't parse is moved aside rather than left in
/// place, because the app saves continuously: leaving it would mean the next
/// keystroke overwrote the only copy of a session we merely failed to read.
pub fn load_state() -> Option<PersistedState> {
    let path = state_path()?;
    let text = fs::read_to_string(&path).ok()?;
    match serde_json::from_str(&text) {
        Ok(state) => Some(state),
        Err(e) => {
            let aside = path.with_extension("json.unreadable");
            let _ = fs::rename(&path, &aside);
            eprintln!(
                "paperboy: could not read {} ({e}); it has been kept as {} and a fresh session started",
                path.display(),
                aside.display()
            );
            None
        }
    }
}

/// Write the given state to disk, creating the config directory if needed.
/// A no-op under `cargo test` so unit tests never touch the real config dir
/// (end-to-end persistence is covered by running the real binary).
pub fn save_state(state: &PersistedState) {
    if cfg!(test) {
        return;
    }
    let Some(path) = state_path() else { return };
    if let Some(parent) = path.parent() {
        let _ = fs::create_dir_all(parent);
    }
    if let Ok(json) = serde_json::to_string_pretty(state) {
        let _ = fs::write(path, json);
    }
}

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

    #[test]
    fn persisted_report_round_trips_through_serde_and_back() {
        let mut r = crate::report::Report::from_text(
            "nightly",
            "# name: Nightly\n# collection: c.hurl\nREQUEST Oauth\n",
        );
        r.path = Some(PathBuf::from("/tmp/nightly.trail"));

        let persisted = PersistedReport::from_report(&r);
        let json = serde_json::to_string(&persisted).unwrap();
        let back: PersistedReport = serde_json::from_str(&json).unwrap();
        let restored = back.into_report();

        assert_eq!(restored.name, "Nightly");
        assert_eq!(restored.text, r.text);
        assert_eq!(restored.path, r.path);
        assert!(!restored.dirty, "a restored report is not dirty");
    }

    /// Build a `.hurl` file of three named GET requests in a fresh temp
    /// folder, and the saved-session tab that goes with it.
    fn saved_tab_for_a_three_request_file(tag: &str) -> (PathBuf, PersistedTab) {
        let dir = std::env::temp_dir().join(format!("paperboy_restore_{tag}"));
        let _ = std::fs::create_dir_all(&dir);
        let path = dir.join("c.hurl");
        let entries: Vec<HurlEntry> = ["one", "two", "three"]
            .iter()
            .map(|n| {
                HurlEntry::from_fields(
                    n,
                    "GET",
                    &format!("https://example.com/{n}"),
                    Vec::new(),
                    "",
                )
            })
            .collect();
        let text: String = entries.iter().map(|e| e.to_hurl()).collect();
        std::fs::write(&path, &text).unwrap();

        // What a collection freshly read from that file looks like: every
        // request agrees with it.
        let mut c = Collection::new("c".to_string(), entries);
        c.path = Some(path.clone());
        c.reset_structure_baseline();
        (path, PersistedTab::from_collection(&c, None))
    }

    /// A request deleted and left unsaved has to still be there to save after
    /// a restart. The restored list was adopted as its own structural
    /// baseline, so the tab came back looking as though it matched the file --
    /// and quitting a second time asked nothing before throwing the deletion
    /// away, which is precisely what the unsaved-changes prompt is for.
    #[test]
    fn a_deletion_left_unsaved_survives_a_restart() {
        let (path, mut tab) = saved_tab_for_a_three_request_file("delete");
        tab.entries.remove(1);

        let (c, _) = tab.into_collection(None);
        assert!(
            c.has_unsaved_edits(),
            "the file still holds the deleted request, so there is something to save"
        );
        let _ = std::fs::remove_dir_all(path.parent().unwrap());
    }

    /// The same for a drag: the requests are all still there, but not in the
    /// order the file has them in.
    #[test]
    fn a_reorder_left_unsaved_survives_a_restart() {
        let (path, mut tab) = saved_tab_for_a_three_request_file("reorder");
        tab.entries.swap(0, 2);

        let (c, _) = tab.into_collection(None);
        assert!(
            c.has_unsaved_edits(),
            "the list is in a different order from the file"
        );
        let _ = std::fs::remove_dir_all(path.parent().unwrap());
    }

    /// And the other way round: a session restored exactly as it was saved
    /// must not claim to hold changes it does not have, or the prompt becomes
    /// noise people learn to dismiss.
    #[test]
    fn an_untouched_session_comes_back_clean() {
        let (path, tab) = saved_tab_for_a_three_request_file("clean");

        let (c, _) = tab.into_collection(None);
        assert!(
            !c.has_unsaved_edits(),
            "nothing was changed, so there is nothing to save"
        );
        let _ = std::fs::remove_dir_all(path.parent().unwrap());
    }

    /// A Workspace tab reopens on whatever node was last selected in its tree,
    /// including the `.trail` reports and `.vars` environments that previously
    /// left no trace at all.
    #[test]
    fn a_workspaces_selected_node_round_trips_and_drops_when_it_vanishes() {
        let root =
            std::env::temp_dir().join(format!("paperboy_ws_selected_test_{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&root);
        std::fs::create_dir_all(root.join("nightly")).unwrap();
        let report = root.join("nightly/run.trail");
        std::fs::write(&report, "REQUEST A\n").unwrap();

        let mut c = Collection::new("ws".to_string(), Vec::new());
        c.workspace_root = Some(root.clone());
        c.workspace_selected = Some(report.clone());

        let persisted = PersistedTab::from_collection(&c, None);
        assert_eq!(
            persisted.workspace_selected_path.as_deref(),
            Some("nightly/run.trail"),
            "stored relative to the root, with forward slashes"
        );

        let json = serde_json::to_string(&persisted).unwrap();
        let back: PersistedTab = serde_json::from_str(&json).unwrap();
        let (restored, _) = back.into_collection(None);
        assert_eq!(restored.workspace_selected, Some(report.clone()));

        // A workspace is a live folder: a node deleted since the last session
        // must not come back as a selection that only produces an error.
        std::fs::remove_file(&report).unwrap();
        let json = serde_json::to_string(&PersistedTab::from_collection(&c, None)).unwrap();
        let back: PersistedTab = serde_json::from_str(&json).unwrap();
        let (restored, _) = back.into_collection(None);
        assert_eq!(restored.workspace_selected, None);
        let _ = std::fs::remove_dir_all(&root);
    }

    /// An older `state.json` has no selection recorded; the tab must still open.
    #[test]
    fn a_state_file_without_a_workspace_selection_still_loads() {
        let tab: PersistedTab = serde_json::from_str(r#"{"name":"ws","entries":[]}"#).unwrap();
        assert_eq!(tab.workspace_selected_path, None);
        let (c, _) = tab.into_collection(None);
        assert_eq!(c.workspace_selected, None);
    }

    #[test]
    fn persisted_state_defaults_have_no_reports() {
        let state = PersistedState::default();
        assert!(state.reports.is_empty());
    }

    /// Regression: a value a newer build invented must cost that one setting,
    /// not the session. A strict parse failed the whole document, `load_state`
    /// turned that into "no state", and the next save wrote the empty default
    /// over a file that still held every tab the user had open.
    #[test]
    fn an_unknown_setting_written_by_a_newer_build_costs_only_that_setting() {
        let json = r#"{
            "language": "English",
            "base_url": "",
            "tabs": [{"name": "Coll", "entries": [], "selected_entry": 0}],
            "env_source": "OnlyRemote",
            "default_request_view": "SomethingNewer"
        }"#;
        let state: PersistedState = serde_json::from_str(json).expect("the document still parses");
        assert_eq!(state.tabs.len(), 1, "the open tab survives");
        assert_eq!(state.tabs[0].name, "Coll");
        assert_eq!(state.env_source, EnvSource::default());
        assert_eq!(state.default_request_view, RequestView::default());
    }

    /// The same forward-compatibility has to hold for the enums *nested inside*
    /// a saved request, which is where a new feature is most likely to add a
    /// variant. A form-field kind or comment anchor this build doesn't know
    /// used to fail the whole document, so one new field type in a newer
    /// PaperBoy still cost every tab, collection and environment.
    ///
    /// Built by serializing a real state and then editing the two enum values,
    /// so the test can't drift out of step with the rest of the shape.
    #[test]
    fn a_form_field_kind_from_a_newer_build_costs_only_that_field() {
        use crate::hurl::{CommentAnchor, EntryComment, FormField, FormFieldKind};
        let mut entry =
            crate::hurl::HurlEntry::from_fields("Upload", "POST", "https://h/x", vec![], "");
        entry.form_fields = vec![
            FormField {
                key: "a".into(),
                value: "1".into(),
                kind: FormFieldKind::Text,
                enabled: true,
                ..FormField::default()
            },
            FormField {
                key: "b".into(),
                value: "/tmp/x".into(),
                kind: FormFieldKind::File,
                enabled: true,
                ..FormField::default()
            },
        ];
        entry.comments = vec![EntryComment {
            anchor: CommentAnchor::Body,
            text: "# note".into(),
        }];
        let state = PersistedState {
            tabs: vec![PersistedTab {
                name: "Coll".into(),
                entries: vec![entry],
                ..PersistedTab::default()
            }],
            ..PersistedState::default()
        };
        let json = serde_json::to_string(&state)
            .unwrap()
            .replace("\"File\"", "\"Directory\"")
            .replace("\"Body\"", "\"SomewhereNew\"");

        let back: PersistedState = serde_json::from_str(&json).expect("the document still parses");
        let entry = &back.tabs[0].entries[0];
        assert_eq!(entry.title, "Upload", "the request survives");
        assert_eq!(entry.form_fields.len(), 2, "both rows survive");
        assert_eq!(
            entry.form_fields[1].kind,
            FormFieldKind::default(),
            "only the unknown kind falls back"
        );
        assert_eq!(entry.comments.len(), 1, "and the comment is still there");
        assert_eq!(entry.comments[0].anchor, CommentAnchor::default());
    }
    /// The delete-request confirmation is a new preference, so a `state.json`
    /// written before it existed has no field for it; that older document must
    /// default the guard *on* (the safe choice, matching the environment one),
    /// and an explicit choice must survive a save/load cycle.
    #[test]
    fn confirm_on_delete_request_defaults_on_and_round_trips() {
        // An older state.json simply omits the field.
        let mut value = serde_json::to_value(PersistedState::default()).unwrap();
        value
            .as_object_mut()
            .unwrap()
            .remove("confirm_on_delete_request");
        let older: PersistedState = serde_json::from_value(value).unwrap();
        assert!(
            older.confirm_on_delete_request,
            "a document without the field defaults the guard on"
        );

        // An explicit off survives serialisation and the Session round trip.
        let mut session = crate::session::Session::default();
        assert!(session.confirm_on_delete_request, "on by default");
        session.confirm_on_delete_request = false;
        let persisted = session.to_persisted();
        assert!(!persisted.confirm_on_delete_request);
        let mut restored = crate::session::Session::default();
        restored.apply_persisted(persisted);
        assert!(
            !restored.confirm_on_delete_request,
            "the choice is preserved across a save/load cycle"
        );
    }
}