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
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
//! Front-end-agnostic application session.
//!
//! This is the single home for the *core state* (open tabs/collections, the
//! global environments, the shared response buffer, user settings and themes)
//! and the *orchestration logic* (running requests, resolving the effective
//! environment, loading collections/environments, tab management and
//! persistence) that used to live only inside the terminal UI's `TuiApp`.
//!
//! Both front-ends own one of these and drive the exact same logic through it,
//! so there is a single copy of the state in the process and a single writer of
//! `state.json`. The GUI holds a [`Session`] as a field; the terminal UI's
//! `TuiApp` holds one and `Deref`s to it, so `self.collections` in the terminal
//! UI and `session.collections` in the GUI are the same data reached two ways.
//! `TuiApp` keeps only *view* state of its own — cursors, scroll offsets,
//! overlays, focus, wrap caches, and its richer report tabs.
//!
//! The practical consequence: a new persisted setting is added **here**, in
//! [`Session`] and [`PersistedState`], and both front-ends get it. Before this
//! was true the two copies could (and did) silently disagree — a default set in
//! one place and not the other.
use std::collections::{HashSet, VecDeque};
use std::path::PathBuf;
use std::sync::mpsc::Receiver;
use std::sync::{Arc, Mutex};
use crate::collection::Collection;
use crate::env_panel::EnvSource;
use crate::environment::{
EnvUpdate, Environment, PendingEnvSecrets, looks_like_env, parse_vars_pending,
spawn_resolution, spawn_resolution_many,
};
use crate::git_remote::GitOrigin;
use crate::http::ApiResponse;
use crate::hurl::RunStatus;
use crate::i18n::{Language, Status};
use crate::persistence::{
self, GuiLayout, PendingWorkspaceReload, PersistedEnv, PersistedReport, PersistedState,
PersistedTab,
};
use crate::remote_flow::WorkspaceGitOrigin;
use crate::request::{self, AppVars, BatchRunUpdate, CaptureUpdate, RequestView};
use crate::theme::{self, ThemeSpec};
// ── Shared pure helpers (called by both front-ends) ─────────────────────────
/// Build the effective, merged [`Environment`] used for substitution in
/// collection `ci`: the active Global Environment's vars, overridden by the
/// collection's own Linked Environment's vars on any name collision (Linked
/// wins). `None` when neither is set.
pub fn effective_env(
collections: &[Collection],
global_envs: &[Environment],
ci: usize,
active_env_id: Option<u64>,
) -> Option<Environment> {
let linked = collections
.get(ci)
.and_then(|c| c.linked_env_id)
.and_then(|id| global_envs.iter().find(|e| e.id == id));
let active = active_env_id.and_then(|id| global_envs.iter().find(|e| e.id == id));
match (linked, active) {
(None, None) => None,
(Some(env), None) | (None, Some(env)) => Some(env.clone()),
(Some(linked), Some(active)) => {
let mut merged = active.clone();
for lv in &linked.vars {
match merged.vars.iter_mut().find(|v| v.key == lv.key) {
Some(existing) => *existing = lv.clone(),
None => merged.vars.push(lv.clone()),
}
}
merged.id = linked.id;
merged.name = linked.name.clone();
Some(merged)
}
}
}
/// Keys defined in *both* the active collection's linked Environment and the
/// active Global Environment — per [`effective_env`]'s merge rule the linked
/// value always wins, so these keys' Global Environment value is silently
/// shadowed. Used to flag such substitutions with a warning icon.
pub fn shadowed_env_keys(
collections: &[Collection],
global_envs: &[Environment],
ci: usize,
active_env_id: Option<u64>,
) -> HashSet<String> {
let linked = collections
.get(ci)
.and_then(|c| c.linked_env_id)
.and_then(|id| global_envs.iter().find(|e| e.id == id));
let active = active_env_id.and_then(|id| global_envs.iter().find(|e| e.id == id));
match (linked, active) {
(Some(linked), Some(active)) if linked.id != active.id => linked
.vars
.iter()
.filter(|lv| active.vars.iter().any(|av| av.key == lv.key))
.map(|lv| lv.key.clone())
.collect(),
_ => HashSet::new(),
}
}
/// Every selectable theme, in display order: the built-in presets followed by
/// the user's custom themes.
pub fn all_themes(custom_themes: &[ThemeSpec]) -> Vec<ThemeSpec> {
let mut themes = theme::builtin_presets();
themes.extend(custom_themes.iter().cloned());
themes
}
/// Look a theme up by name across presets and custom themes.
pub fn find_theme(name: &str, custom_themes: &[ThemeSpec]) -> Option<ThemeSpec> {
all_themes(custom_themes)
.into_iter()
.find(|t| t.name == name)
}
/// The theme spec currently in effect: the manually-chosen theme if set (and
/// still present), otherwise the current language's preset.
pub fn active_theme_spec(
active_theme: Option<&str>,
custom_themes: &[ThemeSpec],
language: &Language,
) -> ThemeSpec {
if let Some(name) = active_theme
&& let Some(spec) = find_theme(name, custom_themes)
{
return spec;
}
theme::preset_for_language(language)
}
/// Which "last used" directory a file picker should start from. Environments
/// get their own memory because they usually live somewhere quite different
/// from collections (a shared secrets folder vs. a project tree), so a single
/// shared directory would send one picker to the other's folder every time.
#[derive(Clone, Copy, PartialEq, Eq)]
#[cfg_attr(not(feature = "gui"), allow(dead_code))]
pub enum PickerKind {
Environment,
/// Where an imported Postman workspace is written. Kept apart from the
/// general last-browsed folder because imports are collected somewhere
/// deliberate — a folder of downloaded workspaces — and that choice must
/// not be dragged around by every unrelated file the user opens.
Import,
Other,
}
// ── The Session ─────────────────────────────────────────────────────────────
/// The whole front-end-agnostic application state. The GUI holds one of these;
/// the terminal UI keeps its own view state but shares this module's logic.
pub struct Session {
pub language: Language,
pub vars: AppVars,
/// Open collection tabs. `collections[0]` is the built-in "Request" tab.
pub collections: Vec<Collection>,
/// The active tab index (into `collections`).
pub active_tab: usize,
/// The global list of Environments, shared across all collections (in the
/// terminal UI, the "Global Environments" panel, `Pane::GlobalEnv`).
/// Individual collections may `linked_env_id` one of these; at most one may
/// be `active_env_id` at a time.
pub global_envs: Vec<Environment>,
/// The currently-activated Global Environment, if any — its vars are used
/// for substitution in any collection (subject to being overridden by that
/// collection's own `linked_env_id`, if set, on name collision).
pub active_env_id: Option<u64>,
/// The shared response buffer written by the background request runner.
pub response: Arc<Mutex<ApiResponse>>,
/// In-flight background work (drained by [`Session::poll`]).
pub pending_env: Vec<Receiver<EnvUpdate>>,
pub pending_captures: Vec<Receiver<CaptureUpdate>>,
pub pending_batch_runs: Vec<Receiver<BatchRunUpdate>>,
/// User-created themes (persisted). Shown in the Theme editor alongside the
/// built-in presets; deletable (unlike presets).
pub custom_themes: Vec<ThemeSpec>,
/// The explicitly-chosen theme name, or `None` to follow the language's
/// preset. Set the moment the user picks any theme in the Theme editor;
/// while `None`, changing language also changes the effective theme.
///
/// A new install starts on [`theme::default_preset`] rather than on `None`:
/// the language presets are decorative, and the default should be the
/// neutral one. Restoring a saved state overwrites this, so an existing
/// install's choice — including `None` — is preserved across an upgrade.
pub active_theme: Option<String>,
// Persisted settings / preferences.
/// Confirm before quitting / before closing all collections.
pub confirm_on_exit: bool,
pub confirm_on_clear: bool,
/// Confirm before deleting a Global Environment. On by default; turn it off
/// to always delete immediately (the deletion stays undoable).
pub confirm_on_delete_env: bool,
/// When set, a "Save / Discard / Cancel" prompt for unsaved in-memory edits
/// (switching collections in a Workspace, or pushing one to git) is skipped
/// and the "Save" action taken automatically. Off by default, so the prompt
/// is shown.
pub always_save_when_prompted: bool,
/// Which of JSON / Hurl text the Request view shows by default, for every
/// request.
pub default_request_view: RequestView,
/// Run "Run All" in batch mode — the whole collection in one Hurl execution,
/// so Hurl's cookie jar and `[Captures]` chain across every request. Off by
/// default, so Run All streams results as they finish (matching the CLI
/// default), at the cost of not carrying automatic cookies between requests.
pub run_all_batch_mode: bool,
/// Width (columns) of the terminal UI's left column.
pub list_width: u16,
pub response_pct: u16,
pub env_source: EnvSource,
/// Git URLs the user has loaded a collection/environment from, most recent
/// first. Offered as a pickable list in the "Load from Git" wizard.
pub recent_git_urls: Vec<String>,
/// Provider references the Postman API key has been read from, most recent
/// first. Offered in the import wizard so the item path only has to be
/// found once. Only references are kept — never a pasted key.
pub recent_key_refs: Vec<String>,
/// The parameter values each report was last run with, keyed by
/// [`crate::report::Report::param_key`] and offered back the next time its
/// run settings open. Most recently used first, and capped — a value
/// nobody has used for fifty reports is not worth carrying forever.
pub report_params: Vec<crate::persistence::PersistedReportParams>,
/// Folder the file browser last selected a file from; it reopens here.
pub last_browse_dir: Option<PathBuf>,
/// Folder the last *environment* file was loaded from; the environment
/// picker reopens here (falling back to `last_browse_dir`), so it isn't
/// dragged around by loads of unrelated file types.
pub last_env_dir: Option<PathBuf>,
/// Folder the last Postman import was written into; the next import
/// suggests the same place, so downloaded workspaces end up together
/// instead of wherever the app happened to be started from.
pub last_import_dir: Option<PathBuf>,
/// Window/panel geometry and last-open view for the graphical front-end.
/// The terminal UI never reads it but still round-trips it, so alternating
/// between the two front-ends doesn't wipe the GUI's layout.
pub gui: GuiLayout,
/// A transient status message for the footer.
pub status: Option<Status>,
/// Persisted report tabs, preserved verbatim so a session saved from one
/// front-end never drops the reports the other front-end created. The GUI's
/// reports panel manages these through [`Session::reports`] accessors.
pub reports: Vec<PersistedReport>,
/// Workspace tabs restored with a vanished `workspace_root` that are known
/// to have been downloaded from git, paired with the tab index they were
/// restored at. Filled by [`Session::apply_persisted`]; the front-end drains
/// this to offer redownloading each one (see
/// [`crate::persistence::PendingWorkspaceReload`]) rather than silently
/// resetting the tab. Transient — never persisted.
pub pending_workspace_reloads: VecDeque<(usize, PendingWorkspaceReload)>,
/// The active report index within a workspace tab, mirrored so persistence
/// round-trips faithfully. Front-ends own their own richer view state.
active_report: Option<usize>,
}
impl Default for Session {
fn default() -> Self {
Self {
language: Language::default(),
vars: AppVars::default(),
collections: vec![Collection::new("Request".to_string(), Vec::new())],
active_tab: 0,
global_envs: Vec::new(),
active_env_id: None,
response: Arc::new(Mutex::new(ApiResponse::default())),
pending_env: Vec::new(),
pending_captures: Vec::new(),
pending_batch_runs: Vec::new(),
custom_themes: Vec::new(),
// A fresh install opens on the default theme rather than on the
// current language's preset. `None` still means "follow language" —
// it is an explicit choice in the Theme menu — so an existing
// install that never picked a theme keeps following its language
// and is not repainted by an upgrade.
active_theme: Some(theme::default_preset().name),
confirm_on_exit: true,
confirm_on_clear: true,
confirm_on_delete_env: true,
always_save_when_prompted: false,
default_request_view: RequestView::default(),
run_all_batch_mode: false,
list_width: 38,
response_pct: 42,
env_source: EnvSource::Both,
recent_git_urls: Vec::new(),
recent_key_refs: Vec::new(),
report_params: Vec::new(),
last_browse_dir: None,
last_env_dir: None,
last_import_dir: None,
gui: GuiLayout::default(),
status: None,
reports: Vec::new(),
pending_workspace_reloads: VecDeque::new(),
active_report: None,
}
}
}
#[cfg_attr(not(feature = "gui"), allow(dead_code))]
impl Session {
/// A session restored from the persisted `state.json`, or a fresh one when
/// there is nothing to restore.
pub fn restored() -> Self {
let mut s = Self::default();
if let Some(state) = persistence::load_state() {
s.apply_persisted(state);
}
s
}
// ── Theme ────────────────────────────────────────────────────────────
pub fn all_themes(&self) -> Vec<ThemeSpec> {
all_themes(&self.custom_themes)
}
pub fn active_theme_spec(&self) -> ThemeSpec {
active_theme_spec(
self.active_theme.as_deref(),
&self.custom_themes,
&self.language,
)
}
// ── Environments ──────────────────────────────────────────────────────
/// The merged environment used for substitution in collection `ci`.
pub fn effective_env(&self, ci: usize) -> Option<Environment> {
effective_env(&self.collections, &self.global_envs, ci, self.active_env_id)
}
/// Keys whose active Global Environment value is silently shadowed by the
/// collection's linked Environment (see the free [`shadowed_env_keys`]).
pub fn shadowed_env_keys(&self, ci: usize) -> HashSet<String> {
shadowed_env_keys(&self.collections, &self.global_envs, ci, self.active_env_id)
}
/// Toggle which Global Environment is active (activating the same one again
/// deactivates it), rebuilding affected previews.
pub fn set_active_env(&mut self, env_id: Option<u64>) {
self.active_env_id = if self.active_env_id == env_id {
None
} else {
env_id
};
for col in &mut self.collections {
col.invalidate_request_json();
}
self.save();
}
/// Link (pin) a Global Environment to collection `ci` (linking the same one
/// again unlinks it).
pub fn set_linked_env(&mut self, ci: usize, env_id: Option<u64>) {
if let Some(col) = self.collections.get_mut(ci) {
col.linked_env_id = if col.linked_env_id == env_id {
None
} else {
env_id
};
col.invalidate_request_json();
}
self.save();
}
/// Load a `.vars` environment from text. Returns its id on success. On a
/// name collision with an existing environment the new one is renamed with
/// a numeric suffix (the GUI resolves collisions with an explicit dialog if
/// it prefers).
pub fn load_environment_text(
&mut self,
name: String,
content: &str,
path: Option<PathBuf>,
git_origin: Option<GitOrigin>,
) -> Option<u64> {
if !looks_like_env(content) {
self.status = Some(Status::NotEnvironment);
return None;
}
let (mut env, pending) = parse_vars_pending(name, content);
// Disambiguate a duplicate name so both stay usable.
if self.global_envs.iter().any(|e| e.name == env.name) {
let base = env.name.clone();
let mut n = 2;
while self
.global_envs
.iter()
.any(|e| e.name == format!("{base} ({n})"))
{
n += 1;
}
env.name = format!("{base} ({n})");
}
env.path = path;
env.git_origin = git_origin;
let id = env.id;
self.global_envs.push(env);
for col in &mut self.collections {
col.invalidate_request_json();
}
if !pending.is_empty() {
self.pending_env.push(spawn_resolution(id, pending));
}
self.status = Some(Status::Loaded);
self.save();
Some(id)
}
/// Delete the Global Environment with `env_id`, unlinking any collections
/// that referenced it.
pub fn delete_environment(&mut self, env_id: u64) {
self.global_envs.retain(|e| e.id != env_id);
if self.active_env_id == Some(env_id) {
self.active_env_id = None;
}
for col in &mut self.collections {
if col.linked_env_id == Some(env_id) {
col.linked_env_id = None;
}
col.invalidate_request_json();
}
self.save();
}
// ── Collections / tabs ────────────────────────────────────────────────
/// Load a collection (Hurl or Postman JSON) from text into a new tab.
/// Returns `true` on success.
pub fn load_collection_text(
&mut self,
name: String,
content: &str,
path: Option<PathBuf>,
) -> bool {
let entries = crate::postman::parse_collection(content);
if entries.is_empty() {
let reason = if crate::postman::looks_like_postman(content) {
None
} else {
crate::hurl::parse_hurl_error(content)
};
self.status = Some(match reason {
Some(why) => Status::Error(format!("{why}")),
None => Status::NotCollection,
});
return false;
}
let mut col = Collection::new(name, entries);
col.path = path;
self.collections.push(col);
self.active_tab = self.collections.len() - 1;
self.status = Some(Status::Loaded);
self.save();
true
}
/// Append a fresh empty collection tab and make it active.
pub fn add_collection(&mut self, name: impl Into<String>) -> usize {
self.collections
.push(Collection::new(name.into(), Vec::new()));
let idx = self.collections.len() - 1;
self.active_tab = idx;
idx
}
/// Append a fresh empty Global Environment and return its id.
pub fn add_environment(&mut self, name: impl Into<String>) -> u64 {
let env = Environment {
id: crate::environment::next_env_id(),
name: name.into(),
vars: Vec::new(),
path: None,
git_origin: None,
};
let id = env.id;
self.global_envs.push(env);
self.save();
id
}
/// Total number of collection tabs.
pub fn tab_count(&self) -> usize {
self.collections.len()
}
pub fn activate_tab(&mut self, idx: usize) {
if idx < self.tab_count() {
self.active_tab = idx;
}
}
/// The directory a file picker for `kind` should open at: the last folder
/// the user picked something of that kind from, falling back to the general
/// last-browsed folder so a first-ever environment picker still lands
/// somewhere useful rather than the process's working directory.
pub fn picker_dir(&self, kind: PickerKind) -> Option<&std::path::Path> {
let specific = match kind {
PickerKind::Environment => self.last_env_dir.as_deref(),
PickerKind::Import => self.last_import_dir.as_deref(),
PickerKind::Other => None,
};
specific
.or(self.last_browse_dir.as_deref())
.filter(|d| d.is_dir())
}
/// Remember where a picker just landed, so the next one reopens there.
/// `path` may be the chosen file itself — its parent directory is stored.
pub fn remember_picker_dir(&mut self, kind: PickerKind, path: &std::path::Path) {
let dir = if path.is_dir() {
Some(path.to_path_buf())
} else {
path.parent().map(|p| p.to_path_buf())
};
let Some(dir) = dir.filter(|d| d.is_dir()) else {
return;
};
match kind {
PickerKind::Environment => self.last_env_dir = Some(dir.clone()),
PickerKind::Import => self.last_import_dir = Some(dir.clone()),
PickerKind::Other => {}
}
self.last_browse_dir = Some(dir);
}
/// Record `key` as a most-recently-used Postman key *reference*: moved to
/// the front, deduplicated, capped at 10.
///
/// A pasted key is refused outright. Finding the 1Password item path is the
/// tedious part of setting an import up and worth remembering; the key
/// itself is a live credential, and this list is written to disk.
///
/// Returns whether anything changed, so a caller polling every frame does
/// not rewrite `state.json` sixty times a second.
pub fn remember_key_ref(&mut self, key: &str) -> bool {
let key = key.trim();
if key.is_empty() || crate::postman_flow::KeySource::detect(key).0.is_secret() {
return false;
}
if self.recent_key_refs.first().is_some_and(|k| k == key) {
return false;
}
self.recent_key_refs.retain(|known| known != key);
self.recent_key_refs.insert(0, key.to_string());
self.recent_key_refs.truncate(10);
true
}
/// The values report `key` was last run with, as a map ready for a run.
/// Empty when this report has never been run with parameters — which is
/// also what a report with no parameters looks like, so callers need no
/// special case.
pub fn remembered_params(&self, key: &str) -> crate::report::params::ParamValues {
self.report_params
.iter()
.find(|r| r.key == key)
.map(|r| r.values.iter().cloned().collect())
.unwrap_or_default()
}
/// Remember the values report `key` was just run with, so its run settings
/// open on them next time. Returns whether anything actually changed, so a
/// caller polling every frame doesn't rewrite `state.json` for nothing.
///
/// Values are stored sorted, and the report moves to the front of the
/// list: the cap has to evict something, and the report you last ran is
/// the one you are least likely to want forgotten.
pub fn remember_params(
&mut self,
key: &str,
values: &crate::report::params::ParamValues,
) -> bool {
if key.is_empty() {
return false;
}
let mut pairs: Vec<(String, String)> =
values.iter().map(|(k, v)| (k.clone(), v.clone())).collect();
pairs.sort();
let entry = crate::persistence::PersistedReportParams {
key: key.to_string(),
values: pairs,
};
if self.report_params.first().is_some_and(|r| *r == entry) {
return false;
}
let had_key = self.report_params.iter().any(|r| r.key == key);
self.report_params.retain(|r| r.key != key);
// Nothing to remember: a report run entirely on its defaults shouldn't
// hold a slot, and clearing the values should forget them. Only a
// report that *had* an entry has changed by losing it.
if entry.values.is_empty() {
return had_key;
}
self.report_params.insert(0, entry);
self.report_params.truncate(50);
true
}
/// Close tab `idx` (the built-in Request tab at index 0 is never closed).
pub fn close_tab(&mut self, idx: usize) {
self.close_tab_inner(idx, false);
}
/// Close tab `idx` *and* wipe its Workspace folder from disk. Only ever
/// valid for a tab whose folder the app downloaded itself
/// ([`Collection::workspace_downloaded_from_git`]) and only when the user
/// explicitly asked for it — a folder the user picked from their own
/// filesystem is never deleted, so this silently falls back to an ordinary
/// close for any other tab.
pub fn close_tab_deleting_workspace(&mut self, idx: usize) {
self.close_tab_inner(idx, true);
}
fn close_tab_inner(&mut self, idx: usize, delete_workspace: bool) {
if idx == 0 || idx >= self.collections.len() {
return;
}
let removed = self.collections.remove(idx);
if delete_workspace
&& removed.workspace_downloaded_from_git
&& let Some(root) = &removed.workspace_root
{
crate::git_remote::cleanup(root);
}
if self.active_tab >= self.collections.len() {
self.active_tab = self.collections.len() - 1;
}
self.save();
}
// ── Workspaces ────────────────────────────────────────────────────────
/// Open a folder as a Workspace: a new tab whose file tree is the real
/// filesystem under `root` (see [`Collection::ws_rows`]). The tab starts
/// with no loaded collection; selecting a `.hurl`/`.json` file in the tree
/// loads it. Returns the new tab index.
pub fn open_workspace(&mut self, root: PathBuf) -> usize {
let name = root
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| root.to_string_lossy().into_owned());
self.push_workspace_tab(name, root, None)
}
/// Open a Workspace whose (filtered) files were just downloaded from git
/// into `root` — a throwaway directory reused in place as the tab's
/// `workspace_root`, exactly like a locally picked folder, since its
/// checked-out files already sit at the right relative paths. `name` comes
/// from the repo URL rather than the meaningless temp-directory name, and
/// `origin` records the exact commit so the download can be repeated if
/// the folder later vanishes (e.g. the OS clears `/tmp`).
///
/// Unlike a single-file load this directory is deliberately *not* cleaned
/// up afterwards — the tab reads from it live for as long as it stays open.
/// `workspace_downloaded_from_git` marks it as the app's own throwaway, so
/// closing the tab may offer to delete it (a folder the user picked
/// themselves must never be deleted).
pub fn open_workspace_from_git(
&mut self,
root: PathBuf,
name: String,
origin: Option<WorkspaceGitOrigin>,
) -> usize {
self.push_workspace_tab(name, root, origin)
}
/// Rebind Workspace tab `idx` to `root`, a folder that has just been
/// redownloaded from git for a tab whose original download had vanished
/// (see [`Session::pending_workspace_reloads`]). The file that was open
/// last session is re-selected if it still exists in the new download —
/// its path has to be re-resolved *relatively*, because the fresh checkout
/// lands in a different temp directory than the one recorded.
pub fn rebind_redownloaded_workspace(
&mut self,
idx: usize,
root: PathBuf,
relative_selected_path: Option<String>,
) {
let Some(col) = self.collections.get_mut(idx) else {
return;
};
let selected = relative_selected_path
.map(|rel| root.join(rel))
.filter(|p| p.exists());
col.workspace_root = Some(root);
col.workspace_downloaded_from_git = true;
// The redownload may not contain the file that was open last time (the
// filter or the commit's contents can differ), so a failed reopen just
// leaves the tab on its tree rather than being an error.
match selected {
Some(path) => {
if col.load_workspace_file(path).is_err() {
col.path = None;
}
}
None => col.path = None,
}
self.status = Some(Status::WorkspaceReloaded);
self.save();
}
fn push_workspace_tab(
&mut self,
name: String,
root: PathBuf,
git_origin: Option<WorkspaceGitOrigin>,
) -> usize {
let mut col = Collection::new(name, Vec::new());
col.workspace_root = Some(root);
col.workspace_downloaded_from_git = git_origin.is_some();
col.workspace_git_origin = git_origin;
self.collections.push(col);
let ci = self.collections.len() - 1;
self.active_tab = ci;
self.save();
ci
}
/// Load a collection file from a Workspace tab's tree into that tab (the
/// shared core of the terminal UI's workspace file open). Returns `true` on
/// success; on an I/O error it sets an error status and returns `false`.
pub fn load_workspace_file(&mut self, ci: usize, path: PathBuf) -> bool {
let Some(col) = self.collections.get_mut(ci) else {
return false;
};
match col.load_workspace_file(path) {
Ok(()) => {
self.active_tab = ci;
self.status = Some(Status::Loaded);
self.save();
true
}
Err(e) => {
self.status = Some(Status::Error(e.to_string()));
false
}
}
}
/// Load a `.vars` environment file selected from a Workspace tree as a
/// Global Environment (the same path as File → Load → Environment). Returns
/// the new environment's id on success.
pub fn open_workspace_environment(&mut self, path: &std::path::Path) -> Option<u64> {
let content = match std::fs::read_to_string(path) {
Ok(c) => c,
Err(e) => {
self.status = Some(Status::Error(e.to_string()));
return None;
}
};
let name = path
.file_stem()
.and_then(|n| n.to_str())
.unwrap_or("env")
.to_string();
self.load_environment_text(name, &content, Some(path.to_path_buf()), None)
}
// ── Running requests ──────────────────────────────────────────────────
fn begin_request(&self) {
self.response.lock().unwrap().begin();
}
/// Run the selected request of collection `ci`. Returns the blocking secret
/// keys (and does nothing) if the request references still-loading secrets.
pub fn run_entry(&mut self, ci: usize) -> Vec<String> {
if self.collections.get(ci).is_none() {
return Vec::new();
}
let env = self.effective_env(ci);
let blocking = request::pending_request_keys(&self.collections[ci], env.as_ref());
if !blocking.is_empty() {
self.status = Some(Status::WaitingSecrets(blocking.clone()));
return blocking;
}
self.status = None;
self.begin_request();
let selected = self.collections[ci].selected_entry;
if let Some(entry) = self.collections[ci].entries.get_mut(selected) {
entry.last_run = RunStatus::Running;
}
if let Some(rx) =
request::run_collection(&self.collections[ci], env.as_ref(), self.response.clone())
{
self.pending_captures.push(rx);
}
Vec::new()
}
/// Run every request of collection `ci` in order ("Run All").
pub fn run_all_entries(&mut self, ci: usize) -> Vec<String> {
let Some(col) = self.collections.get(ci) else {
return Vec::new();
};
if col.entries.is_empty() {
return Vec::new();
}
let env = self.effective_env(ci);
let blocking = request::pending_request_keys_all(col, env.as_ref());
if !blocking.is_empty() {
self.status = Some(Status::WaitingSecrets(blocking.clone()));
return blocking;
}
self.status = None;
self.begin_request();
for entry in self.collections[ci].entries.iter_mut() {
entry.last_run = RunStatus::Running;
}
if let Some(rx) = request::run_all_entries(
&self.collections[ci],
env.as_ref(),
self.response.clone(),
self.run_all_batch_mode,
) {
self.pending_batch_runs.push(rx);
}
Vec::new()
}
/// Drain every in-flight background result (secret resolution, single-run
/// captures and "Run All" passes) and apply them. Returns `true` if any
/// state changed (so a front-end can request a repaint).
pub fn poll(&mut self) -> bool {
let before_env = self.pending_env.len();
let before_cap = self.pending_captures.len();
let before_batch = self.pending_batch_runs.len();
request::drain_env_updates(
&mut self.pending_env,
&mut self.global_envs,
&mut self.collections,
);
request::drain_capture_updates(&mut self.pending_captures, &mut self.collections);
self.drain_batch_runs();
// A crude but effective "something happened" signal: any queue shrank,
// or a response is still loading (spinner needs animating).
before_env != self.pending_env.len()
|| before_cap != self.pending_captures.len()
|| before_batch != self.pending_batch_runs.len()
|| self.response.lock().map(|r| r.loading).unwrap_or(false)
}
fn drain_batch_runs(&mut self) {
if self.pending_batch_runs.is_empty() {
return;
}
let mut still = Vec::new();
for rx in std::mem::take(&mut self.pending_batch_runs) {
let mut disconnected = false;
let mut run_col_id: Option<u64> = None;
loop {
match rx.try_recv() {
Ok(update) => {
run_col_id = Some(update.col_id);
if let Some(col) =
self.collections.iter_mut().find(|c| c.id == update.col_id)
{
for (k, v) in &update.captures {
col.captures.insert(k.clone(), v.clone());
}
col.invalidate_request_json();
let mut passed = 0usize;
let mut failed = 0usize;
for ((entry, result), response) in col
.entries
.iter_mut()
.zip(update.results.iter())
.zip(update.responses.iter())
{
entry.last_run = match result {
Some(true) => RunStatus::Passed,
Some(false) => RunStatus::Failed,
None => RunStatus::Running,
};
if let Some(response) = response {
entry.last_response = Some(response.clone());
}
match result {
Some(true) => passed += 1,
Some(false) => failed += 1,
None => {}
}
}
let total = passed + failed;
if total > 0 {
self.status = Some(Status::CollectionRunSummary {
passed,
failed,
total,
});
}
}
}
Err(std::sync::mpsc::TryRecvError::Empty) => break,
Err(std::sync::mpsc::TryRecvError::Disconnected) => {
disconnected = true;
break;
}
}
}
if disconnected
&& let Some(col_id) = run_col_id
&& let Some(col) = self.collections.iter_mut().find(|c| c.id == col_id)
{
for entry in col.entries.iter_mut() {
if entry.last_run == RunStatus::Running {
entry.last_run = RunStatus::NotRun;
}
}
}
if !disconnected {
still.push(rx);
}
}
self.pending_batch_runs = still;
}
// ── Persistence ───────────────────────────────────────────────────────
/// Snapshot for saving (environments in source form only — resolved secrets
/// are never written to disk).
pub fn to_persisted(&self) -> PersistedState {
PersistedState {
language: self.language.clone(),
base_url: self.vars.base_url.clone(),
tabs: self
.collections
.iter()
.map(|c| {
let linked_env_index = c
.linked_env_id
.and_then(|id| self.global_envs.iter().position(|e| e.id == id));
PersistedTab::from_collection(c, linked_env_index)
})
.collect(),
reports: self.reports.clone(),
active_tab: self.active_tab,
last_browse_dir: self
.last_browse_dir
.as_ref()
.map(|p| p.to_string_lossy().into_owned()),
last_env_dir: self
.last_env_dir
.as_ref()
.map(|p| p.to_string_lossy().into_owned()),
last_import_dir: self
.last_import_dir
.as_ref()
.map(|p| p.to_string_lossy().into_owned()),
confirm_on_exit: self.confirm_on_exit,
confirm_on_clear: self.confirm_on_clear,
confirm_on_delete_env: self.confirm_on_delete_env,
always_save_when_prompted: self.always_save_when_prompted,
list_width: self.list_width,
response_pct: self.response_pct,
env_source: self.env_source,
recent_git_urls: self.recent_git_urls.clone(),
recent_key_refs: self.recent_key_refs.clone(),
report_params: self.report_params.clone(),
default_request_view: self.default_request_view,
run_all_batch_mode: self.run_all_batch_mode,
custom_themes: self.custom_themes.clone(),
active_theme: self.active_theme.clone(),
global_envs: self
.global_envs
.iter()
.map(PersistedEnv::from_environment)
.collect(),
active_global_env: self
.active_env_id
.and_then(|id| self.global_envs.iter().position(|e| e.id == id)),
gui: self.gui,
}
}
/// Restore from persisted state.
pub fn apply_persisted(&mut self, state: PersistedState) {
self.language = state.language;
if !state.base_url.trim().is_empty() {
self.vars.base_url = state.base_url;
}
let mut pending_groups = Vec::new();
let mut global_envs = Vec::with_capacity(state.global_envs.len());
for pe in &state.global_envs {
let (env, pending) = pe.restore();
if !pending.is_empty() {
pending_groups.push(PendingEnvSecrets {
env_id: env.id,
pending,
});
}
global_envs.push(env);
}
self.active_env_id = state
.active_global_env
.and_then(|idx| global_envs.get(idx))
.map(|e| e.id);
self.global_envs = global_envs;
if !pending_groups.is_empty() {
self.pending_env.push(spawn_resolution_many(pending_groups));
}
if !state.tabs.is_empty() {
let mut collections = Vec::with_capacity(state.tabs.len());
let mut reloads = VecDeque::new();
let mut missing_workspace_name = None;
for (idx, tab) in state.tabs.into_iter().enumerate() {
let had_root = tab.workspace_root.is_some();
let name = tab.name.clone();
let linked_env_id = tab
.linked_env_index
.and_then(|i| self.global_envs.get(i))
.map(|e| e.id);
let (col, pending_reload) = tab.into_collection(linked_env_id);
if had_root && col.workspace_root.is_none() {
match pending_reload {
// A git-downloaded Workspace whose folder has vanished
// since the last session (typically `/tmp` swept between
// restarts) is queued rather than silently reset — the
// front-end offers to redownload it, pinned to the exact
// commit it recorded.
Some(reload) => reloads.push_back((idx, reload)),
// Nothing to redownload (a local folder that was moved or
// deleted), so just say so rather than presenting an
// empty tab with no explanation.
None => missing_workspace_name = Some(name),
}
}
collections.push(col);
}
self.collections = collections;
self.pending_workspace_reloads = reloads;
if let Some(name) = missing_workspace_name {
self.status = Some(Status::WorkspaceFolderMissing(name));
}
}
self.reports = state.reports;
self.active_report = None;
self.active_tab = state.active_tab.min(self.tab_count().saturating_sub(1));
self.last_browse_dir = state
.last_browse_dir
.filter(|s| !s.is_empty())
.map(PathBuf::from);
self.last_env_dir = state
.last_env_dir
.filter(|s| !s.is_empty())
.map(PathBuf::from);
self.last_import_dir = state
.last_import_dir
.filter(|s| !s.is_empty())
.map(PathBuf::from);
self.gui = state.gui;
self.confirm_on_exit = state.confirm_on_exit;
self.confirm_on_clear = state.confirm_on_clear;
self.confirm_on_delete_env = state.confirm_on_delete_env;
self.always_save_when_prompted = state.always_save_when_prompted;
self.list_width = state.list_width;
self.response_pct = state.response_pct;
self.env_source = state.env_source;
self.recent_git_urls = state.recent_git_urls;
self.recent_key_refs = state.recent_key_refs;
self.report_params = state.report_params;
self.default_request_view = state.default_request_view;
self.run_all_batch_mode = state.run_all_batch_mode;
self.custom_themes = state.custom_themes;
self.active_theme = state.active_theme;
}
/// Persist the current state to disk.
pub fn save(&self) {
persistence::save_state(&self.to_persisted());
}
}
#[cfg(test)]
mod param_memory_tests {
use super::*;
fn values(pairs: &[(&str, &str)]) -> crate::report::params::ParamValues {
pairs
.iter()
.map(|(k, v)| (k.to_string(), v.to_string()))
.collect()
}
#[test]
fn a_report_is_offered_the_values_it_was_last_run_with() {
let mut s = Session::default();
assert!(s.remember_params("name:Face", &values(&[("TICKET", "42")])));
assert_eq!(
s.remembered_params("name:Face"),
values(&[("TICKET", "42")])
);
// Another report's answers are its own.
assert!(s.remembered_params("name:Other").is_empty());
}
#[test]
fn remembering_the_same_values_twice_doesnt_rewrite_the_state_file() {
let mut s = Session::default();
assert!(s.remember_params("name:Face", &values(&[("TICKET", "42")])));
assert!(!s.remember_params("name:Face", &values(&[("TICKET", "42")])));
assert!(s.remember_params("name:Face", &values(&[("TICKET", "43")])));
}
#[test]
fn clearing_every_value_forgets_the_report_rather_than_keeping_an_empty_slot() {
let mut s = Session::default();
s.remember_params("name:Face", &values(&[("TICKET", "42")]));
assert!(s.remember_params("name:Face", &Default::default()));
assert!(s.remembered_params("name:Face").is_empty());
// Nothing was remembered, so there is nothing to forget the second time.
assert!(!s.remember_params("name:Face", &Default::default()));
}
#[test]
fn only_the_fifty_most_recently_run_reports_are_remembered() {
let mut s = Session::default();
for i in 0..60 {
s.remember_params(&format!("name:r{i}"), &values(&[("N", "1")]));
}
assert_eq!(s.report_params.len(), 50);
// The oldest fell off the end; the one just run is at the front.
assert!(s.remembered_params("name:r0").is_empty());
assert_eq!(s.remembered_params("name:r59"), values(&[("N", "1")]));
}
#[test]
fn remembered_values_survive_a_restart() {
let mut s = Session::default();
s.remember_params("name:Face", &values(&[("TICKET", "42"), ("ENV", "au")]));
let persisted = s.to_persisted();
let mut restored = Session::default();
restored.apply_persisted(persisted);
assert_eq!(
restored.remembered_params("name:Face"),
values(&[("TICKET", "42"), ("ENV", "au")])
);
}
}
#[cfg(test)]
mod workspace_tests {
use super::*;
use crate::collection::WsRow;
use crate::remote_flow::WorkspaceGitFilter;
fn tmp(tag: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!(
"paperboy_ws_session_{tag}_{}_{:?}",
std::process::id(),
std::thread::current().id()
));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(dir.join("api")).unwrap();
std::fs::write(dir.join("health.hurl"), "GET https://example.com/health\n").unwrap();
std::fs::write(
dir.join("api/users.hurl"),
"GET https://example.com/users\nHTTP 200\n\nGET https://example.com/users/1\n",
)
.unwrap();
std::fs::write(dir.join("api/dev.vars"), "BASE_URL=https://example.com\n").unwrap();
std::fs::write(dir.join("api/run.trail"), "{\"nodes\":[]}\n").unwrap();
dir
}
#[test]
fn open_workspace_tab_lists_the_folder_tree_and_loads_files_and_envs() {
let dir = tmp("open");
let mut s = Session::default();
let ci = s.open_workspace(dir.clone());
// A Workspace tab is a collection with a root and no loaded entries.
assert!(s.collections[ci].is_workspace());
assert!(s.collections[ci].entries.is_empty());
// The top level lists the `api` folder and `health.hurl` (dirs first).
let rows = s.collections[ci].ws_rows();
assert!(matches!(&rows[0], WsRow::Folder { name, .. } if name == "api"));
assert!(
rows.iter()
.any(|r| matches!(r, WsRow::Collection { name, .. } if name == "health.hurl"))
);
// Expand `api` so its children (a collection, an env and a report) show.
let api = dir.join("api");
s.collections[ci].workspace_expanded.insert(api.clone());
let rows = s.collections[ci].ws_rows();
assert!(
rows.iter()
.any(|r| matches!(r, WsRow::Collection { name, .. } if name == "users.hurl"))
);
assert!(
rows.iter()
.any(|r| matches!(r, WsRow::Environment { name, .. } if name == "dev.vars"))
);
assert!(
rows.iter()
.any(|r| matches!(r, WsRow::Report { name, .. } if name == "run.trail"))
);
// Loading a collection file brings its requests into the tab in place.
assert!(s.load_workspace_file(ci, api.join("users.hurl")));
assert_eq!(
s.collections[ci].path.as_deref(),
Some(api.join("users.hurl").as_path())
);
assert_eq!(s.collections[ci].entries.len(), 2);
// The loaded file's requests now appear as detailed rows under it.
let rows = s.collections[ci].ws_rows();
assert!(
rows.iter()
.any(|r| matches!(r, WsRow::Request { loaded: true, .. }))
);
// Selecting a `.vars` file loads it as a global environment.
let before = s.global_envs.len();
assert!(
s.open_workspace_environment(&api.join("dev.vars"))
.is_some()
);
assert_eq!(s.global_envs.len(), before + 1);
let _ = std::fs::remove_dir_all(&dir);
}
/// The exit warning has to count a Workspace tab's *parked* edits — a file
/// the user edited and then switched away from is precisely the case with
/// nothing on disk to fall back on — without double-counting the file the
/// tab is currently showing.
#[test]
fn unsaved_edits_are_counted_once_across_parked_and_loaded_workspace_files() {
let dir = tmp("count");
let mut s = Session::default();
s.collections.clear();
let ci = s.open_workspace(dir.clone());
assert!(s.load_workspace_file(ci, dir.join("api/users.hurl")));
s.collections[ci].entries[0].modified = true;
s.collections[ci].entries[1].modified = true;
assert_eq!(
s.collections[ci].unsaved_edit_count(),
2,
"the loaded file's own edits"
);
// Switching away parks those two and loads a clean file.
assert!(s.load_workspace_file(ci, dir.join("health.hurl")));
assert_eq!(
s.collections[ci].unsaved_edit_count(),
2,
"parked edits still count, and the clean loaded file adds none"
);
// Editing the new file too adds to the total rather than replacing it.
s.collections[ci].entries[0].modified = true;
assert_eq!(s.collections[ci].unsaved_edit_count(), 3);
// Coming back must not count the same edits twice: the file is now both
// loaded and still listed in `workspace_pending`.
assert!(s.load_workspace_file(ci, dir.join("api/users.hurl")));
assert_eq!(
s.collections[ci].unsaved_edit_count(),
3,
"a file that is both loaded and parked is counted once"
);
let _ = std::fs::remove_dir_all(&dir);
}
/// Quitting only warns about edits a quit would really destroy.
///
/// A plain tab's requests are written to the session state exactly as they
/// stand, edit markers and all, so they come back edited next start — the
/// warning used to count those and so appeared on every single quit, and
/// went on appearing no matter how many times it was dismissed, because
/// nothing about the edits ever changed.
#[test]
fn quitting_only_counts_edits_that_a_restart_would_not_bring_back() {
let dir = tmp("lost");
let mut s = Session::default();
s.collections.clear();
// A plain tab, edited and never saved to its file.
let mut plain = crate::collection::Collection::new(
"plain".to_string(),
vec![crate::hurl::HurlEntry::default()],
);
plain.path = Some(dir.join("plain.hurl"));
plain.entries[0].modified = true;
s.collections.push(plain);
// And a Workspace tab, likewise.
let ci = s.open_workspace(dir.clone());
assert!(s.load_workspace_file(ci, dir.join("api/users.hurl")));
s.collections[ci].entries[0].modified = true;
assert_eq!(
s.collections[0].unsaved_edit_count(),
1,
"closing the plain tab would still throw its edit away"
);
assert_eq!(
s.collections[0].edits_lost_on_exit(),
0,
"but quitting would not: the session state keeps it, still flagged"
);
assert_eq!(
s.collections[ci].edits_lost_on_exit(),
1,
"while a Workspace tab is re-read from disk on restore, so its edit \
really would be gone"
);
let _ = std::fs::remove_dir_all(&dir);
}
/// The GUI's pixel geometry survives a save/load round-trip. (The matching
/// terminal-UI half — that it carries the field through untouched — is
/// asserted in `tui::tests`, where `TuiApp` is reachable.)
#[test]
fn the_gui_layout_round_trips_through_a_save_and_load() {
let layout = GuiLayout {
window: Some((1440.0, 900.0)),
left_width: Some(312.0),
env_height: Some(240.0),
response_height: Some(360.0),
report_diag_height: Some(96.0),
report_palette_width: Some(200.0),
report_detail_height: Some(280.0),
report_summary_height: Some(200.0),
view: crate::persistence::GuiView::Report(2),
report_source_view: true,
};
let mut s = Session::default();
s.gui = layout;
let saved = s.to_persisted();
let mut restored = Session::default();
restored.apply_persisted(saved);
assert_eq!(restored.gui, layout, "the GUI restores its own layout");
}
#[test]
fn load_workspace_file_on_a_bad_index_or_path_fails_without_panicking() {
let dir = tmp("bad");
let mut s = Session::default();
let ci = s.open_workspace(dir.clone());
// A non-existent file path is reported as a failure, not a panic.
assert!(!s.load_workspace_file(ci, dir.join("nope.hurl")));
// An out-of-range collection index is a graceful false.
assert!(!s.load_workspace_file(999, dir.join("health.hurl")));
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn edits_survive_switching_to_another_collection_and_back() {
let dir = tmp("pending");
let mut s = Session::default();
let ci = s.open_workspace(dir.clone());
// Edit the first request of health.hurl, exactly as the request editor
// does (write through to the entry, then flag it).
assert!(s.load_workspace_file(ci, dir.join("health.hurl")));
s.collections[ci].entries[0].url = "https://example.com/health?deep=1".into();
s.collections[ci].entries[0].modified = true;
assert!(s.collections[ci].workspace_file_edited(&dir.join("health.hurl")));
// Look at a different collection in the same Workspace tab...
assert!(s.load_workspace_file(ci, dir.join("api/users.hurl")));
assert_eq!(s.collections[ci].entries.len(), 2, "users.hurl is loaded");
// ...the edit is still remembered against the file it belongs to,
// even though those entries are no longer the tab's live ones.
assert!(
s.collections[ci].workspace_file_edited(&dir.join("health.hurl")),
"switching away must not discard unsaved edits"
);
// ...and the individual request still reads as edited, so the tree can
// pencil the row even while a different collection is the loaded one.
assert!(
s.collections[ci].workspace_request_edited(&dir.join("health.hurl"), 0),
"a parked request is still an edited request"
);
assert!(
!s.collections[ci].workspace_request_edited(&dir.join("api/users.hurl"), 0),
"an untouched request in the loaded file carries no pencil"
);
// ...and coming back hands them straight back rather than re-reading
// the (unchanged) file from disk.
assert!(s.load_workspace_file(ci, dir.join("health.hurl")));
assert_eq!(
s.collections[ci].entries[0].url,
"https://example.com/health?deep=1"
);
assert!(s.collections[ci].entries[0].modified);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn saving_a_collection_clears_its_edit_markers_and_parked_edits() {
let dir = tmp("saved");
let mut s = Session::default();
let ci = s.open_workspace(dir.clone());
assert!(s.load_workspace_file(ci, dir.join("health.hurl")));
s.collections[ci].entries[0].modified = true;
s.collections[ci].mark_saved();
assert!(
!s.collections[ci].workspace_file_edited(&dir.join("health.hurl")),
"a saved file matches disk, so it carries no pencil"
);
// A file saved while parked is likewise no longer pending, so
// reopening it reads the (now current) file rather than stale entries.
s.collections[ci].entries[0].modified = true;
assert!(s.load_workspace_file(ci, dir.join("api/users.hurl")));
assert!(
s.collections[ci]
.workspace_pending
.contains_key(&dir.join("health.hurl"))
);
assert!(s.load_workspace_file(ci, dir.join("health.hurl")));
s.collections[ci].mark_saved();
assert!(s.collections[ci].workspace_pending.is_empty());
let _ = std::fs::remove_dir_all(&dir);
}
/// "Save all changes" on the quit dialog has to reach the files a Workspace
/// tab is *not* showing as well as the one it is: switching away from an
/// edited file parks its entries, and those are exactly as lost on exit as
/// the loaded file's.
#[test]
fn saving_all_workspace_edits_writes_the_parked_files_too_not_just_the_loaded_one() {
let dir = tmp("save_all");
let mut s = Session::default();
let ci = s.open_workspace(dir.clone());
// Edit one file, switch away (parking it), then edit the next.
assert!(s.load_workspace_file(ci, dir.join("health.hurl")));
s.collections[ci].entries[0].url = "https://example.com/health/v2".into();
s.collections[ci].entries[0].modified = true;
assert!(s.load_workspace_file(ci, dir.join("api/users.hurl")));
s.collections[ci].entries[0].url = "https://example.com/people".into();
s.collections[ci].entries[0].modified = true;
assert_eq!(
s.collections[ci].edits_lost_on_exit(),
2,
"one edit parked and one loaded, both of them at risk"
);
let written = s.collections[ci]
.save_workspace_edits()
.expect("both files are writable");
assert_eq!(
written, 2,
"the parked file counts as much as the loaded one"
);
// Both edits are on disk, not merely marked as saved.
let parked = std::fs::read_to_string(dir.join("health.hurl")).unwrap();
assert!(
parked.contains("https://example.com/health/v2"),
"the file that was switched away from was written: {parked}"
);
let loaded = std::fs::read_to_string(dir.join("api/users.hurl")).unwrap();
assert!(
loaded.contains("https://example.com/people"),
"the file on screen was written: {loaded}"
);
assert_eq!(
s.collections[ci].edits_lost_on_exit(),
0,
"with everything written there is nothing left for the dialog to warn about"
);
assert!(
s.collections[ci].workspace_pending.is_empty(),
"and no stale snapshot is left to be written back over a saved file later"
);
let _ = std::fs::remove_dir_all(&dir);
}
/// An ordinary tab is left alone: its edits are persisted with the session,
/// so a bulk save has nothing it needs to rescue and no file to guess at.
#[test]
fn saving_all_workspace_edits_leaves_an_ordinary_tab_alone() {
let mut plain = crate::collection::Collection::new("scratch".into(), Vec::new());
let mut e = crate::hurl::HurlEntry::default();
e.title = "req".into();
e.modified = true;
plain.entries.push(e);
let written = plain.save_workspace_edits().expect("a no-op cannot fail");
assert_eq!(written, 0, "nothing was written");
assert!(
plain.has_unsaved_edits(),
"and the edit is still flagged, because it is still unsaved -- it is \
just not in danger"
);
}
fn git_origin(url: &str) -> WorkspaceGitOrigin {
WorkspaceGitOrigin {
repo_url: url.to_string(),
commit_sha: "abc123".into(),
ref_kind: crate::git_remote::RefKind::Branch,
ref_name: "main".into(),
filter: WorkspaceGitFilter::All,
}
}
#[test]
fn a_workspace_opened_from_git_records_where_it_came_from() {
let dir = tmp("fromgit");
let mut s = Session::default();
let origin = git_origin("https://example.com/repo.git");
let ci = s.open_workspace_from_git(dir.clone(), "repo".into(), Some(origin.clone()));
assert!(s.collections[ci].is_workspace());
assert!(s.collections[ci].workspace_downloaded_from_git);
assert_eq!(
s.collections[ci]
.workspace_git_origin
.as_ref()
.map(|o| &o.repo_url),
Some(&origin.repo_url)
);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn closing_a_downloaded_workspace_can_delete_its_folder_but_a_local_one_never_is() {
let downloaded = tmp("del_git");
let local = tmp("del_local");
let mut s = Session::default();
let ci = s.open_workspace_from_git(
downloaded.clone(),
"repo".into(),
Some(git_origin("https://example.com/repo.git")),
);
s.close_tab_deleting_workspace(ci);
assert!(!downloaded.exists(), "a git download is ours to delete");
// The same call on a folder the user chose themselves must leave it
// alone — deleting it would destroy files PaperBoy never created.
let ci = s.open_workspace(local.clone());
s.close_tab_deleting_workspace(ci);
assert!(local.exists(), "a user's own folder is never deleted");
let _ = std::fs::remove_dir_all(&local);
}
#[test]
fn a_redownloaded_workspace_reselects_the_file_that_was_open_before() {
let dir = tmp("rebind");
let mut s = Session::default();
let ci = s.open_workspace_from_git(
dir.clone(),
"repo".into(),
Some(git_origin("https://example.com/repo.git")),
);
s.rebind_redownloaded_workspace(ci, dir.clone(), Some("api/users.hurl".into()));
assert_eq!(
s.collections[ci].workspace_root.as_deref(),
Some(dir.as_path())
);
assert!(s.collections[ci].workspace_downloaded_from_git);
assert_eq!(
s.collections[ci].path.as_deref(),
Some(dir.join("api/users.hurl").as_path())
);
assert!(matches!(
s.status,
Some(crate::i18n::Status::WorkspaceReloaded)
));
let _ = std::fs::remove_dir_all(&dir);
}
}