secs-types 0.4.1

Shared vocabulary of SECS 2R: domain types, error codes and the IPC request and response types (with generated TypeScript bindings).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
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
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
//! IPC between the screen and the service.
//!
//! The screen sends a [`Request`] as `{"method": "...", "params": {...}}` and
//! always receives an envelope: `{"ok": true, "data": Response}` or
//! `{"ok": false, "error": IpcError}`. The service never throws across this
//! seam. Long jobs report progress through the event sink supplied with the call.
//!
//! Errors carry a code and parameters, not prose: the screen turns them into
//! a sentence in the current language and keeps `detail` (the raw text) for
//! the details view and the log.

use std::collections::BTreeMap;

use serde::{Deserialize, Serialize};
use ts_rs::TS;

use crate::calibration::{CalibrationSettings, Mode};
use crate::compute::{ComputePreference, ComputeReport, ComputeStatus};
pub use crate::settings_edit::CalibrationSettingsEditParams;

/// A call from the screen.
///
/// The method names come from the variant names in one place: serde and
/// strum both rename them to snake_case, and `method_names_match_the_wire`
/// checks that the two agree.
#[derive(
    Debug, Clone, PartialEq, Serialize, Deserialize, TS, strum::VariantNames, strum::IntoStaticStr,
)]
#[serde(tag = "method", content = "params", rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
#[ts(export)]
pub enum Request {
    /// Version, the upstream release this build is ported from, and the
    /// platform. The first call the screen makes.
    Bootstrap,
    /// The `ProjectNew` Request variant.
    ProjectNew(ProjectNewParams),
    /// The `ProjectOpen` Request variant.
    ProjectOpen(ProjectPathParams),
    /// The `ProjectSave` Request variant.
    ProjectSave(ProjectSaveParams),
    /// The `ProjectInfo` Request variant.
    ProjectInfo,
    /// The `SampleLoad` Request variant.
    SampleLoad(SampleLoadParams),
    /// The `Calibrate` Request variant.
    Calibrate(CalibrateParams),
    /// The `RecommendXo` Request variant.
    RecommendXo,
    /// The `Mimo` Request variant.
    Mimo(MimoParams),
    /// The `Results` Request variant.
    Results,
    /// The `Export` Request variant.
    Export(ExportParams),
    /// The `JobCancel` Request variant.
    JobCancel(JobCancelParams),
    /// The `Jobs` Request variant.
    Jobs,
    /// The `MeasureMethods` Request variant.
    MeasureMethods,
    /// The `MeasureConfigure` Request variant.
    MeasureConfigure(MeasureConfigureParams),
    /// Returns the measurement settings stored in the open project.
    MeasureConfigGet,
    /// Returns one recording-status entry per arranged position.
    MeasurementRecords,
    /// Returns the project's microphone calibration and attachment counts.
    MicCalibrationGet,
    /// Reads, validates and stores a microphone calibration file in the project.
    MicCalibrationSet(MicCalibrationSetParams),
    /// Removes the project's selected microphone calibration file.
    MicCalibrationClear,
    /// Attaches the selected file to sweep measurements that have no mic curve.
    MicCalibrationAttach,
    /// Returns stored per-role level and SPL values.
    LevelsGet,
    /// Fills only missing per-role level values with upstream defaults.
    LevelsFillDefaults,
    /// Stops the current 2.5-second level burst without stopping its monitor.
    LevelStop,
    /// The `MeasurePosition` Request variant.
    MeasurePosition(MeasurePositionParams),
    /// The `PositionClear` Request variant.
    PositionClear(PositionClearParams),
    /// The `Undo` Request variant.
    Undo(UndoParams),
    /// The `RewLaunch` Request variant.
    RewLaunch,
    /// The `MdatScan` Request variant.
    MdatScan(MdatScanParams),
    /// The `MdatImport` Request variant.
    MdatImport(MdatImportParams),
    /// Returns the editable speaker configuration.
    ConfigGet,
    /// Replaces the speaker configuration with a built-in preset.
    ConfigApplyPreset(ConfigPresetParams),
    /// Changes the number of configured subwoofers.
    ConfigSetSubCount(ConfigSubCountParams),
    /// Changes one speaker or one of its bands.
    ConfigSetSpeaker(ConfigSetSpeakerParams),
    /// Adds the first unused upstream speaker role.
    ConfigAddSpeaker,
    /// Removes one configured speaker.
    ConfigRemoveSpeaker(ConfigIndexParams),
    /// Renumbers outputs in configuration order.
    ConfigRenumber,
    /// Returns structured configuration validation notices.
    ConfigValidate,
    /// Writes the upstream patch-sheet CSV.
    PatchSheetCsv(PathParams),
    /// Returns the editable DSP profile.
    DspGet,
    /// Applies a DSP preset or manual fields.
    DspSet(DspSetParams),
    /// Returns measurement arrangement and timing options.
    LayoutGet,
    /// Changes measurement arrangement or timing options.
    LayoutSet(LayoutSetParams),
    /// Returns the current per-position and total estimate.
    PositionEstimate,
    /// Returns the target curve and presets.
    TargetGet,
    /// Replaces target control points.
    TargetSetPoints(TargetPointsParams),
    /// Applies a built-in target preset.
    TargetApplyPreset(TargetPresetParams),
    /// Saves the target curve as upstream JSON.
    TargetSave(PathParams),
    /// Loads the target curve from upstream JSON.
    TargetLoad(PathParams),
    /// Returns calibration settings stored in the project.
    CalibrationSettingsGet,
    /// Stores calibration settings in the project.
    CalibrationSettingsSet(CalibrationSettingsParams),
    /// Applies one upstream calibration-screen edit and stores the settings.
    CalibrationSettingsEdit(CalibrationSettingsEditParams),
    /// Filter warnings from current settings (gain warnings require a run).
    SubWarnings,
    /// Optional REW facts read through the injected transport.
    RewInfo,
    /// Changes REW's audio driver and returns refreshed REW facts.
    RewDriverSet(RewDriverSetParams),
    /// Returns numeric capabilities for one calibration mode.
    ModeSpec(ModeSpecParams),
    /// Returns application-local settings.
    AppSettingsGet,
    /// Stores application-local settings.
    AppSettingsSet(AppSettingsParams),
    /// Reports the opt-in local API server and token.
    LocalApiStatus,
    /// Replaces the local API bearer token and restarts its server when needed.
    LocalApiTokenRegenerate,
    /// Available compute devices and the effective application preference.
    ComputeStatus,
    /// Opens the official GPU runtime installation guide for this platform.
    OpenGpuHelp,
    /// Smoothed, normalized measurement curves and their shared frequency grid.
    MeasurementCurves(MeasurementCurvesParams),
    /// Ready-to-draw calibration curves and axis limits for one result tab.
    ResultCurves(ResultCurvesParams),
    /// Numeric metrics, filter counts, BA rows and coded result notices.
    ResultLines,
    /// Copies the last BA output alignment into the manual sub settings.
    SubTakeValues,
    /// Opens a project-file picker through the application host.
    DialogOpenProject,
    /// Opens a project save-file picker through the application host.
    DialogSaveProject(DialogSuggestedParams),
    /// Opens an mdat-file picker through the application host.
    DialogPickMdat,
    /// Opens a folder picker through the application host.
    DialogPickFolder(DialogPickFolderParams),
    /// Opens a typed save-file picker through the application host.
    DialogSaveFile(DialogSaveFileParams),
    /// Opens a typed file picker through the application host.
    DialogOpenFile(DialogOpenFileParams),
    /// Opens a folder in the operating-system file manager.
    OpenFolder(OpenFolderParams),
    /// Starts the live input level monitor.
    LevelMonitorStart(LevelMonitorStartParams),
    /// Stops the live input level monitor.
    LevelMonitorStop,
    /// Plays a role's level-check signal for 2.5 seconds.
    LevelPlay(LevelPlayParams),
    /// Starts watching measurement-method status.
    StatusWatchStart,
    /// Stops watching measurement-method status.
    StatusWatchStop,
    /// Returns the stored or derived export base folder.
    ExportFolderGet,
    /// Stores the export base folder in the open project.
    ExportFolderSet(ExportFolderSetParams),
}

impl Request {
    /// Every method name, as it appears on the wire, derived from the
    /// variants. `secs-policy` checks that each one is registered in
    /// `features.toml` as `ipc.<method>`.
    pub const METHODS: &'static [&'static str] = <Self as strum::VariantNames>::VARIANTS;

    /// The wire name of this request's method.
    pub fn method(&self) -> &'static str {
        self.into()
    }
}

/// The successful result of a [`Request`], tagged with the same method name.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[serde(tag = "method", content = "data", rename_all = "snake_case")]
#[ts(export)]
pub enum Response {
    /// The `Bootstrap` Response variant.
    Bootstrap(BootstrapInfo),
    /// The `ProjectNew` Response variant.
    ProjectNew(ProjectInfo),
    /// The `ProjectOpen` Response variant.
    ProjectOpen(ProjectInfo),
    /// The `ProjectSave` Response variant.
    ProjectSave(ProjectInfo),
    /// The `ProjectInfo` Response variant.
    ProjectInfo(ProjectInfo),
    /// The `SampleLoad` Response variant.
    SampleLoad(JobStarted),
    /// The `Calibrate` Response variant.
    Calibrate(JobStarted),
    /// The `RecommendXo` Response variant.
    RecommendXo(JobStarted),
    /// The `Mimo` Response variant.
    Mimo(JobStarted),
    /// The `Results` Response variant.
    Results(ResultsSummary),
    /// The `Export` Response variant.
    Export(JobStarted),
    /// The `JobCancel` Response variant.
    JobCancel(JobSnapshot),
    /// The `Jobs` Response variant.
    Jobs(Vec<JobSnapshot>),
    /// The `MeasureMethods` Response variant.
    MeasureMethods(MeasureMethodsResult),
    /// The `MeasureConfigure` Response variant.
    MeasureConfigure(MeasureConfigResult),
    /// Measurement settings stored in the open project.
    MeasureConfigGet(MeasureConfigResult),
    /// Recording status for every arranged position.
    MeasurementRecords(MeasurementRecordsResult),
    /// Selected microphone calibration and attachment counts.
    MicCalibrationGet(MicCalibrationStatus),
    /// Selected microphone calibration after storing a file.
    MicCalibrationSet(MicCalibrationStatus),
    /// Empty microphone calibration status after clearing the selection.
    MicCalibrationClear(MicCalibrationStatus),
    /// Microphone calibration status after attaching it to eligible sweeps.
    MicCalibrationAttach(MicCalibrationStatus),
    /// Stored per-role level and SPL values.
    LevelsGet(LevelsResult),
    /// Stored values after filling missing level defaults.
    LevelsFillDefaults(LevelsResult),
    /// Confirms that the current level burst was stopped.
    LevelStop(()),
    /// The `MeasurePosition` Response variant.
    MeasurePosition(JobStarted),
    /// The `PositionClear` Response variant.
    PositionClear(UndoResult),
    /// The `Undo` Response variant.
    Undo(ProjectInfo),
    /// The `RewLaunch` Response variant.
    RewLaunch(RewStatusResult),
    /// The `MdatScan` Response variant.
    MdatScan(MdatScanResult),
    /// The `MdatImport` Response variant.
    MdatImport(JobStarted),
    /// The `ConfigGet` Response variant.
    ConfigGet(ConfigResult),
    /// The `ConfigApplyPreset` Response variant.
    ConfigApplyPreset(ConfigMutationResult),
    /// The `ConfigSetSubCount` Response variant.
    ConfigSetSubCount(ConfigMutationResult),
    /// The `ConfigSetSpeaker` Response variant.
    ConfigSetSpeaker(ConfigResult),
    /// The `ConfigAddSpeaker` Response variant.
    ConfigAddSpeaker(ConfigResult),
    /// The `ConfigRemoveSpeaker` Response variant.
    ConfigRemoveSpeaker(ConfigResult),
    /// The `ConfigRenumber` Response variant.
    ConfigRenumber(ConfigResult),
    /// The `ConfigValidate` Response variant.
    ConfigValidate(Vec<Notice>),
    /// The `PatchSheetCsv` Response variant.
    PatchSheetCsv(PathResult),
    /// The `DspGet` Response variant.
    DspGet(DspResult),
    /// The `DspSet` Response variant.
    DspSet(DspResult),
    /// The `LayoutGet` Response variant.
    LayoutGet(LayoutResult),
    /// The `LayoutSet` Response variant.
    LayoutSet(LayoutMutationResult),
    /// The `PositionEstimate` Response variant.
    PositionEstimate(PositionEstimateResult),
    /// The `TargetGet` Response variant.
    TargetGet(TargetResult),
    /// The `TargetSetPoints` Response variant.
    TargetSetPoints(TargetResult),
    /// The `TargetApplyPreset` Response variant.
    TargetApplyPreset(TargetResult),
    /// The `TargetSave` Response variant.
    TargetSave(PathResult),
    /// The `TargetLoad` Response variant.
    TargetLoad(TargetResult),
    /// The `CalibrationSettingsGet` Response variant.
    CalibrationSettingsGet(CalibrationSettings),
    /// The `CalibrationSettingsSet` Response variant.
    CalibrationSettingsSet(CalibrationSettings),
    /// Settings after one edit.
    CalibrationSettingsEdit(CalibrationSettings),
    /// Current settings-only filter warnings.
    SubWarnings(Vec<Notice>),
    /// Current REW facts; unavailable fields are null.
    RewInfo(RewInfoResult),
    /// Current REW facts after changing its driver.
    RewDriverSet(RewInfoResult),
    /// The `ModeSpec` Response variant.
    ModeSpec(ModeSpecResult),
    /// The `AppSettingsGet` Response variant.
    AppSettingsGet(AppSettings),
    /// The `AppSettingsSet` Response variant.
    AppSettingsSet(AppSettings),
    /// Current local API server and token state.
    LocalApiStatus(LocalApiStatus),
    /// Local API state after replacing its bearer token.
    LocalApiTokenRegenerate(LocalApiStatus),
    /// Device capability and automatic-selection result.
    ComputeStatus(ComputeStatus),
    /// GPU installation documentation opened by the application host.
    OpenGpuHelp(()),
    /// Measurement curves on the common display grid.
    MeasurementCurves(MeasurementCurvesResult),
    /// Calibration tab curves, ranges and staleness.
    ResultCurves(ResultCurvesResult),
    /// Numeric summary lines and BA table.
    ResultLines(ResultLinesResult),
    /// Stored settings after taking the last sub alignment.
    SubTakeValues(CalibrationSettings),
    /// The chosen project path, or null when cancelled.
    DialogOpenProject(Option<String>),
    /// The chosen project destination, or null when cancelled.
    DialogSaveProject(Option<String>),
    /// The chosen mdat path, or null when cancelled.
    DialogPickMdat(Option<String>),
    /// The chosen folder, or null when cancelled.
    DialogPickFolder(Option<String>),
    /// The chosen save destination, or null when cancelled.
    DialogSaveFile(Option<String>),
    /// The chosen source path, or null when cancelled.
    DialogOpenFile(Option<String>),
    /// Confirms that the folder-open request reached the host.
    OpenFolder(()),
    /// The live level-monitor job.
    LevelMonitorStart(JobStarted),
    /// The stopped live level-monitor job, when one was running.
    LevelMonitorStop(Option<JobSnapshot>),
    /// Confirms that role playback was accepted.
    LevelPlay(()),
    /// The measurement-status watch job.
    StatusWatchStart(JobStarted),
    /// The stopped status-watch job, when one was running.
    StatusWatchStop(Option<JobSnapshot>),
    /// The current export base folder.
    ExportFolderGet(ExportFolderResult),
    /// The stored export base folder.
    ExportFolderSet(ExportFolderResult),
}

/// Optional measurement selection; an absent selection includes every recorded pair.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS, Default)]
#[ts(export)]
pub struct MeasurementCurvesParams {
    /// Position numbers to include.
    #[ts(type = "number[] | null")]
    pub positions: Option<Vec<i64>>,
    /// Speaker roles to include.
    pub roles: Option<Vec<String>>,
}
/// A measurement curve, already smoothed and normalized to the mid-band mean.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct MeasurementCurve {
    /// Speaker role.
    pub role: String,
    /// Measurement position.
    #[ts(type = "number")]
    pub position: i64,
    /// Configuration kind: main, sub or top.
    pub kind: String,
    /// Levels in dB on the shared grid.
    pub values: Vec<f64>,
}
/// Display limits; both endpoints are data values, not logarithms.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct CurveAxes {
    /// Frequency bounds in Hz.
    pub frequency_hz: [f64; 2],
    /// Level or delay bounds.
    pub value: [f64; 2],
    /// Vertical unit: db or ms.
    pub unit: String,
}
/// Measurement graph data.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct MeasurementCurvesResult {
    /// Shared 280-point logarithmic frequency grid in Hz.
    pub grid: Vec<f64>,
    /// One curve per recorded role and position.
    pub curves: Vec<MeasurementCurve>,
    /// Upstream default axis bounds.
    pub axes: CurveAxes,
}
/// The calibration graph to display.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)]
#[serde(rename_all = "snake_case")]
#[ts(export)]
pub enum ResultTab {
    /// Sound pressure level relative to the target reference.
    Spl,
    /// Group delay in milliseconds.
    Gd,
    /// Crossover preview.
    Xo,
    /// Bass alignment.
    Ba,
}
/// Selection for one ready-to-draw result graph.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct ResultCurvesParams {
    /// Graph tab.
    pub tab: ResultTab,
    /// Selected main role; absent selects the first available channel.
    pub channel: Option<String>,
    /// Crossover group; absent selects the selected channel's group.
    pub group: Option<String>,
    /// Dragged crossover in Hz; absent uses the configured value.
    pub xo_hz: Option<f64>,
    /// Apply input correction to the XO preview; defaults to true.
    pub corrected: Option<bool>,
}
/// One named series on a result graph.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct ResultCurve {
    /// Series identity: before, after, target, mimo, main, sub, sum_before or sum_after.
    pub kind: String,
    /// Speaker role for per-sub curves, otherwise absent.
    pub role: Option<String>,
    /// Values on the response's shared grid.
    pub values: Vec<f64>,
}
/// A result graph whose calculations are entirely owned by the service.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct ResultCurvesResult {
    /// Requested tab.
    pub tab: ResultTab,
    /// Shared frequency grid in Hz.
    pub grid: Vec<f64>,
    /// Ordered drawable series.
    pub curves: Vec<ResultCurve>,
    /// Upstream default axis bounds.
    pub axes: CurveAxes,
    /// Whether the retained result no longer matches current inputs.
    pub stale: bool,
    /// Whether the graph comes from a dedicated subs-only result.
    pub subs_only: bool,
    /// RC lower and upper bounds, with an unknown auto upper bound represented as null.
    pub rc_band_hz: Option<(f64, Option<f64>)>,
    /// Selected crossover frequency for the draggable line.
    pub xo_hz: Option<f64>,
}
/// Values behind one channel's metrics and filters lines.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct ChannelResultLine {
    /// Main role.
    pub role: String,
    /// Before and after percentage within one dB, 20–200 Hz.
    pub within_1db_pct: [f64; 2],
    /// Before and after group-delay spread, 20–100 Hz, in ms.
    pub gd_spread_ms: [f64; 2],
    /// Number of input PEQs.
    pub peq_count: usize,
    /// FIR taps, absent when no FIR is used.
    pub fir_taps: Option<usize>,
    /// Crossover frequency, absent without bass management.
    pub xo_hz: Option<f64>,
    /// Fresh, enabled MIMO support path count, absent when not shown.
    pub mimo_support_count: Option<usize>,
}
/// One sub's output alignment and fixed filters.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct SubResultRow {
    /// Sub role.
    pub role: String,
    /// Alignment mode code.
    pub mode: String,
    /// Output gain in dB.
    pub gain_db: f64,
    /// Output delay in ms.
    pub delay_ms: f64,
    /// Output polarity, plus or minus one.
    pub polarity: i8,
    /// Ordered all-pass frequency and Q pairs.
    pub allpass: Vec<(f64, f64)>,
    /// High-pass frequency and filter type.
    pub high_pass: (f64, String),
    /// Low-pass frequency and filter type.
    pub low_pass: (f64, String),
    /// Fixed and generated peaking filters as frequency, Q and gain.
    pub peq: Vec<(f64, f64, f64)>,
}
/// A typed BA layout summary.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct SubLayoutLine {
    /// Bundle name.
    pub bundle: String,
    /// Layout code, dba or multi.
    pub kind: String,
    /// All members.
    pub members: Vec<String>,
    /// Front row roles.
    pub front: Vec<String>,
    /// Rear row roles.
    pub rear: Vec<String>,
    /// Rear delay in ms.
    pub rear_ms: f64,
    /// Automatic rear delay in ms, when available.
    pub auto_ms: Option<f64>,
    /// Manual rear trim in ms.
    pub trim_ms: f64,
    /// Shared peaking filters.
    pub peq: Vec<(f64, f64, f64)>,
}
/// BA metrics and table, independent of the selected main channel.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct SubResultLines {
    /// Whether this BA result is stale.
    pub stale: bool,
    /// Whether a dedicated subs-only run supplies these values.
    pub subs_only: bool,
    /// Metric band in Hz.
    pub band_hz: [f64; 2],
    /// Before and after flatness in dB.
    pub flatness_db: [f64; 2],
    /// Before and after across-seat spread, absent for a single seat.
    pub seat_spread_db: Option<[f64; 2]>,
    /// Number of complete sub positions.
    pub positions: usize,
    /// Output rows in configuration order.
    pub rows: Vec<SubResultRow>,
    /// Bundle layouts.
    pub layouts: Vec<SubLayoutLine>,
    /// Filter and gain warning codes and their arguments.
    pub warnings: Vec<Notice>,
}
/// Numeric calibration summary lines; no localized sentences cross IPC.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct ResultLinesResult {
    /// Whether the full calibration result is stale.
    pub stale: bool,
    /// Per-main metrics and filter counts.
    pub channels: Vec<ChannelResultLine>,
    /// Total delay in milliseconds, absent before calibration.
    pub total_delay_ms: Option<f64>,
    /// Engine notes as codes and arguments.
    pub notes: Vec<Notice>,
    /// RC ceiling provenance and room-volume notices.
    pub rc: Vec<Notice>,
    /// BA metrics, table, layouts and warnings when at least two subs are available.
    pub ba: Option<SubResultLines>,
}

/// What the screen needs before it draws anything.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct BootstrapInfo {
    /// Product name shown in the title bar and the about view.
    pub app_name: String,
    /// The SECS 2R version (the workspace version).
    pub version: String,
    /// True while the major version is 0: every 0.x build is a prerelease.
    pub prerelease: bool,
    /// The SECS 2 release this build follows.
    pub upstream: UpstreamBase,
    /// The operating-system platform running this build.
    pub platform: Platform,
}
/// The upstream SECS 2 release a build is ported from (`UPSTREAM.toml`).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct UpstreamBase {
    /// Upstream product name from `UPSTREAM.toml`.
    pub name: String,
    /// Upstream repository URL from `UPSTREAM.toml`.
    pub repository: String,
    /// Upstream release version from `UPSTREAM.toml`.
    pub version: String,
    /// Forty-character upstream Git commit from `UPSTREAM.toml`.
    pub commit: String,
    /// Upstream snapshot date from `UPSTREAM.toml`.
    pub date: String,
}
/// The operating-system platform running the service.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct Platform {
    /// `windows`, `macos` or `linux` (`std::env::consts::OS`).
    pub os: String,
    /// `x86_64` or `aarch64` (`std::env::consts::ARCH`).
    pub arch: String,
}

/// Inputs for creating a project.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct ProjectNewParams {
    /// Destination `.secs` file path.
    pub path: String,
    /// Speaker-layout preset name.
    pub preset: String,
    /// Number of subwoofers.
    pub sub_count: u8,
    /// Whether to create the fixed 7.1.4 sample-room project.
    pub sample: bool,
    /// Whether this is a tutorial session using the sample room. The session
    /// cannot be saved or exported; its measurements and results live in a
    /// temporary folder that is removed when the session ends, and `path` is
    /// only reported back.
    #[serde(default)]
    pub tutorial: bool,
}
/// Inputs for loading embedded or synthetic sample measurements.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS, Default)]
#[ts(export)]
pub struct SampleLoadParams {
    /// Synthetic position count, 2 to 17 (the largest layout); absent loads
    /// the one-position embedded room. Other counts are refused with
    /// `measurement_input` (`field = positions`).
    pub positions: Option<u32>,
}
/// A project file path.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct ProjectPathParams {
    /// Source `.secs` file path.
    pub path: String,
}
/// Inputs for saving the open project.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS, Default)]
#[ts(export)]
pub struct ProjectSaveParams {
    /// Optional save-as `.secs` path; absent saves in place.
    pub path: Option<String>,
}
/// Screen-facing information about the open project.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct ProjectInfo {
    /// Open `.secs` file path.
    pub path: String,
    /// Project display name.
    pub name: String,
    /// Speaker-layout preset name.
    pub preset: String,
    /// Number of configured subwoofers.
    pub sub_count: usize,
    /// Measured position numbers.
    pub positions: Vec<i64>,
    /// Whether the in-memory project has unsaved changes.
    pub dirty: bool,
    /// Whether this open project is a non-writable tutorial session.
    pub tutorial: bool,
    /// Warnings produced while loading legacy project entries.
    pub migration_warnings: Vec<MigrationWarning>,
}
/// A project migration warning code and affected entry.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct MigrationWarning {
    /// Stable warning code translated by the screen.
    pub code: String,
    /// Project entry affected by the warning.
    pub entry: String,
}

/// Optional settings for a calibration run.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS, Default)]
#[ts(export)]
pub struct CalibrateParams {
    /// Settings override; absent uses the open project.
    pub settings: Option<CalibrationSettings>,
    /// Designs the subwoofers only (upstream [서브만 계산]); the result is
    /// kept apart and shown by the BA tab until the next full run.
    #[serde(default)]
    pub subs_only: bool,
}
/// Optional settings for a MIMO run.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS, Default)]
#[ts(export)]
pub struct MimoParams {
    /// Settings override; absent uses the open project.
    pub settings: Option<CalibrationSettings>,
}

/// A service-assigned long-running job identifier.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, TS)]
#[serde(transparent)]
#[ts(export)]
pub struct JobId(#[ts(type = "number")] pub u64);
/// The operation performed by a long-running job.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, TS)]
#[serde(rename_all = "snake_case")]
#[ts(export)]
pub enum JobKind {
    /// Records all configured roles at one measurement position.
    Measure,
    /// Loads embedded or deterministic synthetic sample measurements.
    SampleLoad,
    /// Imports assigned measurements from a REW mdat file.
    MdatImport,
    /// Computes a calibration design from project measurements.
    Calibrate,
    /// Scores crossover-frequency candidates.
    RecommendXo,
    /// Computes MIMO support paths.
    Mimo,
    /// Writes one selected export bundle.
    Export,
    /// Streams microphone levels and controls level-check playback.
    LevelMonitor,
    /// Watches measurement-method status changes.
    StatusWatch,
}
/// The current lifecycle state of a job.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)]
#[serde(rename_all = "snake_case")]
#[ts(export)]
pub enum JobStatus {
    /// The worker is still running and may accept cancellation.
    Running,
    /// Cancellation was requested and the worker has not stopped yet.
    CancelRequested,
    /// The worker completed and produced a result.
    Succeeded,
    /// The worker stopped with an error.
    Failed,
    /// The caller cancelled the operation.
    Cancelled,
}
impl JobStatus {
    /// Whether the job can no longer change state.
    pub fn is_terminal(self) -> bool {
        matches!(self, Self::Succeeded | Self::Failed | Self::Cancelled)
    }
}
/// The immediate response after a job starts.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct JobStarted {
    /// Identifier assigned to the job.
    pub job: JobId,
    /// Operation the job performs.
    pub kind: JobKind,
}
/// The latest observable state of a job.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct JobSnapshot {
    /// Identifier assigned to the job.
    pub job: JobId,
    /// Operation the job performs.
    pub kind: JobKind,
    /// Current lifecycle state.
    pub status: JobStatus,
    /// Whether a cancellation request can still prevent commit.
    pub cancellable: bool,
    /// Most recently reported stage progress.
    pub progress: Option<JobProgress>,
    /// Failure once finished unsuccessfully.
    pub error: Option<IpcError>,
}
/// Progress within one named job stage.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct JobProgress {
    /// Stable stage code translated by the screen.
    pub stage: String,
    #[ts(type = "number")]
    /// Completed work units in this stage.
    pub done: u64,
    #[ts(type = "number")]
    /// Total work units in this stage.
    pub total: u64,
}
/// A pushed lifecycle event for a long-running job.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[serde(tag = "event", rename_all = "snake_case")]
#[ts(export)]
pub enum JobEvent {
    /// Announces a newly accepted job and its operation.
    Started { job: JobId, kind: JobKind },
    /// Reports completed and total work units for a stable stage code.
    Progress {
        job: JobId,
        stage: String,
        #[ts(type = "number")]
        done: u64,
        #[ts(type = "number")]
        total: u64,
    },
    /// Reports a presentation-neutral log code and template parameters.
    Log {
        job: JobId,
        code: String,
        params: BTreeMap<String, String>,
    },
    /// Reports a terminal status and an ephemeral operation result or error.
    /// Calibration and MIMO carry only a marker; read `results` for their summary.
    Finished {
        job: JobId,
        status: JobStatus,
        result: Option<Box<JobResult>>,
        error: Option<IpcError>,
    },
    /// Reports a live input level at the monitor cadence.
    Meter {
        job: JobId,
        rms_dbfs: f64,
        peak_dbfs: f64,
        spl_db: Option<f64>,
        clipping: bool,
    },
    /// Reports a changed measurement-method status snapshot.
    MeasureStatus {
        job: JobId,
        status: MeasureMethodsResult,
    },
}
/// The successful result produced by a job.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[serde(tag = "kind", content = "data", rename_all = "snake_case")]
#[ts(export)]
pub enum JobResult {
    /// Calibration committed; fetch the current screen summary with `results`.
    Calibration,
    /// Crossover recommendation computed for the current project.
    Xo(XoRecommendation),
    /// MIMO committed; fetch the current screen summary with `results`.
    Mimo,
    /// Paths written by an exporter.
    Export(ExportResult),
    /// Project state after a completed measurement.
    Measurement(ProjectInfo),
    /// Project state after an mdat import.
    MdatImport(ProjectInfo),
    /// A long-lived monitor or watcher stopped without a payload.
    Stopped,
}
/// The job to cancel.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct JobCancelParams {
    /// Identifier of the job to cancel.
    pub job: JobId,
}

/// The latest calibration and MIMO results.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct ResultsSummary {
    /// Latest calibration result, including stale state.
    pub calibration: Option<CalibrationSummary>,
    /// Latest MIMO result, including stale state.
    pub mimo: Option<MimoSummary>,
    /// Whether the MIMO result goes into an export, and if not, why.
    pub mimo_export: MimoExportDecision,
}
/// Whether the MIMO result goes into an export, and if not, why.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)]
#[serde(rename_all = "snake_case")]
#[ts(export)]
pub enum MimoExportDecision {
    /// The current MIMO support paths go into the export.
    Included,
    /// MIMO is switched off in the current settings.
    Off,
    /// No MIMO result has been computed or restored.
    None,
    /// The MIMO result does not match the current inputs or compute environment.
    Stale,
    /// MIMO needs at least three measured positions.
    TooFewPositions,
    /// The current MIMO result contains no support paths.
    NoSupports,
}
/// A presentation-neutral note or warning code with template parameters.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct Notice {
    /// Stable snake_case code derived from the engine note variant.
    pub code: String,
    /// String values for the screen message template.
    pub params: BTreeMap<String, String>,
}

/// The screen-facing summary of one calibration design.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct CalibrationSummary {
    /// Whether this result was restored from the project cache instead of computed in this
    /// session; staged and before/after mdat need a live design.
    #[serde(default)]
    pub cached: bool,
    /// Whether current project inputs differ from this result.
    pub stale: bool,
    /// Which input first differs: measurements, settings or target.
    pub stale_reason: Option<String>,
    /// Calibration mode used to compute this result.
    pub mode: Mode,
    /// Ultra-mode latency limit used to compute this result, in milliseconds.
    pub ultra_ms: f64,
    /// Values for the upstream verdict card.
    pub verdict: VerdictSummary,
    /// Per-channel before-and-after metrics.
    pub scorecard: Vec<ChannelScore>,
    /// Late 20–150 Hz energy before and after correction at every measured position.
    #[serde(default)]
    pub late_energy: Vec<LateEnergy>,
    /// Total filter latency in milliseconds.
    pub latency_ms: f64,
    /// Informational codes and values translated by the screen.
    pub notes: Vec<Notice>,
    /// Main-channel roles in design order; filter coefficients stay in Rust.
    pub main_roles: Vec<String>,
    /// Subwoofer roles in design order; filter coefficients stay in Rust.
    pub sub_roles: Vec<String>,
}
/// Values shown by the upstream `step_calibration.py` verdict card.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct VerdictSummary {
    /// Share within ±1 dB before correction, in percent.
    pub within_1db_before_pct: f64,
    /// Share within ±1 dB after correction, in percent.
    pub within_1db_after_pct: f64,
    /// Low-band group-delay spread before correction, in milliseconds.
    pub low_band_time_spread_before_ms: f64,
    /// Low-band group-delay spread after correction, in milliseconds.
    pub low_band_time_spread_after_ms: f64,
    /// Delay added by correction, in milliseconds.
    pub added_delay_ms: f64,
    /// Across-position level spread after correction, in dB.
    pub position_spread_db: f64,
}
/// Before-and-after scorecard metrics for one speaker role.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct ChannelScore {
    /// Internal speaker role.
    pub role: String,
    /// Metrics before correction.
    pub before: MetricsSummary,
    /// Metrics after correction.
    pub after: MetricsSummary,
}
/// Late 20–150 Hz energy for one main role at one measured position.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct LateEnergy {
    /// Internal speaker role.
    pub role: String,
    /// Measured position number.
    pub position: u32,
    /// Late-to-early energy before correction, in dB.
    pub before_db: f64,
    /// Late-to-early energy after correction, in dB.
    pub after_db: f64,
}
/// The upstream `Metrics` fields for one response.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct MetricsSummary {
    /// Reference level from upstream `Metrics.level`, in dB.
    pub level: f64,
    /// Share within ±1 dB from 20 Hz, in percent.
    pub in1_20: f64,
    /// Share within ±2 dB from 20 Hz, in percent.
    pub in2_20: f64,
    /// Share within ±1 dB from 200 Hz, in percent.
    pub in1_200: f64,
    /// Share within ±2 dB from 200 Hz, in percent.
    pub in2_200: f64,
    /// Share within ±1 dB from 2,000 Hz, in percent.
    pub in1_2000: f64,
    /// Share within ±2 dB from 2,000 Hz, in percent.
    pub in2_2000: f64,
    /// Phase rotation from upstream `Metrics.turns`, in turns.
    pub turns: f64,
    /// Group-delay spread near 20 Hz, in milliseconds.
    pub gd_20: f64,
    /// Group-delay spread near 100 Hz, in milliseconds.
    pub gd_100: f64,
    /// Group-delay spread near 500 Hz, in milliseconds.
    pub gd_500: f64,
    /// Largest absolute 1/24-octave group-delay peak, in milliseconds.
    pub gd24_abs: f64,
    /// Frequency of the largest absolute group-delay peak, in Hz.
    pub gd24_abs_hz: f64,
    /// Largest signed 1/24-octave group-delay peak, in milliseconds.
    pub gd24_max: f64,
    /// Span of 1/24-octave group delay, in milliseconds.
    pub gd24_span: f64,
    /// Group-delay spread near 30 Hz, in milliseconds.
    pub gd_30: f64,
    /// Pre-ringing level from upstream `Metrics.pre_db`, in dB.
    pub pre_db: f64,
}
/// The screen-facing summary of one MIMO run.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct MimoSummary {
    /// Actual computation backend, retained with the result.
    #[serde(default)]
    pub compute: ComputeReport,
    /// Whether current calibration inputs differ from this MIMO result.
    pub stale: bool,
    /// Realization kind, `iir` or `fir`.
    pub kind: String,
    /// Upper support frequency in Hz.
    pub fsiso: f64,
    /// Number of generated support paths.
    pub support_count: usize,
    /// Total FIR-tap budget across all generated paths.
    pub fir_taps_total: usize,
    /// Informational codes and values translated by the screen.
    pub notes: Vec<Notice>,
    /// Number of distinct input roles with at least one generated support path.
    pub input_count: usize,
    /// Per-channel metrics after MIMO at the main position.
    #[serde(default)]
    pub scorecard: Vec<MimoChannelScore>,
    /// Late 20–150 Hz energy after MIMO at every measured position.
    #[serde(default)]
    pub late_energy: Vec<MimoLateEnergy>,
}
/// Scorecard metrics after MIMO for one main role.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct MimoChannelScore {
    /// Internal speaker role.
    pub role: String,
    /// Metrics after the MIMO support contributions are added.
    pub after_mimo: MetricsSummary,
}
/// Late 20–150 Hz energy after MIMO for one main role and measured position.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct MimoLateEnergy {
    /// Internal speaker role.
    pub role: String,
    /// Measured position number.
    pub position: u32,
    /// Late-to-early energy after MIMO, in dB.
    pub after_mimo_db: f64,
}
/// Crossover candidates and the best value for each group.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct XoRecommendation {
    /// Best crossover frequency in Hz for each speaker group.
    pub best: Vec<(String, f64)>,
    /// Evaluated crossover frequencies in Hz.
    pub candidates: Vec<f64>,
}

/// The supported export bundle.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)]
#[serde(rename_all = "snake_case")]
#[ts(export)]
pub enum ExportKind {
    /// CamillaDSP configuration and FIR coefficient WAV files.
    CamillaDsp,
    /// REW mdat containing the upstream staged responses.
    StagedMdat,
    /// REW mdat containing the original measurements, the correction results
    /// or both ([`ExportParams::mdat_scope`]; upstream's before-and-after mdat).
    BeforeAfterMdat,
    /// Per-channel filter values as text plus FIR WAV files (upstream
    /// `calibration.export_filter_text`). Results with RC only.
    FilterText,
    /// A complete Equalizer APO configuration: `config.txt`, the filter file
    /// and FIR WAV files (upstream `calibration.export_eqapo`). RC, BA and
    /// MIMO support paths, which upstream refuses (docs/DEVIATIONS.md F12).
    EqualizerApo,
    /// One complete 48 kHz impulse response and response CSV per reachable
    /// input-to-output path, including RC, BA, LFE and MIMO operations.
    Convolution,
}

/// Why a filter export cannot carry the current result (upstream
/// `calibration.filter_export_block`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)]
#[serde(rename_all = "snake_case")]
#[ts(export)]
pub enum ExportBlock {
    /// The result has subs (BA); filter text carries RC only.
    Subs,
    /// The result includes MIMO; filter text does not carry it.
    Mimo,
    /// The result was restored from the cache and is stale; mdat needs the measurements' spectra,
    /// so it must be recalibrated first.
    StaleCache,
}

impl ExportBlock {
    /// The `params.reason` value of an [`ErrorCode::ExportScope`] error.
    pub fn name(self) -> &'static str {
        match self {
            Self::Subs => "subs",
            Self::Mimo => "mimo",
            Self::StaleCache => "stale_cache",
        }
    }
}

/// Upstream `filter_export_block`: whether `kind` can carry a result with
/// subs (`has_subs`) and MIMO support paths (`has_mimo`). CamillaDSP, the
/// mdat exports, Equalizer APO and convolution carry everything; filter text
/// carries RC only (subs are checked first, as upstream). Upstream stops MIMO at
/// Equalizer APO as well; its writer already routes the support paths, and
/// `secs-filters/tests/eqapo_playback.rs` plays them through the engine
/// (DEVIATIONS F12). The screen mirrors this rule (`screens/export/types.ts`).
pub fn filter_export_block(
    kind: ExportKind,
    has_subs: bool,
    has_mimo: bool,
) -> Option<ExportBlock> {
    match kind {
        ExportKind::FilterText if has_subs => Some(ExportBlock::Subs),
        ExportKind::FilterText if has_mimo => Some(ExportBlock::Mimo),
        _ => None,
    }
}

/// Whether an export format can carry the current result. Stale cached
/// calibration blocks mdat; filter formats retain [`filter_export_block`].
pub fn export_block(
    kind: ExportKind,
    has_subs: bool,
    has_mimo: bool,
    stale_cache: bool,
) -> Option<ExportBlock> {
    match kind {
        ExportKind::StagedMdat | ExportKind::BeforeAfterMdat if stale_cache => {
            Some(ExportBlock::StaleCache)
        }
        _ => filter_export_block(kind, has_subs, has_mimo),
    }
}
/// What the REW mdat export ([`ExportKind::BeforeAfterMdat`]) carries
/// (docs/DEVIATIONS.md F19). The file name says which: `원 측정` for the
/// measurements, `보정 결과` for the computed responses.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, TS)]
#[serde(rename_all = "snake_case")]
#[ts(export)]
pub enum MdatScope {
    /// The main position's before-and-after responses (upstream's file) and
    /// the original measurements of the other positions.
    #[default]
    All,
    /// The original measurements of every position, as stored; needs no
    /// correction result.
    Measurements,
    /// The computed responses at the main position only.
    Results,
}

/// Sample formats accepted by CamillaDSP's Wasapi backend.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)]
#[ts(export)]
pub enum CamillaWasapiFormat {
    /// Signed 32-bit integer.
    #[serde(rename = "S32")]
    S32,
    /// Signed 24-bit integer.
    #[serde(rename = "S24")]
    S24,
    /// Signed 16-bit integer.
    #[serde(rename = "S16")]
    S16,
    /// 32-bit floating point.
    #[serde(rename = "F32")]
    F32,
}

impl CamillaWasapiFormat {
    /// CamillaDSP configuration spelling.
    pub fn name(self) -> &'static str {
        match self {
            Self::S32 => "S32",
            Self::S24 => "S24",
            Self::S16 => "S16",
            Self::F32 => "F32",
        }
    }
}

/// CamillaDSP capture backend. Channel counts come from the export plan.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS, Default)]
#[serde(tag = "type", rename_all = "snake_case")]
#[ts(export)]
pub enum CamillaCaptureDevice {
    /// File placeholder compatible with the existing export.
    #[default]
    File,
    /// Windows Audio Session API capture.
    Wasapi {
        /// Endpoint name; absent selects the system default.
        device: Option<String>,
        /// Sample representation.
        format: CamillaWasapiFormat,
        /// Request exclusive access.
        exclusive: bool,
        /// Capture a playback endpoint in shared mode.
        loopback: bool,
    },
    /// ASIO capture. Requires CamillaDSP's ASIO build (`camilladsp-windows-asio`).
    Asio {
        /// ASIO driver name.
        device: String,
    },
}

/// CamillaDSP playback backend. Channel counts come from the export plan.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS, Default)]
#[serde(tag = "type", rename_all = "snake_case")]
#[ts(export)]
pub enum CamillaPlaybackDevice {
    /// File placeholder compatible with the existing export.
    #[default]
    File,
    /// Windows Audio Session API playback.
    Wasapi {
        /// Endpoint name; absent selects the system default.
        device: Option<String>,
        /// Sample representation.
        format: CamillaWasapiFormat,
        /// Request exclusive access.
        exclusive: bool,
    },
    /// ASIO playback. Requires CamillaDSP's ASIO build (`camilladsp-windows-asio`).
    Asio {
        /// ASIO driver name.
        device: String,
    },
}

/// Capture and playback backends for a CamillaDSP export.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS, Default)]
#[ts(export)]
pub struct CamillaDevices {
    /// Capture backend.
    pub capture: CamillaCaptureDevice,
    /// Playback backend.
    pub playback: CamillaPlaybackDevice,
}

/// The export bundle and destination folder.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct ExportParams {
    /// Export bundle to write.
    pub kind: ExportKind,
    /// Destination folder path. An empty path uses the project's export folder
    /// and applies the upstream timestamped subfolder convention.
    pub folder: String,
    /// What the REW mdat carries; absent means [`MdatScope::All`]. Only
    /// [`ExportKind::BeforeAfterMdat`] takes it; other kinds refuse it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[ts(optional)]
    pub mdat_scope: Option<MdatScope>,
    /// Optional stable export name. Named exports replace the matching bundle.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[ts(optional)]
    pub design_name: Option<String>,
    /// Optional CamillaDSP Windows backends. File placeholders are the default.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[ts(optional)]
    pub camilla_devices: Option<CamillaDevices>,
    /// Additional convolution output rates. Other export kinds refuse a non-empty list.
    #[serde(default)]
    #[ts(optional = nullable)]
    pub extra_rates: Vec<u32>,
}
/// Files written by a completed export job.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct ExportResult {
    /// Paths of all files written by the exporter.
    pub files: Vec<String>,
    /// Sample rate of the files in Hz. REW mdat always reports 48000.
    pub output_rate: u32,
    /// Informational notices produced while resolving the output rate.
    #[serde(default)]
    pub notes: Vec<Notice>,
    /// Actual export folder written by the job.
    pub folder: String,
    /// Whether the exported calibration differed from current project inputs.
    pub stale: bool,
}

// P28 host, live-monitor, watch and export-folder types. Keep this block
// contiguous so the parallel M5 IPC additions merge without interleaving.
/// Optional suggested name for a save dialog.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS, Default)]
#[ts(export)]
pub struct DialogSuggestedParams {
    /// Suggested file name.
    pub suggested: String,
}
/// Optional starting folder for a folder picker.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS, Default)]
#[ts(export)]
pub struct DialogPickFolderParams {
    /// Starting folder, when known.
    pub start: Option<String>,
}
/// The kind of file a host save dialog accepts.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)]
#[serde(rename_all = "snake_case")]
#[ts(export)]
pub enum SaveFileKind {
    /// UTF-8 patch-sheet CSV.
    PatchSheet,
    /// Target-curve JSON.
    Target,
}
/// Typed save-file dialog parameters.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct DialogSaveFileParams {
    /// File type and filter.
    pub kind: SaveFileKind,
    /// Suggested file name.
    pub suggested: String,
}
/// The kind of file a host open dialog accepts.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)]
#[serde(rename_all = "snake_case")]
#[ts(export)]
pub enum OpenFileKind {
    /// Target-curve JSON.
    Target,
    /// Microphone response calibration text (`.txt`, `.cal` or `.frd`).
    MicCalibration,
}
/// Typed open-file dialog parameters.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct DialogOpenFileParams {
    /// File type and filter.
    pub kind: OpenFileKind,
}
/// Folder to reveal in the operating-system file manager.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct OpenFolderParams {
    /// Folder path.
    pub path: String,
}
/// Optional role to associate with a level-monitor start.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS, Default)]
#[ts(export)]
pub struct LevelMonitorStartParams {
    /// Speaker role initially selected for playback.
    pub role: Option<String>,
}
/// Role and output level for one 2.5-second level-check burst.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct LevelPlayParams {
    /// Internal speaker role.
    pub role: String,
    /// Master output level in dBFS.
    pub master_dbfs: f64,
}
/// Export base-folder update.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct ExportFolderSetParams {
    /// Folder path to store in the open project.
    pub folder: String,
}
/// Current export base folder and whether it came from project storage.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct ExportFolderResult {
    /// Export base folder.
    pub folder: String,
    /// True when `extra.export.folder` supplied this value.
    pub stored: bool,
}

// Measurement request and response types.
/// A validated microphone calibration file selected for the open project.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct MicCalibrationFile {
    /// File name as selected by the user.
    pub name: String,
    /// Full selected path; the project retains the decoded text separately.
    pub path: String,
    /// miniDSP serial number from `SERNO`, when present.
    pub serial: Option<String>,
    /// USB microphone sensitivity factor in dB.
    pub sens_factor_db: Option<f64>,
    /// Analog input gain from `AGain`, in dB.
    pub analog_gain_db: Option<f64>,
    /// Analog microphone sensitivity at 94 dB SPL, in dBFS.
    pub sensitivity_dbfs: Option<f64>,
    /// Quoted metadata lines other than the sensitivity header.
    pub notes: Vec<String>,
    /// Number of frequency-response points.
    pub points: u32,
    /// Lowest tabulated frequency in Hz.
    pub min_hz: f64,
    /// Highest tabulated frequency in Hz.
    pub max_hz: f64,
    /// Whether any response point includes phase.
    pub has_phase: bool,
}
/// Selected microphone calibration and recorded-measurement attachment counts.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct MicCalibrationStatus {
    /// The project's selected file, or absent when none is selected.
    pub file: Option<MicCalibrationFile>,
    /// Recorded position-role pairs whose sidecar attaches a `meterCal` curve.
    pub attached: u32,
    /// Sweep measurements without a `meterCal` curve that can receive the file.
    pub attachable: u32,
}
/// A microphone calibration file selected by full path.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct MicCalibrationSetParams {
    /// Full path selected by the user.
    pub path: String,
}

/// Measurement methods available on this host.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS, Default)]
#[ts(export)]
pub struct MeasureMethodsResult {
    /// Stable identifiers for available measurement methods.
    pub methods: Vec<String>,
    /// Native endpoints with their channel counts.
    pub native_devices: Vec<MeasureDevice>,
    /// Native enumeration failure, without hiding the other methods.
    pub native_error: Option<IpcError>,
    /// REW process, API, and license status.
    pub rew: RewStatusResult,
    /// Positions present in the unmodified sample room.
    pub mock_positions: Vec<i64>,
    /// Roles present in the unmodified sample room.
    pub mock_roles: Vec<String>,
}
/// An enumerated native audio endpoint.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct MeasureDevice {
    /// Backend endpoint identifier.
    pub id: String,
    /// Backend endpoint display name.
    pub name: String,
    /// Maximum number of input channels.
    pub input_channels: usize,
    /// Maximum number of output channels.
    pub output_channels: usize,
}
/// Measurement method and device settings.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS, Default)]
#[ts(export)]
pub struct MeasureConfigureParams {
    /// Measurement method identifier.
    pub method: String,
    /// Optional input device identifier.
    pub input_device: Option<String>,
    /// Optional output device identifier.
    pub output_device: Option<String>,
    /// Optional one-based input channel number.
    pub input_channel: Option<u16>,
    /// One-based output channels in measurement-plan role order; empty preserves wiring.
    #[serde(default)]
    pub output_channels: Vec<u16>,
    /// Optional sweep length in samples.
    pub sweep_length: Option<usize>,
    /// Optional sweep repetition count; allowed values are 1, 2, 4 and 8.
    pub repetitions: Option<u8>,
    /// Optional sweep level in dBFS.
    pub sweep_level_dbfs: Option<f64>,
    /// Optional timing-reference mode.
    pub timing: Option<String>,
    /// Optional one-based loopback input channel.
    pub loopback_input_channel: Option<u16>,
    /// Optional acoustic timing-reference output channel.
    pub timing_ref_output: Option<u16>,
    /// Optional share preference: auto, exclusive, or shared.
    pub share_mode: Option<String>,
}
/// The active measurement settings.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS, Default)]
#[ts(export)]
pub struct MeasureConfigResult {
    /// Active measurement method identifier.
    pub method: String,
    /// Active sweep level in dBFS.
    pub sweep_level_dbfs: Option<f64>,
    /// Active input endpoint identifier; empty selects the default.
    pub input_device: String,
    /// Active output endpoint identifier; empty selects the default.
    pub output_device: String,
    /// One-based microphone input channel.
    pub input_channel: u16,
    /// Roles in the same order as output_channels.
    pub roles: Vec<String>,
    /// One-based output channels in measurement-plan role order.
    pub output_channels: Vec<u16>,
    /// Sweep length in samples.
    pub sweep_length: usize,
    /// Active repetition count after timing-reference normalization.
    pub repetitions: u8,
    /// Sweep sample rate in Hz.
    pub sample_rate: u32,
    /// Supported sweep lengths in samples.
    pub sweep_lengths: Vec<usize>,
    /// Timing-reference mode.
    pub timing: String,
    /// Optional one-based loopback input channel.
    pub loopback_input_channel: Option<u16>,
    /// Optional acoustic timing-reference output channel.
    pub timing_ref_output: Option<u16>,
    /// Share preference: auto, exclusive, or shared.
    pub share_mode: String,
}
/// Recording status and upstream source values for one arranged position.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct PositionRecord {
    /// One-based arranged position number.
    #[ts(type = "number")]
    pub position: i64,
    /// Whether every planned role is recorded at this position.
    pub done: bool,
    /// Planned roles that have a recording at this position.
    pub roles: Vec<String>,
    /// Source file/value by recorded role; native and REW sweeps use `measured`.
    pub sources: BTreeMap<String, String>,
}
/// Recording status for the complete measurement arrangement.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct MeasurementRecordsResult {
    /// One entry per arranged position.
    pub records: Vec<PositionRecord>,
}
/// Stored level-check readings, keyed by measurement role (upstream `extra['levels']`).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct LevelsResult {
    /// Measured input level in dBFS by role: the meter reading while that channel played.
    pub levels: BTreeMap<String, f64>,
    /// Measured sound-pressure level in dB SPL by role.
    pub spl: BTreeMap<String, f64>,
}
/// The measurement position to record.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct MeasurePositionParams {
    /// One-based measurement position number.
    pub position: i64,
}
/// The measurement position to clear.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct PositionClearParams {
    /// One-based measurement position number.
    pub position: i64,
}
/// A service-issued undo token.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct UndoParams {
    /// Opaque service-issued undo token.
    pub token: String,
}
/// An undo token and the project state it restores.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct UndoResult {
    /// Opaque token for the inverse action.
    pub token: String,
    /// Project state after the action.
    pub project: ProjectInfo,
}
/// Whether REW is running, reachable, and licensed as Pro.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS, Default)]
#[ts(export)]
pub struct RewStatusResult {
    /// Whether an REW process is running.
    pub running: bool,
    /// Whether the REW API responds.
    pub reachable: bool,
    /// Observed automatic-sweep license state: unknown until success or rejection.
    pub pro: Option<bool>,
}
/// A requested REW audio driver.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct RewDriverSetParams {
    /// Driver name as REW reports it (`ASIO` or `Java`).
    pub driver: String,
}
/// Facts from REW, distinct from project-stored measurement preferences.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS, Default)]
#[ts(export)]
pub struct RewInfoResult {
    pub executable_path: Option<String>,
    pub running: bool,
    pub reachable: bool,
    pub version: Option<String>,
    /// REW's current audio driver, or null when it could not be read.
    pub driver: Option<String>,
    /// Observed automatic-sweep license state: unknown until success or rejection.
    pub pro: Option<bool>,
    /// REW's current input device, read from its own audio preferences.
    pub input_device: Option<String>,
    /// REW's current output device, read from its own audio preferences.
    pub output_device: Option<String>,
    /// REW's current input channel name.
    pub input: Option<String>,
    pub blocking: Option<bool>,
    /// Empty means no file loaded; null means unknown or per-input calibration.
    pub input_calibration_file: Option<String>,
    pub input_devices: Option<Vec<RewDeviceInfo>>,
    pub output_devices: Option<Vec<RewDeviceInfo>>,
    pub input_channel_names: Option<Vec<String>>,
    pub sample_rate: Option<f64>,
    pub sweep: Option<RewSweepInfo>,
    pub level_dbfs: Option<f64>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct RewDeviceInfo {
    pub id: String,
    pub name: String,
    pub channels: usize,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct RewSweepInfo {
    pub start_hz: Option<f64>,
    pub end_hz: Option<f64>,
    pub length: Option<String>,
}

/// The REW mdat file to scan.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct MdatScanParams {
    /// Source `.mdat` file path.
    pub path: String,
}
/// Measurements, suggested assignments, and problem codes found in an mdat file.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS, Default)]
#[ts(export)]
pub struct MdatScanResult {
    /// Measurements in file order, including assignment guesses.
    pub measurements: Vec<MdatScanMeasurement>,
    /// Suggested measurement-to-role assignments.
    pub suggestions: Vec<MdatAssignment>,
    /// Stable problem codes and template parameters.
    pub problems: Vec<Notice>,
}
/// One scanned measurement with an unambiguous row identifier.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct MdatScanMeasurement {
    /// Zero-based row index, also usable when titles repeat.
    pub index: usize,
    /// Original measurement title.
    pub title: String,
    /// Suggested internal role, or no assignment.
    pub role: Option<String>,
    /// Guessed one-based measurement position.
    pub position: i64,
    /// Whether the title explicitly names a position, including position 1.
    pub position_tagged: bool,
    /// Low-band classifier result, absent when no IR is available.
    pub looks_like_sub: Option<bool>,
}
/// An mdat measurement assigned to a speaker role.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct MdatAssignment {
    /// Measurement title from the mdat file.
    pub measurement: String,
    /// Internal speaker role.
    pub role: String,
    /// Optional zero-based row index to disambiguate repeated titles.
    pub index: Option<usize>,
    /// Optional per-row position overriding the import destination.
    pub position: Option<i64>,
}
/// An mdat file, its assignments, and destination position.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct MdatImportParams {
    /// Source `.mdat` file path.
    pub path: String,
    /// Accepted measurement-to-role assignments.
    pub assignments: Vec<MdatAssignment>,
    /// Destination measurement position number.
    pub position: i64,
}

// Project editing request and response types.
/// A filesystem path used by a project editor.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct PathParams {
    /// File system path chosen by the user.
    pub path: String,
}
/// A path written by an editor.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct PathResult {
    /// File system path that was written.
    pub path: String,
}
/// A preset change which may need measurement-clearing confirmation.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct ConfigPresetParams {
    /// Preset name (`2.0`, `2.1`, `2.2`, `4.0`, `4.1`, `4.2`, `5.1`, `7.1`, `7.1.4`, `9.1.6`, or `custom` for an empty layout).
    pub preset: String,
    /// Clears existing measurements; without it a project with measurements answers `confirm_required` (U5).
    #[serde(default)]
    pub confirm: bool,
}
/// A sub-count change which may need measurement-clearing confirmation.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct ConfigSubCountParams {
    /// Number of subwoofers, 0 to 8.
    pub count: i64,
    /// Clears existing measurements; without it a project with measurements answers `confirm_required` (U5).
    #[serde(default)]
    pub confirm: bool,
}
/// One speaker index.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct ConfigIndexParams {
    /// Speaker index in `ConfigResult.speakers`.
    pub index: usize,
}
/// Optional edits to one speaker or one of its bands.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct ConfigSetSpeakerParams {
    /// Speaker index in `ConfigResult.speakers`.
    pub index: usize,
    /// New role code; a sub role forces a single SUB band (`step2_config.py:988-1002`).
    pub role: Option<String>,
    /// New size: `small` (crossover applied) or `large` (full range).
    pub size: Option<String>,
    /// Band the output and polarity edits apply to; absent means the first band.
    pub band_index: Option<usize>,
    /// New measurement output channel (1-based).
    pub out: Option<i64>,
    /// New polarity: `+` normal or `-` inverted.
    pub pol: Option<String>,
}
/// One configured output band.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct ConfigBand {
    /// Band name: `FULL`, `LF`, `MF`, `HF` or `SUB`.
    pub band: String,
    /// Measurement output channel (1-based).
    pub out: i64,
    /// Polarity: `+` normal or `-` inverted.
    pub pol: String,
}
/// One configured speaker.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct ConfigSpeaker {
    /// Role code (`L`, `C`, `SW1`, `Tfl`, ...).
    pub role: String,
    /// `small` (crossover applied) or `large` (full range); subs are `sub`.
    pub size: String,
    /// Bands in order; one band unless bi-amped.
    pub bands: Vec<ConfigBand>,
}
/// One upstream speaker group in upstream order.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct ConfigGroup {
    /// Stable presentation group id: front, center, sub, surround, back, wide, top, height or other.
    pub id: String,
    /// Upstream group name used as the project and crossover-map key.
    pub key: String,
    /// Indices into `ConfigResult.speakers` that belong to this group.
    pub speaker_indices: Vec<usize>,
}
/// Values derived from the complete speaker configuration.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct ConfigSummary {
    /// Number of speakers.
    pub speaker_count: usize,
    /// Number of measurement outputs in use.
    pub outputs: Vec<i64>,
    /// Highest output channel in use.
    pub max_channel: i64,
    /// Number of output channels used twice or more.
    pub duplicate_outputs: Vec<i64>,
    /// Number of subwoofers.
    pub sub_count: usize,
}
/// Screen-facing editable speaker configuration.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct ConfigResult {
    /// Speakers in table order.
    pub speakers: Vec<ConfigSpeaker>,
    /// Preset name, or `custom` after any manual edit.
    pub preset: String,
    /// Measurement output device name (`config.device`).
    pub device: String,
    /// Table group header rows in upstream order.
    pub groups: Vec<ConfigGroup>,
    /// Counts the summary line shows.
    pub summary: ConfigSummary,
}
/// Configuration after a destructive edit and its optional inverse token.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct ConfigMutationResult {
    /// The configuration after the edit.
    pub config: ConfigResult,
    /// Token for `undo` when the edit cleared measurements (U5).
    pub undo_token: Option<String>,
}
/// Output sample-rate selection stored with a DSP profile.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)]
#[serde(rename_all = "snake_case")]
#[ts(export)]
pub enum OutputRateChoice {
    /// Resolve the rate from the default output endpoint when exporting.
    Auto,
    /// Always export at this rate in Hz.
    Fixed(u32),
}

/// The manually editable DSP profile fields.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct DspFields {
    /// Output sample rate.
    pub output_rate: OutputRateChoice,
    /// Whether this profile permits changing the output rate.
    pub output_rate_editable: bool,
    /// FIR taps per channel.
    pub fir_taps: i64,
    /// Total FIR taps the DSP can run across channels.
    pub fir_budget: i64,
    /// IIR (PEQ) bands per channel.
    pub iir_bands: i64,
    /// All-pass bands per channel.
    pub allpass_bands: i64,
    /// Bass-management path delays the DSP offers.
    pub bm_path_delays: i64,
}
/// One DSP preset in the built-in table.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct DspPreset {
    /// Preset key (`camilla`, `tesira`, `qsys`, `minidsp`, `custom`).
    pub key: String,
    /// Device name shown in the device list.
    pub name: String,
    /// The preset's filter resources.
    pub fields: DspFields,
}
/// A preset selection or a complete manual edit.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS, Default)]
#[ts(export)]
pub struct DspSetParams {
    /// Selects a preset; absent with `fields` set means a manual edit.
    pub preset: Option<String>,
    /// Manual values; any manual edit makes the profile `custom`.
    pub fields: Option<DspFields>,
}
/// Editable DSP state and derived resolution values.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct DspResult {
    /// Current profile key.
    pub profile: String,
    /// Current device name.
    pub name: String,
    /// Current filter resources.
    pub fields: DspFields,
    /// Every preset, for the device list.
    pub presets: Vec<DspPreset>,
    /// FIR window length the taps give, in ms (note line).
    pub window_ms: f64,
    /// Frequency resolution the taps give, in Hz (note line).
    pub resolution_hz: f64,
}
/// Measurement timing-reference settings stored under `extra.devices`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct LayoutTiming {
    /// Timing reference: `acoustic`, `loopback` or `none`.
    pub reference: String,
    /// Reference speaker role for the acoustic reference (default `R`).
    pub role: String,
    /// Reference output channel for the loopback reference (1-based).
    pub output: i64,
}
/// One measurement microphone point in centimetres.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct LayoutPoint {
    /// Position number; 1 is the listening position.
    pub position: usize,
    /// Left-right offset from the centre seat, in cm (`layout_map.py`).
    pub x_cm: f64,
    /// Front-back offset from the centre seat, in cm (`layout_map.py`).
    pub y_cm: f64,
    /// Height step: 0 at ear height, +1 or -1 for ±20 cm.
    pub height: i8,
}
/// One supported measurement arrangement.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct LayoutArrangement {
    /// Number of positions: 1, 9, 13 or 17.
    pub count: usize,
    /// Microphone points of this arrangement.
    pub points: Vec<LayoutPoint>,
}
/// Editable arrangement and measurement options.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct LayoutResult {
    /// Chosen arrangement (`extra['array']`).
    pub count: usize,
    /// Start delay before each position as stored (`extra['start_delay']`):
    /// one of [`crate::rules::START_DELAYS`], `끄기` or `5 초` to `15 초`.
    pub start_delay: String,
    /// Timing reference and its reference speaker or output.
    pub timing: LayoutTiming,
    /// Every arrangement with its geometry, for the cards and maps.
    pub arrangements: Vec<LayoutArrangement>,
}
/// Optional arrangement and timing edits.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS, Default)]
#[ts(export)]
pub struct LayoutSetParams {
    /// New arrangement; changing it clears measurements (U5).
    pub count: Option<usize>,
    /// New start delay, one of [`crate::rules::START_DELAYS`]; any other
    /// value answers `invalid_request` (field `start_delay`).
    pub start_delay: Option<String>,
    /// New timing reference.
    pub timing: Option<LayoutTiming>,
    /// Clears existing measurements; without it a project with measurements answers `confirm_required` (U5).
    #[serde(default)]
    pub confirm: bool,
}
/// Arrangement after editing and its optional inverse token.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct LayoutMutationResult {
    /// The arrangement and options after the edit.
    pub layout: LayoutResult,
    /// Token for `undo` when the edit cleared measurements (U5).
    pub undo_token: Option<String>,
}
/// Position-duration estimate from upstream step 4 semantics.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct PositionEstimateResult {
    /// Number of positions in the arrangement.
    pub positions: usize,
    /// Estimated time per position, in seconds (`step4_layout.position_seconds`).
    pub per_position_seconds: f64,
    /// Estimated time for every position, without moving the microphone, in seconds.
    pub total_seconds: f64,
}
/// Target control points.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct TargetPointsParams {
    /// Target points as (Hz, dB); clamped to 10–24000 Hz and ±30 dB, at least two.
    pub points: Vec<(f64, f64)>,
}
/// One built-in target preset selection.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct TargetPresetParams {
    /// Target preset: `flat`, `harman` or `cinema`.
    pub preset: String,
}
/// Target curve, selected preset, and built-in preset table.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct TargetResult {
    /// Target points as (Hz, dB).
    pub points: Vec<(f64, f64)>,
    /// Preset name, or absent when the points were edited (custom).
    pub preset: Option<String>,
    /// Preset names the target menu offers.
    pub presets: Vec<(String, Vec<(f64, f64)>)>,
}
/// Complete calibration settings replacement.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct CalibrationSettingsParams {
    /// The complete calibration settings to store.
    pub settings: CalibrationSettings,
}
/// Mode whose numeric specification should be returned.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct ModeSpecParams {
    /// Correction mode: `zero`, `mixed`, `linear` or `ultra`.
    pub mode: Mode,
    /// Latency limit for the ultra mode, in ms.
    pub ultra_ms: Option<f64>,
    /// Whether MIMO support paths use FIR instead of IIR.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[ts(optional)]
    pub mimo_fir: Option<bool>,
}
/// Presentation-neutral values underlying the upstream mode specification line.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct ModeSpecResult {
    /// Room-correction filters: `iir` (IIR only) or `iir_fir` (IIR plus FIR).
    pub rc_filter: String,
    /// FIR taps the mode uses (0 without FIR).
    pub fir_taps: usize,
    /// PEQ bands per channel, when the mode uses IIR.
    pub peq_bands: Option<usize>,
    /// MIMO support filter kind (`fir` when requested, otherwise `iir`).
    pub mimo_filter: String,
    /// Delay the FIR may add ahead of the main arrival (`lift_ms`), in ms.
    pub lift_ms: f64,
    /// Octave fraction of the excess-phase smoothing (6, or 24 in linear and ultra modes).
    pub phase_frac: f64,
    /// Upper latency bound of the mode, in ms.
    pub max_latency_ms: f64,
}
/// Application theme preference.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS, Default)]
#[serde(rename_all = "snake_case")]
#[ts(export)]
pub enum AppTheme {
    /// Follow the operating-system preference.
    #[default]
    System,
    /// Always use the light theme.
    Light,
    /// Always use the dark theme.
    Dark,
}
/// The skin set the screen draws with (docs/skins, ADR 0010).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS, Default)]
#[serde(rename_all = "snake_case")]
#[ts(export)]
pub enum AppSkin {
    /// The instrument skin: the default tokens.
    #[default]
    Default,
    /// Hardware Rack: a 19-inch rack faceplate.
    Rack,
    /// Signal Matrix: a routing board of cells on a grid.
    Matrix,
}
/// The logo on the rail and the window (docs/DEVIATIONS.md U12). The
/// installed program's own icon is always `Expert`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS, Default)]
#[serde(rename_all = "snake_case")]
#[ts(export)]
pub enum AppIcon {
    /// "전문가 모드": upstream's confirmed logo (`logo_b8.svg`).
    #[default]
    Expert,
    /// "킹반인 모드": SECS 2R's own logo (`apps/secs2r/icons/logo/civilian.svg`),
    /// a measured response and its correction on the target.
    Civilian,
}
/// Opt-in loopback API settings.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct LocalApiSettings {
    /// Whether the app starts the local API server.
    pub enabled: bool,
    /// Loopback TCP port; zero asks the operating system for a free port.
    pub port: u16,
}
impl Default for LocalApiSettings {
    fn default() -> Self {
        Self {
            enabled: false,
            port: crate::local_api::DEFAULT_PORT,
        }
    }
}

/// Application-local settings, independent of an open project.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct AppSettings {
    /// Application-local compute preference; never stored in an upstream project.
    #[serde(default)]
    pub compute: ComputePreference,
    /// Screen language: `ko` or `en`.
    pub language: String,
    /// Application theme preference.
    #[serde(default)]
    pub theme: AppTheme,
    /// Logo on the rail and the window.
    #[serde(default)]
    pub icon: AppIcon,
    /// Skin set the screen draws with.
    #[serde(default)]
    pub skin: AppSkin,
    /// Opt-in loopback API server.
    #[serde(default)]
    pub local_api: LocalApiSettings,
    /// Recently opened project paths, newest first (at most 10).
    pub recent_projects: Vec<String>,
    /// Last window size in logical pixels.
    pub last_window_size: Option<(u32, u32)>,
}
impl Default for AppSettings {
    fn default() -> Self {
        Self {
            language: "ko".into(),
            compute: ComputePreference::Auto,
            theme: AppTheme::System,
            icon: AppIcon::Expert,
            skin: AppSkin::Default,
            local_api: LocalApiSettings::default(),
            recent_projects: Vec::new(),
            last_window_size: None,
        }
    }
}
/// Complete application-local settings replacement.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct AppSettingsParams {
    /// The complete app settings to store.
    pub settings: AppSettings,
}

/// App-facing state of the opt-in local API server.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct LocalApiStatus {
    /// Configured enabled state.
    pub enabled: bool,
    /// Configured port, or the selected free port while running with port zero.
    pub port: u16,
    /// Whether a listener is currently running.
    pub running: bool,
    /// Most recent startup failure, when present.
    pub error: Option<String>,
    /// Loopback base URL.
    pub url: String,
    /// Current bearer token.
    pub token: String,
    /// Full token-file path.
    pub token_path: String,
}

/// Why a call failed. The screen maps each code to a written message with the
/// cause and the next action.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)]
#[serde(rename_all = "snake_case")]
#[ts(export)]
pub enum ErrorCode {
    /// The request did not parse or named an unknown method.
    InvalidRequest,
    /// A bug: the service failed in a way it does not expect.
    Internal,
    /// The method is registered but not connected yet.
    NotImplemented,
    /// The method opens a window or program and is unavailable to local API clients.
    UiOnly,
    /// The call requires an open project.
    ProjectNotOpen,
    /// Opening, reading, or writing project data failed.
    ProjectIo,
    /// Another job in the same group is running.
    JobBusy,
    /// The named job does not exist.
    JobNotFound,
    /// The caller cancelled the operation.
    Cancelled,
    /// Project measurements or settings are not valid engine inputs.
    EngineInput,
    /// Explicit GPU execution was requested but no usable GPU backend is available.
    ComputeUnavailable,
    /// The requested exporter failed.
    ExportFailed,
    /// The chosen export cannot carry the result (upstream
    /// `filter_export_block`); `params.reason` is an [`ExportBlock`] name.
    ExportScope,
    /// Cached results no longer match project inputs.
    StaleInputs,
    /// The audio backend or selected endpoint is unavailable.
    DeviceUnavailable,
    /// Recording completed but was discarded because it had a gap or corrupt samples.
    RecordingFailed,
    /// The backend refused a pinned audio share mode.
    ShareModeRefused,
    /// The REW API cannot be reached.
    RewUnreachable,
    /// REW requires a Pro license for this operation.
    RewProRequired,
    /// REW returned an HTTP or schema failure.
    RewFailed,
    /// A measurement setting or plan field is invalid.
    MeasurementInput,
    /// Tutorial sessions cannot save or export project data.
    TutorialBlocked,
    /// A destructive edit needs explicit confirmation while measurements exist.
    ConfirmRequired,
}
/// A coded IPC failure with template parameters and diagnostic detail.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct IpcError {
    /// Stable error code translated by the screen.
    pub code: ErrorCode,
    /// Values for the message template of `code` (file names, counts, ...).
    pub params: BTreeMap<String, String>,
    /// Whether trying the same call again can succeed.
    pub retryable: bool,
    /// The raw error text, for the details view and the log only.
    pub detail: String,
}
impl IpcError {
    /// Creates a non-retryable error without template parameters.
    pub fn new(code: ErrorCode, detail: impl Into<String>) -> Self {
        Self {
            code,
            params: BTreeMap::new(),
            retryable: false,
            detail: detail.into(),
        }
    }
    /// Adds one screen message-template parameter.
    pub fn with_param(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.params.insert(key.into(), value.into());
        self
    }
}

/// The reply to every call: `{"ok": true, "data": ...}` or
/// `{"ok": false, "error": ...}`.
///
/// The TypeScript side declares the same union in `src/ipc/client.ts`
/// (`Envelope`); `envelope_wire_shape` below pins the JSON both sides rely on.
#[derive(Debug, Clone, PartialEq)]
pub enum Envelope {
    /// The `Ok` Envelope variant.
    Ok(Box<Response>),
    /// The `Err` Envelope variant.
    Err(IpcError),
}
impl Serialize for Envelope {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        use serde::ser::SerializeStruct;
        let mut state = serializer.serialize_struct("Envelope", 2)?;
        match self {
            Self::Ok(data) => {
                state.serialize_field("ok", &true)?;
                state.serialize_field("data", data)?;
            }
            Self::Err(error) => {
                state.serialize_field("ok", &false)?;
                state.serialize_field("error", error)?;
            }
        }
        state.end()
    }
}

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

    /// One value of every variant. A new variant fails to compile here until
    /// it gets an example, which `method_names_match_the_wire` then checks.
    fn examples() -> Vec<Request> {
        vec![
            Request::Bootstrap,
            Request::ProjectNew(ProjectNewParams {
                path: "x.secs".into(),
                preset: "2.1".into(),
                sub_count: 1,
                sample: false,
                tutorial: false,
            }),
            Request::ProjectOpen(ProjectPathParams {
                path: "x.secs".into(),
            }),
            Request::ProjectSave(ProjectSaveParams::default()),
            Request::ProjectInfo,
            Request::SampleLoad(SampleLoadParams::default()),
            Request::Calibrate(CalibrateParams::default()),
            Request::RecommendXo,
            Request::Mimo(MimoParams::default()),
            Request::Results,
            Request::Export(ExportParams {
                kind: ExportKind::CamillaDsp,
                folder: ".".into(),
                mdat_scope: None,
                design_name: None,
                camilla_devices: None,
                extra_rates: Vec::new(),
            }),
            Request::JobCancel(JobCancelParams { job: JobId(1) }),
            Request::Jobs,
            Request::MeasureMethods,
            Request::MeasureConfigure(MeasureConfigureParams::default()),
            Request::MeasureConfigGet,
            Request::MeasurementRecords,
            Request::MicCalibrationGet,
            Request::MicCalibrationSet(MicCalibrationSetParams {
                path: "mic.txt".into(),
            }),
            Request::MicCalibrationClear,
            Request::MicCalibrationAttach,
            Request::LevelsGet,
            Request::LevelsFillDefaults,
            Request::LevelStop,
            Request::MeasurePosition(MeasurePositionParams { position: 1 }),
            Request::PositionClear(PositionClearParams { position: 1 }),
            Request::Undo(UndoParams { token: "x".into() }),
            Request::RewLaunch,
            Request::MdatScan(MdatScanParams {
                path: "x.mdat".into(),
            }),
            Request::MdatImport(MdatImportParams {
                path: "x.mdat".into(),
                assignments: vec![],
                position: 1,
            }),
            Request::ConfigGet,
            Request::ConfigApplyPreset(ConfigPresetParams {
                preset: "2.1".into(),
                confirm: false,
            }),
            Request::ConfigSetSubCount(ConfigSubCountParams {
                count: 2,
                confirm: false,
            }),
            Request::ConfigSetSpeaker(ConfigSetSpeakerParams {
                index: 0,
                role: Some("L".into()),
                size: None,
                band_index: Some(0),
                out: Some(1),
                pol: Some("+".into()),
            }),
            Request::ConfigAddSpeaker,
            Request::ConfigRemoveSpeaker(ConfigIndexParams { index: 0 }),
            Request::ConfigRenumber,
            Request::ConfigValidate,
            Request::PatchSheetCsv(PathParams {
                path: "patch.csv".into(),
            }),
            Request::DspGet,
            Request::DspSet(DspSetParams {
                preset: Some("tesira".into()),
                fields: None,
            }),
            Request::LayoutGet,
            Request::LayoutSet(LayoutSetParams {
                count: Some(9),
                ..Default::default()
            }),
            Request::PositionEstimate,
            Request::TargetGet,
            Request::TargetSetPoints(TargetPointsParams {
                points: vec![(20.0, 0.0), (20_000.0, 0.0)],
            }),
            Request::TargetApplyPreset(TargetPresetParams {
                preset: "flat".into(),
            }),
            Request::TargetSave(PathParams {
                path: "target.json".into(),
            }),
            Request::TargetLoad(PathParams {
                path: "target.json".into(),
            }),
            Request::CalibrationSettingsGet,
            Request::CalibrationSettingsEdit(CalibrationSettingsEditParams {
                edit: crate::settings_edit::SettingEdit::MimoOn { on: true },
            }),
            Request::SubWarnings,
            Request::RewInfo,
            Request::RewDriverSet(RewDriverSetParams {
                driver: "ASIO".into(),
            }),
            Request::CalibrationSettingsSet(CalibrationSettingsParams {
                settings: CalibrationSettings::default(),
            }),
            Request::ModeSpec(ModeSpecParams {
                mode: Mode::Mixed,
                ultra_ms: None,
                mimo_fir: None,
            }),
            Request::AppSettingsGet,
            Request::AppSettingsSet(AppSettingsParams {
                settings: AppSettings::default(),
            }),
            Request::LocalApiStatus,
            Request::LocalApiTokenRegenerate,
            Request::ComputeStatus,
            Request::OpenGpuHelp,
            Request::MeasurementCurves(MeasurementCurvesParams::default()),
            Request::ResultCurves(ResultCurvesParams {
                tab: ResultTab::Spl,
                channel: None,
                group: None,
                xo_hz: None,
                corrected: None,
            }),
            Request::ResultLines,
            Request::SubTakeValues,
            Request::DialogOpenProject,
            Request::DialogSaveProject(DialogSuggestedParams {
                suggested: "x.secs".into(),
            }),
            Request::DialogPickMdat,
            Request::DialogPickFolder(DialogPickFolderParams { start: None }),
            Request::DialogSaveFile(DialogSaveFileParams {
                kind: SaveFileKind::PatchSheet,
                suggested: "x.csv".into(),
            }),
            Request::DialogOpenFile(DialogOpenFileParams {
                kind: OpenFileKind::Target,
            }),
            Request::OpenFolder(OpenFolderParams { path: ".".into() }),
            Request::LevelMonitorStart(LevelMonitorStartParams::default()),
            Request::LevelMonitorStop,
            Request::LevelPlay(LevelPlayParams {
                role: "L".into(),
                master_dbfs: -20.0,
            }),
            Request::StatusWatchStart,
            Request::StatusWatchStop,
            Request::ExportFolderGet,
            Request::ExportFolderSet(ExportFolderSetParams { folder: ".".into() }),
        ]
    }
    #[test]
    fn method_names_match_the_wire() {
        let examples = examples();
        assert_eq!(examples.len(), Request::METHODS.len());
        for request in examples {
            let wire = serde_json::to_value(&request).unwrap();
            assert_eq!(wire["method"], request.method());
        }
    }
    #[test]
    fn every_method_name_is_listed_and_parses() {
        for request in examples() {
            let wire = serde_json::to_value(&request).unwrap();
            let parsed: Request = serde_json::from_value(wire).unwrap();
            assert_eq!(parsed.method(), request.method());
        }
    }
    #[test]
    fn old_app_settings_without_local_api_use_the_disabled_default() {
        let settings: AppSettings = serde_json::from_str(
            r#"{"language":"ko","recent_projects":[],"last_window_size":null}"#,
        )
        .unwrap();
        assert_eq!(settings.local_api, LocalApiSettings::default());
        assert!(!settings.local_api.enabled);
        assert_eq!(settings.local_api.port, crate::local_api::DEFAULT_PORT);
    }

    #[test]
    fn mdat_scope_is_optional_on_the_wire() {
        let old: ExportParams =
            serde_json::from_str(r#"{"kind":"before_after_mdat","folder":""}"#).unwrap();
        assert_eq!(old.mdat_scope, None);
        assert!(old.extra_rates.is_empty());
        assert_eq!(old.mdat_scope.unwrap_or_default(), MdatScope::All);
        let wire = serde_json::to_value(&old).unwrap();
        assert!(wire.get("mdat_scope").is_none());
        let scoped = ExportParams {
            mdat_scope: Some(MdatScope::Measurements),
            design_name: None,
            camilla_devices: None,
            ..old
        };
        let wire = serde_json::to_value(&scoped).unwrap();
        assert_eq!(wire["mdat_scope"], "measurements");
        assert_eq!(
            serde_json::from_value::<ExportParams>(wire).unwrap(),
            scoped
        );
    }
    #[test]
    fn envelope_wire_shape() {
        let ok = Envelope::Ok(Box::new(Response::Bootstrap(BootstrapInfo {
            app_name: "SECS 2R".into(),
            version: "0.0.1".into(),
            prerelease: true,
            upstream: UpstreamBase {
                name: "SECS".into(),
                repository: "https://example.invalid/secs".into(),
                version: "Beta".into(),
                commit: "0".repeat(40),
                date: "2026-10-12".into(),
            },
            platform: Platform {
                os: "linux".into(),
                arch: "x86_64".into(),
            },
        })));
        let value = serde_json::to_value(ok).unwrap();
        assert_eq!(value["ok"], true);
        assert_eq!(value["data"]["method"], "bootstrap");
        let value = serde_json::to_value(Envelope::Err(IpcError::new(
            ErrorCode::InvalidRequest,
            "bad",
        )))
        .unwrap();
        assert_eq!(value["ok"], false);
        assert_eq!(value["error"]["code"], "invalid_request");
    }

    #[test]
    fn compute_completion_events_are_payload_free_markers() {
        for (result, kind) in [
            (JobResult::Calibration, "calibration"),
            (JobResult::Mimo, "mimo"),
        ] {
            let event = JobEvent::Finished {
                job: JobId(1),
                status: JobStatus::Succeeded,
                result: Some(Box::new(result)),
                error: None,
            };
            let wire = serde_json::to_vec(&event).unwrap();
            let value: serde_json::Value = serde_json::from_slice(&wire).unwrap();
            assert_eq!(value["result"], serde_json::json!({ "kind": kind }));
            assert!(wire.len() < 128, "completion must not carry a design");
            assert_eq!(serde_json::from_slice::<JobEvent>(&wire).unwrap(), event);
        }
    }

    #[test]
    fn job_snapshot_is_metadata_without_a_result_payload() {
        let snapshot = JobSnapshot {
            job: JobId(42),
            kind: JobKind::Mimo,
            status: JobStatus::Succeeded,
            cancellable: false,
            progress: None,
            error: None,
        };
        let wire = serde_json::to_value(&snapshot).unwrap();
        assert!(wire.get("result").is_none());
        assert_eq!(
            serde_json::from_value::<JobSnapshot>(wire).unwrap(),
            snapshot
        );
    }

    #[test]
    fn filter_export_scope_follows_upstream_but_eqapo_carries_mimo_f12() {
        use ExportKind::*;
        for kind in [
            CamillaDsp,
            StagedMdat,
            BeforeAfterMdat,
            EqualizerApo,
            Convolution,
        ] {
            for (subs, mimo) in [(false, false), (true, false), (false, true), (true, true)] {
                assert_eq!(filter_export_block(kind, subs, mimo), None, "{kind:?}");
            }
        }
        assert_eq!(filter_export_block(FilterText, false, false), None);
        assert_eq!(
            export_block(StagedMdat, false, false, true),
            Some(ExportBlock::StaleCache)
        );
        assert_eq!(
            export_block(BeforeAfterMdat, true, true, true),
            Some(ExportBlock::StaleCache)
        );
        assert_eq!(export_block(CamillaDsp, true, true, true), None);
        assert_eq!(
            filter_export_block(FilterText, true, false),
            Some(ExportBlock::Subs)
        );
        assert_eq!(
            filter_export_block(FilterText, true, true),
            Some(ExportBlock::Subs)
        );
        assert_eq!(
            filter_export_block(FilterText, false, true),
            Some(ExportBlock::Mimo)
        );
        assert_eq!(serde_json::to_value(FilterText).unwrap(), "filter_text");
        assert_eq!(serde_json::to_value(EqualizerApo).unwrap(), "equalizer_apo");
        assert_eq!(serde_json::to_value(Convolution).unwrap(), "convolution");
        assert_eq!(
            serde_json::to_value(ExportBlock::Subs).unwrap(),
            ExportBlock::Subs.name()
        );
        assert_eq!(
            serde_json::to_value(ExportBlock::Mimo).unwrap(),
            ExportBlock::Mimo.name()
        );
        assert_eq!(
            serde_json::to_value(ErrorCode::ExportScope).unwrap(),
            "export_scope"
        );
    }
}