File: app_shim_manager_mac_unittest.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (2350 lines) | stat: -rw-r--r-- 103,262 bytes parent folder | download | duplicates (3)
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
// Copyright 2013 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifdef UNSAFE_BUFFERS_BUILD
// TODO(crbug.com/40285824): Remove this and convert code to safer constructs.
#pragma allow_unsafe_buffers
#endif

#include "chrome/browser/apps/app_shim/app_shim_manager_mac.h"

#include <unistd.h>

#include <map>
#include <memory>
#include <optional>
#include <utility>
#include <vector>

#include "base/apple/scoped_cftyperef.h"
#include "base/functional/bind.h"
#include "base/memory/raw_ptr.h"
#include "base/strings/sys_string_conversions.h"
#include "base/test/gmock_callback_support.h"
#include "base/test/mock_callback.h"
#include "base/test/scoped_feature_list.h"
#include "base/test/test_future.h"
#include "chrome/browser/apps/app_shim/app_shim_host_bootstrap_mac.h"
#include "chrome/browser/apps/app_shim/app_shim_host_mac.h"
#include "chrome/browser/apps/app_shim/code_signature_mac.h"
#include "chrome/browser/profiles/avatar_menu.h"
#include "chrome/browser/web_applications/os_integration/mac/app_shim_registry.h"
#include "chrome/browser/web_applications/web_app_helpers.h"
#include "chrome/common/chrome_features.h"
#include "chrome/common/mac/app_shim.mojom.h"
#include "chrome/services/mac_notifications/public/mojom/mac_notifications.mojom.h"
#include "chrome/test/base/test_browser_window.h"
#include "chrome/test/base/testing_profile.h"
#include "components/prefs/testing_pref_service.h"
#include "content/public/test/browser_task_environment.h"
#include "mojo/public/cpp/bindings/pending_associated_receiver.h"
#include "mojo/public/cpp/bindings/pending_receiver.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace apps {

using ::base::test::RunOnceCallback;
using ::testing::_;
using ::testing::Invoke;
using ::testing::Return;
using ::testing::WithArgs;

class MockDelegate : public AppShimManager::Delegate {
 public:
  ~MockDelegate() override = default;

  MOCK_METHOD2(ShowAppWindows, bool(Profile*, const std::string&));
  MOCK_METHOD2(CloseAppWindows, void(Profile*, const std::string&));

  MOCK_METHOD2(AppIsInstalled, bool(Profile*, const std::string&));
  MOCK_METHOD2(AppUsesRemoteCocoa, bool(Profile*, const std::string&));
  MOCK_METHOD2(AppIsMultiProfile, bool(Profile*, const std::string&));
  MOCK_METHOD3(EnableExtension,
               void(Profile*, const std::string&, base::OnceCallback<void()>));
  MOCK_METHOD7(LaunchApp,
               void(Profile*,
                    const std::string& app_id,
                    const std::vector<base::FilePath>&,
                    const std::vector<GURL>&,
                    const GURL&,
                    chrome::mojom::AppShimLoginItemRestoreState,
                    base::OnceClosure));
  MOCK_METHOD2(GetAppShortcutsMenuItemInfos,
               std::vector<chrome::mojom::ApplicationDockMenuItemPtr>(
                   Profile*,
                   const std::string&));

  // Conditionally mock LaunchShim. Some tests will execute |launch_callback|
  // with a particular value.
  MOCK_METHOD4(DoLaunchShim,
               void(Profile*,
                    const std::string&,
                    web_app::LaunchShimUpdateBehavior,
                    web_app::ShimLaunchMode));
  void LaunchShim(Profile* profile,
                  const std::string& app_id,
                  web_app::LaunchShimUpdateBehavior update_behavior,
                  web_app::ShimLaunchMode launch_mode,
                  ShimLaunchedCallback launched_callback,
                  ShimTerminatedCallback terminated_callback) override {
    if (launch_shim_callback_capture_) {
      *launch_shim_callback_capture_ = std::move(launched_callback);
    }
    if (terminated_shim_callback_capture_) {
      *terminated_shim_callback_capture_ = std::move(terminated_callback);
    }
    DoLaunchShim(profile, app_id, update_behavior, launch_mode);
  }
  void SetCaptureShimLaunchedCallback(ShimLaunchedCallback* callback) {
    launch_shim_callback_capture_ = callback;
  }
  void SetCaptureShimTerminatedCallback(ShimTerminatedCallback* callback) {
    terminated_shim_callback_capture_ = callback;
  }

  MOCK_METHOD0(HasNonBookmarkAppWindowsOpen, bool());

  void SetAppCanCreateHost(bool should_create_host) {
    allow_shim_to_connect_ = should_create_host;
  }
  bool AppCanCreateHost(Profile* profile, const std::string& app_id) override {
    return allow_shim_to_connect_;
  }

 private:
  raw_ptr<ShimLaunchedCallback> launch_shim_callback_capture_ = nullptr;
  raw_ptr<ShimTerminatedCallback> terminated_shim_callback_capture_ = nullptr;
  bool allow_shim_to_connect_ = true;
};

class TestingAppShimManager : public AppShimManager {
 public:
  explicit TestingAppShimManager(std::unique_ptr<Delegate> delegate)
      : AppShimManager(std::move(delegate)) {}
  TestingAppShimManager(const TestingAppShimManager&) = delete;
  TestingAppShimManager& operator=(const TestingAppShimManager&) = delete;
  ~TestingAppShimManager() override { DCHECK(load_profile_callbacks_.empty()); }

  MOCK_METHOD1(OnShimFocus, void(AppShimHost* host));

  void RealOnShimFocus(AppShimHost* host) { AppShimManager::OnShimFocus(host); }

  void SetProfileMenuItems(
      std::vector<chrome::mojom::ProfileMenuItemPtr> new_profile_menu_items) {
    new_profile_menu_items_ = std::move(new_profile_menu_items);
    OnAvatarMenuChanged(nullptr);
  }
  void RebuildProfileMenuItemsFromAvatarMenu() override {
    profile_menu_items_.clear();
    for (const auto& item : new_profile_menu_items_) {
      profile_menu_items_.push_back(item.Clone());
    }
  }

  void SetAcceptablyCodeSigned(bool is_acceptable_code_signed) {
    is_acceptably_code_signed_ = is_acceptable_code_signed;
  }
  bool IsAcceptablyCodeSigned(audit_token_t audit_token) const override {
    return is_acceptably_code_signed_;
  }

  MOCK_METHOD1(ProfileForPath, Profile*(const base::FilePath&));
  MOCK_METHOD1(ProfileForBackgroundShimLaunch,
               Profile*(const webapps::AppId& app_id));
  void LoadProfileAsync(const base::FilePath& path,
                        base::OnceCallback<void(Profile*)> callback) override {
    CaptureLoadProfileCallback(path, std::move(callback));
  }
  void WaitForAppRegistryReadyAsync(
      Profile* profile,
      base::OnceCallback<void()> callback) override {
    std::move(callback).Run();
  }
  MOCK_METHOD1(IsProfileLockedForPath, bool(const base::FilePath&));
  void SetHostForCreate(std::unique_ptr<AppShimHost> host_for_create) {
    host_for_create_ = std::move(host_for_create);
  }
  std::unique_ptr<AppShimHost> CreateHost(AppShimHost::Client* client,
                                          const base::FilePath& profile_path,
                                          const std::string& app_id,
                                          bool use_remote_cocoa) override {
    DCHECK(host_for_create_);
    std::unique_ptr<AppShimHost> result = std::move(host_for_create_);
    return result;
  }
  MOCK_METHOD2(OpenAppURLInBrowserWindow,
               void(const base::FilePath&, const GURL& url));
  MOCK_METHOD0(LaunchProfilePicker, void());
  MOCK_METHOD0(MaybeTerminate, void());

  void CaptureLoadProfileCallback(const base::FilePath& path,
                                  base::OnceCallback<void(Profile*)> callback) {
    load_profile_callbacks_[path] = std::move(callback);
  }
  bool RunLoadProfileCallback(const base::FilePath& path, Profile* profile) {
    std::move(load_profile_callbacks_[path]).Run(profile);
    return load_profile_callbacks_.erase(path);
  }

 private:
  std::map<base::FilePath, base::OnceCallback<void(Profile*)>>
      load_profile_callbacks_;
  std::unique_ptr<AppShimHost> host_for_create_;
  std::vector<chrome::mojom::ProfileMenuItemPtr> new_profile_menu_items_;
  bool is_acceptably_code_signed_ = true;
};

class TestingAppShimHostBootstrap : public AppShimHostBootstrap {
 public:
  TestingAppShimHostBootstrap(
      const base::FilePath& profile_path,
      const std::string& app_id,
      bool is_from_bookmark,
      std::optional<chrome::mojom::AppShimLaunchResult>* launch_result)
      : AppShimHostBootstrap(AuditTokenForCurrentProcess()),
        profile_path_(profile_path),
        app_id_(app_id),
        is_from_bookmark_(is_from_bookmark),
        launch_result_(launch_result),
        weak_factory_(this) {}
  TestingAppShimHostBootstrap(const TestingAppShimHostBootstrap&) = delete;
  TestingAppShimHostBootstrap& operator=(const TestingAppShimHostBootstrap&) =
      delete;

  void DoTestLaunch(
      chrome::mojom::AppShimLaunchType launch_type,
      const std::vector<base::FilePath>& files,
      const std::vector<GURL>& urls,
      chrome::mojom::AppShimLoginItemRestoreState login_item_restore_state,
      mojo::PendingReceiver<
          mac_notifications::mojom::MacNotificationActionHandler>
          notification_action_handler) {
    mojo::Remote<chrome::mojom::AppShimHost> host;
    auto app_shim_info = chrome::mojom::AppShimInfo::New();
    app_shim_info->profile_path = profile_path_;
    app_shim_info->app_id = app_id_;
    if (is_from_bookmark_) {
      app_shim_info->app_url = GURL("https://example.com");
    }
    app_shim_info->launch_type = launch_type;
    app_shim_info->files = files;
    app_shim_info->urls = urls;
    app_shim_info->login_item_restore_state = login_item_restore_state;
    app_shim_info->notification_action_handler =
        std::move(notification_action_handler);
    OnShimConnected(
        host.BindNewPipeAndPassReceiver(), std::move(app_shim_info),
        base::BindOnce(&TestingAppShimHostBootstrap::DoTestLaunchDone,
                       launch_result_));
  }

  static void DoTestLaunchDone(
      std::optional<chrome::mojom::AppShimLaunchResult>* launch_result,
      chrome::mojom::AppShimLaunchResult result,
      variations::VariationsCommandLine feature_state,
      mojo::PendingReceiver<chrome::mojom::AppShim> app_shim_receiver) {
    if (launch_result) {
      launch_result->emplace(result);
    }
  }

  base::WeakPtr<TestingAppShimHostBootstrap> GetWeakPtr() {
    return weak_factory_.GetWeakPtr();
  }

 private:
  const base::FilePath profile_path_;
  const std::string app_id_;
  const bool is_from_bookmark_;
  // Note that |launch_result_| is optional so that we can track whether or not
  // the callback to set it has arrived.
  raw_ptr<std::optional<chrome::mojom::AppShimLaunchResult>> launch_result_ =
      nullptr;
  base::WeakPtrFactory<TestingAppShimHostBootstrap> weak_factory_;

  static audit_token_t AuditTokenForCurrentProcess() {
    audit_token_t token;
    mach_msg_type_number_t size = TASK_AUDIT_TOKEN_COUNT;
    int kr = task_info(mach_task_self(), TASK_AUDIT_TOKEN, (task_info_t)&token,
                       &size);
    CHECK(kr == KERN_SUCCESS) << " Error getting audit token.";
    return token;
  }
};

const char kTestAppIdA[] = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
const char kTestAppIdB[] = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb";

class TestAppShim : public chrome::mojom::AppShim,
                    public mac_notifications::mojom::MacNotificationProvider {
 public:
  // chrome::mojom::AppShim:
  void CreateRemoteCocoaApplication(
      mojo::PendingAssociatedReceiver<remote_cocoa::mojom::Application>
          receiver) override {}
  void CreateCommandDispatcherForWidget(uint64_t widget_id) override {}
  void SetBadgeLabel(const std::string& badge_label) override {
    badge_label_ = badge_label;
  }
  void SetUserAttention(
      chrome::mojom::AppShimAttentionType attention_type) override {}
  void UpdateProfileMenu(std::vector<chrome::mojom::ProfileMenuItemPtr>
                             profile_menu_items) override {
    profile_menu_items_ = std::move(profile_menu_items);
  }
  void UpdateApplicationDockMenu(
      std::vector<chrome::mojom::ApplicationDockMenuItemPtr> dock_menu_items)
      override {
    dock_menu_items_ = std::move(dock_menu_items);
  }
  void BindNotificationProvider(
      mojo::PendingReceiver<mac_notifications::mojom::MacNotificationProvider>
          provider) override {
    notification_provider_receiver_.Bind(std::move(provider));
  }
  void RequestNotificationPermission(
      RequestNotificationPermissionCallback callback) override {
    request_notification_permission_callback_.SetValue(std::move(callback));
  }
  void BindChildHistogramFetcherFactory(
      mojo::PendingReceiver<metrics::mojom::ChildHistogramFetcherFactory>
          receiver) override {}

  // mac_notifications::mojom::MacNotificationProvider:
  void BindNotificationService(
      mojo::PendingReceiver<mac_notifications::mojom::MacNotificationService>
          service,
      mojo::PendingRemote<
          mac_notifications::mojom::MacNotificationActionHandler> handler)
      override {}

  std::vector<chrome::mojom::ProfileMenuItemPtr> profile_menu_items_;
  std::vector<chrome::mojom::ApplicationDockMenuItemPtr> dock_menu_items_;
  std::string badge_label_;
  mojo::Receiver<mac_notifications::mojom::MacNotificationProvider>
      notification_provider_receiver_{this};
  base::test::TestFuture<RequestNotificationPermissionCallback>
      request_notification_permission_callback_;
};

class TestHost : public AppShimHost {
 public:
  TestHost(const base::FilePath& profile_path,
           const std::string& app_id,
           TestingAppShimManager* manager)
      : AppShimHost(manager,
                    app_id,
                    profile_path,
                    false /* uses_remote_views */),
        test_app_shim_(new TestAppShim),
        test_weak_factory_(this) {}
  TestHost(const TestHost&) = delete;
  TestHost& operator=(const TestHost&) = delete;
  ~TestHost() override = default;

  chrome::mojom::AppShim* GetAppShim() const override {
    return test_app_shim_.get();
  }

  // Record whether or not OnBootstrapConnected has been called.
  void OnBootstrapConnected(
      std::unique_ptr<AppShimHostBootstrap> bootstrap) override {
    EXPECT_FALSE(did_connect_to_host_);
    did_connect_to_host_ = true;
    AppShimHost::OnBootstrapConnected(std::move(bootstrap));
  }
  bool did_connect_to_host() const { return did_connect_to_host_; }

  base::WeakPtr<TestHost> GetWeakPtr() {
    return test_weak_factory_.GetWeakPtr();
  }

  using AppShimHost::FilesOpened;
  using AppShimHost::NotificationPermissionStatusChanged;
  using AppShimHost::OpenAppWithOverrideUrl;
  using AppShimHost::ProfileSelectedFromMenu;
  using AppShimHost::ReopenApp;
  using AppShimHost::UrlsOpened;

  std::unique_ptr<TestAppShim> test_app_shim_;

 private:
  bool did_connect_to_host_ = false;

  base::WeakPtrFactory<TestHost> test_weak_factory_;
};

class AppShimManagerTest : public testing::Test {
 protected:
  AppShimManagerTest() = default;
  AppShimManagerTest(const AppShimManagerTest&) = delete;
  AppShimManagerTest& operator=(const AppShimManagerTest&) = delete;
  ~AppShimManagerTest() override = default;

  void SetUp() override {
    profile_path_a_ = profile_a_.GetPath();
    profile_path_b_ = profile_b_.GetPath();
    profile_path_c_ = profile_c_.GetPath();
    const base::FilePath user_data_dir = profile_path_a_.DirName();

    local_state_ = std::make_unique<TestingPrefServiceSimple>();
    AppShimRegistry::Get()->RegisterLocalPrefs(local_state_->registry());
    AppShimRegistry::Get()->SetPrefServiceAndUserDataDirForTesting(
        local_state_.get(), user_data_dir);

    std::unique_ptr<MockDelegate> delegate = std::make_unique<MockDelegate>();
    delegate_ = delegate.get();
    manager_ = std::make_unique<TestingAppShimManager>(std::move(delegate));
    AppShimHostBootstrap::SetClient(manager_.get());
    bootstrap_aa_ = (new TestingAppShimHostBootstrap(
                         profile_path_a_, kTestAppIdA,
                         true /* is_from_bookmark */, &bootstrap_aa_result_))
                        ->GetWeakPtr();
    bootstrap_ba_ = (new TestingAppShimHostBootstrap(
                         profile_path_b_, kTestAppIdA,
                         true /* is_from_bookmark */, &bootstrap_ba_result_))
                        ->GetWeakPtr();
    bootstrap_ca_ = (new TestingAppShimHostBootstrap(
                         profile_path_c_, kTestAppIdA,
                         true /* is_from_bookmark */, &bootstrap_ca_result_))
                        ->GetWeakPtr();
    bootstrap_xa_ = (new TestingAppShimHostBootstrap(
                         base::FilePath(), kTestAppIdA,
                         true /* is_from_bookmark */, &bootstrap_xa_result_))
                        ->GetWeakPtr();
    bootstrap_ab_ = (new TestingAppShimHostBootstrap(
                         profile_path_a_, kTestAppIdB,
                         false /* is_from_bookmark */, &bootstrap_ab_result_))
                        ->GetWeakPtr();
    bootstrap_bb_ = (new TestingAppShimHostBootstrap(
                         profile_path_b_, kTestAppIdB,
                         false /* is_from_bookmark */, &bootstrap_bb_result_))
                        ->GetWeakPtr();
    bootstrap_aa_duplicate_ =
        (new TestingAppShimHostBootstrap(profile_path_a_, kTestAppIdA,
                                         true /* is_from_bookmark */,
                                         &bootstrap_aa_duplicate_result_))
            ->GetWeakPtr();
    bootstrap_aa_thethird_ =
        (new TestingAppShimHostBootstrap(profile_path_a_, kTestAppIdA,
                                         true /* is_from_bookmark */,
                                         &bootstrap_aa_thethird_result_))
            ->GetWeakPtr();

    host_aa_unique_ = std::make_unique<TestHost>(profile_path_a_, kTestAppIdA,
                                                 manager_.get());
    host_ab_unique_ = std::make_unique<TestHost>(profile_path_a_, kTestAppIdB,
                                                 manager_.get());
    host_ba_unique_ = std::make_unique<TestHost>(profile_path_b_, kTestAppIdA,
                                                 manager_.get());
    host_bb_unique_ = std::make_unique<TestHost>(profile_path_b_, kTestAppIdB,
                                                 manager_.get());
    host_aa_duplicate_unique_ = std::make_unique<TestHost>(
        profile_path_a_, kTestAppIdA, manager_.get());

    host_aa_ = host_aa_unique_->GetWeakPtr();
    host_ab_ = host_ab_unique_->GetWeakPtr();
    host_ba_ = host_ba_unique_->GetWeakPtr();
    host_bb_ = host_bb_unique_->GetWeakPtr();

    base::FilePath extension_path("/fake/path");

    EXPECT_CALL(*delegate_, AppIsMultiProfile(_, kTestAppIdA))
        .WillRepeatedly(Return(true));
    EXPECT_CALL(*delegate_, AppIsMultiProfile(_, kTestAppIdB))
        .WillRepeatedly(Return(false));

    EXPECT_CALL(*delegate_, AppUsesRemoteCocoa(_, _))
        .WillRepeatedly(Return(true));

    {
      auto item_a = chrome::mojom::ProfileMenuItem::New();
      item_a->profile_path = profile_path_a_;
      item_a->menu_index = 0;
      auto item_b = chrome::mojom::ProfileMenuItem::New();
      item_b->profile_path = profile_path_b_;
      item_b->menu_index = 1;
      std::vector<chrome::mojom::ProfileMenuItemPtr> items;
      items.push_back(std::move(item_a));
      items.push_back(std::move(item_b));
      manager_->SetProfileMenuItems(std::move(items));
    }

    // Tests that expect this call will override it.
    EXPECT_CALL(*manager_, OpenAppURLInBrowserWindow(_, _)).Times(0);

    EXPECT_CALL(*manager_, IsProfileLockedForPath(profile_path_a_))
        .WillRepeatedly(Return(false));
    EXPECT_CALL(*manager_, ProfileForPath(profile_path_a_))
        .WillRepeatedly(Return(&profile_a_));

    EXPECT_CALL(*manager_, IsProfileLockedForPath(profile_path_b_))
        .WillRepeatedly(Return(false));
    EXPECT_CALL(*manager_, ProfileForPath(profile_path_b_))
        .WillRepeatedly(Return(&profile_b_));

    EXPECT_CALL(*manager_, IsProfileLockedForPath(profile_path_c_))
        .WillRepeatedly(Return(false));
    EXPECT_CALL(*manager_, ProfileForPath(profile_path_c_))
        .WillRepeatedly(Return(&profile_c_));

    EXPECT_CALL(*delegate_, AppIsInstalled(&profile_a_, kTestAppIdA))
        .WillRepeatedly(Return(true));
    EXPECT_CALL(*delegate_, AppIsInstalled(&profile_b_, kTestAppIdA))
        .WillRepeatedly(Return(true));
    EXPECT_CALL(*delegate_, AppIsInstalled(&profile_c_, kTestAppIdA))
        .WillRepeatedly(Return(false));
    EXPECT_CALL(*delegate_, AppIsInstalled(_, kTestAppIdB))
        .WillRepeatedly(Return(true));
    EXPECT_CALL(*delegate_, LaunchApp(_, _, _, _, _, _, _))
        .WillRepeatedly(Return());
  }

  void TearDown() override {
    host_aa_unique_.reset();
    host_ab_unique_.reset();
    host_ba_unique_.reset();
    host_bb_unique_.reset();
    host_aa_duplicate_unique_.reset();
    delegate_ = nullptr;
    manager_->SetHostForCreate(nullptr);
    manager_.reset();

    // Delete the bootstraps via their weak pointers if they haven't been
    // deleted yet. Note that this must be done after the profiles and hosts
    // have been destroyed (because they may now own the bootstraps).
    delete bootstrap_aa_.get();
    delete bootstrap_ba_.get();
    delete bootstrap_ca_.get();
    delete bootstrap_xa_.get();
    delete bootstrap_ab_.get();
    delete bootstrap_bb_.get();
    delete bootstrap_aa_duplicate_.get();
    delete bootstrap_aa_thethird_.get();

    AppShimHostBootstrap::SetClient(nullptr);

    AppShimRegistry::Get()->SetPrefServiceAndUserDataDirForTesting(
        nullptr, base::FilePath());
  }

  void DoShimLaunch(
      base::WeakPtr<TestingAppShimHostBootstrap> bootstrap,
      std::unique_ptr<TestHost> host,
      chrome::mojom::AppShimLaunchType launch_type,
      const std::vector<base::FilePath>& files,
      const std::vector<GURL>& urls,
      chrome::mojom::AppShimLoginItemRestoreState login_item_restore_state,
      mojo::PendingReceiver<
          mac_notifications::mojom::MacNotificationActionHandler>
          notification_action_handler = mojo::NullReceiver()) {
    if (host) {
      manager_->SetHostForCreate(std::move(host));
    }
    bootstrap->DoTestLaunch(launch_type, files, urls, login_item_restore_state,
                            std::move(notification_action_handler));
  }

  void NormalLaunch(base::WeakPtr<TestingAppShimHostBootstrap> bootstrap,
                    std::unique_ptr<TestHost> host) {
    DoShimLaunch(bootstrap, std::move(host),
                 chrome::mojom::AppShimLaunchType::kNormal,
                 std::vector<base::FilePath>(), std::vector<GURL>(),
                 chrome::mojom::AppShimLoginItemRestoreState::kNone);
  }

  void RegisterOnlyLaunch(base::WeakPtr<TestingAppShimHostBootstrap> bootstrap,
                          std::unique_ptr<TestHost> host) {
    DoShimLaunch(bootstrap, std::move(host),
                 chrome::mojom::AppShimLaunchType::kRegisterOnly,
                 std::vector<base::FilePath>(), std::vector<GURL>(),
                 chrome::mojom::AppShimLoginItemRestoreState::kNone);
  }

  void NotificationActionLaunch(
      base::WeakPtr<TestingAppShimHostBootstrap> bootstrap,
      std::unique_ptr<TestHost> host,
      mac_notifications::mojom::NotificationActionInfoPtr notification) {
    mojo::Remote<mac_notifications::mojom::MacNotificationActionHandler>
        notification_remote;
    DoShimLaunch(bootstrap, std::move(host),
                 chrome::mojom::AppShimLaunchType::kNotificationAction,
                 std::vector<base::FilePath>(), std::vector<GURL>(),
                 chrome::mojom::AppShimLoginItemRestoreState::kNone,
                 notification_remote.BindNewPipeAndPassReceiver());
    notification_remote->OnNotificationAction(std::move(notification));
  }

  // Completely launch a shim host and leave it running.
  void LaunchAndActivate(base::WeakPtr<TestingAppShimHostBootstrap> bootstrap,
                         std::unique_ptr<TestHost> host_unique,
                         Profile* profile) {
    base::WeakPtr<TestHost> host = host_unique->GetWeakPtr();
    NormalLaunch(bootstrap, std::move(host_unique));
    EXPECT_EQ(host.get(), manager_->FindHost(profile, host->GetAppId()));
    EXPECT_CALL(*manager_, OnShimFocus(host.get()));
    manager_->OnAppActivated(profile, host->GetAppId());
    EXPECT_TRUE(host->did_connect_to_host());
  }

  // Simulates a focus request coming from a running app shim.
  void ShimNormalFocus(TestHost* host) {
    EXPECT_CALL(*manager_, OnShimFocus(host))
        .WillOnce(
            Invoke(manager_.get(), &TestingAppShimManager::RealOnShimFocus));
    manager_->OnShimFocus(host);
  }

  content::BrowserTaskEnvironment task_environment_;
  raw_ptr<MockDelegate> delegate_ = nullptr;
  std::unique_ptr<TestingAppShimManager> manager_;
  base::FilePath profile_path_a_;
  base::FilePath profile_path_b_;
  base::FilePath profile_path_c_;
  TestingProfile profile_a_;
  TestingProfile profile_b_;
  TestingProfile profile_c_;

  base::WeakPtr<TestingAppShimHostBootstrap> bootstrap_aa_;
  base::WeakPtr<TestingAppShimHostBootstrap> bootstrap_ba_;
  base::WeakPtr<TestingAppShimHostBootstrap> bootstrap_ca_;
  base::WeakPtr<TestingAppShimHostBootstrap> bootstrap_xa_;
  base::WeakPtr<TestingAppShimHostBootstrap> bootstrap_ab_;
  base::WeakPtr<TestingAppShimHostBootstrap> bootstrap_bb_;
  base::WeakPtr<TestingAppShimHostBootstrap> bootstrap_aa_duplicate_;
  base::WeakPtr<TestingAppShimHostBootstrap> bootstrap_aa_thethird_;

  std::optional<chrome::mojom::AppShimLaunchResult> bootstrap_aa_result_;
  std::optional<chrome::mojom::AppShimLaunchResult> bootstrap_ba_result_;
  std::optional<chrome::mojom::AppShimLaunchResult> bootstrap_ca_result_;
  std::optional<chrome::mojom::AppShimLaunchResult> bootstrap_xa_result_;
  std::optional<chrome::mojom::AppShimLaunchResult> bootstrap_ab_result_;
  std::optional<chrome::mojom::AppShimLaunchResult> bootstrap_bb_result_;
  std::optional<chrome::mojom::AppShimLaunchResult>
      bootstrap_aa_duplicate_result_;
  std::optional<chrome::mojom::AppShimLaunchResult>
      bootstrap_aa_thethird_result_;

  // Unique ptr to the TestsHosts used by the tests. These are passed by
  // std::move during tests. To access them after they have been passed, use
  // the WeakPtr versions.
  std::unique_ptr<TestHost> host_aa_unique_;
  std::unique_ptr<TestHost> host_ab_unique_;
  std::unique_ptr<TestHost> host_ba_unique_;
  std::unique_ptr<TestHost> host_bb_unique_;
  std::unique_ptr<TestHost> host_aa_duplicate_unique_;

  base::WeakPtr<TestHost> host_aa_;
  base::WeakPtr<TestHost> host_ab_;
  base::WeakPtr<TestHost> host_ba_;
  base::WeakPtr<TestHost> host_bb_;

  base::test::ScopedFeatureList scoped_feature_list_;

 private:
  std::unique_ptr<TestingPrefServiceSimple> local_state_;
};

TEST_F(AppShimManagerTest, LaunchProfileNotFound) {
  // Bad profile path, opens a bookmark app in a new window.
  EXPECT_CALL(*manager_, ProfileForPath(profile_path_a_))
      .WillRepeatedly(Return(static_cast<Profile*>(nullptr)));
  NormalLaunch(bootstrap_aa_, nullptr);
  EXPECT_CALL(*manager_, OpenAppURLInBrowserWindow(profile_path_a_, _));
  manager_->RunLoadProfileCallback(profile_path_a_, nullptr);
  EXPECT_EQ(chrome::mojom::AppShimLaunchResult::kProfileNotFound,
            *bootstrap_aa_result_);
}

TEST_F(AppShimManagerTest, LaunchProfileNotFoundNotBookmark) {
  // Bad profile path, not a bookmark app, doesn't open anything.
  EXPECT_CALL(*manager_, ProfileForPath(profile_path_a_))
      .WillRepeatedly(Return(static_cast<Profile*>(nullptr)));
  NormalLaunch(bootstrap_ab_, nullptr);
  manager_->RunLoadProfileCallback(profile_path_a_, nullptr);
  EXPECT_EQ(chrome::mojom::AppShimLaunchResult::kProfileNotFound,
            *bootstrap_ab_result_);
}

TEST_F(AppShimManagerTest, LaunchProfileIsLocked) {
  // Profile is locked.
  EXPECT_CALL(*manager_, IsProfileLockedForPath(profile_path_a_))
      .WillOnce(Return(true));
  EXPECT_CALL(*manager_, LaunchProfilePicker());
  NormalLaunch(bootstrap_aa_, nullptr);
  EXPECT_EQ(chrome::mojom::AppShimLaunchResult::kProfileLocked,
            *bootstrap_aa_result_);
}

TEST_F(AppShimManagerTest, LaunchAppNotFound) {
  // App not found.
  EXPECT_CALL(*delegate_, AppIsInstalled(&profile_a_, kTestAppIdA))
      .WillRepeatedly(Return(false));
  EXPECT_CALL(*delegate_, EnableExtension(&profile_a_, kTestAppIdA, _))
      .WillOnce(RunOnceCallback<2>());
  EXPECT_CALL(*manager_, OpenAppURLInBrowserWindow(profile_path_a_, _));
  NormalLaunch(bootstrap_aa_, std::move(host_aa_unique_));
  EXPECT_EQ(chrome::mojom::AppShimLaunchResult::kAppNotFound,
            *bootstrap_aa_result_);
}

TEST_F(AppShimManagerTest, LaunchAppNotEnabled) {
  // App not found.
  EXPECT_CALL(*delegate_, AppIsInstalled(&profile_a_, kTestAppIdA))
      .WillOnce(Return(false))
      .WillRepeatedly(Return(true));
  EXPECT_CALL(*delegate_, EnableExtension(&profile_a_, kTestAppIdA, _))
      .WillOnce(RunOnceCallback<2>());
  NormalLaunch(bootstrap_aa_, std::move(host_aa_unique_));
}

TEST_F(AppShimManagerTest, LaunchAndCloseShim) {
  // Normal startup.
  NormalLaunch(bootstrap_aa_, std::move(host_aa_unique_));
  EXPECT_EQ(host_aa_.get(), manager_->FindHost(&profile_a_, kTestAppIdA));

  NormalLaunch(bootstrap_ab_, std::move(host_ab_unique_));
  EXPECT_EQ(host_ab_.get(), manager_->FindHost(&profile_a_, kTestAppIdB));

  std::vector<base::FilePath> some_file(1, base::FilePath("some_file"));
  std::vector<GURL> some_url(1, GURL("web+test://foo"));
  EXPECT_CALL(*delegate_,
              LaunchApp(&profile_b_, kTestAppIdB, some_file, some_url, _,
                        chrome::mojom::AppShimLoginItemRestoreState::kNone, _));
  DoShimLaunch(bootstrap_bb_, std::move(host_bb_unique_),
               chrome::mojom::AppShimLaunchType::kNormal, some_file, some_url,
               chrome::mojom::AppShimLoginItemRestoreState::kNone);
  EXPECT_EQ(host_bb_.get(), manager_->FindHost(&profile_b_, kTestAppIdB));

  // Activation when there is a registered shim finishes launch with success and
  // focuses the app.
  EXPECT_CALL(*manager_, OnShimFocus(host_aa_.get()));
  manager_->OnAppActivated(&profile_a_, kTestAppIdA);
  EXPECT_EQ(chrome::mojom::AppShimLaunchResult::kSuccess,
            *bootstrap_aa_result_);

  // Starting and closing a second host does nothing.
  DoShimLaunch(bootstrap_aa_duplicate_, std::move(host_aa_duplicate_unique_),
               chrome::mojom::AppShimLaunchType::kNormal, some_file, some_url,
               chrome::mojom::AppShimLoginItemRestoreState::kNone);
  EXPECT_EQ(chrome::mojom::AppShimLaunchResult::kDuplicateHost,
            *bootstrap_aa_duplicate_result_);
  EXPECT_EQ(host_aa_.get(), manager_->FindHost(&profile_a_, kTestAppIdA));

  // Normal close.
  manager_->OnShimProcessDisconnected(host_aa_.get());
  EXPECT_FALSE(manager_->FindHost(&profile_a_, kTestAppIdA));
  EXPECT_EQ(host_aa_.get(), nullptr);
}

TEST_F(AppShimManagerTest, RunOnOsLoginLaunchAndCloseShim) {
  NormalLaunch(bootstrap_aa_, std::move(host_aa_unique_));
  EXPECT_EQ(host_aa_.get(), manager_->FindHost(&profile_a_, kTestAppIdA));

  NormalLaunch(bootstrap_ab_, std::move(host_ab_unique_));
  EXPECT_EQ(host_ab_.get(), manager_->FindHost(&profile_a_, kTestAppIdB));

  // Run on OS Login Launch
  std::vector<base::FilePath> some_file(1, base::FilePath("some_file"));
  std::vector<GURL> some_url(1, GURL("web+test://foo"));
  EXPECT_CALL(
      *delegate_,
      LaunchApp(&profile_b_, kTestAppIdB, some_file, some_url, _,
                chrome::mojom::AppShimLoginItemRestoreState::kWindowed, _));
  DoShimLaunch(bootstrap_bb_, std::move(host_bb_unique_),
               chrome::mojom::AppShimLaunchType::kNormal, some_file, some_url,
               chrome::mojom::AppShimLoginItemRestoreState::kWindowed);
  EXPECT_EQ(host_bb_.get(), manager_->FindHost(&profile_b_, kTestAppIdB));

  // Activation when there is a registered shim finishes launch with success and
  // focuses the app.
  EXPECT_CALL(*manager_, OnShimFocus(host_aa_.get()));
  manager_->OnAppActivated(&profile_a_, kTestAppIdA);
  EXPECT_EQ(chrome::mojom::AppShimLaunchResult::kSuccess,
            *bootstrap_aa_result_);

  // Starting and closing a second host does nothing.
  DoShimLaunch(bootstrap_aa_duplicate_, std::move(host_aa_duplicate_unique_),
               chrome::mojom::AppShimLaunchType::kNormal, some_file, some_url,
               chrome::mojom::AppShimLoginItemRestoreState::kNone);
  EXPECT_EQ(chrome::mojom::AppShimLaunchResult::kDuplicateHost,
            *bootstrap_aa_duplicate_result_);
  EXPECT_EQ(host_aa_.get(), manager_->FindHost(&profile_a_, kTestAppIdA));

  // Normal close.
  manager_->OnShimProcessDisconnected(host_aa_.get());
  EXPECT_FALSE(manager_->FindHost(&profile_a_, kTestAppIdA));
  EXPECT_EQ(host_aa_.get(), nullptr);
}

TEST_F(AppShimManagerTest, AppLaunchCancelled) {
  // Validate that if no browser is registered during a launch that
  // OnAppLaunchCancelled removes the host and closes the app.
  NormalLaunch(bootstrap_bb_, std::move(host_bb_unique_));
  EXPECT_EQ(host_bb_.get(), manager_->FindHost(&profile_b_, kTestAppIdB));
  EXPECT_CALL(*manager_, MaybeTerminate()).WillOnce(Return());
  manager_->OnAppLaunchCancelled(&profile_b_, kTestAppIdB);
  EXPECT_FALSE(manager_->FindHost(&profile_b_, kTestAppIdB));
  EXPECT_EQ(host_bb_.get(), nullptr);

  // Validate that if a browser is registered during a launch
  // that OnAppLaunchCancelled is an no-op
  NormalLaunch(bootstrap_aa_, std::move(host_aa_unique_));
  EXPECT_EQ(host_aa_.get(), manager_->FindHost(&profile_a_, kTestAppIdA));

  // Notify manager that a new browser has been associated with the app.
  auto browser_window = std::make_unique<TestBrowserWindow>();
  std::string app_name = web_app::GenerateApplicationNameFromAppId(kTestAppIdA);
  Browser::CreateParams params = Browser::CreateParams::CreateForApp(
      app_name, true, browser_window->GetBounds(), &profile_a_, true);
  params.window = browser_window.get();
  auto browser = Browser::DeprecatedCreateOwnedForTesting(params);
  manager_->OnBrowserAdded(browser.get());

  // Validate that OnAppLaunchCancelled does not close the app,
  // and that the state is still valid.
  EXPECT_CALL(*manager_, MaybeTerminate()).Times(0);
  manager_->OnAppLaunchCancelled(&profile_a_, kTestAppIdA);
  EXPECT_EQ(host_aa_.get(), manager_->FindHost(&profile_a_, kTestAppIdA));

  // Removing the browser should close the app.
  EXPECT_CALL(*manager_, MaybeTerminate()).WillOnce(Return());
  manager_->OnBrowserRemoved(browser.get());
  EXPECT_EQ(host_aa_.get(), manager_->FindHost(&profile_a_, kTestAppIdA));
}

TEST_F(AppShimManagerTest, AppLifetime) {
  scoped_feature_list_.InitWithFeatures({features::kAppShimNewCloseBehavior},
                                        {});

  // This app is installed for profile A throughout this test.
  AppShimRegistry::Get()->OnAppInstalledForProfile(kTestAppIdA,
                                                   profile_path_a_);

  // When the app activates, a host is created. If there is no shim, one is
  // launched.
  manager_->SetHostForCreate(std::move(host_aa_unique_));
  EXPECT_CALL(*delegate_,
              DoLaunchShim(&profile_a_, kTestAppIdA,
                           web_app::LaunchShimUpdateBehavior::kDoNotRecreate,
                           web_app::ShimLaunchMode::kNormal));
  manager_->OnAppActivated(&profile_a_, kTestAppIdA);
  EXPECT_EQ(host_aa_.get(), manager_->FindHost(&profile_a_, kTestAppIdA));

  // Normal shim launch adds an entry in the map.
  // App should not be launched here, but return success to the shim.
  EXPECT_CALL(*delegate_, LaunchApp(&profile_a_, kTestAppIdA, _, _, _, _, _))
      .Times(0);
  RegisterOnlyLaunch(bootstrap_aa_, nullptr);
  EXPECT_EQ(chrome::mojom::AppShimLaunchResult::kSuccess,
            *bootstrap_aa_result_);
  EXPECT_EQ(host_aa_.get(), manager_->FindHost(&profile_a_, kTestAppIdA));

  // Return no app windows for OnShimFocus. This will do nothing.
  EXPECT_CALL(*delegate_, ShowAppWindows(&profile_a_, kTestAppIdA))
      .WillRepeatedly(Return(false));
  EXPECT_CALL(*delegate_, LaunchApp(&profile_a_, kTestAppIdA, _, _, _, _, _))
      .Times(0);
  ShimNormalFocus(host_aa_.get());

  // Return no app windows for OnShimReopen. This will result in a launch call.
  EXPECT_CALL(*delegate_, ShowAppWindows(&profile_a_, kTestAppIdA))
      .WillRepeatedly(Return(false));
  EXPECT_CALL(*delegate_, LaunchApp(&profile_a_, kTestAppIdA, _, _, _, _, _))
      .Times(1);
  host_aa_->ReopenApp();

  // Return one window. This should do nothing.
  EXPECT_CALL(*delegate_, ShowAppWindows(&profile_a_, kTestAppIdA))
      .WillRepeatedly(Return(true));
  EXPECT_CALL(*delegate_,
              LaunchApp(&profile_a_, kTestAppIdA, _, _, _,
                        chrome::mojom::AppShimLoginItemRestoreState::kNone, _))
      .Times(0);
  host_aa_->ReopenApp();

  // Open files should trigger a launch with those files.
  std::vector<base::FilePath> some_file(1, base::FilePath("some_file"));
  EXPECT_CALL(
      *delegate_,
      LaunchApp(&profile_a_, kTestAppIdA, some_file, std::vector<GURL>(),
                GURL(), chrome::mojom::AppShimLoginItemRestoreState::kNone, _));
  host_aa_->FilesOpened(some_file);

  // Open urls should trigger a launch with those urls
  std::vector<GURL> some_url(1, GURL("web+test://foo"));
  EXPECT_CALL(*delegate_,
              LaunchApp(&profile_a_, kTestAppIdA, std::vector<base::FilePath>(),
                        some_url, GURL(),
                        chrome::mojom::AppShimLoginItemRestoreState::kNone, _));
  host_aa_->UrlsOpened(some_url);

  // Open app with override url should trigger a launch with that url
  GURL some_override_url("https://some-override-url.com");
  EXPECT_CALL(*delegate_,
              LaunchApp(&profile_a_, kTestAppIdA, std::vector<base::FilePath>(),
                        std::vector<GURL>(), some_override_url,
                        chrome::mojom::AppShimLoginItemRestoreState::kNone, _));
  host_aa_->OpenAppWithOverrideUrl(some_override_url);

  // OnAppDeactivated should not close the shim.
  EXPECT_CALL(*manager_, MaybeTerminate()).Times(0);
  manager_->OnAppDeactivated(&profile_a_, kTestAppIdA);
  EXPECT_NE(nullptr, host_aa_.get());

  // Process disconnect will cause the shim to close.
  EXPECT_CALL(*manager_, MaybeTerminate()).WillOnce(Return());
  manager_->OnShimProcessDisconnected(host_aa_.get());
  EXPECT_EQ(nullptr, host_aa_.get());
}

TEST_F(AppShimManagerTest, AppLifetimeOld) {
  scoped_feature_list_.InitWithFeatures({},
                                        {features::kAppShimNewCloseBehavior});

  // When the app activates, a host is created. If there is no shim, one is
  // launched.
  manager_->SetHostForCreate(std::move(host_aa_unique_));
  EXPECT_CALL(*delegate_,
              DoLaunchShim(&profile_a_, kTestAppIdA,
                           web_app::LaunchShimUpdateBehavior::kDoNotRecreate,
                           web_app::ShimLaunchMode::kNormal));
  manager_->OnAppActivated(&profile_a_, kTestAppIdA);
  EXPECT_EQ(host_aa_.get(), manager_->FindHost(&profile_a_, kTestAppIdA));

  // Normal shim launch adds an entry in the map.
  // App should not be launched here, but return success to the shim.
  EXPECT_CALL(*delegate_, LaunchApp(&profile_a_, kTestAppIdA, _, _, _, _, _))
      .Times(0);
  RegisterOnlyLaunch(bootstrap_aa_, nullptr);
  EXPECT_EQ(chrome::mojom::AppShimLaunchResult::kSuccess,
            *bootstrap_aa_result_);
  EXPECT_EQ(host_aa_.get(), manager_->FindHost(&profile_a_, kTestAppIdA));

  // Return no app windows for OnShimFocus. This will do nothing.
  EXPECT_CALL(*delegate_, ShowAppWindows(&profile_a_, kTestAppIdA))
      .WillRepeatedly(Return(false));
  EXPECT_CALL(*delegate_, LaunchApp(&profile_a_, kTestAppIdA, _, _, _, _, _))
      .Times(0);
  ShimNormalFocus(host_aa_.get());

  // Return no app windows for OnShimReopen. This will result in a launch call.
  EXPECT_CALL(*delegate_, ShowAppWindows(&profile_a_, kTestAppIdA))
      .WillRepeatedly(Return(false));
  EXPECT_CALL(*delegate_, LaunchApp(&profile_a_, kTestAppIdA, _, _, _, _, _))
      .Times(1);
  host_aa_->ReopenApp();

  // Return one window. This should do nothing.
  EXPECT_CALL(*delegate_, ShowAppWindows(&profile_a_, kTestAppIdA))
      .WillRepeatedly(Return(true));
  EXPECT_CALL(*delegate_, LaunchApp(&profile_a_, kTestAppIdA, _, _, _, _, _))
      .Times(0);
  host_aa_->ReopenApp();

  // Open files should trigger a launch with those files.
  std::vector<base::FilePath> some_file(1, base::FilePath("some_file"));
  EXPECT_CALL(*delegate_, LaunchApp(&profile_a_, kTestAppIdA, some_file,
                                    std::vector<GURL>(), GURL(), _, _));
  host_aa_->FilesOpened(some_file);

  // Open urls should trigger a launch with those urls
  std::vector<GURL> some_url(1, GURL("web+test://foo"));
  EXPECT_CALL(*delegate_,
              LaunchApp(&profile_a_, kTestAppIdA, std::vector<base::FilePath>(),
                        some_url, GURL(), _, _));
  host_aa_->UrlsOpened(some_url);

  // Open app with override url should trigger a launch with that url
  GURL some_override_url("https://some-override-url.com");
  EXPECT_CALL(*delegate_,
              LaunchApp(&profile_a_, kTestAppIdA, std::vector<base::FilePath>(),
                        std::vector<GURL>(), some_override_url, _, _));
  host_aa_->OpenAppWithOverrideUrl(some_override_url);

  // Process disconnect will cause the host to be deleted.
  manager_->OnShimProcessDisconnected(host_aa_.get());
  EXPECT_EQ(nullptr, host_aa_.get());

  // OnAppDeactivated should trigger a MaybeTerminate call.
  EXPECT_CALL(*manager_, MaybeTerminate()).WillOnce(Return());
  manager_->OnAppDeactivated(&profile_a_, kTestAppIdA);
}

TEST_F(AppShimManagerTest, FailToLaunch) {
  AppShimRegistry::Get()->OnAppInstalledForProfile(kTestAppIdA,
                                                   profile_path_a_);

  // When the app activates, it requests a launch.
  ShimLaunchedCallback launch_callback;
  delegate_->SetCaptureShimLaunchedCallback(&launch_callback);
  manager_->SetHostForCreate(std::move(host_aa_unique_));
  EXPECT_CALL(*delegate_,
              DoLaunchShim(&profile_a_, kTestAppIdA,
                           web_app::LaunchShimUpdateBehavior::kDoNotRecreate,
                           web_app::ShimLaunchMode::kNormal));
  manager_->OnAppActivated(&profile_a_, kTestAppIdA);
  EXPECT_EQ(host_aa_.get(), manager_->FindHost(&profile_a_, kTestAppIdA));
  EXPECT_TRUE(launch_callback);

  // Run the callback claiming that the launch failed. This should trigger
  // another launch, this time forcing shim recreation.
  EXPECT_CALL(
      *delegate_,
      DoLaunchShim(&profile_a_, kTestAppIdA,
                   web_app::LaunchShimUpdateBehavior::kRecreateUnconditionally,
                   web_app::ShimLaunchMode::kNormal));
  std::move(launch_callback).Run(base::Process());
  EXPECT_TRUE(launch_callback);

  // Report that the launch failed. This should trigger deletion of the host.
  EXPECT_NE(nullptr, host_aa_.get());
  std::move(launch_callback).Run(base::Process());
  EXPECT_EQ(nullptr, host_aa_.get());
}

TEST_F(AppShimManagerTest, FailToConnect) {
  AppShimRegistry::Get()->OnAppInstalledForProfile(kTestAppIdA,
                                                   profile_path_a_);

  // When the app activates, it requests a launch.
  ShimLaunchedCallback launched_callback;
  delegate_->SetCaptureShimLaunchedCallback(&launched_callback);
  ShimTerminatedCallback terminated_callback;
  delegate_->SetCaptureShimTerminatedCallback(&terminated_callback);

  manager_->SetHostForCreate(std::move(host_aa_unique_));
  EXPECT_CALL(*delegate_,
              DoLaunchShim(&profile_a_, kTestAppIdA,
                           web_app::LaunchShimUpdateBehavior::kDoNotRecreate,
                           web_app::ShimLaunchMode::kNormal));
  manager_->OnAppActivated(&profile_a_, kTestAppIdA);
  EXPECT_EQ(host_aa_.get(), manager_->FindHost(&profile_a_, kTestAppIdA));
  EXPECT_TRUE(launched_callback);
  EXPECT_TRUE(terminated_callback);

  // Run the launch callback claiming that the launch succeeded.
  std::move(launched_callback).Run(base::Process(5));
  EXPECT_FALSE(launched_callback);
  EXPECT_TRUE(terminated_callback);

  // Report that the process terminated. This should trigger a re-create and
  // re-launch.
  EXPECT_CALL(
      *delegate_,
      DoLaunchShim(&profile_a_, kTestAppIdA,
                   web_app::LaunchShimUpdateBehavior::kRecreateUnconditionally,
                   web_app::ShimLaunchMode::kNormal));
  std::move(terminated_callback).Run();
  EXPECT_TRUE(launched_callback);
  EXPECT_TRUE(terminated_callback);

  // Run the launch callback claiming that the launch succeeded.
  std::move(launched_callback).Run(base::Process(7));
  EXPECT_FALSE(launched_callback);
  EXPECT_TRUE(terminated_callback);

  // Report that the process terminated again. This should trigger deletion of
  // the host.
  EXPECT_NE(nullptr, host_aa_.get());
  std::move(terminated_callback).Run();
  EXPECT_EQ(nullptr, host_aa_.get());
}

TEST_F(AppShimManagerTest, FailCodeSignature) {
  AppShimRegistry::Get()->OnAppInstalledForProfile(kTestAppIdA,
                                                   profile_path_a_);

  manager_->SetAcceptablyCodeSigned(false);
  ShimLaunchedCallback launched_callback;
  delegate_->SetCaptureShimLaunchedCallback(&launched_callback);
  ShimTerminatedCallback terminated_callback;
  delegate_->SetCaptureShimTerminatedCallback(&terminated_callback);

  // Fail to code-sign. This should result in a host being created, and a launch
  // having been requested.
  EXPECT_CALL(*delegate_,
              DoLaunchShim(&profile_a_, kTestAppIdA,
                           web_app::LaunchShimUpdateBehavior::kDoNotRecreate,
                           web_app::ShimLaunchMode::kNormal));
  NormalLaunch(bootstrap_aa_, std::move(host_aa_unique_));
  EXPECT_EQ(host_aa_.get(), manager_->FindHost(&profile_a_, kTestAppIdA));
  EXPECT_TRUE(launched_callback);
  EXPECT_TRUE(terminated_callback);
  EXPECT_FALSE(host_aa_->HasBootstrapConnected());

  // Run the launch callback claiming that the launch succeeded.
  std::move(launched_callback).Run(base::Process(5));
  EXPECT_FALSE(launched_callback);
  EXPECT_TRUE(terminated_callback);
  EXPECT_FALSE(host_aa_->HasBootstrapConnected());

  // Simulate the register call that then fails due to signature failing.
  RegisterOnlyLaunch(bootstrap_aa_duplicate_, std::move(host_aa_unique_));
  EXPECT_FALSE(host_aa_->HasBootstrapConnected());

  // Simulate the termination after the register failed.
  manager_->SetAcceptablyCodeSigned(true);
  EXPECT_CALL(
      *delegate_,
      DoLaunchShim(&profile_a_, kTestAppIdA,
                   web_app::LaunchShimUpdateBehavior::kRecreateUnconditionally,
                   web_app::ShimLaunchMode::kNormal));
  std::move(terminated_callback).Run();
  EXPECT_TRUE(launched_callback);
  EXPECT_TRUE(terminated_callback);
  RegisterOnlyLaunch(bootstrap_aa_thethird_, std::move(host_aa_unique_));
  EXPECT_TRUE(host_aa_->HasBootstrapConnected());
}

TEST_F(AppShimManagerTest, MaybeTerminate) {
  scoped_feature_list_.InitWithFeatures({features::kAppShimNewCloseBehavior},
                                        {});

  AppShimRegistry::Get()->OnAppInstalledForProfile(kTestAppIdA,
                                                   profile_path_a_);
  AppShimRegistry::Get()->OnAppInstalledForProfile(kTestAppIdB,
                                                   profile_path_a_);

  // Launch shims, adding entries in the map.
  RegisterOnlyLaunch(bootstrap_aa_, std::move(host_aa_unique_));
  EXPECT_EQ(chrome::mojom::AppShimLaunchResult::kSuccess,
            *bootstrap_aa_result_);
  EXPECT_EQ(host_aa_.get(), manager_->FindHost(&profile_a_, kTestAppIdA));

  RegisterOnlyLaunch(bootstrap_ab_, std::move(host_ab_unique_));
  EXPECT_EQ(chrome::mojom::AppShimLaunchResult::kSuccess,
            *bootstrap_ab_result_);
  EXPECT_EQ(host_ab_.get(), manager_->FindHost(&profile_a_, kTestAppIdB));

  // Quitting when there's another shim should not terminate.
  EXPECT_CALL(*manager_, MaybeTerminate()).Times(0);
  manager_->OnAppDeactivated(&profile_a_, kTestAppIdA);

  // Quitting when it's the last shim should not terminate in the new behavior.
  EXPECT_CALL(*manager_, MaybeTerminate()).Times(0);
  manager_->OnAppDeactivated(&profile_a_, kTestAppIdB);
}

TEST_F(AppShimManagerTest, MaybeTerminateOnUninstall) {
  scoped_feature_list_.InitWithFeatures({features::kAppShimNewCloseBehavior},
                                        {});

  AppShimRegistry::Get()->OnAppInstalledForProfile(kTestAppIdA,
                                                   profile_path_a_);
  AppShimRegistry::Get()->OnAppInstalledForProfile(kTestAppIdB,
                                                   profile_path_a_);

  // Launch shims, adding entries in the map.
  RegisterOnlyLaunch(bootstrap_aa_, std::move(host_aa_unique_));
  EXPECT_EQ(chrome::mojom::AppShimLaunchResult::kSuccess,
            *bootstrap_aa_result_);
  EXPECT_EQ(host_aa_.get(), manager_->FindHost(&profile_a_, kTestAppIdA));

  RegisterOnlyLaunch(bootstrap_ab_, std::move(host_ab_unique_));
  EXPECT_EQ(chrome::mojom::AppShimLaunchResult::kSuccess,
            *bootstrap_ab_result_);
  EXPECT_EQ(host_ab_.get(), manager_->FindHost(&profile_a_, kTestAppIdB));

  // Quitting when there's another shim should not terminate.
  AppShimRegistry::Get()->OnAppUninstalledForProfile(kTestAppIdA,
                                                     profile_path_a_);
  EXPECT_CALL(*manager_, MaybeTerminate()).Times(0);
  manager_->OnAppDeactivated(&profile_a_, kTestAppIdA);

  // Quitting when it's the last shim and the app is uninstalled should
  // terminate.
  AppShimRegistry::Get()->OnAppUninstalledForProfile(kTestAppIdB,
                                                     profile_path_a_);
  EXPECT_CALL(*manager_, MaybeTerminate()).Times(1);
  manager_->OnAppDeactivated(&profile_a_, kTestAppIdB);
}

TEST_F(AppShimManagerTest, MaybeTerminateOld) {
  scoped_feature_list_.InitWithFeatures({},
                                        {features::kAppShimNewCloseBehavior});

  // Launch shims, adding entries in the map.
  RegisterOnlyLaunch(bootstrap_aa_, std::move(host_aa_unique_));
  EXPECT_EQ(chrome::mojom::AppShimLaunchResult::kSuccess,
            *bootstrap_aa_result_);
  EXPECT_EQ(host_aa_.get(), manager_->FindHost(&profile_a_, kTestAppIdA));

  RegisterOnlyLaunch(bootstrap_ab_, std::move(host_ab_unique_));
  EXPECT_EQ(chrome::mojom::AppShimLaunchResult::kSuccess,
            *bootstrap_ab_result_);
  EXPECT_EQ(host_ab_.get(), manager_->FindHost(&profile_a_, kTestAppIdB));

  // Quitting when there's another shim should not terminate.
  EXPECT_CALL(*manager_, MaybeTerminate()).Times(0);
  manager_->OnAppDeactivated(&profile_a_, kTestAppIdA);

  // Quitting when it's the last shim should terminate.
  EXPECT_CALL(*manager_, MaybeTerminate());
  manager_->OnAppDeactivated(&profile_a_, kTestAppIdB);
}

TEST_F(AppShimManagerTest, RegisterOnly) {
  // For an chrome::mojom::AppShimLaunchType::kRegisterOnly, don't launch the
  // app.
  EXPECT_CALL(*delegate_, LaunchApp(_, _, _, _, _, _, _)).Times(0);
  RegisterOnlyLaunch(bootstrap_aa_, std::move(host_aa_unique_));
  EXPECT_EQ(chrome::mojom::AppShimLaunchResult::kSuccess,
            *bootstrap_aa_result_);
  EXPECT_TRUE(manager_->FindHost(&profile_a_, kTestAppIdA));

  // Close the shim, removing the entry in the map.
  manager_->OnShimProcessDisconnected(host_aa_.get());
  EXPECT_FALSE(manager_->FindHost(&profile_a_, kTestAppIdA));
}

TEST_F(AppShimManagerTest, DontCreateHost) {
  delegate_->SetAppCanCreateHost(false);

  // The app should be launched.
  EXPECT_CALL(*delegate_, LaunchApp(_, _, _, _, _, _, _)).Times(1);
  NormalLaunch(bootstrap_ab_, std::move(host_ab_unique_));
  // But the bootstrap should be closed.
  EXPECT_EQ(chrome::mojom::AppShimLaunchResult::kSuccessAndDisconnect,
            *bootstrap_ab_result_);
  // And we should create no host.
  EXPECT_FALSE(manager_->FindHost(&profile_a_, kTestAppIdB));
}

TEST_F(AppShimManagerTest, NotificationAction) {
  class AppShimObserver : public AppShimManager::AppShimObserver {
   public:
    void OnShimProcessConnectedAndAllLaunchesDone(
        base::ProcessId pid,
        chrome::mojom::AppShimLaunchResult result) override {
      launch_result_.SetValue(result);
    }
    bool OnNotificationAction(
        mac_notifications::mojom::NotificationActionInfoPtr& info) override {
      notification_action_.SetValue(std::move(info));
      return false;
    }

    base::test::TestFuture<chrome::mojom::AppShimLaunchResult> launch_result_;
    base::test::TestFuture<mac_notifications::mojom::NotificationActionInfoPtr>
        notification_action_;
  };

  scoped_feature_list_.InitWithFeatures(
      {features::kAppShimNotificationAttribution,
       features::kUseAdHocSigningForWebAppShims},
      {});

  // Use SetAppCanCreateHost to simulate the case where there isn't already a
  // loaded profile.
  delegate_->SetAppCanCreateHost(false);

  AppShimObserver observer;
  manager_->SetAppShimObserverForTesting(&observer);

  // Create a test notification action.
  auto profile_identifier = mac_notifications::mojom::ProfileIdentifier::New(
      profile_a_.GetBaseName().AsUTF8Unsafe(), /*incognito=*/false);
  auto notification_identifier =
      mac_notifications::mojom::NotificationIdentifier::New(
          "notificaiton-id", std::move(profile_identifier));
  auto notification = mac_notifications::mojom::NotificationActionInfo::New();
  notification->meta = mac_notifications::mojom::NotificationMetadata::New(
      std::move(notification_identifier), /*notification_type=*/0,
      /*origin_url=*/GURL("https://example.com"), /*user_data_dir=*/"");
  notification->operation = NotificationOperation::kClick;
  notification->button_index = -1;

  // For an chrome::mojom::AppShimLaunchType::kNotificationAction, don't launch
  // the app.
  EXPECT_CALL(*delegate_, LaunchApp(_, _, _, _, _, _, _)).Times(0);
  NotificationActionLaunch(bootstrap_aa_, std::move(host_aa_unique_),
                           std::move(notification));
  // Should not have a result yet since the notification action hasn't been
  // handled yet.
  EXPECT_FALSE(bootstrap_aa_result_.has_value());
  EXPECT_FALSE(observer.launch_result_.IsReady());
  EXPECT_FALSE(observer.notification_action_.IsReady());

  // Wait for the notification action to be handled.
  ASSERT_TRUE(observer.notification_action_.Wait());
  EXPECT_FALSE(observer.launch_result_.IsReady());

  // Which should now allow to launch to finish.
  EXPECT_EQ(chrome::mojom::AppShimLaunchResult::kSuccessAndDisconnect,
            observer.launch_result_.Get());
  ASSERT_TRUE(bootstrap_aa_result_.has_value());
  EXPECT_EQ(chrome::mojom::AppShimLaunchResult::kSuccessAndDisconnect,
            *bootstrap_aa_result_);
  EXPECT_FALSE(manager_->FindHost(&profile_a_, kTestAppIdA));
}

TEST_F(AppShimManagerTest, LoadProfile) {
  // If the profile is not loaded when an OnShimProcessConnected arrives, return
  // false and load the profile asynchronously. Launch the app when the profile
  // is ready.
  EXPECT_CALL(*manager_, ProfileForPath(profile_path_a_))
      .WillOnce(Return(static_cast<Profile*>(nullptr)))
      .WillRepeatedly(Return(&profile_a_));
  NormalLaunch(bootstrap_aa_, std::move(host_aa_unique_));
  EXPECT_FALSE(manager_->FindHost(&profile_a_, kTestAppIdA));
  manager_->RunLoadProfileCallback(profile_path_a_, &profile_a_);
  EXPECT_TRUE(manager_->FindHost(&profile_a_, kTestAppIdA));
}

// Tests that calls to OnShimFocus, OnShimHide correctly handle a null extension
// being provided by the extension system.
TEST_F(AppShimManagerTest, ExtensionUninstalled) {
  LaunchAndActivate(bootstrap_aa_, std::move(host_aa_unique_), &profile_a_);

  ShimNormalFocus(host_aa_.get());
  EXPECT_NE(nullptr, host_aa_.get());

  // Set up the mock to return a null extension, as if it were uninstalled.
  EXPECT_CALL(*delegate_, AppIsInstalled(&profile_a_, kTestAppIdA))
      .WillRepeatedly(Return(false));

  // Trying to focus will do nothing -- the shim will have to be closed by
  // the user manually.
  ShimNormalFocus(host_aa_.get());
  EXPECT_NE(nullptr, host_aa_.get());
}

TEST_F(AppShimManagerTest, PreExistingHost) {
  // Create a host for our profile.
  manager_->SetHostForCreate(std::move(host_aa_unique_));
  EXPECT_EQ(nullptr, manager_->FindHost(&profile_a_, kTestAppIdA));
  EXPECT_CALL(*delegate_,
              DoLaunchShim(&profile_a_, kTestAppIdA,
                           web_app::LaunchShimUpdateBehavior::kDoNotRecreate,
                           web_app::ShimLaunchMode::kNormal))
      .Times(1);
  manager_->OnAppActivated(&profile_a_, kTestAppIdA);
  EXPECT_EQ(host_aa_.get(), manager_->FindHost(&profile_a_, kTestAppIdA));
  EXPECT_FALSE(host_aa_->did_connect_to_host());

  // Launch the app for this host. It should find the pre-existing host, and the
  // pre-existing host's launch result should be set.
  EXPECT_CALL(*delegate_,
              LaunchApp(&profile_a_, kTestAppIdA, _, _, _,
                        chrome::mojom::AppShimLoginItemRestoreState::kNone, _))
      .Times(0);
  EXPECT_FALSE(host_aa_->did_connect_to_host());
  DoShimLaunch(bootstrap_aa_, nullptr,
               chrome::mojom::AppShimLaunchType::kRegisterOnly,
               std::vector<base::FilePath>(), std::vector<GURL>(),
               chrome::mojom::AppShimLoginItemRestoreState::kNone);
  EXPECT_TRUE(host_aa_->did_connect_to_host());
  EXPECT_EQ(chrome::mojom::AppShimLaunchResult::kSuccess,
            *bootstrap_aa_result_);
  EXPECT_EQ(host_aa_.get(), manager_->FindHost(&profile_a_, kTestAppIdA));

  // Try to launch the app again. It should fail to launch, and the previous
  // profile should remain.
  DoShimLaunch(bootstrap_aa_duplicate_, nullptr,
               chrome::mojom::AppShimLaunchType::kRegisterOnly,
               std::vector<base::FilePath>(), std::vector<GURL>(),
               chrome::mojom::AppShimLoginItemRestoreState::kNone);
  EXPECT_TRUE(host_aa_->did_connect_to_host());
  EXPECT_EQ(chrome::mojom::AppShimLaunchResult::kDuplicateHost,
            *bootstrap_aa_duplicate_result_);
  EXPECT_EQ(host_aa_.get(), manager_->FindHost(&profile_a_, kTestAppIdA));
}

TEST_F(AppShimManagerTest, MultiProfile) {
  // Test with a bookmark app (host is shared).
  {
    // Create a host for profile A.
    manager_->SetHostForCreate(std::move(host_aa_unique_));
    EXPECT_EQ(nullptr, manager_->FindHost(&profile_a_, kTestAppIdA));
    manager_->OnAppActivated(&profile_a_, kTestAppIdA);
    EXPECT_EQ(host_aa_.get(), manager_->FindHost(&profile_a_, kTestAppIdA));
    EXPECT_FALSE(host_aa_->did_connect_to_host());

    // Ensure that profile B has the same host.
    manager_->SetHostForCreate(std::move(host_ba_unique_));
    EXPECT_EQ(nullptr, manager_->FindHost(&profile_b_, kTestAppIdA));
    manager_->OnAppActivated(&profile_b_, kTestAppIdA);
    EXPECT_EQ(host_aa_.get(), manager_->FindHost(&profile_b_, kTestAppIdA));
    EXPECT_FALSE(host_aa_->did_connect_to_host());
  }

  // Test with a non-bookmark app (host is not shared).
  {
    // Create a host for profile A.
    manager_->SetHostForCreate(std::move(host_ab_unique_));
    EXPECT_EQ(nullptr, manager_->FindHost(&profile_a_, kTestAppIdB));
    manager_->OnAppActivated(&profile_a_, kTestAppIdB);
    EXPECT_EQ(host_ab_.get(), manager_->FindHost(&profile_a_, kTestAppIdB));
    EXPECT_FALSE(host_ab_->did_connect_to_host());

    // Ensure that profile B has the same host.
    manager_->SetHostForCreate(std::move(host_bb_unique_));
    EXPECT_EQ(nullptr, manager_->FindHost(&profile_b_, kTestAppIdB));
    manager_->OnAppActivated(&profile_b_, kTestAppIdB);
    EXPECT_EQ(host_bb_.get(), manager_->FindHost(&profile_b_, kTestAppIdB));
    EXPECT_FALSE(host_bb_->did_connect_to_host());
  }
}

TEST_F(AppShimManagerTest, MultiProfileShimLaunch) {
  manager_->SetHostForCreate(std::move(host_aa_unique_));
  ShimLaunchedCallback launched_callback;
  delegate_->SetCaptureShimLaunchedCallback(&launched_callback);
  ShimTerminatedCallback terminated_callback;
  delegate_->SetCaptureShimTerminatedCallback(&terminated_callback);

  // Launch the app for profile A. This should trigger a shim launch request.
  EXPECT_CALL(*delegate_,
              DoLaunchShim(&profile_a_, kTestAppIdA,
                           web_app::LaunchShimUpdateBehavior::kDoNotRecreate,
                           web_app::ShimLaunchMode::kNormal));
  EXPECT_EQ(nullptr, manager_->FindHost(&profile_a_, kTestAppIdA));
  manager_->OnAppActivated(&profile_a_, kTestAppIdA);
  EXPECT_EQ(host_aa_.get(), manager_->FindHost(&profile_a_, kTestAppIdA));
  EXPECT_FALSE(host_aa_->did_connect_to_host());

  // Launch the app for profile B. This should not cause a shim launch request.
  EXPECT_CALL(*delegate_, DoLaunchShim(_, _, _, _)).Times(0);
  manager_->OnAppActivated(&profile_b_, kTestAppIdA);

  // Indicate the profile A that its launch succeeded.
  EXPECT_TRUE(launched_callback);
  EXPECT_TRUE(terminated_callback);
  std::move(launched_callback).Run(base::Process(5));
  EXPECT_FALSE(launched_callback);
  EXPECT_TRUE(terminated_callback);
}

TEST_F(AppShimManagerTest, MultiProfileSelectMenu) {
  EXPECT_CALL(*delegate_, ShowAppWindows(_, _)).WillRepeatedly(Return(false));
  manager_->SetHostForCreate(std::move(host_aa_unique_));
  ShimLaunchedCallback launched_callback;
  delegate_->SetCaptureShimLaunchedCallback(&launched_callback);
  ShimTerminatedCallback terminated_callback;
  delegate_->SetCaptureShimTerminatedCallback(&terminated_callback);

  // Launch the app for profile A. This should trigger a shim launch request.
  EXPECT_CALL(*delegate_,
              DoLaunchShim(&profile_a_, kTestAppIdA,
                           web_app::LaunchShimUpdateBehavior::kDoNotRecreate,
                           web_app::ShimLaunchMode::kNormal));
  EXPECT_EQ(nullptr, manager_->FindHost(&profile_a_, kTestAppIdA));
  manager_->OnAppActivated(&profile_a_, kTestAppIdA);
  EXPECT_EQ(host_aa_.get(), manager_->FindHost(&profile_a_, kTestAppIdA));
  EXPECT_FALSE(host_aa_->did_connect_to_host());

  // Indicate the profile A that its launch succeeded.
  EXPECT_TRUE(launched_callback);
  EXPECT_TRUE(terminated_callback);
  std::move(launched_callback).Run(base::Process(5));
  EXPECT_FALSE(launched_callback);
  EXPECT_TRUE(terminated_callback);

  // Select profile B from the menu. This should request that the app be
  // launched.
  EXPECT_CALL(*delegate_,
              LaunchApp(&profile_b_, kTestAppIdA, _, _, _,
                        chrome::mojom::AppShimLoginItemRestoreState::kNone, _));
  host_aa_->ProfileSelectedFromMenu(profile_path_b_);
  EXPECT_CALL(*delegate_, DoLaunchShim(_, _, _, _)).Times(0);
  manager_->OnAppActivated(&profile_b_, kTestAppIdA);

  // Select profile A and B from the menu -- this should not request a launch,
  // because the profiles are already enabled.
  EXPECT_CALL(*delegate_, ShowAppWindows(_, _)).WillRepeatedly(Return(true));
  EXPECT_CALL(*delegate_,
              LaunchApp(_, _, _, _, _,
                        chrome::mojom::AppShimLoginItemRestoreState::kNone, _))
      .Times(0);
  host_aa_->ProfileSelectedFromMenu(profile_path_a_);
  host_aa_->ProfileSelectedFromMenu(profile_path_b_);
}

namespace {
// A helper that records when Show is called on a BrowserWindow to verify
// activation of existing browser windows.
class TestBrowserWindowShow : public TestBrowserWindow {
 public:
  void Show() override { did_show = true; }

  bool did_show = false;
};
}  // namespace

TEST_F(AppShimManagerTest, MultiProfileSelectMenu_ShowsBrowser) {
  EXPECT_CALL(*delegate_, ShowAppWindows(_, _)).WillRepeatedly(Return(false));
  manager_->SetHostForCreate(std::move(host_aa_unique_));
  ShimLaunchedCallback launched_callback;
  delegate_->SetCaptureShimLaunchedCallback(&launched_callback);
  ShimTerminatedCallback terminated_callback;
  delegate_->SetCaptureShimTerminatedCallback(&terminated_callback);

  // Launch the app for profile A. This should trigger a shim launch request.
  EXPECT_CALL(*delegate_,
              DoLaunchShim(&profile_a_, kTestAppIdA,
                           web_app::LaunchShimUpdateBehavior::kDoNotRecreate,
                           web_app::ShimLaunchMode::kNormal));
  EXPECT_EQ(nullptr, manager_->FindHost(&profile_a_, kTestAppIdA));
  manager_->OnAppActivated(&profile_a_, kTestAppIdA);
  EXPECT_EQ(host_aa_.get(), manager_->FindHost(&profile_a_, kTestAppIdA));
  EXPECT_FALSE(host_aa_->did_connect_to_host());

  // Indicate the profile A that its launch succeeded.
  EXPECT_TRUE(launched_callback);
  EXPECT_TRUE(terminated_callback);
  std::move(launched_callback).Run(base::Process(5));
  EXPECT_FALSE(launched_callback);
  EXPECT_TRUE(terminated_callback);

  // Notify manager that a new browser has been associated with the app.
  auto browser_window_a = std::make_unique<TestBrowserWindowShow>();
  std::string app_name = web_app::GenerateApplicationNameFromAppId(kTestAppIdA);
  Browser::CreateParams params_a = Browser::CreateParams::CreateForApp(
      app_name, true, browser_window_a->GetBounds(), &profile_a_, true);
  params_a.window = browser_window_a.get();
  auto browser_a = Browser::DeprecatedCreateOwnedForTesting(params_a);
  manager_->OnBrowserAdded(browser_a.get());

  // Select profile B from the menu. This should request that the app be
  // launched.
  EXPECT_CALL(*delegate_,
              LaunchApp(&profile_b_, kTestAppIdA, _, _, _,
                        chrome::mojom::AppShimLoginItemRestoreState::kNone, _));
  host_aa_->ProfileSelectedFromMenu(profile_path_b_);
  EXPECT_CALL(*delegate_, DoLaunchShim(_, _, _, _)).Times(0);
  manager_->OnAppActivated(&profile_b_, kTestAppIdA);

  // Notify manager that a new browser has been associated with the app.
  auto browser_window_b = std::make_unique<TestBrowserWindowShow>();
  Browser::CreateParams params_b = Browser::CreateParams::CreateForApp(
      app_name, true, browser_window_b->GetBounds(), &profile_b_, true);
  params_b.window = browser_window_b.get();
  auto browser_b = Browser::DeprecatedCreateOwnedForTesting(params_b);
  manager_->OnBrowserAdded(browser_b.get());

  EXPECT_FALSE(browser_window_a->did_show);
  EXPECT_FALSE(browser_window_b->did_show);

  // Select profile A and B from the menu -- this should not request a launch,
  // because the profiles are already enabled.
  EXPECT_CALL(*delegate_, ShowAppWindows(_, _)).WillRepeatedly(Return(false));
  EXPECT_CALL(*delegate_,
              LaunchApp(_, _, _, _, _,
                        chrome::mojom::AppShimLoginItemRestoreState::kNone, _))
      .Times(0);
  host_aa_->ProfileSelectedFromMenu(profile_path_a_);
  EXPECT_TRUE(browser_window_a->did_show);
  EXPECT_FALSE(browser_window_b->did_show);
  browser_window_a->did_show = false;

  host_aa_->ProfileSelectedFromMenu(profile_path_b_);
  EXPECT_FALSE(browser_window_a->did_show);
  EXPECT_TRUE(browser_window_b->did_show);
}

TEST_F(AppShimManagerTest, ProfileMenuOneProfile) {
  {
    auto item_a = chrome::mojom::ProfileMenuItem::New();
    item_a->profile_path = profile_path_a_;
    item_a->menu_index = 999;

    std::vector<chrome::mojom::ProfileMenuItemPtr> items;
    items.push_back(std::move(item_a));
    manager_->SetProfileMenuItems(std::move(items));
  }

  // Set this app to be installed for profile A.
  AppShimRegistry::Get()->OnAppInstalledForProfile(kTestAppIdA,
                                                   profile_path_a_);

  // When the app activates, a host is created. This will trigger building
  // the avatar menu.
  manager_->SetHostForCreate(std::move(host_aa_unique_));
  EXPECT_CALL(*delegate_,
              DoLaunchShim(&profile_a_, kTestAppIdA,
                           web_app::LaunchShimUpdateBehavior::kDoNotRecreate,
                           web_app::ShimLaunchMode::kNormal));
  manager_->OnAppActivated(&profile_a_, kTestAppIdA);
  EXPECT_EQ(host_aa_.get(), manager_->FindHost(&profile_a_, kTestAppIdA));

  // Launch the shim.
  EXPECT_CALL(*delegate_,
              LaunchApp(&profile_a_, kTestAppIdA, _, _, _,
                        chrome::mojom::AppShimLoginItemRestoreState::kNone, _))
      .Times(0);
  RegisterOnlyLaunch(bootstrap_aa_, nullptr);
  EXPECT_EQ(chrome::mojom::AppShimLaunchResult::kSuccess,
            *bootstrap_aa_result_);
  EXPECT_EQ(host_aa_.get(), manager_->FindHost(&profile_a_, kTestAppIdA));
  const auto& menu_items = host_aa_->test_app_shim_->profile_menu_items_;

  // We should have no menu items, because there is only one installed profile.
  EXPECT_TRUE(menu_items.empty());

  // Add profile B to the avatar menu and call the avatar menu observer update
  // method.
  {
    auto item_a = chrome::mojom::ProfileMenuItem::New();
    item_a->profile_path = profile_path_a_;
    item_a->menu_index = 999;

    auto item_b = chrome::mojom::ProfileMenuItem::New();
    item_b->profile_path = profile_path_b_;
    item_b->menu_index = 111;

    std::vector<chrome::mojom::ProfileMenuItemPtr> items;
    items.push_back(std::move(item_a));
    items.push_back(std::move(item_b));
    manager_->SetProfileMenuItems(std::move(items));
  }

  // We should still only have no menu items, because the app is not installed
  // for multiple profiles.
  EXPECT_TRUE(menu_items.empty());

  // Now install for profile B.
  AppShimRegistry::Get()->OnAppInstalledForProfile(kTestAppIdA,
                                                   profile_path_b_);
  manager_->OnAppActivated(&profile_b_, kTestAppIdA);
  EXPECT_EQ(menu_items.size(), 2u);
  EXPECT_EQ(menu_items[0]->profile_path, profile_path_b_);
  EXPECT_EQ(menu_items[1]->profile_path, profile_path_a_);
}

TEST_F(AppShimManagerTest, FindProfileFromBadProfile) {
  // Set this app to be installed for profile A and B.
  AppShimRegistry::Get()->OnAppInstalledForProfile(kTestAppIdA,
                                                   profile_path_a_);
  AppShimRegistry::Get()->OnAppInstalledForProfile(kTestAppIdA,
                                                   profile_path_b_);

  // Set the app to be last-active on profile A.
  std::set<base::FilePath> last_active_profile_paths;
  last_active_profile_paths.insert(profile_path_a_);
  AppShimRegistry::Get()->SaveLastActiveProfilesForApp(
      kTestAppIdA, last_active_profile_paths);

  // Launch the shim requesting profile C.
  manager_->SetHostForCreate(std::move(host_aa_unique_));
  EXPECT_CALL(*delegate_,
              LaunchApp(&profile_a_, kTestAppIdA, _, _, _,
                        chrome::mojom::AppShimLoginItemRestoreState::kNone, _))
      .Times(1);
  EXPECT_CALL(*delegate_,
              LaunchApp(&profile_b_, kTestAppIdA, _, _, _,
                        chrome::mojom::AppShimLoginItemRestoreState::kNone, _))
      .Times(0);
  EXPECT_CALL(*delegate_, EnableExtension(&profile_c_, kTestAppIdA, _))
      .WillOnce(RunOnceCallback<2>());
  NormalLaunch(bootstrap_ca_, nullptr);
  EXPECT_EQ(chrome::mojom::AppShimLaunchResult::kSuccess,
            *bootstrap_ca_result_);
  EXPECT_EQ(host_aa_.get(), manager_->FindHost(&profile_a_, kTestAppIdA));
}

TEST_F(AppShimManagerTest, FindProfileFromNoProfile) {
  // Set this app to be installed for profile A.
  AppShimRegistry::Get()->OnAppInstalledForProfile(kTestAppIdA,
                                                   profile_path_a_);

  // Launch the shim without specifying a profile.
  manager_->SetHostForCreate(std::move(host_aa_unique_));
  EXPECT_CALL(*delegate_,
              LaunchApp(&profile_a_, kTestAppIdA, _, _, _,
                        chrome::mojom::AppShimLoginItemRestoreState::kNone, _))
      .Times(1);
  EXPECT_CALL(*delegate_,
              LaunchApp(&profile_b_, kTestAppIdA, _, _, _,
                        chrome::mojom::AppShimLoginItemRestoreState::kNone, _))
      .Times(0);
  NormalLaunch(bootstrap_xa_, nullptr);
  EXPECT_EQ(chrome::mojom::AppShimLaunchResult::kSuccess,
            *bootstrap_xa_result_);
  EXPECT_EQ(host_aa_.get(), manager_->FindHost(&profile_a_, kTestAppIdA));
}

TEST_F(AppShimManagerTest, FindProfileFromFilePaths) {
  // Set this app to be install for profile A, B and C.
  AppShimRegistry::Get()->OnAppInstalledForProfile(kTestAppIdA,
                                                   profile_path_a_);
  AppShimRegistry::Get()->OnAppInstalledForProfile(kTestAppIdA,
                                                   profile_path_b_);
  AppShimRegistry::Get()->OnAppInstalledForProfile(kTestAppIdA,
                                                   profile_path_c_);

  // Configure different file handlers in each of the three profiles.
  AppShimRegistry::Get()->SaveFileHandlersForAppAndProfile(
      kTestAppIdA, profile_path_a_, {".md"}, {});
  AppShimRegistry::Get()->SaveFileHandlersForAppAndProfile(
      kTestAppIdA, profile_path_b_, {".txt", ".csv"}, {});
  AppShimRegistry::Get()->SaveFileHandlersForAppAndProfile(
      kTestAppIdA, profile_path_c_, {".txt"}, {});

  // Launch the shim passing in several files.
  EXPECT_CALL(*delegate_,
              LaunchApp(&profile_a_, kTestAppIdA, _, _, _,
                        chrome::mojom::AppShimLoginItemRestoreState::kNone, _))
      .Times(0);
  EXPECT_CALL(*delegate_,
              LaunchApp(&profile_b_, kTestAppIdA, _, _, _,
                        chrome::mojom::AppShimLoginItemRestoreState::kNone, _))
      .Times(1);
  EXPECT_CALL(*delegate_,
              LaunchApp(&profile_c_, kTestAppIdA, _, _, _,
                        chrome::mojom::AppShimLoginItemRestoreState::kNone, _))
      .Times(0);
  DoShimLaunch(bootstrap_xa_, std::move(host_ba_unique_),
               chrome::mojom::AppShimLaunchType::kNormal,
               {base::FilePath("/foo/bar/test.txt"),
                base::FilePath("/home/test/data.csv"),
                base::FilePath("/data/README.md")},
               {}, chrome::mojom::AppShimLoginItemRestoreState::kNone);
  EXPECT_EQ(chrome::mojom::AppShimLaunchResult::kSuccess,
            *bootstrap_xa_result_);
  EXPECT_EQ(host_ba_.get(), manager_->FindHost(&profile_b_, kTestAppIdA));
}

TEST_F(AppShimManagerTest, FindProfileFromFileURL) {
  // Set this app to be install for profile A, B and C.
  AppShimRegistry::Get()->OnAppInstalledForProfile(kTestAppIdA,
                                                   profile_path_a_);
  AppShimRegistry::Get()->OnAppInstalledForProfile(kTestAppIdA,
                                                   profile_path_b_);
  AppShimRegistry::Get()->OnAppInstalledForProfile(kTestAppIdA,
                                                   profile_path_c_);

  // Configure different file handlers in each of the three profiles.
  AppShimRegistry::Get()->SaveFileHandlersForAppAndProfile(
      kTestAppIdA, profile_path_a_, {".md"}, {});
  AppShimRegistry::Get()->SaveFileHandlersForAppAndProfile(
      kTestAppIdA, profile_path_b_, {".txt", ".csv"}, {});
  AppShimRegistry::Get()->SaveFileHandlersForAppAndProfile(
      kTestAppIdA, profile_path_c_, {".txt"}, {});

  // Launch the shim passing in a file URL.
  EXPECT_CALL(*delegate_,
              LaunchApp(&profile_a_, kTestAppIdA, _, _, _,
                        chrome::mojom::AppShimLoginItemRestoreState::kNone, _))
      .Times(1);
  EXPECT_CALL(*delegate_,
              LaunchApp(&profile_b_, kTestAppIdA, _, _, _,
                        chrome::mojom::AppShimLoginItemRestoreState::kNone, _))
      .Times(0);
  EXPECT_CALL(*delegate_,
              LaunchApp(&profile_c_, kTestAppIdA, _, _, _,
                        chrome::mojom::AppShimLoginItemRestoreState::kNone, _))
      .Times(0);
  DoShimLaunch(bootstrap_xa_, std::move(host_aa_unique_),
               chrome::mojom::AppShimLaunchType::kNormal, {},
               {GURL("file:///data/README.md")},
               chrome::mojom::AppShimLoginItemRestoreState::kNone);
  EXPECT_EQ(chrome::mojom::AppShimLaunchResult::kSuccess,
            *bootstrap_xa_result_);
  EXPECT_EQ(host_aa_.get(), manager_->FindHost(&profile_a_, kTestAppIdA));
}

TEST_F(AppShimManagerTest, FindProfileFromURL) {
  // Set this app to be install for profile A, B and C.
  AppShimRegistry::Get()->OnAppInstalledForProfile(kTestAppIdA,
                                                   profile_path_a_);
  AppShimRegistry::Get()->OnAppInstalledForProfile(kTestAppIdA,
                                                   profile_path_b_);
  AppShimRegistry::Get()->OnAppInstalledForProfile(kTestAppIdA,
                                                   profile_path_c_);

  // Configure different protocol handlers in each of the three profiles.
  AppShimRegistry::Get()->SaveProtocolHandlersForAppAndProfile(
      kTestAppIdA, profile_path_a_, {"web+music"});
  AppShimRegistry::Get()->SaveProtocolHandlersForAppAndProfile(
      kTestAppIdA, profile_path_b_, {"web+jngl"});
  AppShimRegistry::Get()->SaveProtocolHandlersForAppAndProfile(
      kTestAppIdA, profile_path_c_, {"mailto"});

  // Launch the shim passing in a URL to be handled in profile B.
  EXPECT_CALL(*delegate_,
              LaunchApp(&profile_a_, kTestAppIdA, _, _, _,
                        chrome::mojom::AppShimLoginItemRestoreState::kNone, _))
      .Times(0);
  EXPECT_CALL(*delegate_,
              LaunchApp(&profile_b_, kTestAppIdA, _, _, _,
                        chrome::mojom::AppShimLoginItemRestoreState::kNone, _))
      .Times(1);
  EXPECT_CALL(*delegate_,
              LaunchApp(&profile_c_, kTestAppIdA, _, _, _,
                        chrome::mojom::AppShimLoginItemRestoreState::kNone, _))
      .Times(0);
  DoShimLaunch(bootstrap_xa_, std::move(host_ba_unique_),
               chrome::mojom::AppShimLaunchType::kNormal, {},
               {GURL("web+jngl://foo/bar")},
               chrome::mojom::AppShimLoginItemRestoreState::kNone);
  EXPECT_EQ(chrome::mojom::AppShimLaunchResult::kSuccess,
            *bootstrap_xa_result_);
  EXPECT_EQ(host_ba_.get(), manager_->FindHost(&profile_b_, kTestAppIdA));
}

TEST_F(AppShimManagerTest, UpdateAppBadge) {
  // Set this app to be installed for profile A and B.
  AppShimRegistry::Get()->OnAppInstalledForProfile(kTestAppIdA,
                                                   profile_path_a_);
  AppShimRegistry::Get()->OnAppInstalledForProfile(kTestAppIdA,
                                                   profile_path_b_);

  // Activate the app for profile_a_ and profile_b_
  manager_->SetHostForCreate(std::move(host_aa_unique_));
  EXPECT_EQ(nullptr, manager_->FindHost(&profile_a_, kTestAppIdA));
  manager_->OnAppActivated(&profile_a_, kTestAppIdA);
  EXPECT_EQ(host_aa_.get(), manager_->FindHost(&profile_a_, kTestAppIdA));

  manager_->SetHostForCreate(std::move(host_ba_unique_));
  EXPECT_EQ(nullptr, manager_->FindHost(&profile_b_, kTestAppIdA));
  manager_->OnAppActivated(&profile_b_, kTestAppIdA);
  EXPECT_EQ(host_aa_.get(), manager_->FindHost(&profile_b_, kTestAppIdA));

  // And update the badge in either profile, verifying that the combined value
  // is reflected.
  EXPECT_EQ("", host_aa_->test_app_shim_->badge_label_);
  manager_->UpdateAppBadge(&profile_a_, kTestAppIdA,
                           badging::BadgeManager::BadgeValue(4));
  EXPECT_EQ("4", host_aa_->test_app_shim_->badge_label_);
  manager_->UpdateAppBadge(&profile_b_, kTestAppIdA,
                           badging::BadgeManager::BadgeValue(3));
  EXPECT_EQ("7", host_aa_->test_app_shim_->badge_label_);
  manager_->UpdateAppBadge(&profile_a_, kTestAppIdA,
                           badging::BadgeManager::BadgeValue());
  EXPECT_EQ("3", host_aa_->test_app_shim_->badge_label_);
  manager_->UpdateAppBadge(&profile_b_, kTestAppIdA,
                           badging::BadgeManager::BadgeValue());
  EXPECT_EQ("•", host_aa_->test_app_shim_->badge_label_);
  manager_->UpdateAppBadge(&profile_a_, kTestAppIdA, std::nullopt);
  EXPECT_EQ("•", host_aa_->test_app_shim_->badge_label_);
  manager_->UpdateAppBadge(&profile_b_, kTestAppIdA, std::nullopt);
  EXPECT_EQ("", host_aa_->test_app_shim_->badge_label_);
}

TEST_F(AppShimManagerTest, UpdateApplicationDockMenu) {
  // Set this app to be installed for profile A and B.
  AppShimRegistry::Get()->OnAppInstalledForProfile(kTestAppIdA,
                                                   profile_path_a_);
  AppShimRegistry::Get()->OnAppInstalledForProfile(kTestAppIdA,
                                                   profile_path_b_);

  struct DockMenuItems {
    std::u16string name;
    GURL url;
  };

  DockMenuItems menu_items_profile_a[] = {
      {u"dock_menu_item_a_1", GURL(".")},
      {u"dock_menu_item_a_2", GURL("/settings")},
      {u"dock_menu_item_a_3", GURL("https://anothersite.com")},
  };
  const size_t kNumMenuItemsForProfileA = std::size(menu_items_profile_a);

  DockMenuItems menu_items_profile_b[] = {
      {u"dock_menu_item_b_1", GURL("/about")},
      {u"dock_menu_item_b_2", GURL("/another-link")},
  };
  const size_t kNumMenuItemsForProfileB = std::size(menu_items_profile_b);

  // Lambda to help with creation of application dock menu items.
  auto MakeDockMenuItems = [](DockMenuItems* menu_items,
                              size_t menu_items_size) {
    std::vector<chrome::mojom::ApplicationDockMenuItemPtr> mock_dock_menu_items;
    for (size_t i = 0; i < menu_items_size; i++) {
      auto dock_menu_item = chrome::mojom::ApplicationDockMenuItem::New();
      dock_menu_item->name = menu_items[i].name;
      dock_menu_item->url = menu_items[i].url;
      mock_dock_menu_items.push_back(std::move(dock_menu_item));
    }
    return mock_dock_menu_items;
  };

  auto ValidateDockMenuItems = [&](DockMenuItems* expected_menu_items,
                                   size_t expected_menu_items_size) {
    const auto& dock_menu_items = host_aa_->test_app_shim_->dock_menu_items_;
    EXPECT_EQ(expected_menu_items_size, dock_menu_items.size());
    for (size_t i = 0; i < dock_menu_items.size(); i++) {
      EXPECT_EQ(expected_menu_items[i].name, dock_menu_items[i]->name);
      EXPECT_EQ(expected_menu_items[i].url, dock_menu_items[i]->url);
    }
  };

  // Activate the app for profile_a_ and profile_b_
  manager_->SetHostForCreate(std::move(host_aa_unique_));
  EXPECT_EQ(nullptr, manager_->FindHost(&profile_a_, kTestAppIdA));
  manager_->OnAppActivated(&profile_a_, kTestAppIdA);
  EXPECT_EQ(host_aa_.get(), manager_->FindHost(&profile_a_, kTestAppIdA));

  manager_->SetHostForCreate(std::move(host_ba_unique_));
  EXPECT_EQ(nullptr, manager_->FindHost(&profile_b_, kTestAppIdA));
  manager_->OnAppActivated(&profile_b_, kTestAppIdA);
  EXPECT_EQ(host_aa_.get(), manager_->FindHost(&profile_b_, kTestAppIdA));

  // Validate no application dock menu items have been set yet.
  ValidateDockMenuItems(nullptr, 0);

  // Create browser objects that can be passed via OnBrowserSetLastActive.
  std::string app_name = web_app::GenerateApplicationNameFromAppId(kTestAppIdA);
  std::unique_ptr<BrowserWindow> browser_window_a, browser_window_b;
  std::unique_ptr<Browser> browser_profile_a, browser_profile_b;

  {
    browser_window_a = std::make_unique<TestBrowserWindow>();
    Browser::CreateParams params = Browser::CreateParams::CreateForApp(
        app_name, true, browser_window_a->GetBounds(), &profile_a_, true);
    params.window = browser_window_a.get();
    browser_profile_a = Browser::DeprecatedCreateOwnedForTesting(params);
  }

  {
    browser_window_b = std::make_unique<TestBrowserWindow>();
    Browser::CreateParams params = Browser::CreateParams::CreateForApp(
        app_name, true, browser_window_b->GetBounds(), &profile_b_, true);
    params.window = browser_window_b.get();
    browser_profile_b = Browser::DeprecatedCreateOwnedForTesting(params);
  }

  // Set profile A browser as last active, and validate the application dock
  // menu items.
  EXPECT_CALL(*delegate_,
              GetAppShortcutsMenuItemInfos(&profile_a_, kTestAppIdA))
      .WillOnce(Return(testing::ByMove(
          MakeDockMenuItems(menu_items_profile_a, kNumMenuItemsForProfileA))));

  manager_->OnBrowserSetLastActive(browser_profile_a.get());
  ValidateDockMenuItems(menu_items_profile_a, kNumMenuItemsForProfileA);

  // Set profile B browser as last active, and validate the application dock
  // menu items.
  EXPECT_CALL(*delegate_,
              GetAppShortcutsMenuItemInfos(&profile_b_, kTestAppIdA))
      .WillOnce(Return(testing::ByMove(
          MakeDockMenuItems(menu_items_profile_b, kNumMenuItemsForProfileB))));

  manager_->OnBrowserSetLastActive(browser_profile_b.get());
  ValidateDockMenuItems(menu_items_profile_b, kNumMenuItemsForProfileB);
}

TEST_F(AppShimManagerTest,
       BuildAppShimRequirementStringFromFrameworkRequirementStringTest) {
  EXPECT_TRUE(
      manager_->BuildAppShimRequirementStringFromFrameworkRequirementString(
          CFSTR("identifier \"com.google.Chrome.framework\" and certificate "
                "leaf = H\"c9a99324ca3fcb23dbcc36bd5fd4f9753305130a\"")));
  EXPECT_TRUE(
      manager_->BuildAppShimRequirementStringFromFrameworkRequirementString(
          CFSTR("identifier \"com.google.Chrome.framework\" and certificate "
                "leaf[subject.OU] = \"42HXZ8M8AV\"")));

  EXPECT_FALSE(
      manager_->BuildAppShimRequirementStringFromFrameworkRequirementString(
          CFSTR(
              "cdhash H\"daa66a31aeb85125bd2459bebf548b2dff5ee83b\" or cdhash "
              "H\"a8e5300bf9223510fc5b107b23de0d12f419acac\"")));
  EXPECT_FALSE(
      manager_->BuildAppShimRequirementStringFromFrameworkRequirementString(
          CFSTR("identifier \"com.google.Chrome.framework\"")));
  EXPECT_FALSE(
      manager_->BuildAppShimRequirementStringFromFrameworkRequirementString(
          CFSTR("identifier")));
  EXPECT_FALSE(
      manager_->BuildAppShimRequirementStringFromFrameworkRequirementString(
          CFSTR("malformed")));
  EXPECT_FALSE(
      manager_->BuildAppShimRequirementStringFromFrameworkRequirementString(
          CFSTR("")));
  EXPECT_FALSE(
      manager_->BuildAppShimRequirementStringFromFrameworkRequirementString(
          CFSTR("\"\"\"")));
  EXPECT_FALSE(
      manager_->BuildAppShimRequirementStringFromFrameworkRequirementString(
          CFSTR("\"\"")));
  EXPECT_FALSE(
      manager_->BuildAppShimRequirementStringFromFrameworkRequirementString(
          CFSTR("\"")));

  // Crafted to pass all our requirement checks but fail
  // SecRequirementCreateWithString().
  base::apple::ScopedCFTypeRef<CFStringRef> requirement_string =
      manager_->BuildAppShimRequirementStringFromFrameworkRequirementString(
          CFSTR("identifier \"com.google.Chrome.framework\" and fail here"));
  EXPECT_TRUE(requirement_string);
  EXPECT_FALSE(apps::RequirementFromString(requirement_string.get()));
  // Missing quote in the post "identifier" portion which is caught by
  // SecRequirementCreateWithString().
  requirement_string =
      manager_->BuildAppShimRequirementStringFromFrameworkRequirementString(
          CFSTR("identifier \"com.google.Chrome.framework\" and certificate "
                "leaf = Hc9a99324ca3fcb23dbcc36bd5fd4f9753305130a\""));
  EXPECT_TRUE(requirement_string);
  EXPECT_FALSE(apps::RequirementFromString(requirement_string.get()));

  CFStringRef framework_req_string = CFSTR(
      "identifier \"com.google.Chrome.framework\" and anchor "
      "apple generic and certificate 1[field.1.2.840.113635.100.6.2.6] /* "
      "exists */ and certificate leaf[field.1.2.840.113635.100.6.1.13] "
      "/* exists */ and certificate leaf[subject.OU] = EQHXZ8M8AV");
  base::apple::ScopedCFTypeRef<SecRequirementRef> got_req(
      apps::RequirementFromString(
          manager_
              ->BuildAppShimRequirementStringFromFrameworkRequirementString(
                  framework_req_string)
              .get()));
  ASSERT_TRUE(got_req);
  base::apple::ScopedCFTypeRef<CFStringRef> got_req_string;
  ASSERT_EQ(SecRequirementCopyString(got_req.get(), kSecCSDefaultFlags,
                                     got_req_string.InitializeInto()),
            errSecSuccess);
  CFStringRef want_req_string = CFSTR(
      "identifier \"app_mode_loader\" and anchor "
      "apple generic and certificate 1[field.1.2.840.113635.100.6.2.6] /* "
      "exists */ and certificate leaf[field.1.2.840.113635.100.6.1.13] "
      "/* exists */ and certificate leaf[subject.OU] = EQHXZ8M8AV");
  EXPECT_EQ(base::SysCFStringRefToUTF8(got_req_string.get()),
            base::SysCFStringRefToUTF8(want_req_string));
}

TEST_F(AppShimManagerTest, LaunchNotificationProviderWithAppRunning) {
  scoped_feature_list_.InitWithFeatures(
      {features::kAppShimNotificationAttribution,
       features::kUseAdHocSigningForWebAppShims},
      {});

  // This app is installed for profile A throughout this test.
  AppShimRegistry::Get()->OnAppInstalledForProfile(kTestAppIdA,
                                                   profile_path_a_);

  // Launch the app shim.
  manager_->SetHostForCreate(std::move(host_aa_unique_));
  EXPECT_CALL(*delegate_,
              DoLaunchShim(&profile_a_, kTestAppIdA,
                           web_app::LaunchShimUpdateBehavior::kDoNotRecreate,
                           web_app::ShimLaunchMode::kNormal));
  manager_->OnAppActivated(&profile_a_, kTestAppIdA);
  EXPECT_EQ(host_aa_.get(), manager_->FindHost(&profile_a_, kTestAppIdA));

  // Connect to its notification provider.
  mojo::Remote<mac_notifications::mojom::MacNotificationProvider> provider =
      manager_->LaunchNotificationProvider(kTestAppIdA);
  EXPECT_TRUE(provider.is_bound());
  EXPECT_TRUE(
      host_aa_->test_app_shim_->notification_provider_receiver_.is_bound());
  provider.FlushForTesting();
  EXPECT_TRUE(provider.is_connected());
}

TEST_F(AppShimManagerTest, LaunchNotificationProviderWithoutAppRunning) {
  scoped_feature_list_.InitWithFeatures(
      {features::kAppShimNotificationAttribution,
       features::kUseAdHocSigningForWebAppShims},
      {});

  // This app is installed for profile A throughout this test.
  AppShimRegistry::Get()->OnAppInstalledForProfile(kTestAppIdA,
                                                   profile_path_a_);
  EXPECT_CALL(*manager_, ProfileForBackgroundShimLaunch(kTestAppIdA))
      .WillOnce(Return(&profile_a_));

  manager_->SetHostForCreate(std::move(host_aa_unique_));
  EXPECT_CALL(*delegate_,
              DoLaunchShim(&profile_a_, kTestAppIdA,
                           web_app::LaunchShimUpdateBehavior::kDoNotRecreate,
                           web_app::ShimLaunchMode::kBackground));

  mojo::Remote<mac_notifications::mojom::MacNotificationProvider> provider =
      manager_->LaunchNotificationProvider(kTestAppIdA);
  EXPECT_TRUE(provider.is_bound());
  EXPECT_TRUE(
      host_aa_->test_app_shim_->notification_provider_receiver_.is_bound());
  provider.FlushForTesting();
  EXPECT_TRUE(provider.is_connected());
}

TEST_F(AppShimManagerTest, LaunchNotificationProviderWithAppNotInstalled) {
  scoped_feature_list_.InitWithFeatures(
      {features::kAppShimNotificationAttribution,
       features::kUseAdHocSigningForWebAppShims},
      {});

  EXPECT_CALL(*manager_, ProfileForBackgroundShimLaunch(kTestAppIdA))
      .WillOnce(Return(nullptr));

  mojo::Remote<mac_notifications::mojom::MacNotificationProvider> provider =
      manager_->LaunchNotificationProvider(kTestAppIdA);
  // AppShimManager binds `provider` to a dummy implementation if an app can't
  // be found, since notifications code expects to always get a bound provider.
  EXPECT_TRUE(provider.is_bound());
  provider.FlushForTesting();
  EXPECT_TRUE(provider.is_connected());

  // Attempting to bind a notification service on the dummy provider should
  // immediately disconnect.
  mojo::Remote<mac_notifications::mojom::MacNotificationService> service;
  mojo::PendingReceiver<mac_notifications::mojom::MacNotificationActionHandler>
      handler;
  provider->BindNotificationService(service.BindNewPipeAndPassReceiver(),
                                    handler.InitWithNewPipeAndPassRemote());
  EXPECT_TRUE(service.is_connected());
  service.FlushForTesting();
  EXPECT_FALSE(service.is_connected());
  EXPECT_TRUE(provider.is_connected());
}

TEST_F(AppShimManagerTest, RequestNotificationPermissionWithAppRunning) {
  scoped_feature_list_.InitWithFeatures(
      {features::kAppShimNotificationAttribution,
       features::kUseAdHocSigningForWebAppShims},
      {});

  // This app is installed for profile A throughout this test.
  AppShimRegistry::Get()->OnAppInstalledForProfile(kTestAppIdA,
                                                   profile_path_a_);

  // Launch the app shim.
  manager_->SetHostForCreate(std::move(host_aa_unique_));
  EXPECT_CALL(*delegate_,
              DoLaunchShim(&profile_a_, kTestAppIdA,
                           web_app::LaunchShimUpdateBehavior::kDoNotRecreate,
                           web_app::ShimLaunchMode::kNormal));
  manager_->OnAppActivated(&profile_a_, kTestAppIdA);
  EXPECT_EQ(host_aa_.get(), manager_->FindHost(&profile_a_, kTestAppIdA));

  // Trigger a notification permission request.
  base::test::TestFuture<mac_notifications::mojom::RequestPermissionResult>
      result;
  manager_->ShowNotificationPermissionRequest(kTestAppIdA,
                                              result.GetCallback());
  EXPECT_TRUE(host_aa_->test_app_shim_
                  ->request_notification_permission_callback_.Wait());
  host_aa_->test_app_shim_->request_notification_permission_callback_.Take()
      .Run(mac_notifications::mojom::RequestPermissionResult::
               kPermissionPreviouslyGranted);
  EXPECT_EQ(mac_notifications::mojom::RequestPermissionResult::
                kPermissionPreviouslyGranted,
            result.Get());
}

TEST_F(AppShimManagerTest, RequestNotificationPermissionWithoutAppRunning) {
  scoped_feature_list_.InitWithFeatures(
      {features::kAppShimNotificationAttribution,
       features::kUseAdHocSigningForWebAppShims},
      {});

  // This app is installed for profile A throughout this test.
  AppShimRegistry::Get()->OnAppInstalledForProfile(kTestAppIdA,
                                                   profile_path_a_);
  EXPECT_CALL(*manager_, ProfileForBackgroundShimLaunch(kTestAppIdA))
      .WillOnce(Return(&profile_a_));

  manager_->SetHostForCreate(std::move(host_aa_unique_));
  EXPECT_CALL(*delegate_,
              DoLaunchShim(&profile_a_, kTestAppIdA,
                           web_app::LaunchShimUpdateBehavior::kDoNotRecreate,
                           web_app::ShimLaunchMode::kBackground));

  // Trigger a notification permission request.
  base::test::TestFuture<mac_notifications::mojom::RequestPermissionResult>
      result;
  manager_->ShowNotificationPermissionRequest(kTestAppIdA,
                                              result.GetCallback());
  EXPECT_TRUE(host_aa_->test_app_shim_
                  ->request_notification_permission_callback_.Wait());
  host_aa_->test_app_shim_->request_notification_permission_callback_.Take()
      .Run(mac_notifications::mojom::RequestPermissionResult::
               kPermissionPreviouslyDenied);
  EXPECT_EQ(mac_notifications::mojom::RequestPermissionResult::
                kPermissionPreviouslyDenied,
            result.Get());
}

TEST_F(AppShimManagerTest,
       RequestNotificationPermissionWithoutAppRunningAndBrowserClosing) {
  scoped_feature_list_.InitWithFeatures(
      {features::kAppShimNotificationAttribution,
       features::kUseAdHocSigningForWebAppShims},
      {});

  // This app is installed for profile A throughout this test.
  AppShimRegistry::Get()->OnAppInstalledForProfile(kTestAppIdA,
                                                   profile_path_a_);
  EXPECT_CALL(*manager_, ProfileForBackgroundShimLaunch(kTestAppIdA))
      .WillOnce(Return(&profile_a_));

  manager_->SetHostForCreate(std::move(host_aa_unique_));
  EXPECT_CALL(*delegate_,
              DoLaunchShim(&profile_a_, kTestAppIdA,
                           web_app::LaunchShimUpdateBehavior::kDoNotRecreate,
                           web_app::ShimLaunchMode::kBackground));

  // Trigger a notification permission request.
  base::test::TestFuture<mac_notifications::mojom::RequestPermissionResult>
      result;
  manager_->ShowNotificationPermissionRequest(kTestAppIdA,
                                              result.GetCallback());

  EXPECT_TRUE(host_aa_->test_app_shim_
                  ->request_notification_permission_callback_.Wait());

  // Pretend the last browser for this app/profile was just closed, and the
  // profile has been unloaded as a result of that.
  manager_->OnAppDeactivated(&profile_a_, kTestAppIdA);
  EXPECT_CALL(*manager_, ProfileForPath(profile_path_a_))
      .WillRepeatedly(Return(nullptr));
  EXPECT_CALL(*delegate_, AppIsInstalled(nullptr, kTestAppIdA))
      .WillRepeatedly(Return(false));

  // Now have the app shim connect to the browser process.
  RegisterOnlyLaunch(bootstrap_aa_, nullptr);

  host_aa_->test_app_shim_->request_notification_permission_callback_.Take()
      .Run(mac_notifications::mojom::RequestPermissionResult::
               kPermissionPreviouslyDenied);
  EXPECT_EQ(mac_notifications::mojom::RequestPermissionResult::
                kPermissionPreviouslyDenied,
            result.Get());
}

TEST_F(AppShimManagerTest,
       AppShimFailToConnectForNotificationPermissionAfterBrowserClosed) {
  scoped_feature_list_.InitWithFeatures(
      {features::kAppShimNotificationAttribution,
       features::kUseAdHocSigningForWebAppShims},
      {});

  // This app is installed for profile A throughout this test.
  AppShimRegistry::Get()->OnAppInstalledForProfile(kTestAppIdA,
                                                   profile_path_a_);
  EXPECT_CALL(*manager_, ProfileForBackgroundShimLaunch(kTestAppIdA))
      .WillOnce(Return(&profile_a_));

  manager_->SetHostForCreate(std::move(host_aa_unique_));
  EXPECT_CALL(*delegate_,
              DoLaunchShim(&profile_a_, kTestAppIdA,
                           web_app::LaunchShimUpdateBehavior::kDoNotRecreate,
                           web_app::ShimLaunchMode::kBackground));

  // Capture the terminated callback so we can simulate the app shim failing
  // to launch.
  ShimTerminatedCallback terminated_callback;
  delegate_->SetCaptureShimTerminatedCallback(&terminated_callback);

  // Trigger a notification permission request.
  base::test::TestFuture<mac_notifications::mojom::RequestPermissionResult>
      result;
  manager_->ShowNotificationPermissionRequest(kTestAppIdA,
                                              result.GetCallback());

  EXPECT_TRUE(host_aa_->test_app_shim_
                  ->request_notification_permission_callback_.Wait());

  // Pretend the last browser for this app/profile was just closed, and the
  // profile has been unloaded as a result of that.
  manager_->OnAppDeactivated(&profile_a_, kTestAppIdA);
  EXPECT_CALL(*manager_, ProfileForPath(profile_path_a_))
      .WillRepeatedly(Return(nullptr));
  EXPECT_CALL(*delegate_, AppIsInstalled(nullptr, kTestAppIdA))
      .WillRepeatedly(Return(false));

  // Report that the process terminated.
  ASSERT_TRUE(terminated_callback);
  std::move(terminated_callback).Run();
}

TEST_F(AppShimManagerTest,
       RequestNotificationPermissionWithAppShimFailingToLaunch) {
  scoped_feature_list_.InitWithFeatures(
      {features::kAppShimNotificationAttribution,
       features::kUseAdHocSigningForWebAppShims},
      {});

  // This app is installed for profile A throughout this test.
  AppShimRegistry::Get()->OnAppInstalledForProfile(kTestAppIdA,
                                                   profile_path_a_);
  EXPECT_CALL(*manager_, ProfileForBackgroundShimLaunch(kTestAppIdA))
      .WillOnce(Return(&profile_a_));

  manager_->SetHostForCreate(std::move(host_aa_unique_));
  EXPECT_CALL(*delegate_,
              DoLaunchShim(&profile_a_, kTestAppIdA,
                           web_app::LaunchShimUpdateBehavior::kDoNotRecreate,
                           web_app::ShimLaunchMode::kBackground));

  // Trigger a notification permission request.
  base::test::TestFuture<mac_notifications::mojom::RequestPermissionResult>
      result;
  manager_->ShowNotificationPermissionRequest(kTestAppIdA,
                                              result.GetCallback());
  EXPECT_TRUE(host_aa_->test_app_shim_
                  ->request_notification_permission_callback_.Wait());

  // Simulate the app shim failing to launch (or otherwise terminating) by
  // dropping the callback.
  host_aa_->test_app_shim_->request_notification_permission_callback_.Take()
      .Reset();

  EXPECT_EQ(mac_notifications::mojom::RequestPermissionResult::kRequestFailed,
            result.Get());
}

TEST_F(AppShimManagerTest, RequestNotificationPermissionWithAppNotInstalled) {
  scoped_feature_list_.InitWithFeatures(
      {features::kAppShimNotificationAttribution,
       features::kUseAdHocSigningForWebAppShims},
      {});

  EXPECT_CALL(*manager_, ProfileForBackgroundShimLaunch(kTestAppIdA))
      .WillOnce(Return(nullptr));

  // Trigger a notification permission request.
  base::test::TestFuture<mac_notifications::mojom::RequestPermissionResult>
      result;
  manager_->ShowNotificationPermissionRequest(kTestAppIdA,
                                              result.GetCallback());
  EXPECT_EQ(mac_notifications::mojom::RequestPermissionResult::kRequestFailed,
            result.Get());
}

TEST_F(AppShimManagerTest, CachedNotificationPermissionStatus) {
  using PermissionStatus = mac_notifications::mojom::PermissionStatus;
  scoped_feature_list_.InitWithFeatures(
      {features::kAppShimNotificationAttribution,
       features::kUseAdHocSigningForWebAppShims},
      {});

  // Create and launch shim for app A in profile A.
  AppShimRegistry::Get()->OnAppInstalledForProfile(kTestAppIdA,
                                                   profile_path_a_);
  manager_->SetHostForCreate(std::move(host_aa_unique_));
  EXPECT_CALL(*delegate_,
              DoLaunchShim(&profile_a_, kTestAppIdA,
                           web_app::LaunchShimUpdateBehavior::kDoNotRecreate,
                           web_app::ShimLaunchMode::kNormal));
  manager_->OnAppActivated(&profile_a_, kTestAppIdA);

  // Initial cached status should be "not determined".
  EXPECT_EQ(PermissionStatus::kNotDetermined,
            AppShimRegistry::Get()->GetNotificationPermissionStatusForApp(
                kTestAppIdA));

  // Trigger updates to the notification status.
  base::test::TestFuture<const std::string&> app_changed;
  auto app_changed_registration =
      AppShimRegistry::Get()->RegisterAppChangedCallback(
          app_changed.GetRepeatingCallback());

  for (auto status :
       {PermissionStatus::kGranted, PermissionStatus::kNotDetermined,
        PermissionStatus::kPromptPending, PermissionStatus::kDenied}) {
    host_aa_->NotificationPermissionStatusChanged(status);
    EXPECT_EQ(kTestAppIdA, app_changed.Take());
    EXPECT_EQ(status,
              AppShimRegistry::Get()->GetNotificationPermissionStatusForApp(
                  kTestAppIdA));
  }
}

}  // namespace apps