File size: 329,301 Bytes
8a29801 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 | /**
* LocalMiniappRuntime
*
* Singleton service that bridges local miniapps (running in WebViews) with
* phone capabilities: display, audio, storage, sensors, LED, etc.
*
* Each miniapp communicates via the @mentra/miniapp envelope protocol.
* This runtime handles request dispatch, stream fan-out, and lifecycle
* management (connect/disconnect/ping).
*/
import {parsePhotoCompression} from "@mentra/cloud-protocol/photo-compression"
import {acquireGlassesHotspot} from "./GlassesHotspotLease"
import {AppState, Platform} from "react-native"
import * as Battery from "expo-battery"
import * as Clipboard from "expo-clipboard"
import * as Location from "expo-location"
import BluetoothSdk, {type RgbLedAction, type RgbLedColor} from "@mentra/bluetooth-sdk"
import {
MiniappErrorCode,
MiniappRequestType,
MiniappResponseType,
MiniappStreamType,
CLOUD_STATUS_STREAM,
parseEnvelope,
serializeEnvelope,
} from "@mentra/miniapp"
import type {MiniappEnvelope} from "@mentra/miniapp"
import {DeviceTypes, getModelCapabilities} from "../types"
import {storage as mmkvStorage} from "../utils/storage/storage"
import {BgTimer} from "../utils/timers"
import devServerBridge from "./DevServerBridge"
import {islandNotifications} from "./NotificationsEmitter"
import {isGlassesConnected, isGlassesReady, waitForGlassesReady} from "./GlassesReadiness"
import {toMiniappConnectionData} from "./GlassesStatusProjection"
import audioPlaybackService from "./AudioPlaybackService"
import {phoneLocationService} from "./PhoneLocationService"
import {useGlassesStore} from "../stores/glasses"
import {useSettingsStore} from "../stores/settings"
import localDisplayManager from "./LocalDisplayManager"
import type {DisplayPayload} from "./LocalDisplayManager"
import headingService from "./HeadingService"
import localSttFallbackCoordinator from "./LocalSttFallbackCoordinator"
import micStateCoordinator from "./MicStateCoordinator"
import {speechActivityService} from "./SpeechActivityService"
import {wakeWordService} from "./WakeWordService"
import micSessionManager, {MIC_SOURCE_CONFLICT, type MicSession} from "./MicSessionManager"
import {ENGINE_ONLY_USE_CASES, MIC_USE_CASES, VOICE_CALL_PACKAGES, type MicUseCase} from "./micPolicy"
import {BlobStore} from "./BlobStore"
import {MiniappSystemActions} from "./MiniappSystemActions"
import {CloudAudioSubscriptionSync} from "./CloudAudioSubscriptionSync"
import {phoneCameraFovCoordinator} from "./PhoneCameraFovCoordinator"
import {fleetEvents} from "./fleet/fleetEvents"
import {phonePhotoCoordinator} from "./PhonePhotoCoordinator"
import {phoneStreamCoordinator} from "./PhoneStreamCoordinator"
import {phoneVideoCoordinator} from "./PhoneVideoCoordinator"
import {runSentenceTtsPipeline} from "./SentenceTtsPipeline"
import {
needsCloud,
needsLocal,
onDeviceServes,
readSpeechProcessing,
targetSource,
UtteranceTracker,
type SpeechProcessing,
type TranscriptionRoutingState,
} from "./TranscriptionRouting"
import {
addStreamProcessing,
transcriptionRegistrations,
TranscriptionSubscriptions,
type TranscriptionStreamEntry,
} from "./TranscriptionSubscriptions"
import {prepareTtsSentences} from "./TtsTextSanitizer"
import {handleWifiAdbRequest} from "./WifiAdbRequest"
import {cloudClientService} from "./CloudClientService"
import {miniappLauncher} from "./MiniappLauncher"
import {
ISLAND_SETTINGS_KEYS,
type CameraFovPreset,
type CameraFovRequest,
type CameraRoiPosition,
type CloudClientStatusSnapshot,
type InteropAuditEvent,
type MiniappAuthToken,
type TtsSynthesisResult,
} from "../runtime/config"
import {
getAnalytics,
getConfigValues,
getMiniappConfiguration,
getUiSeams,
isFeatureEnabled,
isMiniappAvailable,
} from "../runtime/bootstrap"
import {invokeScanQrSeam} from "../runtime/scanQrSeam"
import {invokePhoneWifiSeam} from "../runtime/phoneWifiSeam"
import {
normalizeStreamAudioConfig,
normalizeStreamVideoConfig,
normalizeCaptureAudio,
resolveCaptureAudio,
} from "../runtime/streamConfig"
import {toLanguageHint} from "@mentra/cloud-protocol/languages"
import type {
AudioPosition,
AudioSubscription,
LanguageSource,
TranscriptionData,
TranslationData,
} from "@mentra/cloud-protocol"
import {buildMiniappManifestSnapshot, type MiniappRuntimeDiagnosticSnapshot} from "../utils/miniappDiagnostics"
import sttModelManager from "./STTModelManager"
import ttsModelManager from "./TTSModelManager"
import {NavigationHandlers} from "./NavigationHandlers"
import type {ClientApp} from "../types/applet"
import {useAppStatusStore, visibleMiniappPackage} from "../stores/apps"
import appRegistry, {getDevAppRecords} from "./AppRegistry"
import {resolveForegroundLocationPermission} from "./ForegroundLocationPermission"
import {advanceMiniappPingLiveness, shouldHoldMiniappPingLiveness} from "./MiniappLiveness"
import {listPhoneCalendarEvents, PhoneCalendarError} from "./PhoneCalendarService"
import {LocalMiniappStorage} from "./LocalMiniappStorage"
import {isLocalBuildContext} from "./miniappBuildKind"
import {configureMiniappDataPartitions, miniappDataSessionOf, resolveMiniappDataPartition} from "./miniappDataPartition"
import {sameCoreUrl} from "./fleet/coreUrl"
import {isHostTrustedSystemMiniapp, isSystemMiniappPackage} from "./SystemMiniappPolicy"
import {installMiniapp, InstallMiniappError, type InstallMiniappErrorCode} from "./installMiniapp"
import {dismissRunningUpdatePrompts} from "./runningUpdatePrompt"
import {
checkMiniappInstallCompatibility,
type MiniappCompatibilityPolicy,
type MiniappInstallCompatibility,
} from "./miniappInstallCompatibility"
import {TransientActionWakeCoordinator} from "./TransientActionWakeCoordinator"
import {projectSystemActions} from "./manifestActions"
import {
createMeeting,
meetingConfiguration,
meetingIdentity,
meetingCredential,
retireMeeting,
type MeetingIdentity,
} from "./MeetingCredentials"
import {loadOutgoingStill} from "./outgoingStill"
import {MeetingStillError, STILL_MAX_DURATION_MS, type MeetingStillFailure} from "./MeetingStillController"
import acsMeetingService, {
parseAcsCallOrigin,
parseAcsOutgoingVideo,
parseAcsVideoSource,
resolveAcsAudioSource,
type AcsCallOrigin,
type AcsOutgoingVideo,
type AcsVideoSource,
type MeetingState,
} from "./AcsMeetingService"
import {
createSoftapCallDeps,
SoftapCallError,
SoftapCallTransport,
RETURN_DEADLINE_MS,
SOFTAP_STEPS,
type SoftapProgress,
type SoftapTeardownMode,
} from "./SoftapCallTransport"
import {awaitCleanupBarrier} from "./SoftapCleanupBarrier"
import {softapTrace, softapTraceFailure} from "../utils/softapTrace"
import {PermissionFeatures, permissions} from "../facades/permissions"
import {getStreamPreviewHost} from "./streamPreviewPort"
// =============================================================================
// Types
// =============================================================================
export interface InstalledMiniappManifest {
packageName?: string
/** Human-facing app name (from miniapp.json `name`). Shown in the "Starting
* <name>…" boot message; falls back to the package name when absent. */
name?: string
version?: string
sdkVersion?: string
minHostVersion?: string
type?: string
entry?: {background?: string; ui?: string}
permissions?: Array<{type: string; required?: boolean; description?: string}>
hardwareRequirements?: Array<{type: string; level: string; description?: string}>
actions?: Array<{
id?: unknown
description?: unknown
parameters?: unknown
outputSchema?: unknown
lifecycle?: unknown
audience?: unknown
}>
}
type SpeakerStateValue = "idle" | "loading" | "playing" | "stopped" | "error"
interface ConnectedMiniapp {
/** Transcription listeners, each with the source (cloud or on-device) it gets text from. */
transcriptionListeners: TranscriptionSubscriptions
subscriptions: Set<string>
sendMessage: (raw: string) => void
lastPongAt: number
unansweredPingRounds: number
installedManifest?: InstalledMiniappManifest
/** Host-derived provenance (a bundled release, or one from a Mentra host); never from miniapp.json. */
hostTrustedSystem: boolean
authRefreshTimerId: number | null
/**
* Backoff timer for re-attempting the INITIAL miniapp-token mint after it
* failed (distinct from `authRefreshTimerId`, which renews an already-issued
* token near expiry). Null when no retry is queued.
*/
authRetryTimerId: number | null
/**
* True once this app has received a miniapp auth token (in CONNECT_ACK or a
* follow-up AUTH_UPDATE). Gates the initial-mint retry loop and the
* on-reconnect re-drive so we stop hammering once auth has landed.
*/
authDelivered: boolean
/**
* Identifies the CONNECT handshake whose token this app is waiting for or holding (0 before its first
* CONNECT). Every token request records the value it started under and applies its answer only while the
* app still has it, so a slow answer for an earlier CONNECT or a replaced instance cannot mark the
* current handshake delivered, deliver a stale token or re-arm its timers.
*/
authSession: number
/**
* True while a request for the token this CONNECT is waiting for is out. The reconnect re-drive leaves such an
* app alone: a cache-first request now would deliver the cached token and the fresh one still on its way would
* then be discarded.
*/
authRequestPending: boolean
/** Last speaker state pushed to this app. Used to dedup SPEAKER_STATE pushes. */
speakerState: SpeakerStateValue
/** Live PCM output stream this app has open (speaker.createStream), if any. */
activeSpeakerStreamId?: string
/** Prewarmed speaker stream that hasn't received audio; the speaker stays idle until its first write. */
preparedSpeakerStreamId?: string
/** Last on-device model status sent to this app, to skip repeats. */
lastTranscriptionModelStatus?: string
/**
* Location-tier rate this app is currently asking for via its
* `location_stream` subscription, or null if it hasn't asked for
* one. The aggregate tier handed to the host is the strictest
* (highest-accuracy) rate across all currently connected apps —
* see {@link LOCATION_RATE_PRIORITY}.
*/
requestedLocationRate: string | null
/** One spawn of this package's background; a respawn gets a new id. Scopes preview leases. */
runtimeId: string
}
interface SpeechRun {
id: string
cancelled: boolean
playbackRequestId?: string
onCancelled?: () => void
}
type TranscriptionEventSource = "cloud" | "local"
/**
* Strictness ordering for `location_stream` rate values. Higher index =
* higher accuracy and higher power cost. The aggregate tier applied to
* the OS is the max of every connected miniapp's requested rate;
* miniapps that didn't ask for `location_stream` contribute nothing.
*
* If a miniapp passes a value we don't recognize, we treat it like the
* weakest known rate ("passive") rather than blanket-overwriting an
* active stronger request from another app.
*/
const LOCATION_RATE_PRIORITY = ["off", "passive", "low", "high", "realtime"] as const
type LocationRate = (typeof LOCATION_RATE_PRIORITY)[number]
function locationRateRank(rate: string | null | undefined): number {
if (!rate) return -1
const i = LOCATION_RATE_PRIORITY.indexOf(rate as LocationRate)
return i >= 0 ? i : LOCATION_RATE_PRIORITY.indexOf("passive")
}
/** Why this deployment refuses a transcription listener's processing, or null. */
function speechProcessingDisabled(processing: SpeechProcessing): string | null {
const cloud = isFeatureEnabled("cloudSpeech")
const onDevice = isFeatureEnabled("onDeviceSpeech")
if (processing === "localOnly" && !onDevice) return "On-device speech is disabled by this deployment"
if (processing === "preferCloud" && !cloud) return "Cloud speech is disabled by this deployment"
if (processing === "preferLocal" && !cloud && !onDevice) {
return "Cloud and on-device speech are disabled by this deployment"
}
return null
}
const LOG_TAG = "LOCAL_MINIAPP"
/**
* Cloud speech arrives as raw 24 kHz 16-bit mono PCM and streams into the
* native PCM player. One startup buffer for every miniapp's cloud speech:
* enough to ride out ordinary cellular jitter, short enough to start quickly.
* Tune it once on a weak cellular link; if first words get cut, raise it.
*/
const CLOUD_SPEECH_FORMAT = "pcm_24000" as const
const CLOUD_SPEECH_SAMPLE_RATE = 24000
const CLOUD_SPEECH_JITTER_MS = 250
/**
* Spoken TTS doesn't mute the cloud microphone uplink. The mute is global to
* the uplink, so arming it made every reply punch a hole in Captions and Live
* Translation for every app (removed in abd85f30a3). The PCM stream path
* supports the same opt-in; flip this to arm it for all cloud speech.
*/
const SUPPRESS_CLOUD_UPLINK_DURING_SPEECH = false
/**
* True when cloud speech failed before any audio played: the runtime refused
* it (an HTTP status, or a body that isn't PCM), or the audio output changed
* before the first byte. A dropped connection mid-sentence is not one of these.
*/
function cloudSpeechRefused(error: string | null): boolean {
return (
error !== null && /\bhttp_error\b|\bunsupported_format\b|\bnot open\b|\b(?:HTTP|status)\b|\b[45]\d\d\b/i.test(error)
)
}
const DIAGNOSTIC_MAX_LIST_ITEMS = 100
const DIAGNOSTIC_MAX_STRING_LENGTH = 512
const SYSTEM_MINIAPP_PACKAGE_SET = new Set([
"com.mentra.camera",
"com.mentra.gallery",
"com.mentra.settings",
"com.mentra.simulated",
"com.mentra.mirror",
"com.mentra.ai",
"cloud.augmentos.notify",
"com.mentra.feedback",
"com.mentra.miniappdev",
])
/** The trusted host's identity as an action caller; never a miniapp package. */
const HOST_ACTION_CALLER = "__mentra_host__"
function diagnosticStringList(values: Iterable<string>): string[] {
return [...values]
.map((value) => value.slice(0, DIAGNOSTIC_MAX_STRING_LENGTH))
.sort()
.slice(0, DIAGNOSTIC_MAX_LIST_ITEMS)
}
const PING_INTERVAL_MS = 5_000
const MINIAPP_AUTH_REFRESH_HEADROOM_MS = 5 * 60 * 1000
const MINIAPP_AUTH_REFRESH_MIN_DELAY_MS = 5_000
// Backoff bounds for re-minting the INITIAL miniapp token after a failed mint
// (e.g. the cloud client had not finished its first-boot Core token exchange
// when the miniapp connected). Exponential from base, capped, so a transient
// not-yet-connected client self-heals within seconds instead of needing a full
// manual Cloud V2 reconnect.
const MINIAPP_AUTH_RETRY_BASE_MS = 1_000
const MINIAPP_AUTH_RETRY_MAX_MS = 15_000
const FOREGROUND_LIVENESS_PROBE_TIMEOUT_MS = 2_500
/**
* How long a SoftAP call waits for the first frame to reach ACS before failing the join.
*
* Generous because it covers the glasses' whole publish path — WHIP POST, host-only ICE, and the
* first decode — but bounded, since a call that connects and never paints has to fail as a join
* rather than sit in "connecting" while the wearer waits.
*/
const SOFTAP_FIRST_FRAME_MS = 20_000
/**
* How long the BLE link must stay up before SoftAP recovery trusts it. Covers the gap between
* the hotspot dying and the phone noticing the link died with it.
*/
const GLASSES_LINK_SETTLE_MS = 4_000
const REQUEST_WIFI_SETUP_TYPE = "miniapp_request_wifi_setup"
// Unregister after this many missed pongs. Generous on purpose: a busy
// context (heavy interim translation traffic) or OS scheduling while idle can
// delay pongs well past one interval, and killing a healthy-but-busy script
// drops its subscriptions (releasing the mic). With the liveness-timeout
// respawn path wired (MentraJSRouter.start), a genuinely dead context still
// comes back automatically — this threshold only bounds how long that takes.
const PING_TIMEOUT_THRESHOLD = 6 // ~30s
const TRANSCRIPT_TIMING_TELEMETRY = (globalThis as {__DEV__?: boolean}).__DEV__ === true
const RGB_LED_ACTIONS = new Set<RgbLedAction>(["on", "off"])
const RGB_LED_COLORS = new Set<RgbLedColor>(["red", "green", "blue", "orange", "white"])
const CAMERA_FOV_MIN = 62
const CAMERA_FOV_MAX = 118
const CAMERA_FOV_DEFAULT = 118
const CAMERA_FOV_PRESETS: Record<CameraFovPreset, number> = {narrow: 82, standard: 102, wide: 118}
const CAMERA_ROI_POSITION_BY_NAME: Record<string, CameraRoiPosition> = {center: "center", bottom: "bottom", top: "top"}
const localMiniappStorageBackend = {
get(key: string): unknown | null {
const result = mmkvStorage.load<unknown>(key)
return result.is_ok() ? result.value : null
},
has(key: string): boolean {
return mmkvStorage.load<unknown>(key).is_ok()
},
set(key: string, value: unknown): void {
mmkvStorage.save(key, value)
},
remove(key: string): void {
mmkvStorage.remove(key)
},
keys(): string[] {
return mmkvStorage.getAllKeys()
},
}
configureMiniappDataPartitions({
getSession: () => miniappDataSessionOf(cloudClientService.getCoreSession(), cloudClientService.getDeploymentUserId()),
assignedWorkspace: (packageName, session) => {
const assignment = appRegistry.getMiniappAssignment(packageName)
return assignment &&
assignment.mentraUserId === session.mentraUserId &&
sameCoreUrl(assignment.coreUrl, session.coreUrl)
? assignment.workspaceId
: null
},
})
// =============================================================================
// Declared-permission record helper (for CONNECT_ACK / PERMISSIONS_UPDATE)
// =============================================================================
/**
* Map from manifest permission types (uppercase, snake-y) to the lowercase
* canonical permission keys the SDK exposes via session.permissions. Mirrors
* cloud SDK v3's PermissionType union.
*
* BACKGROUND_LOCATION + POST_NOTIFICATIONS aren't in v3's surface; they map
* onto the same canonical keys (location / notifications) since the SDK's
* `has()` is "do I have *any* form of this permission declared".
*/
const PERMISSION_TYPE_TO_CANONICAL: Record<string, string> = {
MICROPHONE: "microphone",
CAMERA: "camera",
LOCATION: "location",
BACKGROUND_LOCATION: "location",
READ_NOTIFICATIONS: "notifications",
POST_NOTIFICATIONS: "notifications",
CALENDAR: "calendar",
}
function normalizeRgbLedAction(value: unknown): RgbLedAction {
return typeof value === "string" && RGB_LED_ACTIONS.has(value as RgbLedAction) ? (value as RgbLedAction) : "off"
}
function normalizeRgbLedColor(value: unknown): RgbLedColor | null {
return typeof value === "string" && RGB_LED_COLORS.has(value as RgbLedColor) ? (value as RgbLedColor) : null
}
function normalizeCameraFovPayload(payload: Record<string, unknown>): CameraFovRequest {
if (typeof payload.preset === "string") {
const preset = payload.preset in CAMERA_FOV_PRESETS ? (payload.preset as CameraFovPreset) : "standard"
return {preset}
}
const rawFov = typeof payload.fov === "number" && Number.isFinite(payload.fov) ? payload.fov : CAMERA_FOV_DEFAULT
return {
fov: Math.min(CAMERA_FOV_MAX, Math.max(CAMERA_FOV_MIN, rawFov)),
roiPosition: normalizeCameraRoiPosition(payload.roiPosition ?? payload.roi_position),
}
}
function normalizeCameraRoiPosition(value: unknown): CameraRoiPosition {
if (typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= 2) {
return value === 1 ? "bottom" : value === 2 ? "top" : "center"
}
if (typeof value === "string") {
return CAMERA_ROI_POSITION_BY_NAME[value] ?? "center"
}
return "center"
}
const ALL_CANONICAL_PERMISSIONS = ["location", "microphone", "camera", "notifications", "calendar"] as const
/**
* Build the {location, microphone, camera, notifications, calendar} record the
* SDK's session.permissions module reads from. Missing types are false.
*/
function computeDeclaredPermissionRecord(manifest: InstalledMiniappManifest | undefined): Record<string, boolean> {
const record: Record<string, boolean> = {}
for (const k of ALL_CANONICAL_PERMISSIONS) record[k] = false
for (const perm of manifest?.permissions ?? []) {
const canonical = PERMISSION_TYPE_TO_CANONICAL[perm.type?.toUpperCase()]
if (canonical) record[canonical] = true
}
return record
}
// =============================================================================
// PERMISSION_NOT_DECLARED warnings — per-session dedup
// =============================================================================
//
// When a miniapp tries to subscribe / call something whose required permission
// isn't declared in miniapp.json, the runtime rejects with
// PERMISSION_NOT_DECLARED. The error reaches the SDK but most authors don't
// subscribe to session.on("error", ...), so it's silent in practice.
//
// To make the failure discoverable for developers running the MentraOS app
// from source, log a clear, copy-pasteable message in the phone console that
// names the offending permission, the offending stream/op, and the JSON
// snippet to add to miniapp.json. Once-per-session per (packageName, permission)
// to avoid spam from a tight retry loop.
//
// Production users running the App Store build of MentraOS won't see these
// (they don't watch Metro/adb logcat). For them, the WebView console bridge
// (#5 of the quick-fixes round) ships the structured error to the miniapp
// itself, and the miniapp's own console.warn flows to the dev terminal.
const warnedPermission = new Set<string>() // key: `${packageName}::${permission}`
function logPermissionNotDeclared(
packageName: string,
permission: string,
context: string,
manifestSnippet: string,
): void {
const key = `${packageName}::${permission}`
if (warnedPermission.has(key)) return
warnedPermission.add(key)
console.warn(
`${LOG_TAG}: ${packageName} attempted ${context}, but permission ${permission} is not declared in miniapp.json.\n` +
`Add this to the "permissions" array:\n ${manifestSnippet}`,
)
}
/** Reset the per-session dedup; called when a miniapp unregisters so a fresh launch warns again. */
function resetPermissionWarnings(packageName: string): void {
for (const key of warnedPermission) {
if (key.startsWith(`${packageName}::`)) warnedPermission.delete(key)
}
}
/**
* One attempt to start a SoftAP call, from the first permission check to the last release.
*
* The unit is the attempt rather than the transport because the transport only exists for the
* second half of it. Everything the wearer can cancel — the Nearby-devices prompt, the wait for
* mobile data, the ACS sign-in — happens before `transport.start()`, and each of those leaves
* something behind (a signed-in agent, a process-wide cellular pin) that only the attempt knows
* about.
*/
type SoftapAttempt = {
id: number
packageName: string
startedAt: number
/** Set by leave, end, or a superseding join. Checked after every await the join performs. */
cancelled: boolean
/** Set only after the preceding attempt has fully settled. */
releaseHotspot?: () => void
ownsResources: boolean
transport: SoftapCallTransport | null
/** The checklist as the miniapp last saw it; preflight rows live here until `start()` takes over. */
progress: SoftapProgress
scopedLostUnsub: (() => void) | null
/**
* Mid-call media rebuild. Single-flight while [recoveryActive] is true; the promise is
* cleared when that run settles so a later walk-away can start another. Joined to the
* attempt barrier so a late re-arm cannot resurrect resources after Leave/End.
*/
recovery: Promise<void> | null
recoveryActive: boolean
recoveryDeadlineAt: number | null
/**
* The join itself, settled either way. A native call still in flight owns state the teardown
* cannot see — a `createCallAgent` mid-sign-in — so the barrier covers this as well.
*/
body: Promise<void> | null
/** Single-flight teardown, so a leave and the join's own failure path cannot both unwind. */
teardown: Promise<void> | null
/** Opens only once the attempt *and* its cleanup are finished. The next join waits on it. */
settled: Promise<void>
settledDone: boolean
markSettled: () => void
}
/** How long a stalled SoftAP cleanup goes unremarked before it is logged. It is never abandoned. */
const SOFTAP_CLEANUP_STALL_LOG_MS = 10_000
/**
* The WHIP listener's tombstone (3s) plus a margin for the close itself.
*
* Sized to the grace period rather than picked round, so an expiry here means something actually
* went wrong instead of meaning we guessed short.
*/
const SOFTAP_INGEST_CLOSE_WAIT_MS = 3_500
/** How long the glasses get to acknowledge their hotspot off, over BLE. */
const SOFTAP_HOTSPOT_OFF_ACK_MS = 5_000
/** After a forced close there is nothing left to wait for, so this only catches a real failure. */
const SOFTAP_FORCED_VERIFY_MS = 500
/**
* Rejection codes meaning the glasses replaced their Wi-Fi protocol session, not that the
* command failed.
*
* The glasses emit `wifi_protocol_session_ready` on every `glasses_ready`, which fires on BLE
* reconnects and ASG restarts — routine during a SoftAP teardown. The SDK cancels every pending
* Wi-Fi request when that lands, so a hotspot command in flight is lost even though nothing is
* actually wrong. `wifi_session_disconnected` is deliberately absent: that one is raised from the
* store update where the glasses went away, so there is nothing left to re-send to.
*/
const HOTSPOT_SESSION_REFRESH_CODES = new Set(["wifi_session_restarted", "wifi_session_changed"])
/**
* Let the restarted ASG command path settle before re-sending.
*
* `handleSetHotspotState` returns false when its network manager is not up yet, which drops the
* command silently, so an immediate re-send would just race the same initialization. Mirrors the
* retry spacing `disableHotspotWithRetry` uses for the sibling ASG-replacement case.
*/
const HOTSPOT_SESSION_RETRY_DELAY_MS = 500
/** Reject with [reason] if [work] has not settled in [ms]. The work itself is not cancellable. */
function withTimeout<T>(work: Promise<T>, ms: number, reason: string): Promise<T> {
return new Promise<T>((resolve, reject) => {
const timer = setTimeout(() => reject(new Error(reason)), ms)
work.then(
(value) => {
clearTimeout(timer)
resolve(value)
},
(error) => {
clearTimeout(timer)
reject(error)
},
)
})
}
/** How long the next call waits for the previous one's cleanup before telling the wearer about it. */
const SOFTAP_CLEANUP_NARRATE_AFTER_MS = 250
// =============================================================================
// LocalMiniappRuntime
// =============================================================================
class LocalMiniappRuntime {
private static instance: LocalMiniappRuntime | null = null
/**
* The SoftAP call being started or running, if any.
*
* An *attempt*, not a transport, because the cancellable part of a SoftAP call begins long
* before the transport exists: a Nearby-devices prompt and an ACS sign-in run first, and a
* wearer who taps Cancel during either of them has to be obeyed. The attempt is registered
* before the first `await` and is what every later stage checks itself against.
*/
private softapAttempt: SoftapAttempt | null = null
/**
* The outer generation. Every async callback that can outlive an attempt checks itself against
* it and traces `softap_stale_callback` when it loses: ACS state, SoftAP progress, glasses
* stream status, scoped-network loss, and each checkpoint through the join.
*
* There are inner generations below this one — `AcsMeetingSession.joinGeneration` and
* `LocalWhipIngestSource.generation` — and they are not redundant. They fence work inside one
* native session against itself; this one fences whole attempts against each other, and only it
* knows that the wearer pressed Cancel before any of that native work existed.
*/
private softapAttemptSeq = 0
/**
* Why the previous SoftAP call's cleanup failed, if it did.
*
* Read once by the next join, which refuses rather than building on leaked state: a hotspot that
* would not turn off is precisely what makes the next call fail somewhere far less legible.
*/
private softapCleanupError: string | null = null
/**
* SoftAP teardown disables the glasses hotspot from the transport and again
* from the host barrier. Native used to throw `request_in_flight` on the
* second call, which was recorded as a cleanup failure and refused the next
* join. One queue so those overlapping disables wait their turn.
*/
private glassesHotspotCommand: Promise<unknown> = Promise.resolve()
/** Connected miniapps keyed by packageName. */
private connectedApps: Map<string, ConnectedMiniapp> = new Map()
/**
* Packages that have completed their CONNECT handshake (sent
* `miniapp_connect`, got `CONNECT_ACK`). Distinct from `connectedApps`,
* which is populated at spawn/registration time — handshake is later.
* Drives {@link waitForConnect}.
*/
private handshookApps: Set<string> = new Set()
/** Pending {@link waitForConnect} resolvers, keyed by packageName. */
private connectWaiters: Map<string, Set<(err?: Error) => void>> = new Map()
/** Ref-counted stream subscriptions: stream → set of packageNames. */
private streamSubscribers: Map<string, Set<string>> = new Map()
/** Host observers for the Mentra Live button-capture policy. */
private buttonPressSubscriberListeners = new Set<(packageNames: string[]) => void>()
/** Guards one-time wiring of the cloud transcript/translation fan-out. */
private cloudResultsWired = false
private cloudStatusWired = false
private cloudAudioSubscriptionSync = new CloudAudioSubscriptionSync()
/**
* Per-miniapp language hints from TRANSCRIPTION_CONFIG (issue 021 WP3).
* Bare ISO 639-1 codes, already registry-validated by the SDK and
* re-normalized here (defense in depth). Merged (union) into the auto-mode
* cloud transcription subscription in buildCloudAudioSubscriptions.
*/
private transcriptionHintsByApp = new Map<string, string[]>()
/**
* Microphone sessions taken through session.mic.acquire, by session id.
*
* Bookkeeping only, so a release can be matched to its owner; MicSessionManager holds the real
* leases and resolves them into hardware state.
*/
private micSessionsByApp = new Map<number, {packageName: string; session: MicSession}>()
/** Ping interval handle. */
private pingIntervalId: number | null = null
private foregroundProbeTimers: Map<string, number> = new Map()
/**
* Notified when a miniapp is unregistered for missing liveness pings.
* MentraJSRouter wires this into its crash-respawn machinery so a
* silently-stalled background script is restarted (with crash-loop
* protection) instead of staying dead — a dead background drops its
* subscriptions, which releases the mic while the webview still looks
* alive.
*/
public onLivenessTimeout: ((packageName: string) => void) | null = null
private speechRuns = new Map<string, SpeechRun>()
private runtimeSeq = 0
private authSessionSeq = 0
// Browser fallback token auth — HMAC-signed blob with a phone-local
// secret. Both issuer and verifier are the same process, so the
// secret never leaves the device.
private localSecret = `miniapp_${Date.now()}_${Math.random().toString(36).slice(2, 14)}`
private usedTokens = new Set<string>()
private constructor() {}
private readonly transientActionWakes = new TransientActionWakeCoordinator({
isContextRunning: (packageName) => miniappLauncher.isRunning(packageName),
isProjectedRunning: (packageName) => miniappLauncher.isProjectedRunning(packageName),
ensureConnectedHidden: (packageName) =>
miniappLauncher.ensureConnected(packageName, 10_000, undefined, {projectRunning: false}),
stopContext: (packageName) => miniappLauncher.stop(packageName),
})
/** Snapshot of miniapps actively subscribed to hardware button events. */
public getButtonPressSubscribers(): string[] {
return [...(this.streamSubscribers.get(MiniappStreamType.BUTTON_PRESS) ?? [])].sort()
}
/** Observe active hardware-button subscriptions. */
public onButtonPressSubscribersChanged(listener: (packageNames: string[]) => void): () => void {
this.buttonPressSubscriberListeners.add(listener)
return () => this.buttonPressSubscriberListeners.delete(listener)
}
/** Report-safe live miniapp/subscription/resource snapshot. */
public getDiagnosticSnapshot(nowMs = Date.now()): MiniappRuntimeDiagnosticSnapshot {
const connectedApps = [...this.connectedApps.entries()]
.sort(([a], [b]) => a.localeCompare(b))
.slice(0, DIAGNOSTIC_MAX_LIST_ITEMS)
.map(([packageName, app]) => ({
packageName: packageName.slice(0, DIAGNOSTIC_MAX_STRING_LENGTH),
handshakeComplete: this.handshookApps.has(packageName),
subscriptions: diagnosticStringList(app.subscriptions),
lastMessageAgeMs: Math.max(0, nowMs - app.lastPongAt),
requestedLocationRate: app.requestedLocationRate,
hasActiveSpeakerStream: app.activeSpeakerStreamId !== undefined,
...(app.installedManifest
? {
manifest: buildMiniappManifestSnapshot(app.installedManifest, {
packageName,
name: app.installedManifest.name,
version: app.installedManifest.version,
type: app.installedManifest.type,
}),
}
: {}),
}))
const subscriptionsByStream = Object.fromEntries(
[...this.streamSubscribers.entries()]
.filter(([, packageNames]) => packageNames.size > 0)
.sort(([a], [b]) => a.localeCompare(b))
.slice(0, DIAGNOSTIC_MAX_LIST_ITEMS)
.map(([stream, packageNames]) => [
stream.slice(0, DIAGNOSTIC_MAX_STRING_LENGTH),
diagnosticStringList(packageNames),
]),
)
return {
connectedApps,
subscriptionsByStream,
resources: {
display: localDisplayManager.getDiagnosticSnapshot(),
camera: phonePhotoCoordinator.getDiagnosticSnapshot(),
video: phoneVideoCoordinator.getDiagnosticSnapshot(),
stream: phoneStreamCoordinator.getDiagnosticSnapshot(),
cameraFov: phoneCameraFovCoordinator.getDiagnosticSnapshot(),
},
}
}
private replaceStreamSubscribers(
packageName: string,
previousStreams: Iterable<string>,
nextStreams: Iterable<string>,
) {
const previousButtonSubscribers = this.getButtonPressSubscribers().join("\u0000")
for (const stream of previousStreams) {
const subscribers = this.streamSubscribers.get(stream)
if (!subscribers) continue
subscribers.delete(packageName)
if (subscribers.size === 0) this.streamSubscribers.delete(stream)
}
for (const stream of nextStreams) {
let subscribers = this.streamSubscribers.get(stream)
if (!subscribers) {
subscribers = new Set()
this.streamSubscribers.set(stream, subscribers)
}
subscribers.add(packageName)
}
const nextButtonSubscribers = this.getButtonPressSubscribers()
if (previousButtonSubscribers !== nextButtonSubscribers.join("\u0000")) {
for (const listener of this.buttonPressSubscriberListeners) {
try {
listener(nextButtonSubscribers)
} catch (error) {
console.warn(`${LOG_TAG}: button press subscriber listener threw:`, error)
}
}
}
}
/**
* Generate an HMAC-signed local session token for browser fallback auth.
* Token format: base64(JSON({userId, packageName, exp})).base64(HMAC-SHA256(payload, secret))
* Single-use, 5-minute TTL.
*/
public generateLocalToken(userId: string, packageName: string): string {
const payload = JSON.stringify({
userId,
packageName,
exp: Date.now() + 5 * 60 * 1000, // 5 min TTL
nonce: Math.random().toString(36).slice(2, 10),
})
const payloadB64 = btoa(payload)
const sig = this.hmacSign(payload)
return `${payloadB64}.${sig}`
}
/**
* Validate and consume a local session token. Single-use.
*/
public validateLocalToken(token: string): {userId: string; packageName: string} | null {
const parts = token.split(".")
if (parts.length !== 2) return null
const [payloadB64, sig] = parts
// Check single-use
if (this.usedTokens.has(token)) return null
// Verify signature
let payload: string
try {
payload = atob(payloadB64!)
} catch {
return null
}
if (this.hmacSign(payload) !== sig) return null
// Parse and check expiry
let parsed: {userId: string; packageName: string; exp: number}
try {
parsed = JSON.parse(payload)
} catch {
return null
}
if (Date.now() > parsed.exp) return null
// Mark as used
this.usedTokens.add(token)
// Prune old used tokens periodically (keep set from growing unbounded)
if (this.usedTokens.size > 1000) {
this.usedTokens.clear()
}
return {userId: parsed.userId, packageName: parsed.packageName}
}
/**
* Simple HMAC-SHA256 using Web Crypto API (available in React Native).
* Returns base64url-encoded signature.
* Falls back to a simpler hash if crypto.subtle is not available.
*/
private hmacSign(payload: string): string {
// Synchronous HMAC using a simple hash — Web Crypto's subtle.sign is async
// which doesn't fit cleanly here. For phone-local single-process auth,
// a keyed hash is sufficient.
let hash = 0
const key = this.localSecret
const input = key + payload + key
for (let i = 0; i < input.length; i++) {
const ch = input.charCodeAt(i)
hash = ((hash << 5) - hash + ch) | 0
}
// Mix in more bytes for collision resistance
let hash2 = 0x811c9dc5 // FNV offset basis
for (let i = 0; i < input.length; i++) {
hash2 ^= input.charCodeAt(i)
hash2 = Math.imul(hash2, 0x01000193) // FNV prime
}
return btoa(String(hash >>> 0) + "." + String(hash2 >>> 0))
}
public static getInstance(): LocalMiniappRuntime {
if (!LocalMiniappRuntime.instance) {
LocalMiniappRuntime.instance = new LocalMiniappRuntime()
}
return LocalMiniappRuntime.instance
}
private initialized = false
private visiblePackage: string | null = null
private visibilityUnsubscribe: (() => void) | null = null
private appStateSubscription: ReturnType<typeof AppState.addEventListener> | null = null
/**
* Initialize the runtime. Called from MantleManager.init().
* Idempotent — safe to call multiple times.
*/
public initialize(): void {
if (this.initialized) return
this.initialized = true
console.log(`${LOG_TAG}: initialize()`)
this.visiblePackage = this.currentVisiblePackage()
this.visibilityUnsubscribe = useAppStatusStore.subscribe(() => this.updateVisibility())
this.appStateSubscription = AppState.addEventListener("change", () => this.updateVisibility())
this.ensurePingLoop()
// Native background tasks can survive a previous JS runtime. Reconcile even
// when no miniapps register and the previous aggregate was already off.
this.lastAppliedLocationRate = null
this.recomputeLocationTier()
}
private currentVisiblePackage(): string | null {
return visibleMiniappPackage()
}
private updateVisibility(): void {
const next = this.currentVisiblePackage()
if (next === this.visiblePackage) return
const previous = this.visiblePackage
this.visiblePackage = next
// UI_OPEN also fires during periodic foreground resync. Only the authoritative
// selection/host-activity edge should trigger a miniapp's foreground redraw.
if (previous && this.handshookApps.has(previous)) this.sendVisibilityChange(previous, "background")
if (next && this.handshookApps.has(next)) {
this.sendVisibilityChange(next, "foreground")
// Coming back to the foreground is an open: the miniapp gets a token minted now, so what the user
// acquired while it was away (a purchase) is in the token it uses next. A miniapp still waiting for its
// first token already has a fresh mint on the way (CONNECT's, or its retry), so it is left to that.
if (this.connectedApps.get(next)?.authDelivered) {
void this.refreshMiniappAuth(next, {fresh: true}).catch((err) => {
console.warn(`${LOG_TAG}: miniapp auth refresh failed for ${next}: ${(err as Error)?.message ?? err}`)
})
}
}
}
// ===========================================================================
// App registration
// ===========================================================================
/** The installed version of a connected miniapp, for Fleet's records; undefined when it is not known. */
public installedVersionOf(packageName: string): string | undefined {
return this.connectedApps.get(packageName)?.installedManifest?.version || undefined
}
public registerApp(
packageName: string,
sendFn: (raw: string) => void,
installedManifest?: InstalledMiniappManifest,
hostTrustedSystem = false,
userVisible = true,
): void {
console.log(`${LOG_TAG}: registerApp(${packageName})`)
this.clearForegroundProbe(packageName)
// Fresh spawn → fresh handshake. Clear any prior handshake flag so
// waitForConnect() blocks until this context's own CONNECT arrives.
this.handshookApps.delete(packageName)
// If the app is already registered (e.g. QR scanned again for same package),
// tear down its old subscriptions first so streamSubscribers doesn't keep
// dangling references. The WebView will re-subscribe after its CONNECT.
if (this.connectedApps.has(packageName)) {
const existing = this.connectedApps.get(packageName)!
this.cancelSpeech(packageName)
// A crash respawn replaces the ConnectedMiniapp without going through
// unregisterApp(). Abort the old incarnation's native PCM player before
// its only stream id is lost. Target the exact stream rather than using
// stopForApp(), whose async playback cleanup could race with audio the
// replacement app starts after it connects.
const existingSpeakerStreamId = existing.activeSpeakerStreamId
if (existingSpeakerStreamId) {
existing.activeSpeakerStreamId = undefined
void audioPlaybackService.abortStream(existingSpeakerStreamId).catch((error) => {
console.warn(`${LOG_TAG}: failed to abort speaker stream while replacing ${packageName}`, error)
})
}
if (existing.authRefreshTimerId !== null) {
BgTimer.clearTimeout(existing.authRefreshTimerId)
existing.authRefreshTimerId = null
}
if (existing.authRetryTimerId !== null) {
BgTimer.clearTimeout(existing.authRetryTimerId)
existing.authRetryTimerId = null
}
this.replaceStreamSubscribers(packageName, existing.subscriptions, [])
this.recomputeMicRequirements()
this.updateCloudSubscriptions()
// Managed streams and ACS meetings deliberately survive a respawn: the new
// incarnation re-adopts them on restore (Mentra Call does exactly this) so a
// WebView reload does not drop the wearer out of a live call. An unmanaged
// stream cannot be re-adopted — startUnmanaged rejects while any stream is
// active, even for the same owner — so release it or the respawned miniapp
// is stuck behind STREAM_ALREADY_ACTIVE until the process restarts.
// Unlike a managed stream, a preview lease is bound to the runtime that took it and is not
// re-adopted: the respawned background asks again.
getStreamPreviewHost()?.releaseRuntime(packageName, existing.runtimeId, "runtime_replaced")
const streamSnapshot = phoneStreamCoordinator.getDiagnosticSnapshot()
if (
streamSnapshot.active === true &&
streamSnapshot.kind === "unmanaged" &&
streamSnapshot.ownerPackageName === packageName
) {
void phoneStreamCoordinator.stop(packageName).catch((error) => {
console.warn(`${LOG_TAG}: failed to stop unmanaged stream while replacing ${packageName}`, error)
})
}
}
this.connectedApps.set(packageName, {
subscriptions: new Set(),
transcriptionListeners: new TranscriptionSubscriptions(),
sendMessage: sendFn,
lastPongAt: Date.now(),
unansweredPingRounds: 0,
installedManifest,
hostTrustedSystem,
authRefreshTimerId: null,
authRetryTimerId: null,
authDelivered: false,
authSession: 0,
authRequestPending: false,
speakerState: "idle",
requestedLocationRate: null,
runtimeId: `rt-${++this.runtimeSeq}`,
})
// If we just clobbered an existing entry, its requestedLocationRate is
// now gone — recompute so the aggregate doesn't include a stale rate.
// The WebView will re-SUBSCRIBE shortly and the rate will reappear.
this.recomputeLocationTier()
this.ensureCloudStatusWired()
this.ensurePingLoop()
// Show the system boot message ("Starting <name>…") on the glasses for the
// bounded boot window, mirroring the cloud DisplayManager boot screen. The
// window ends early once this app pushes its first display (see
// LocalDisplayManager.request), or after ~1.5s. Fires once per spawn —
// including a crash-respawn, since each spawn is a fresh "app is starting".
// An invisible transient action wake is not the app starting for the user.
if (userVisible) localDisplayManager.onMount(packageName, installedManifest?.name ?? packageName)
}
/** A transiently woken context became normal user-visible activity. */
public onUserActivated(packageName: string): void {
const app = this.connectedApps.get(packageName)
if (!app) return
localDisplayManager.onMount(packageName, app.installedManifest?.name ?? packageName)
}
/**
* Resolve once `packageName` has completed its CONNECT handshake. If it has
* already connected, resolves immediately. Rejects if the timeout elapses
* first, or if the app is unregistered while waiting.
*
* Used by the launcher's `ensureConnected` (and thus the action broker) so a
* just-spawned target is known to be live before anything is delivered to it.
*/
public waitForConnect(packageName: string, timeoutMs: number): Promise<void> {
if (this.handshookApps.has(packageName)) return Promise.resolve()
return new Promise<void>((resolve, reject) => {
let settled = false
const waiter = (err?: Error) => {
if (settled) return
settled = true
clearTimeout(timer)
this.connectWaiters.get(packageName)?.delete(waiter)
if (err) reject(err)
else resolve()
}
const timer = setTimeout(() => {
waiter(new Error(`waitForConnect: ${packageName} did not connect within ${timeoutMs}ms`))
}, timeoutMs)
let set = this.connectWaiters.get(packageName)
if (!set) {
set = new Set()
this.connectWaiters.set(packageName, set)
}
set.add(waiter)
})
}
/** Resolve/reject all pending {@link waitForConnect} waiters for a package. */
private flushConnectWaiters(packageName: string, err?: Error): void {
const waiters = this.connectWaiters.get(packageName)
if (!waiters) return
this.connectWaiters.delete(packageName)
for (const w of waiters) w(err)
}
/**
* Invalidate the CONNECT handshake for a package whose native context is
* being replaced WITHOUT going through register/unregister — i.e. a crash
* respawn. Without this, {@link waitForConnect} would treat the dead/
* not-yet-initialized context as connected and deliver to it. Pending waiters
* are failed so a wake mid-respawn retries rather than hanging.
*/
public resetHandshake(packageName: string): void {
this.handshookApps.delete(packageName)
this.flushConnectWaiters(packageName, new Error(`${packageName} respawning`))
}
/**
* Attach (or update) the installedManifest for an already-registered app.
* Used when the manifest is fetched asynchronously (dev miniapps) after the
* miniapp has already CONNECTed — preserves existing subscriptions.
*/
public setInstalledManifest(packageName: string, installedManifest: InstalledMiniappManifest): void {
const app = this.connectedApps.get(packageName)
if (!app) return
app.installedManifest = installedManifest
// Push declared-permission record to the SDK so session.permissions stays
// in sync. Sent regardless of CONNECT_ACK timing — covers the dev-miniapp
// case where the manifest is fetched async after the miniapp CONNECTs.
this.sendToMiniapp(packageName, {
type: MiniappResponseType.PERMISSIONS_UPDATE,
permissions: computeDeclaredPermissionRecord(installedManifest),
})
}
/**
* Graceful version of {@link unregisterApp}: notify the miniapp via
* `WILL_DISCONNECT`, wait ~50ms so its `beforeDisconnect` handlers can
* fire one last `sendOneShot` (e.g. `display.clear()`), then run the
* normal teardown. Use this for any disconnect path where the socket
* is still open. For ungraceful paths (transport already closed),
* call {@link unregisterApp} directly — the heads-up would be
* undeliverable anyway.
*/
public async gracefullyUnregisterApp(packageName: string, reason = "unregistering"): Promise<void> {
const app = this.connectedApps.get(packageName)
if (!app) return
console.log(`${LOG_TAG}: gracefullyUnregisterApp(${packageName}) — sending WILL_DISCONNECT`)
this.sendToMiniapp(packageName, {
type: MiniappResponseType.WILL_DISCONNECT,
reason,
})
// 50 ms: imperceptible to the user, plenty of time for the SDK's
// synchronous `beforeDisconnect` handlers to flush a final
// sendOneShot through the still-open transport.
await new Promise<void>((resolve) => setTimeout(resolve, 50))
this.unregisterApp(packageName)
}
public unregisterApp(packageName: string): void {
console.log(`${LOG_TAG}: unregisterApp(${packageName})`)
this.clearActionState(packageName)
const releasedMicGateOverride = micStateCoordinator.clearMiniappGateOverrides(packageName)
// Backstop for a miniapp that crashed or was killed mid-call: the microphone profile and the
// PCM claim must not outlive the app that asked for them.
this.forgetMicSessions(packageName)
micSessionManager.releaseOwner(packageName)
this.clearForegroundProbe(packageName)
this.clearMiniappAuthRefresh(packageName)
this.clearMiniappAuthDeliveryRetry(packageName)
// Drop the handshake flag and fail any in-flight waitForConnect() callers
// (e.g. a wake that's mid-handshake when the app is torn down). Done before
// the early-return so it runs even if the connectedApps entry is already gone.
this.handshookApps.delete(packageName)
this.flushConnectWaiters(packageName, new Error(`${packageName} unregistered before connect`))
// Drop this app's transcription hints; the cloud subscription rebuild
// below (via replaceStreamSubscribers) re-derives the hint union without it.
this.transcriptionHintsByApp.delete(packageName)
// Warm-up is a request-owned camera lease. Cancel it even if the app record was already
// removed so a close racing the camera-open promise cannot leave the sensor running.
// Close all camera consumers before restoring FOV. A shared publisher may
// remain active for another subscriber; a rejected FOV release then stops
// renewing the departed owner's lease and ASG restores it once idle.
const cameraCleanup = Promise.allSettled([
this.leaveMeetingForApp(packageName),
phonePhotoCoordinator.stopWarmUpForApp(packageName),
phoneStreamCoordinator.stop(packageName),
phoneVideoCoordinator.stopForApp(packageName),
]).then((results) => {
for (const result of results) {
if (result.status === "rejected") {
console.warn(`${LOG_TAG}: failed to stop miniapp resource for ${packageName} on unregister`, result.reason)
}
}
})
void phoneCameraFovCoordinator.releaseForApp(packageName, cameraCleanup).catch((error) => {
console.warn(`${LOG_TAG}: failed to release camera FOV override for ${packageName} on unregister`, error)
})
const app = this.connectedApps.get(packageName)
if (!app) {
if (releasedMicGateOverride) {
void micStateCoordinator.syncEffectiveGatePolicy(this.getConfiguredMicGates()).catch((error) => {
console.warn(`${LOG_TAG}: failed to restore mic gate policy for ${packageName}`, error)
})
}
return
}
getStreamPreviewHost()?.releaseRuntime(packageName, app.runtimeId, "runtime_stopped")
// Remove from all stream subscriber sets
this.replaceStreamSubscribers(packageName, app.subscriptions, [])
// Reset per-session warning dedup so a relaunch surfaces issues again.
resetPermissionWarnings(packageName)
// Cancel lookahead/in-flight synthesis before stopping the current file so
// an interrupted sentence cannot advance and reclaim playback.
this.cancelSpeech(packageName)
// Stop audio for this app, including a prewarmed stream that never played.
audioPlaybackService.stopForApp(packageName, {includeUnstarted: true})
// Tear down this app's blob state: abort in-flight uploads + close readers
// so a crashed/closed miniapp doesn't leak partial files or file handles.
this.blobStore.onAppGone(packageName)
// Release native navigation and its GPS request when the miniapp stops.
this.navigationHandlers.onDisconnect(packageName)
// Recompute heading subscription — if this app was the last subscriber,
// the sensor will stop.
this.recomputeHeadingSubscription()
// Same for the IMU/accelerometer stream.
this.recomputeImuSubscription()
// Drop this app's location-tier request before recomputing so the
// aggregate falls back down if it was the strictest. Done before
// `connectedApps.delete` below so it doesn't matter that the iter
// in `recomputeLocationTier` is over connectedApps — clearing the
// field is enough.
app.requestedLocationRate = null
this.recomputeLocationTier()
// Release any display real estate this app held — if it owned the
// current on-glasses frame, this clears the glasses (or restores the
// core app's saved frame).
localDisplayManager.onUnmount(packageName)
this.connectedApps.delete(packageName)
this.recomputeMicRequirements()
if (releasedMicGateOverride) {
void micStateCoordinator.syncEffectiveGatePolicy(this.getConfiguredMicGates()).catch((error) => {
console.warn(`${LOG_TAG}: failed to restore mic gate policy for ${packageName}`, error)
})
}
this.updateCloudSubscriptions()
if (this.connectedApps.size === 0) {
this.stopPingLoop()
}
}
// ===========================================================================
// Inbound message handling
// ===========================================================================
public handleRawMessage(packageName: string, raw: string): void {
const envelope = parseEnvelope(raw)
if (!envelope) {
// Not a miniapp envelope — ignore (could be legacy bridge message)
return
}
const payload = envelope.payload as Record<string, unknown>
const requestType = payload.type as string | undefined
const requestId = envelope.requestId
if (!requestType) {
console.warn(`${LOG_TAG}: Envelope from ${packageName} missing payload.type`)
return
}
// ANY inbound message proves the context is alive — a busy background
// script streaming DISPLAY/storage traffic shouldn't be killed by the
// liveness watchdog just because its PONG replies queue behind real work.
this.handlePong(packageName)
// Console-tap forwarding. The miniapp's console.log/warn/etc is wrapped
// (via injected shim from miniappGlobals.ts) to post a `dev_log`
// envelope. We fan out to two destinations:
// 1. DevServerBridge — forwards to the laptop's `mentra-miniapp dev`
// terminal. No-op when there's no sidecar (installed miniapps).
// 2. React Native console — surfaces the log in Metro / Xcode console
// / adb logcat so installed-miniapp errors are still inspectable
// when there's no laptop to forward to.
if (requestType === "dev_log") {
const level = (payload.level as string | undefined) ?? "log"
const args = Array.isArray(payload.args) ? (payload.args as unknown[]) : []
const timestamp = (payload.timestamp as number | undefined) ?? Date.now()
// Source is "ui" because the single-bundle WebView console-tap
// shim in miniappGlobals.ts is the only thing that posts
// `dev_log`; the two-layer path uses a separate envelope
// (`{type:"log", source}`) routed by MentraUIRouter.
devServerBridge.forwardLog(packageName, level, args, timestamp, "ui")
const tag = `[MINIAPP ${packageName}]`
const fn = (console as unknown as Record<string, (...a: unknown[]) => void>)[level] ?? console.log
try {
fn(tag, ...args)
} catch {
console.log(tag, ...args)
}
return
}
// Dispatch
switch (requestType) {
case MiniappRequestType.CONNECT:
void this.handleConnect(packageName, payload, requestId)
break
case MiniappRequestType.AUTH_REFRESH:
void this.handleAuthRefresh(packageName, payload, requestId)
break
case MiniappRequestType.SUBSCRIBE:
this.handleSubscribe(packageName, payload, requestId)
break
case MiniappRequestType.DISPLAY:
this.handleDisplay(packageName, payload, requestId)
break
case MiniappRequestType.RENDER:
this.handleRender(packageName, payload, requestId)
break
case MiniappRequestType.PLAY_AUDIO:
this.handlePlayAudio(packageName, payload, requestId)
break
case MiniappRequestType.STOP_AUDIO:
this.handleStopAudio(packageName, payload, requestId)
break
case MiniappRequestType.SPEAK:
this.handleSpeak(packageName, payload, requestId)
break
case MiniappRequestType.SPEAKER_STREAM_OPEN:
void this.handleSpeakerStreamOpen(packageName, payload, requestId)
break
case MiniappRequestType.SPEAKER_STREAM_WRITE:
void this.handleSpeakerStreamWrite(packageName, payload, requestId)
break
case MiniappRequestType.SPEAKER_STREAM_CLOSE:
void this.handleSpeakerStreamClose(packageName, payload, requestId)
break
case MiniappRequestType.SPEAKER_STREAM_ABORT:
void this.handleSpeakerStreamAbort(packageName, payload, requestId)
break
case MiniappRequestType.RGB_LED:
void this.handleRgbLed(packageName, payload, requestId)
break
case MiniappRequestType.LOCATION_POLL:
this.handleLocationPoll(packageName, requestId)
break
case MiniappRequestType.CALENDAR_LIST_EVENTS:
void this.handleCalendarListEvents(packageName, payload, requestId)
break
case MiniappRequestType.NAVIGATION_START:
this.navigationHandlers.handleStart(packageName, payload, requestId)
break
case MiniappRequestType.NAVIGATION_STOP:
this.navigationHandlers.handleStop(packageName, requestId)
break
case MiniappRequestType.NAVIGATION_DEVIATE:
this.navigationHandlers.handleDeviate(packageName, payload, requestId)
break
case MiniappRequestType.NAVIGATION_SET_WRONG_SIDEWALK:
this.navigationHandlers.handleSetWrongSidewalk(packageName, payload, requestId)
break
case MiniappRequestType.NAVIGATION_SET_SKIP_CROSSINGS:
this.navigationHandlers.handleSetSkipCrossings(packageName, payload, requestId)
break
case MiniappRequestType.NAVIGATION_GET_STATE:
this.navigationHandlers.handleGetState(packageName, requestId)
break
case MiniappRequestType.NAVIGATION_COMPUTE_ROUTE:
this.navigationHandlers.handleComputeRoute(packageName, payload, requestId)
break
case MiniappRequestType.NAVIGATION_REVERSE_GEOCODE:
this.navigationHandlers.handleReverseGeocode(packageName, payload, requestId)
break
case MiniappRequestType.NAVIGATION_PLACE_AUTOCOMPLETE:
this.navigationHandlers.handlePlaceAutocomplete(packageName, payload, requestId)
break
case MiniappRequestType.NAVIGATION_PLACE_DETAILS:
this.navigationHandlers.handlePlaceDetails(packageName, payload, requestId)
break
case MiniappRequestType.NAVIGATION_REQUEST_PERMISSION:
this.navigationHandlers.handleRequestPermission(packageName, requestId)
break
case MiniappRequestType.STORAGE_GET:
this.handleStorageGet(packageName, payload, requestId)
break
case MiniappRequestType.STORAGE_SET:
this.handleStorageSet(packageName, payload, requestId)
break
case MiniappRequestType.STORAGE_DELETE:
this.handleStorageDelete(packageName, payload, requestId)
break
case MiniappRequestType.STORAGE_LIST:
this.handleStorageList(packageName, payload, requestId)
break
case MiniappRequestType.STORAGE_CLEAR:
this.handleStorageClear(packageName, requestId)
break
case MiniappRequestType.STORAGE_HAS:
this.handleStorageHas(packageName, payload, requestId)
break
case MiniappRequestType.STORAGE_GET_ALL:
this.handleStorageGetAll(packageName, requestId)
break
case MiniappRequestType.STORAGE_SET_MULTIPLE:
this.handleStorageSetMultiple(packageName, payload, requestId)
break
case MiniappRequestType.STORAGE_FLUSH:
// No-op today — MMKV writes through synchronously. Reserved so
// a future debounced backend can honor "flush before I quit"
// calls without breaking the API.
this.sendResult(packageName, requestId, true)
break
case MiniappRequestType.CAMERA_FOV:
void this.handleCameraFov(packageName, payload, requestId)
break
case MiniappRequestType.SET_WIFI_ADB_STATE:
void this.handleSetWifiAdbState(packageName, payload, requestId)
break
case MiniappRequestType.IMU_SET_ENABLED:
this.handleImuSetEnabled(packageName, payload, requestId)
break
case MiniappRequestType.MIC_SET_VAD_ENABLED:
void this.handleMicSetVadEnabled(packageName, payload, requestId)
break
case MiniappRequestType.MIC_SET_LOUDNESS_GATE_ENABLED:
void this.handleMicSetLoudnessGateEnabled(packageName, payload, requestId)
break
case MiniappRequestType.MIC_ACQUIRE:
this.handleMicAcquire(packageName, payload, requestId)
break
case MiniappRequestType.MIC_RELEASE:
this.handleMicRelease(packageName, payload, requestId)
break
case MiniappRequestType.PING:
// SDK should handle this itself; reply PONG just in case
this.sendToMiniapp(packageName, {type: MiniappResponseType.PONG}, requestId)
break
case MiniappResponseType.PONG: {
// Liveness already touched above for every inbound message; the
// PONG carries no other action.
break
}
case MiniappRequestType.SHARE:
void this.systemActions.handleShare(packageName, payload, requestId)
break
case MiniappRequestType.OPEN_URL:
void this.systemActions.handleOpenUrl(packageName, payload)
break
case MiniappRequestType.COPY_CLIPBOARD:
this.handleCopyClipboard(packageName, payload, requestId)
break
case MiniappRequestType.DOWNLOAD:
void this.systemActions.handleDownload(packageName, payload, requestId)
break
case MiniappRequestType.SCAN_QR:
void this.handleScanQr(packageName, payload, requestId)
break
// Persistent binary blob storage (session.blob)
case MiniappRequestType.BLOB_CREATE:
this.enqueueBlobRequest(packageName, requestId, () =>
this.blobStore.handleCreate(packageName, payload, requestId),
)
break
case MiniappRequestType.BLOB_WRITE:
this.enqueueBlobRequest(packageName, requestId, () =>
this.blobStore.handleWrite(packageName, payload, requestId),
)
break
case MiniappRequestType.BLOB_COMMIT:
this.enqueueBlobRequest(packageName, requestId, () =>
this.blobStore.handleCommit(packageName, payload, requestId),
)
break
case MiniappRequestType.BLOB_ABORT:
this.enqueueBlobRequest(packageName, requestId, () =>
this.blobStore.handleAbort(packageName, payload, requestId),
)
break
case MiniappRequestType.BLOB_SET_FROM_URL:
this.enqueueBlobRequest(packageName, requestId, () =>
this.blobStore.handleSetFromUrl(packageName, payload, requestId),
)
break
case MiniappRequestType.BLOB_IMPORT:
this.enqueueBlobRequest(packageName, requestId, () =>
this.blobStore.handleImport(packageName, payload, requestId),
)
break
case MiniappRequestType.BLOB_GET:
this.enqueueBlobRequest(packageName, requestId, () => this.blobStore.handleGet(packageName, payload, requestId))
break
case MiniappRequestType.BLOB_LIST:
this.enqueueBlobRequest(packageName, requestId, () =>
this.blobStore.handleList(packageName, payload, requestId),
)
break
case MiniappRequestType.BLOB_USAGE:
this.enqueueBlobRequest(packageName, requestId, () =>
this.blobStore.handleUsage(packageName, payload, requestId),
)
break
case MiniappRequestType.BLOB_DELETE:
this.enqueueBlobRequest(packageName, requestId, () =>
this.blobStore.handleDelete(packageName, payload, requestId),
)
break
case MiniappRequestType.BLOB_CLEAR:
this.enqueueBlobRequest(packageName, requestId, () =>
this.blobStore.handleClear(packageName, payload, requestId),
)
break
case MiniappRequestType.BLOB_OPEN_READ:
this.enqueueBlobRequest(packageName, requestId, () =>
this.blobStore.handleOpenRead(packageName, payload, requestId),
)
break
case MiniappRequestType.BLOB_READ:
this.enqueueBlobRequest(packageName, requestId, () =>
this.blobStore.handleRead(packageName, payload, requestId),
)
break
case MiniappRequestType.BLOB_CLOSE_READ:
this.enqueueBlobRequest(packageName, requestId, () =>
this.blobStore.handleCloseRead(packageName, payload, requestId),
)
break
case MiniappRequestType.BLOB_SHARE:
this.enqueueBlobRequest(packageName, requestId, () =>
this.blobStore.handleShare(packageName, payload, requestId),
)
break
// Cloud-coordinated features
case MiniappRequestType.PHOTO:
void this.handlePhoto(packageName, payload, requestId)
break
case MiniappRequestType.CAMERA_WARM_UP:
void this.handleCameraWarmUp(packageName, payload, requestId)
break
case MiniappRequestType.VIDEO_RECORDING_START:
void this.handleVideoRecordingStart(packageName, payload, requestId)
break
case MiniappRequestType.VIDEO_RECORDING_STOP:
void this.handleVideoRecordingStop(packageName, payload, requestId)
break
case MiniappRequestType.STREAM_START:
void this.handleStreamStart(packageName, payload, requestId)
break
case MiniappRequestType.STREAM_STOP:
void this.handleStreamStop(packageName, payload, requestId)
break
case MiniappRequestType.MANAGED_STREAM_START:
void this.handleManagedStreamStart(packageName, payload, requestId)
break
case MiniappRequestType.MANAGED_STREAM_STOP:
void this.handleManagedStreamStop(packageName, payload, requestId)
break
case MiniappRequestType.MEETING_GET_CONFIGURATION:
this.sendResult(packageName, requestId, true, meetingConfiguration())
break
case MiniappRequestType.MEETING_GET_IDENTITY:
void this.handleMeetingIdentity(packageName, requestId)
break
case MiniappRequestType.MEETING_CREATE:
void this.handleMeetingCreate(packageName, payload, requestId)
break
case MiniappRequestType.MEETING_RETIRE:
void this.handleMeetingRetire(packageName, payload, requestId)
break
case MiniappRequestType.STREAM_PREVIEW_START:
void this.handleStreamPreviewStart(packageName, payload, requestId)
break
case MiniappRequestType.STREAM_PREVIEW_STOP:
void this.handleStreamPreviewStop(packageName, payload, requestId)
break
case MiniappRequestType.MEETING_JOIN:
void this.handleMeetingJoin(packageName, payload, requestId)
break
case MiniappRequestType.MEETING_LEAVE:
void this.handleMeetingLeave(packageName, requestId)
break
case MiniappRequestType.MEETING_ADMIT:
void this.handleMeetingAdmit(packageName, payload, requestId)
break
case MiniappRequestType.MEETING_END:
void this.handleMeetingEnd(packageName, requestId)
break
case MiniappRequestType.MEETING_SET_MUTED:
void this.handleMeetingSetMuted(packageName, payload, requestId)
break
case MiniappRequestType.MEETING_SET_VIDEO_ENABLED:
void this.handleMeetingSetVideoEnabled(packageName, payload, requestId)
break
case MiniappRequestType.MEETING_UPDATE_VIDEO_SOURCE:
void this.handleMeetingUpdateVideoSource(packageName, payload, requestId)
break
case MiniappRequestType.MEETING_GET_STATE:
void this.handleMeetingGetState(packageName, requestId)
break
case MiniappRequestType.MEETING_PAUSE_VIDEO_PUBLISHER:
void this.handleMeetingPauseVideoPublisher(packageName, payload, requestId)
break
case MiniappRequestType.MEETING_RESUME_VIDEO_PUBLISHER:
void this.handleMeetingResumeVideoPublisher(packageName, payload, requestId)
break
case MiniappRequestType.MEETING_SHOW_CARD:
void this.handleMeetingShowCard(packageName, payload, requestId)
break
case MiniappRequestType.MEETING_SHOW_IMAGE:
void this.handleMeetingShowImage(packageName, payload, requestId)
break
case MiniappRequestType.MEETING_SHOW_LIVE:
void this.handleMeetingShowLive(packageName, requestId)
break
case MiniappRequestType.MEETING_CAPTURE_STILL:
void this.handleMeetingCaptureStill(packageName, payload, requestId)
break
case MiniappRequestType.PHONE_IS_WIFI_ENABLED:
case MiniappRequestType.PHONE_REQUEST_WIFI_ENABLE:
void this.handlePhoneWifiRequest(packageName, payload, requestId)
break
case REQUEST_WIFI_SETUP_TYPE:
void this.handleRequestWifiSetup(packageName, payload, requestId)
break
// Inter-miniapp interop (SYSTEM apps only)
case MiniappRequestType.MINIAPPS_LIST:
this.handleMiniappsList(packageName, payload, requestId)
break
case MiniappRequestType.MINIAPPS_START:
void this.handleMiniappsStart(packageName, payload, requestId)
break
case MiniappRequestType.MINIAPPS_STOP:
void this.handleMiniappsStop(packageName, payload, requestId)
break
case MiniappRequestType.MINIAPPS_INSTALL:
void this.handleMiniappsInstall(packageName, payload, requestId)
break
case MiniappRequestType.MINIAPPS_INSTALL_CHECK:
this.handleMiniappsInstallCheck(packageName, payload, requestId)
break
case MiniappRequestType.MINIAPPS_UNINSTALL:
void this.handleMiniappsUninstall(packageName, payload, requestId)
break
case MiniappRequestType.ACTION_INVOKE:
void this.handleActionInvoke(packageName, payload, requestId)
break
case MiniappRequestType.ACTION_RESULT:
this.handleActionResult(packageName, payload)
break
// Deferred in v1
case MiniappRequestType.DASHBOARD_CONTENT_UPDATE:
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.NOT_IMPLEMENTED,
message: "Dashboard API is deferred in v1",
})
break
case MiniappRequestType.TRANSCRIPTION_FINISH: {
const app = this.connectedApps.get(packageName)
if (
!app?.transcriptionListeners
.routes()
.some((route) => route.processing === "localOnly" || route.source === "local") ||
!app.installedManifest?.permissions?.some((p) => p.type === "MICROPHONE")
) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.PERMISSION_DENIED,
message: "An active local microphone transcription subscription is required",
})
break
}
void this.finishLocalUtterance().then(
(text) => this.sendResult(packageName, requestId, true, text),
(error) =>
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: error instanceof Error ? error.message : String(error),
}),
)
break
}
case MiniappRequestType.TRANSCRIPTION_CONFIG:
this.handleTranscriptionConfig(packageName, payload, requestId)
break
case MiniappRequestType.READY:
// MentraJSRouter observes READY to open the UI; nothing to do here.
break
case MiniappRequestType.TELEMETRY_CAPTURE:
// A miniapp's own event (`session.telemetry.capture`). It is this package's because it came over this
// package's bridge, whatever the payload says; the Fleet collector applies the limits. One-shot: no reply.
fleetEvents.telemetry({
packageName,
...(this.connectedApps.get(packageName)?.installedManifest?.version
? {versionName: this.connectedApps.get(packageName)!.installedManifest!.version}
: {}),
event: payload.event,
properties: payload.properties,
})
break
default:
// NACK instead of silent drop (issue 021 S3): an SDK that sends a
// request this runtime doesn't implement must get a rejected promise,
// not a permanently-pending silent gap. One-shots (no requestId) can
// only be logged.
console.warn(`${LOG_TAG}: Unknown request type from ${packageName}: ${requestType}`)
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.NOT_IMPLEMENTED,
message: `Unknown or unimplemented request type: ${requestType}`,
})
break
}
}
// ===========================================================================
// Request handlers
// ===========================================================================
private async handleConnect(
packageName: string,
_payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
console.log(`${LOG_TAG}: CONNECT from ${packageName}`)
// Register if not already
const existing = this.connectedApps.get(packageName)
if (!existing) {
console.warn(`${LOG_TAG}: CONNECT from unregistered app ${packageName}, dropping — isolate already torn down`)
return
}
// Update lastPongAt so it doesn't time out right away
existing.lastPongAt = Date.now()
existing.unansweredPingRounds = 0
// Read current glasses capabilities from the settings store
const defaultWearable = useSettingsStore.getState().getSetting(ISLAND_SETTINGS_KEYS.defaultWearable) as
| DeviceTypes
| undefined
const capabilities = getModelCapabilities(defaultWearable || DeviceTypes.NONE)
// Build the declared-permission record for the SDK's session.permissions
// module. Lower-cased to match v3's PermissionType union (microphone,
// camera, location, notifications, calendar). Missing permissions default
// to false; this is manifest-declaration tracking only — OS-grant state
// is intentionally not modeled here.
const declaredPermissions = computeDeclaredPermissionRecord(existing.installedManifest)
// Fresh handshake → clear any auth state from a prior context so a stale
// retry timer can't fire against this new connection and so the retry loop
// below re-arms from scratch.
existing.authDelivered = false
existing.authSession = ++this.authSessionSeq
this.clearMiniappAuthDeliveryRetry(packageName)
// A connect is an open, so the token is minted now rather than taken from the cache: it must carry
// whatever the user has acquired since the last one. If this mint fails, the retries in
// deliverInitialMiniappAuth fall back to the cache-first path.
const authPromise = this.requestMiniappAuth(packageName, {fresh: true})
// Send CONNECT_ACK in this turn, before any await. A 1.5s auth wait let a
// concurrent unregister (dev respawn, tray stop, glasses-not-ready teardown)
// drop the ACK; Mentra Call then dies with CONNECT_ACK timeout even though
// CONNECT landed. Auth still arrives on AUTH_UPDATE.
this.sendToMiniapp(
packageName,
{
type: MiniappResponseType.CONNECT_ACK,
userId: "",
packageName,
capabilities,
permissions: declaredPermissions,
visibility: this.currentVisiblePackage() === packageName ? "foreground" : "background",
configuration: getMiniappConfiguration(packageName),
// The SDK's HostFeatures. miniappInstall: system-list miniapps may call session.miniapps.install({url});
// the Mentra Apps before it answer NOT_PERMITTED.
// telemetry: `session.telemetry.capture` reaches the workspace's Fleet Management (Phase 12).
hostFeatures: {captureAudio: true, initReady: true, transcriptionListeners: true, miniappInstall: true, telemetry: true},
},
requestId,
)
this.deliverInitialMiniappAuth(packageName, authPromise, 0)
this.sendCloudStatusToMiniapp(packageName)
// Handshake complete — unblock any launcher.waitForConnect() callers.
this.handshookApps.add(packageName)
this.flushConnectWaiters(packageName)
}
private async requestMiniappAuth(
packageName: string,
opts?: {minTtlMs?: number; fresh?: boolean},
): Promise<MiniappAuthToken | null> {
// Core owns miniapp-backend token minting. A Runtime-only deployment has
// no such capability, so fail once instead of entering the retry loop.
if (!cloudClientService.hasCore()) return null
// A local or development build may claim any package name, so its token says it is a local build: a backend
// accepts it only where it allows local builds, and it never names a workspace. Every other context gets its
// package's ordinary token.
return cloudClientService.getMiniappAuthToken(
packageName,
isLocalBuildContext(packageName) ? {...opts, localBuild: true} : opts,
)
}
private async handleAuthRefresh(
packageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
try {
const auth = await this.refreshMiniappAuth(packageName, this.authRefreshOptions(payload))
if (!auth) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.NOT_CONNECTED,
message: "Miniapp auth is not configured",
})
return
}
this.sendResult(packageName, requestId, true, {auth})
} catch (err) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: (err as Error)?.message ?? "Miniapp auth refresh failed",
})
}
}
private async refreshMiniappAuth(
packageName: string,
opts?: {minTtlMs?: number; fresh?: boolean},
): Promise<MiniappAuthToken | null> {
const session = this.connectedApps.get(packageName)?.authSession
const auth = await this.requestMiniappAuth(packageName, opts)
if (!auth) return null
// The miniapp that asked may have reconnected or been replaced while the mint was out. Its successor has
// its own token on the way, so this one is neither delivered nor handed back to a requester that could be
// that successor: the SDK would apply it over the newer token.
if (!this.currentAuthApp(packageName, session)) {
throw new Error("The miniapp reconnected or stopped while its auth token was being refreshed")
}
this.scheduleMiniappAuthRefresh(packageName, auth)
this.sendToMiniapp(packageName, {
type: MiniappResponseType.AUTH_UPDATE,
auth,
})
return auth
}
/** The app registered under `packageName`, if it is still in the auth session a token request started under. */
private currentAuthApp(packageName: string, session: number | undefined): ConnectedMiniapp | undefined {
const app = this.connectedApps.get(packageName)
return app && app.authSession === session ? app : undefined
}
private authRefreshOptions(payload: Record<string, unknown>): {minTtlMs?: number} | undefined {
const minTtlMs = Number(payload.minTtlMs)
if (!Number.isFinite(minTtlMs) || minTtlMs <= 0) return undefined
return {minTtlMs}
}
private scheduleMiniappAuthRefresh(packageName: string, auth: MiniappAuthToken): void {
const app = this.connectedApps.get(packageName)
if (!app) return
this.clearMiniappAuthRefresh(packageName)
const refreshAt = auth.expiresAt - MINIAPP_AUTH_REFRESH_HEADROOM_MS
this.armMiniappAuthRefresh(packageName, Math.max(MINIAPP_AUTH_REFRESH_MIN_DELAY_MS, refreshAt - Date.now()), 0)
}
/**
* Arm the refresh timer. A refresh that fails (Core or the network is down at that moment) arms it again with the
* same backoff as the first token's delivery, until a new token lands, the miniapp reconnects or it stops; the
* miniapp must not be left holding a token that runs out.
*/
private armMiniappAuthRefresh(packageName: string, delay: number, attempt: number): void {
const app = this.connectedApps.get(packageName)
if (!app) return
const session = app.authSession
app.authRefreshTimerId = BgTimer.setTimeout(() => {
const current = this.currentAuthApp(packageName, session)
if (!current) return
current.authRefreshTimerId = null
// Fresh: the cached token is the one being replaced and has no more than the headroom left, so asking
// for it again would hand the miniapp the same token and re-arm this timer for the minimum delay.
void this.refreshMiniappAuth(packageName, {fresh: true}).catch((err) => {
console.warn(`${LOG_TAG}: miniapp auth refresh failed for ${packageName}: ${(err as Error)?.message ?? err}`)
// Nothing else (a foreground refresh, a miniapp request) has armed the timer in the meantime.
const stillCurrent = this.currentAuthApp(packageName, session)
if (!stillCurrent || stillCurrent.authRefreshTimerId !== null) return
this.armMiniappAuthRefresh(
packageName,
Math.min(MINIAPP_AUTH_RETRY_MAX_MS, MINIAPP_AUTH_RETRY_BASE_MS * 2 ** attempt),
attempt + 1,
)
})
}, delay)
}
private clearMiniappAuthRefresh(packageName: string): void {
const app = this.connectedApps.get(packageName)
if (!app || app.authRefreshTimerId === null) return
const timerId = app.authRefreshTimerId
BgTimer.clearTimeout(timerId)
app.authRefreshTimerId = null
}
/**
* Deliver the miniapp's FIRST auth token, retrying until it lands. Called from
* {@link handleConnect} when the initial mint didn't resolve in the CONNECT_ACK
* window. `inFlight` lets attempt 0 reuse the mint the handshake already
* started (avoids a redundant duplicate request); that request is fresh (see
* {@link handleConnect}). Later attempts take the default, cache-first path: a
* still-valid cached token reaches the miniapp at once while Core is
* unreachable, and with no usable cached token the default path mints. The
* foreground edge and the scheduled refresh are fresh and pick up anything
* newer.
*
* A `null` result means auth is fundamentally unavailable (no miniappAuth hook)
* — permanent, so we do NOT retry. A REJECTION means a transient failure
* (typically the cloud client isn't connection-ready yet) — retry with backoff.
* Either way we bail if the app has since disconnected, reconnected (a later CONNECT
* delivers its own token; see {@link ConnectedMiniapp.authSession}) or already got a
* token (e.g. via {@link redriveMiniappAuthDelivery} on cloud-connect).
*/
private deliverInitialMiniappAuth(
packageName: string,
inFlight: Promise<MiniappAuthToken | null> | undefined,
attempt: number,
): void {
const app = this.connectedApps.get(packageName)
if (!app || app.authDelivered) return
const session = app.authSession
app.authRequestPending = true
const mint = inFlight ?? this.requestMiniappAuth(packageName)
void mint
.then((auth) => {
const current = this.currentAuthApp(packageName, session)
if (!current) return
current.authRequestPending = false
if (current.authDelivered) return
if (!auth) return // no auth hook — permanent, don't spin
current.authDelivered = true
this.clearMiniappAuthDeliveryRetry(packageName)
this.scheduleMiniappAuthRefresh(packageName, auth)
this.sendToMiniapp(packageName, {type: MiniappResponseType.AUTH_UPDATE, auth})
})
.catch((err) => {
console.warn(
`${LOG_TAG}: miniapp auth mint failed for ${packageName} (attempt ${attempt}): ${
(err as Error)?.message ?? err
}`,
)
// A later CONNECT (or a replacement) owns its own delivery and retries.
const current = this.currentAuthApp(packageName, session)
if (!current) return
current.authRequestPending = false
this.scheduleInitialMiniappAuthRetry(packageName, attempt)
})
}
private scheduleInitialMiniappAuthRetry(packageName: string, attempt: number): void {
const app = this.connectedApps.get(packageName)
if (!app || app.authDelivered) return
this.clearMiniappAuthDeliveryRetry(packageName)
const delay = Math.min(MINIAPP_AUTH_RETRY_MAX_MS, MINIAPP_AUTH_RETRY_BASE_MS * 2 ** attempt)
app.authRetryTimerId = BgTimer.setTimeout(() => {
const current = this.connectedApps.get(packageName)
if (!current) return
current.authRetryTimerId = null
this.deliverInitialMiniappAuth(packageName, undefined, attempt + 1)
}, delay)
}
private clearMiniappAuthDeliveryRetry(packageName: string): void {
const app = this.connectedApps.get(packageName)
if (!app || app.authRetryTimerId === null) return
BgTimer.clearTimeout(app.authRetryTimerId)
app.authRetryTimerId = null
}
/**
* When the cloud client (re)connects, immediately re-attempt the initial mint
* for any handshook app still missing its token, instead of waiting out the
* backoff. This is what turns "scan a dev app before the cloud is ready" from
* "dead until you manually reconnect Cloud V2" into "authenticates on its own
* the instant the connection comes up".
*/
private redriveMiniappAuthDelivery(): void {
for (const [packageName, app] of this.connectedApps) {
if (app.authDelivered || app.authRequestPending) continue
// Only apps that finished their CONNECT handshake are in the mint-retry
// state; skip anything still mid-handshake (handleConnect owns that).
if (!this.handshookApps.has(packageName)) continue
this.clearMiniappAuthDeliveryRetry(packageName)
this.deliverInitialMiniappAuth(packageName, undefined, 0)
}
}
/**
* TRANSCRIPTION_CONFIG (issue 021 WP3): store the miniapp's language hints
* and rebuild the cloud subscription set so the auto-mode subscription
* carries them. Replies with a REQUEST_RESULT so the SDK's configure()
* promise settles: unknown hint values are an error, not a silent drop.
*/
private handleTranscriptionConfig(packageName: string, payload: Record<string, unknown>, requestId?: string): void {
const app = this.connectedApps.get(packageName)
if (!app) return
const config = (payload.config ?? {}) as Record<string, unknown>
const rawHints = config.languageHints
if (rawHints !== undefined && !Array.isArray(rawHints)) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: "languageHints must be an array of language codes",
})
return
}
if (rawHints === undefined || rawHints.length === 0) {
this.transcriptionHintsByApp.delete(packageName)
} else {
// Defense in depth: the SDK already validated, but the wire is untyped.
const hints: string[] = []
const invalid: string[] = []
for (const raw of rawHints as unknown[]) {
const hint = typeof raw === "string" ? toLanguageHint(raw) : null
if (hint) hints.push(hint)
else invalid.push(String(raw))
}
if (invalid.length > 0) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: `Unknown language hint(s): ${invalid.join(", ")}`,
})
return
}
this.transcriptionHintsByApp.set(packageName, [...new Set(hints)].sort())
}
this.updateCloudSubscriptions()
this.sendResult(packageName, requestId, true, {applied: true})
}
private handleSubscribe(packageName: string, payload: Record<string, unknown>, requestId?: string): void {
const app = this.connectedApps.get(packageName)
if (!app) return
const rawStreams = (payload.subscriptions ?? payload.streams) as
(string | ({rate?: string} & TranscriptionStreamEntry))[] | undefined
// Normalize: objects like {stream: "location_stream", rate: "realtime"} → extract stream name
// "location_stream" is the rate-bearing alias for "location_update".
// The strictest rate wins when multiple `location_stream` entries appear
// in one SUBSCRIBE — the same rule we apply across apps.
let requestedLocationRate: string | null = null
// What each transcription stream's entries ask for: `{stream, processing}`,
// or `{stream, forceLocal, includeCloud}` from SDKs before `processing`.
const streamProcessing = new Map<string, Set<SpeechProcessing>>()
const streams = rawStreams?.map((s) => {
if (typeof s === "object" && s !== null) {
if (s.stream === "location_stream") {
if (s.rate && locationRateRank(s.rate) > locationRateRank(requestedLocationRate)) {
requestedLocationRate = s.rate
}
return "location_update"
}
if (s.stream.startsWith("transcription:")) addStreamProcessing(streamProcessing, s)
return s.stream
}
if (s.startsWith("transcription:")) addStreamProcessing(streamProcessing, {stream: s})
return s
}) as string[] | undefined
if (!Array.isArray(streams)) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: "subscribe requires a subscriptions array",
})
return
}
const transcriptionListeners = transcriptionRegistrations(payload.transcriptionListeners, streams, streamProcessing)
for (const stream of streams) {
if (stream.startsWith("translation:") && !isFeatureEnabled("cloudSpeech")) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.NOT_IMPLEMENTED,
message: "Cloud speech is disabled by this deployment",
})
return
}
if (stream === "wake_word" && !isFeatureEnabled("onDeviceSpeech")) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.NOT_IMPLEMENTED,
message: "On-device speech is disabled by this deployment",
})
return
}
}
for (const {processing} of transcriptionListeners) {
const disabled = speechProcessingDisabled(processing)
if (disabled) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.NOT_IMPLEMENTED,
message: disabled,
})
return
}
}
console.log(`${LOG_TAG}: SUBSCRIBE from ${packageName}: [${streams.join(", ")}]`)
// Gate each stream on the permission type its data requires. The manifest
// must declare the permission (miniapp.json -> permissions) or we reject
// the whole subscribe with PERMISSION_NOT_DECLARED.
const declaredTypes = new Set((app.installedManifest?.permissions ?? []).map((p) => p.type?.toUpperCase()))
const permissionForStream = (s: string): string | null => {
if (s === "audio_chunk" || s === "vad" || s === "wake_word") return "MICROPHONE"
if (s.startsWith("transcription") || s.startsWith("translation")) return "MICROPHONE"
if (s === "location_update") return "LOCATION"
if (s === "phone_notification") return "READ_NOTIFICATIONS"
if (s === "phone_notification_dismissed") return "READ_NOTIFICATIONS"
return null
}
for (const stream of streams) {
const required = permissionForStream(stream)
if (required && !declaredTypes.has(required)) {
logPermissionNotDeclared(packageName, required, `to subscribe to "${stream}"`, `{"type": "${required}"}`)
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.PERMISSION_NOT_DECLARED,
message: `${required} permission not declared in miniapp.json (required for "${stream}"). Add {"type": "${required}"} to the "permissions" array.`,
// Extra context fields read by the SDK so authors that subscribe
// to session.on("error") can format their own messages.
permission: required,
subscription: stream,
})
return
}
}
// Add new subscriptions
const previousSubscriptions = app.subscriptions
app.subscriptions = new Set(streams)
// A miniapp that subscribes to the model status again gets it again.
if (!app.subscriptions.has(MiniappStreamType.TRANSCRIPTION_MODEL_STATUS))
app.lastTranscriptionModelStatus = undefined
this.replaceStreamSubscribers(packageName, previousSubscriptions, app.subscriptions)
app.transcriptionListeners.replace(transcriptionListeners, cloudClientService.getAudioPosition())
this.recomputeMicRequirements()
this.updateCloudSubscriptions()
this.recomputeHeadingSubscription()
this.recomputeImuSubscription()
// Persist this app's requested rate (or clear it if SUBSCRIBE didn't
// include `location_stream` this time), then ask the host for the
// strictest rate across all connected apps.
app.requestedLocationRate = requestedLocationRate
this.recomputeLocationTier()
this.sendResult(packageName, requestId, true)
// Fire initial snapshot values for stateful streams so miniapps don't have
// to wait for the first change event.
this.emitInitialSnapshots(packageName, streams, previousSubscriptions)
}
private async handleCalendarListEvents(
packageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
const app = this.connectedApps.get(packageName)
const declared = app?.installedManifest?.permissions?.some(
(permission) => permission.type?.toUpperCase() === "CALENDAR",
)
if (!declared) {
logPermissionNotDeclared(packageName, "CALENDAR", "to list calendar events", '{"type": "CALENDAR"}')
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.PERMISSION_NOT_DECLARED,
message: 'CALENDAR permission not declared in miniapp.json. Add {"type": "CALENDAR"} to the permissions array.',
permission: "CALENDAR",
})
return
}
try {
const result = await listPhoneCalendarEvents(payload)
this.sendResult(packageName, requestId, true, result)
} catch (error) {
const known = error instanceof PhoneCalendarError
this.sendResult(packageName, requestId, false, undefined, {
code: known ? error.code : MiniappErrorCode.INTERNAL,
message: error instanceof Error ? error.message : "Failed to read phone calendar events",
})
}
}
/**
* For state-bearing streams (battery, connection), deliver the current value
* immediately on subscribe. Other streams (button press, transcription, etc.)
* are pure event streams with no "current value" to snapshot.
*/
private emitInitialSnapshots(
packageName: string,
streams: string[],
previous: ReadonlySet<string> = new Set(),
): void {
// Read the engine glasses store directly (was a host glassesStatus hook).
const gs = useGlassesStore.getState()
const glassesState = {
connected: isGlassesConnected(gs.connection),
deviceModel: gs.deviceModel,
batteryLevel: gs.batteryLevel,
charging: gs.charging,
}
const isSimulated = (glassesState.deviceModel || "").toLowerCase().includes("simulated")
for (const stream of streams) {
if (stream === MiniappStreamType.WAKE_WORD) {
// The current state once per subscription; changes follow as events.
if (previous.has(stream)) continue
this.sendToMiniapp(packageName, {
type: MiniappResponseType.EVENT,
streamType: MiniappStreamType.WAKE_WORD,
data: wakeWordService.currentStatus(),
})
} else if (stream === MiniappStreamType.TRANSCRIPTION_MODEL_STATUS) {
// Usually already sent by the subscription update; this only fills a gap.
this.sendTranscriptionModelStatus(packageName)
} else if (stream === "glasses_battery") {
// Simulated glasses have no real battery; mirror the phone's battery
// so miniapps see a sensible value during development.
if (isSimulated) {
void this.emitPhoneBatteryAs(packageName, "glasses_battery")
} else if (typeof glassesState.batteryLevel === "number" && glassesState.batteryLevel >= 0) {
this.sendToMiniapp(packageName, {
type: MiniappResponseType.EVENT,
streamType: "glasses_battery",
data: {
level: glassesState.batteryLevel,
charging: !!glassesState.charging,
timestamp: Date.now(),
},
})
}
} else if (stream === "phone_battery") {
void this.emitPhoneBatteryAs(packageName, "phone_battery")
} else if (stream === "glasses_connection") {
this.sendToMiniapp(packageName, {
type: MiniappResponseType.EVENT,
streamType: "glasses_connection",
data: {
connected: glassesState.connected,
modelName: glassesState.deviceModel || undefined,
},
})
} else if (stream === "glasses_wifi") {
// Snapshot the current glasses Wi-Fi state on subscribe (like battery).
// Read the canonical nested `wifi: {state, ssid}` from the STORE state
// (`glassesState` is the narrowed 4-field projection and has no `wifi`;
// the pre-engine host hook spread the full store, so read gs directly —
// NOT the legacy flat wifiConnected). Effective connectivity requires the
// glasses connected AND on Wi-Fi — mirrors the host's store-derived
// forward, so an already-disconnected device reports `connected: false`
// rather than silently emitting nothing. Always emits so onWifi gets an
// initial value.
const wifi = gs.wifi.state === "connected" ? gs.wifi : null
const connected = glassesState.connected === true && wifi !== null
this.sendToMiniapp(packageName, {
type: MiniappResponseType.EVENT,
streamType: "glasses_wifi",
data: {
connected,
linkConnected: glassesState.connected === true,
ssid: connected ? wifi?.ssid : undefined,
localIp: connected ? wifi?.localIp : undefined,
timestamp: Date.now(),
},
})
} else if (stream === "head_position") {
// The glasses store has no headUp field (same on the pre-engine host
// hook), so this stays a no-emit until head state lands in the store.
const headUp = (gs as {headUp?: boolean}).headUp
if (typeof headUp === "boolean") {
this.sendToMiniapp(packageName, {
type: MiniappResponseType.EVENT,
streamType: "head_position",
data: {
position: headUp ? "up" : "down",
timestamp: Date.now(),
},
})
}
}
}
}
/**
* Read the phone's battery state right now and emit it as the given stream.
* Used for both phone_battery snapshot on subscribe, and as a stand-in for
* glasses_battery when connected to Simulated Glasses.
*/
private async emitPhoneBatteryAs(
packageName: string,
streamType: "phone_battery" | "glasses_battery",
): Promise<void> {
try {
const level = await Battery.getBatteryLevelAsync()
const state = await Battery.getBatteryStateAsync()
const charging = state === Battery.BatteryState.CHARGING || state === Battery.BatteryState.FULL
this.sendToMiniapp(packageName, {
type: MiniappResponseType.EVENT,
streamType,
data: {
level: Math.round(level * 100),
charging,
timestamp: Date.now(),
},
})
} catch (err) {
console.log(`${LOG_TAG}: phone battery snapshot failed`, err)
}
}
private handleDisplay(packageName: string, payload: Record<string, unknown>, requestId?: string): void {
try {
// Zombie-frame gate: a dying miniapp's last in-flight frame can arrive
// AFTER onUnmount cleared its display — repainting a dead app's UI (and
// poisoning the next boot's pre-boot restore snapshot). Killed mid-route
// nav reproduced this reliably; its 3s re-push raced the teardown.
if (!this.connectedApps.has(packageName)) {
console.log(`${LOG_TAG}: dropping display from unmounted app ${packageName}`)
return
}
if (!payload.layout || typeof payload.layout !== "object") {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: "display request missing layout object",
})
return
}
// Hand off to LocalDisplayManager — it owns boot/throttle/arbitration/
// expiry + the native BluetoothSdk.displayEvent call + useDisplayStore.
localDisplayManager.request(packageName, {
view: (payload.view as DisplayPayload["view"]) ?? "main",
layout: payload.layout as DisplayPayload["layout"],
durationMs: payload.durationMs as number | undefined,
})
this.sendResult(packageName, requestId, true)
} catch (err) {
console.error(`${LOG_TAG}: display error:`, err)
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: err instanceof Error ? err.message : "Display error",
})
}
}
/**
* Scene render (session.display.render()). Same arbitration as DISPLAY, but
* the payload is a whole frame of positioned elements and the caller may be
* awaiting the outcome: LocalDisplayManager guarantees the resolver fires
* exactly once (displayed/blocked, with degraded/dropped reporting), and that
* becomes the REQUEST_RESULT data.
*/
private handleRender(packageName: string, payload: Record<string, unknown>, requestId?: string): void {
try {
// Zombie-frame gate — see handleDisplay.
if (!this.connectedApps.has(packageName)) {
this.sendResult(packageName, requestId, true, {status: "blocked", reason: "app stopped"})
return
}
if (!Array.isArray(payload.elements)) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: "render request missing elements array",
})
return
}
if (
payload.ifDisplayToken !== undefined &&
(typeof payload.ifDisplayToken !== "string" || !payload.ifDisplayToken)
) {
this.sendResult(packageName, requestId, true, {status: "blocked", reason: "invalid display token"})
return
}
localDisplayManager.request(
packageName,
{
view: (payload.view as DisplayPayload["view"]) ?? "main",
ifDisplayToken: payload.ifDisplayToken as string | undefined,
scene: payload.elements as DisplayPayload["scene"],
includeTextLayout: payload.includeTextLayout === true,
durationMs: payload.durationMs as number | undefined,
},
(result) => this.sendResult(packageName, requestId, true, result),
)
} catch (err) {
console.error(`${LOG_TAG}: render error:`, err)
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: err instanceof Error ? err.message : "Render error",
})
}
}
private handlePlayAudio(packageName: string, payload: Record<string, unknown>, requestId?: string): void {
const audioUrl = (payload.audioUrl ?? payload.url) as string | undefined
if (!audioUrl) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: "play_audio requires an audioUrl",
})
return
}
// The player opens local files too: a file URL must be one of this miniapp's own blobs.
if (!this.systemActions.allowsMediaUrl(packageName, audioUrl)) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INVALID_ARGUMENT,
message: "play_audio: audioUrl must be an http(s) or data: URL, or a file from this miniapp's blob storage",
})
return
}
const audioRequestId = requestId || `local_${Date.now()}`
const volume = typeof payload.volume === "number" ? payload.volume : 1.0
const stopOtherAudio = payload.stopOtherAudio !== false
this.cancelSpeech(packageName)
this.setSpeakerState(packageName, "loading")
audioPlaybackService.play(
{
requestId: audioRequestId,
audioUrl,
appId: packageName,
volume,
stopOtherAudio,
startPositionMs: typeof payload.startPositionMs === "number" ? payload.startPositionMs : 0,
},
(_respId, success, error, duration) => {
if (success) {
this.setSpeakerState(packageName, "stopped", {durationMs: duration ?? undefined})
} else {
this.setSpeakerState(packageName, "error", {
errorCode: MiniappErrorCode.INTERNAL,
errorMessage: error ?? "play failed",
durationMs: duration ?? undefined,
})
}
this.sendResult(
packageName,
requestId,
success,
{duration},
error
? {
code: MiniappErrorCode.INTERNAL,
message: error,
}
: undefined,
)
},
)
// Optimistic "started playing" transition. The audio service doesn't
// have a "playback actually started" callback today; cloud SDK v3 has
// the same constraint and uses optimistic timing. Microtask so the
// initial "loading" envelope flushes first.
queueMicrotask(() => this.setSpeakerState(packageName, "playing"))
}
private handleStopAudio(packageName: string, _payload: Record<string, unknown>, requestId?: string): void {
this.cancelSpeech(packageName)
audioPlaybackService.stopForApp(packageName)
this.setSpeakerState(packageName, "stopped")
this.sendResult(packageName, requestId, true)
}
// ── speaker.createStream (live PCM output) ────────────────────────────────
/** Valid PCM sample rates for speaker streams. Mirrors the SDK contract. */
private static readonly SPEAKER_STREAM_SAMPLE_RATES = new Set([16000, 24000, 48000])
private static readonly SPEAKER_STREAM_MAX_BASE64_CHARS = Math.ceil((256 * 1024) / 3) * 4
private speakerStreamCounter = 0
private async handleSpeakerStreamOpen(
packageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
const app = this.connectedApps.get(packageName)
if (!app) return
// One stream per miniapp: opening a second closes the first.
const previous = app.activeSpeakerStreamId
if (previous) {
app.activeSpeakerStreamId = undefined
await audioPlaybackService.abortStream(previous).catch((error) => {
console.warn(`${LOG_TAG}: failed to abort previous speaker stream for ${packageName}`, error)
})
}
const sampleRate = typeof payload.sampleRate === "number" ? payload.sampleRate : 16000
if (!LocalMiniappRuntime.SPEAKER_STREAM_SAMPLE_RATES.has(sampleRate)) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INVALID_ARGUMENT,
message: `unsupported sampleRate ${sampleRate} (use 16000, 24000, or 48000)`,
})
return
}
const channels = typeof payload.channels === "number" ? payload.channels : 1
if (channels !== 1) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INVALID_ARGUMENT,
message: "speaker streams currently support mono PCM only",
})
return
}
const volume = typeof payload.volume === "number" ? payload.volume : 1
if (!Number.isFinite(volume) || volume < 0 || volume > 1) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INVALID_ARGUMENT,
message: "speaker stream volume must be between 0 and 1",
})
return
}
const jitterMs = payload.jitterMs
if (
jitterMs !== undefined &&
(typeof jitterMs !== "number" || !Number.isFinite(jitterMs) || jitterMs < 80 || jitterMs > 500)
) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INVALID_ARGUMENT,
message: "speaker stream jitterMs must be between 80 and 500",
})
return
}
const streamId = `spkstream_${Date.now()}_${++this.speakerStreamCounter}`
const prewarm = payload.prewarm === true
// A prewarmed stream is silent until its first write, so the speaker stays idle.
if (!prewarm) this.setSpeakerState(packageName, "loading")
try {
await audioPlaybackService.openStream({
streamId,
appId: packageName,
sampleRate,
channels,
volume,
...(typeof jitterMs === "number" ? {jitterMs} : {}),
prewarm,
stopOtherAudio: payload.stopOtherAudio !== false,
onEnded: (endedId, success, error, durationMs, started) => {
const current = this.connectedApps.get(packageName)
// Ignore completion from an app incarnation replaced by a crash
// respawn. Its abort may finish after the new app has registered and
// must not overwrite that app's speaker state.
if (current !== app) return
if (current.activeSpeakerStreamId === endedId) current.activeSpeakerStreamId = undefined
if (current.preparedSpeakerStreamId === endedId) current.preparedSpeakerStreamId = undefined
// A prewarmed stream that never played leaves the speaker as it was.
if (!started && success) return
if (success) {
this.setSpeakerState(packageName, "stopped", {durationMs: durationMs ?? undefined})
} else {
this.setSpeakerState(packageName, "error", {
errorCode: MiniappErrorCode.INTERNAL,
errorMessage: error ?? "speaker stream failed",
durationMs: durationMs ?? undefined,
})
}
},
})
} catch (error) {
const message = error instanceof Error ? error.message : String(error)
this.setSpeakerState(packageName, "error", {
errorCode: MiniappErrorCode.INTERNAL,
errorMessage: message,
})
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message,
})
return
}
// The native open can outlive a miniapp disconnect. Its ordinary teardown
// ran while no StreamState existed yet, so close this late result here
// instead of leaving an orphan AudioTrack/AVAudioEngine session.
if (this.connectedApps.get(packageName) !== app) {
await audioPlaybackService.abortStream(streamId)
return
}
app.activeSpeakerStreamId = streamId
app.preparedSpeakerStreamId = prewarm ? streamId : undefined
// Optimistic "playing", same as play(): the chunk player starts as soon
// as the first write lands. Microtask so "loading" flushes first.
if (!prewarm) queueMicrotask(() => this.setSpeakerState(packageName, "playing"))
this.sendResult(packageName, requestId, true, {streamId})
}
/** Resolve + validate a stream id from a payload against the app's active stream. */
private activeSpeakerStream(packageName: string, payload: Record<string, unknown>): string | null {
const streamId = typeof payload.streamId === "string" ? payload.streamId : undefined
const app = this.connectedApps.get(packageName)
if (!streamId || !app || app.activeSpeakerStreamId !== streamId) return null
return streamId
}
private async handleSpeakerStreamWrite(
packageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
const streamId = this.activeSpeakerStream(packageName, payload)
if (!streamId) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: "speaker stream is not open",
})
return
}
const base64 = typeof payload.base64 === "string" ? payload.base64 : ""
if (!base64 || base64.length % 4 !== 0) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INVALID_ARGUMENT,
message: "speaker stream write requires padded base64 PCM data",
})
return
}
if (base64.length > LocalMiniappRuntime.SPEAKER_STREAM_MAX_BASE64_CHARS) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.PAYLOAD_TOO_LARGE,
message: "speaker stream chunk exceeds the 256 KB raw PCM limit",
})
return
}
try {
const result = await audioPlaybackService.writeStreamChunk(streamId, base64)
const app = this.connectedApps.get(packageName)
if (app?.preparedSpeakerStreamId === streamId) {
app.preparedSpeakerStreamId = undefined
this.setSpeakerState(packageName, "playing")
}
this.sendResult(packageName, requestId, true, result)
} catch (error) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: error instanceof Error ? error.message : String(error),
})
}
}
private async handleSpeakerStreamClose(
packageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
const streamId = this.activeSpeakerStream(packageName, payload)
if (!streamId) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: "speaker stream is not open",
})
return
}
try {
// Resolves once the buffered audio has drained; onEnded delivers the
// terminal SPEAKER_STATE ("stopped").
const result = await audioPlaybackService.closeStream(streamId)
this.sendResult(packageName, requestId, true, result)
} catch (error) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: error instanceof Error ? error.message : String(error),
})
}
}
private async handleSpeakerStreamAbort(
packageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
const streamId = this.activeSpeakerStream(packageName, payload)
if (!streamId) {
// Aborting an already-gone stream is fine — abort() is idempotent.
this.sendResult(packageName, requestId, true)
return
}
try {
await audioPlaybackService.abortStream(streamId)
this.sendResult(packageName, requestId, true)
} catch (error) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: error instanceof Error ? error.message : String(error),
})
}
}
private async handleSpeak(packageName: string, payload: Record<string, unknown>, requestId?: string): Promise<void> {
const rawText = payload.text
const rawSentences =
typeof rawText === "string"
? [rawText.trim()].filter(Boolean)
: Array.isArray(rawText)
? rawText
.filter((sentence): sentence is string => typeof sentence === "string")
.map((sentence) => sentence.trim())
.filter(Boolean)
: []
const enableSanitization = payload.enableSanitization !== false
const sentences = prepareTtsSentences(rawSentences, enableSanitization)
if (sentences.length === 0) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: "speak requires text or a non-empty sentence list with speakable content",
})
return
}
const cloudText = sentences.join(" ")
const voice = ((payload.voice_id ?? payload.voice) as string) || "default"
const audioRequestId = requestId || `tts_${Date.now()}`
const volume = typeof payload.volume === "number" ? payload.volume : 1.0
const stopOtherAudio = payload.stopOtherAudio !== false
const voiceSettings =
payload.voice_settings && typeof payload.voice_settings === "object"
? (payload.voice_settings as Record<string, unknown>)
: undefined
const speed = typeof voiceSettings?.speed === "number" ? voiceSettings.speed : undefined
const run: SpeechRun = {id: audioRequestId, cancelled: false}
this.cancelSpeech(packageName)
this.speechRuns.set(packageName, run)
this.setSpeakerState(packageName, "loading")
let terminalSent = false
const sendPlaybackResult = (
success: boolean,
error: string | null,
duration: number | null,
fallbackErrorMessage: string,
completed = success,
errorCode: MiniappErrorCode = MiniappErrorCode.TTS_UPSTREAM_ERROR,
) => {
if (terminalSent) return
terminalSent = true
// A superseded run still owns its bridge request, but it no longer owns
// the package's shared speaker state.
const ownsSpeakerState = this.speechRuns.get(packageName) === run
if (ownsSpeakerState) this.speechRuns.delete(packageName)
if (ownsSpeakerState) {
if (success) {
this.setSpeakerState(packageName, "stopped", {durationMs: duration ?? undefined})
} else {
this.setSpeakerState(packageName, "error", {
errorCode,
errorMessage: error ?? fallbackErrorMessage,
durationMs: duration ?? undefined,
})
}
}
this.sendResult(
packageName,
requestId,
success,
{completed, duration},
error
? {
code: errorCode,
message: error,
}
: undefined,
)
}
run.onCancelled = () => sendPlaybackResult(true, null, null, "tts playback stopped", false)
try {
const voiceExplicit = payload.voice_id !== undefined || payload.voice !== undefined
const offlineSupportsVoice =
!voiceExplicit || voice === "default" || ttsModelManager.getAvailableLanguages().some((l) => l.code === voice)
const modelId = typeof payload.model_id === "string" ? payload.model_id : undefined
// `processing` wins; SDKs before it send only `forceLocal`.
const processing = readSpeechProcessing(payload)
const cloudConnected = cloudClientService.isConnected()
console.log(
`${LOG_TAG}: TTS decision for ${packageName}: cloudConnected=${cloudConnected}, runtimeTts=yes, offlineVoice=${offlineSupportsVoice}, processing=${processing}`,
)
const playOfflineTts = async (reason?: string): Promise<boolean> => {
if (run.cancelled) return true
if (!isFeatureEnabled("onDeviceSpeech")) return false
if (!offlineSupportsVoice || !(await ttsModelManager.isModelAvailable())) {
return false
}
if (run.cancelled) return true
const languageCode = ttsModelManager.getAvailableLanguages().some((l) => l.code === voice) ? voice : undefined
const offlineSentences = sentences
if (offlineSentences.length > 1) {
let firstSentence: TtsSynthesisResult
try {
firstSentence = await ttsModelManager.synthesizeToFile(offlineSentences[0], {languageCode, speed})
} catch (offlineErr) {
if (run.cancelled) return true
console.warn(
`${LOG_TAG}: offline sentence TTS synthesize failed${reason ? ` after ${reason}` : ""}:`,
offlineErr,
)
return false
}
if (run.cancelled) {
await Promise.resolve(firstSentence.cleanup?.())
return true
}
void runSentenceTtsPipeline({
sentences: offlineSentences,
firstAudio: firstSentence,
run,
synthesize: (sentence) => ttsModelManager.synthesizeToFile(sentence, {languageCode, speed}),
play: (audio, index) =>
new Promise((resolve) => {
const sentenceRequestId = `${audioRequestId}_sentence_${index}`
run.playbackRequestId = sentenceRequestId
audioPlaybackService.play(
{
requestId: sentenceRequestId,
audioUrl: audio.audioUrl,
appId: packageName,
volume,
stopOtherAudio,
},
(_responseId, success, error, duration, completionReason) => {
if (run.playbackRequestId === sentenceRequestId) run.playbackRequestId = undefined
resolve({success, completed: completionReason === "completed", error, duration})
},
)
}),
onCleanupError: (cleanupError) => {
console.warn(`${LOG_TAG}: sentence TTS cleanup failed`, cleanupError)
},
}).then(
({success, completed, error, duration}) => {
sendPlaybackResult(success, error, duration, "offline sentence tts playback failed", completed)
},
(pipelineError: unknown) => {
const message = pipelineError instanceof Error ? pipelineError.message : String(pipelineError)
sendPlaybackResult(false, message, null, "offline sentence tts playback failed", false)
},
)
queueMicrotask(() => {
if (this.speechRuns.get(packageName) === run) this.setSpeakerState(packageName, "playing")
})
return true
}
let offlineGenerated: TtsSynthesisResult | undefined
try {
offlineGenerated = await ttsModelManager.synthesizeToFile(offlineSentences[0], {languageCode, speed})
} catch (offlineErr) {
if (run.cancelled) return true
console.warn(`${LOG_TAG}: offline TTS synthesize failed${reason ? ` after ${reason}` : ""}:`, offlineErr)
return false
}
const generated = offlineGenerated
if (run.cancelled) {
await Promise.resolve(generated.cleanup?.())
return true
}
run.playbackRequestId = audioRequestId
audioPlaybackService.play(
{
requestId: audioRequestId,
audioUrl: generated.audioUrl,
appId: packageName,
volume,
stopOtherAudio,
},
(_respId, success, error, duration, completionReason) => {
if (run.playbackRequestId === audioRequestId) run.playbackRequestId = undefined
void Promise.resolve(generated.cleanup?.()).catch((cleanupError) => {
console.warn(`${LOG_TAG}: offline TTS cleanup failed`, cleanupError)
})
sendPlaybackResult(
success,
error,
duration,
"offline tts playback failed",
completionReason === "completed",
)
},
)
queueMicrotask(() => {
if (this.speechRuns.get(packageName) === run) this.setSpeakerState(packageName, "playing")
})
return true
}
const playCloudTts = async (fallbackToOffline: boolean): Promise<boolean> => {
if (run.cancelled) return true
let audioUrl: string
try {
const source = await cloudClientService.tts.speak(cloudText, {
// Every cloud speech request skips a repeat readiness check for 30 s.
reusePreflight: true,
format: CLOUD_SPEECH_FORMAT,
...(voiceExplicit && voice !== "default" ? {voice_id: voice} : {}),
...(modelId ? {model_id: modelId} : {}),
...(voiceSettings ? {voice_settings: voiceSettings} : {}),
})
audioUrl = source.audioUrl
} catch (cloudErr) {
if (run.cancelled) return true
const error = cloudErr instanceof Error ? cloudErr.message : String(cloudErr)
console.warn(`${LOG_TAG}: cloud TTS source failed: ${error}`)
if (fallbackToOffline && (await playOfflineTts("cloud tts source failed"))) {
return true
}
sendPlaybackResult(false, error, null, "tts failed")
return true
}
if (run.cancelled) return true
// Stream the synthesis into the native PCM player as it arrives, the
// same way on both platforms; the audio never crosses into JavaScript.
run.playbackRequestId = audioRequestId
void audioPlaybackService.playPcmUrl(
{
requestId: audioRequestId,
appId: packageName,
url: audioUrl,
sampleRate: CLOUD_SPEECH_SAMPLE_RATE,
volume,
jitterMs: CLOUD_SPEECH_JITTER_MS,
stopOtherAudio,
suppressCloudUplink: SUPPRESS_CLOUD_UPLINK_DURING_SPEECH,
},
(_respId, success, error, duration, completionReason) => {
if (run.playbackRequestId === audioRequestId) run.playbackRequestId = undefined
// A refused request (HTTP error) played nothing, so offline speech
// can still say it. A connection lost mid-sentence already played
// part of it; report that instead of starting over in another voice.
if (!success && fallbackToOffline && !run.cancelled && cloudSpeechRefused(error)) {
void playOfflineTts("cloud tts request refused").then((started) => {
if (!started) sendPlaybackResult(false, error, duration, "tts failed")
})
return
}
sendPlaybackResult(success, error, duration, "tts failed", completionReason === "completed")
},
)
queueMicrotask(() => {
if (this.speechRuns.get(packageName) === run) this.setSpeakerState(packageName, "playing")
})
return true
}
if (processing === "localOnly") {
if (await playOfflineTts()) {
return
}
if (run.cancelled) return
const message = "tts unavailable: localOnly requested but offline TTS model is not available"
sendPlaybackResult(false, message, null, message, false, MiniappErrorCode.TTS_LOCAL_UNAVAILABLE)
return
}
if (processing === "preferLocal") {
// On-device first; the cloud when the offline model is missing or can't say it.
if (await playOfflineTts()) {
return
}
if (await playCloudTts(false)) {
return
}
} else {
if (cloudConnected && (await playCloudTts(true))) {
return
}
// Offline is the disconnected-cloud fallback. If the model is not
// available, preserve the old behavior by trying cloud as a last resort.
if (await playOfflineTts(cloudConnected ? undefined : "cloud disconnected")) {
return
}
if (await playCloudTts(false)) {
return
}
}
const message = "tts unavailable: no cloud TTS URL or offline TTS model"
sendPlaybackResult(false, message, null, message, false)
} catch (err) {
console.error(`${LOG_TAG}: speak error:`, err)
const message = err instanceof Error ? err.message : "TTS error"
sendPlaybackResult(false, message, null, "TTS error", false)
}
}
private cancelSpeech(packageName: string): void {
const run = this.speechRuns.get(packageName)
if (!run) return
run.cancelled = true
this.speechRuns.delete(packageName)
if (run.playbackRequestId) audioPlaybackService.cancelPlayback(run.playbackRequestId)
run.onCancelled?.()
}
private async handleRgbLed(packageName: string, payload: Record<string, unknown>, requestId?: string): Promise<void> {
const coerceNumber = (value: unknown, fallback: number): number => {
const coerced = Number(value)
return Number.isFinite(coerced) ? coerced : fallback
}
const ledRequestId = requestId || `led_${Date.now()}`
const action = normalizeRgbLedAction(payload.action)
const color = normalizeRgbLedColor(payload.color)
try {
const result = await BluetoothSdk.rgbLedControl(
ledRequestId,
packageName,
action,
color,
coerceNumber(payload.ontime, 1000),
coerceNumber(payload.offtime, 0),
coerceNumber(payload.count, 1),
)
this.sendResult(packageName, requestId, true, result)
} catch (err) {
this.sendResult(packageName, requestId, false, undefined, {
code: (err as {code?: string}).code || MiniappErrorCode.INTERNAL,
message: err instanceof Error ? err.message : "RGB LED command failed",
})
}
}
private async handleLocationPoll(packageName: string, requestId?: string): Promise<void> {
try {
// Expo's Android requestForegroundPermissionsAsync always delegates to
// Activity.requestPermissions(), even when permission is already granted.
// Calling it after the user presses Home therefore waits until the Activity
// resumes. Read the current grant first, and only enter the prompt flow
// while the Activity is actually foregrounded.
const permissionStartedAt = Date.now()
const permission = await resolveForegroundLocationPermission(Location, () => AppState.currentState)
const {status} = permission
console.log(
`${LOG_TAG}: location poll permission status=${status} appState=${AppState.currentState} elapsed=${
Date.now() - permissionStartedAt
}ms`,
)
if (status !== "granted") {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.PERMISSION_NOT_DECLARED,
message: "Location permission not granted",
})
return
}
// Try the OS cache first — usually instant — and only fall back to
// a fresh fix if the cache is empty. Use Low accuracy on the fresh
// path so we get a cell/wifi-tower fix in ~1s instead of waiting
// for full GPS warm-up.
const locationStartedAt = Date.now()
const cached = await Location.getLastKnownPositionAsync({maxAge: 60_000})
console.log(`${LOG_TAG}: location poll cache hit=${cached !== null} elapsed=${Date.now() - locationStartedAt}ms`)
const location = cached ?? (await Location.getCurrentPositionAsync({accuracy: Location.Accuracy.Low}))
console.log(`${LOG_TAG}: location poll resolved elapsed=${Date.now() - locationStartedAt}ms`)
this.sendResult(packageName, requestId, true, {
lat: location.coords.latitude,
lng: location.coords.longitude,
accuracy: location.coords.accuracy ?? undefined,
timestamp: location.timestamp,
})
} catch (err) {
console.error(`${LOG_TAG}: location poll error:`, err)
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: err instanceof Error ? err.message : "Location error",
})
}
}
// ---------------------------------------------------------------------------
// Navigation
// ---------------------------------------------------------------------------
/**
* All navigation handlers + their state live in NavigationHandlers. The
* dispatcher's NAVIGATION_* cases delegate here; the rest of the runtime
* cross-cuts navigation through {@link NavigationHandlers.onDisconnect}
* (mini-app disconnect) and {@link NavigationHandlers.isTripActive}
* (location-stream gating during a trip).
*/
private readonly navigationHandlers = new NavigationHandlers(
(packageName, envelope) => this.sendToMiniapp(packageName, envelope),
(packageName, requestId, ok, result, error) => this.sendResult(packageName, requestId, ok, result, error),
)
/**
* `session.blob` — persistent, per-app binary storage. Like NavigationHandlers,
* the BLOB_* dispatcher cases delegate here. It's a generic byte store; audio
* recording lives entirely in the miniapp (mic.onAudioChunk → chunked
* BLOB_WRITE), so nothing audio-specific runs in the host.
*/
private readonly blobStore = new BlobStore({
sendResult: (packageName, requestId, ok, result, error) =>
this.sendResult(packageName, requestId, ok, result, error),
getPartition: (packageName) => resolveMiniappDataPartition(packageName),
})
private readonly blobRequestQueues = new Map<string, Promise<void>>()
/** session.system share, download and openUrl; a file URL must name one of the miniapp's own blobs. */
private readonly systemActions = new MiniappSystemActions({
sendResult: (packageName, requestId, ok, result, error) =>
this.sendResult(packageName, requestId, ok, result, error),
ownFilesDirectory: (packageName) => this.blobStore.ownFilesDirectory(packageName),
isHostLink: (url) => getConfigValues().isHostLink?.(url) === true,
})
private readonly simpleStorage = new LocalMiniappStorage({
backend: localMiniappStorageBackend,
getPartition: async (packageName) => {
await cloudClientService.resolveMentraUserId()
return resolveMiniappDataPartition(packageName)
},
})
/**
* BlobStore's file helpers are synchronous once a user namespace is selected,
* but first-boot Core auth is not. Queue requests per app behind stable
* identity resolution so CREATE/WRITE/COMMIT ordering survives that wait.
*/
private enqueueBlobRequest(
packageName: string,
requestId: string | undefined,
operation: () => Promise<void> | void,
): void {
const app = this.connectedApps.get(packageName)
const previous = this.blobRequestQueues.get(packageName) ?? Promise.resolve()
const queued = previous.then(async () => {
try {
await cloudClientService.resolveMentraUserId()
} catch (err) {
console.error(`${LOG_TAG}: blob identity error:`, err)
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.NOT_CONNECTED,
message: "Blob storage is unavailable before sign-in completes",
})
return
}
// unregisterApp() or a crash-respawn may have replaced this app while
// identity resolution was pending. Never replay an old context's request
// against its replacement.
if (!app || this.connectedApps.get(packageName) !== app) return
// Invoke in request order, but do not keep the queue occupied for the
// lifetime of an async picker, download, or share sheet. CREATE/WRITE/
// COMMIT are synchronous and therefore still dispatch strictly in order.
try {
const pending = operation()
if (pending) {
void pending.catch((err) => this.handleBlobRequestError(packageName, requestId, err))
}
} catch (err) {
this.handleBlobRequestError(packageName, requestId, err)
}
})
this.blobRequestQueues.set(packageName, queued)
void queued.finally(() => {
if (this.blobRequestQueues.get(packageName) === queued) this.blobRequestQueues.delete(packageName)
})
}
private handleBlobRequestError(packageName: string, requestId: string | undefined, err: unknown): void {
console.error(`${LOG_TAG}: blob request error:`, err)
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: err instanceof Error ? err.message : "Blob storage error",
})
}
/**
* Heading is a sensor stream — start the native compass when any mini
* app is subscribed to "heading_update", stop it when none are.
*/
private headingUnsub: (() => void) | null = null
private recomputeHeadingSubscription(): void {
const wantsHeading = this.streamSubscribers.has(MiniappStreamType.HEADING_UPDATE)
if (wantsHeading && !this.headingUnsub) {
// Heading sensor lives in engine (HeadingService) — subscribe directly.
this.headingUnsub = headingService.addListener((degrees: number) => {
this.forwardEvent(MiniappStreamType.HEADING_UPDATE, {degrees})
})
} else if (!wantsHeading && this.headingUnsub) {
this.headingUnsub()
this.headingUnsub = null
}
}
/**
* Accelerometer is a sensor stream — enable the glasses IMU when any mini
* app is subscribed to "accel_data", disable it when none are. Mirrors the
* heading pattern. Only G2 streams IMU today; on other devices the native
* call is a no-op so this is harmless.
*/
private imuEnabled = false
private recomputeImuSubscription(): void {
const wantsImu = this.streamSubscribers.has(MiniappStreamType.ACCEL_DATA)
if (wantsImu === this.imuEnabled) return
this.imuEnabled = wantsImu
void BluetoothSdk.setImuEnabled(wantsImu)
}
/**
* Last rate we asked the host for. Lets us skip the cross-process call
* when nothing actually changed (most SUBSCRIBE / unregister churn
* leaves the aggregate unchanged) and tracks state for the no-active-
* subscribers → tell host to back off case.
*/
private lastAppliedLocationRate: LocationRate | null = null
/**
* Recompute the aggregate location tier across every connected
* miniapp and push the result to the host. The aggregate is the
* STRICTEST rate any single app has requested — see
* {@link LOCATION_RATE_PRIORITY} — because the GPS sample rate is a
* shared OS-level setting that we can't bias per-app.
*
* Called after every SUBSCRIBE and every unregister so that when a
* realtime-requesting app goes away the tier falls back down. If no
* connected app is asking for a location rate, we tell the host
* "off" so it can drop GPS power.
*/
private recomputeLocationTier(): void {
let bestRank = -1
for (const app of this.connectedApps.values()) {
const r = app.requestedLocationRate
if (!r) continue
const rank = locationRateRank(r)
if (rank > bestRank) {
bestRank = rank
}
}
// When no app is asking, downgrade to "off". Without this we'd
// leak the last-known-strictest rate forever (the original bug).
const next: LocationRate = bestRank >= 0 ? LOCATION_RATE_PRIORITY[bestRank] : "off"
if (next === this.lastAppliedLocationRate) return
this.lastAppliedLocationRate = next
console.log(`[LOCATION] aggregate tier → ${next}`)
void phoneLocationService.setLocationTier(next)
}
// ---------------------------------------------------------------------------
// Storage helpers
// ---------------------------------------------------------------------------
private async handleStorageGet(
packageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
try {
const key = payload.key as string
if (!key) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: "storage_get requires a key",
})
return
}
const value = await this.simpleStorage.get(packageName, key)
this.sendResult(packageName, requestId, true, {key, value})
} catch (err) {
console.error(`${LOG_TAG}: storage_get error:`, err)
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: err instanceof Error ? err.message : "Storage error",
})
}
}
private async handleStorageSet(
packageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
try {
const key = payload.key as string
if (!key) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: "storage_set requires a key",
})
return
}
await this.simpleStorage.set(packageName, key, payload.value ?? null)
this.sendResult(packageName, requestId, true)
} catch (err) {
console.error(`${LOG_TAG}: storage_set error:`, err)
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: err instanceof Error ? err.message : "Storage error",
})
}
}
private async handleStorageDelete(
packageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
try {
const key = payload.key as string
if (!key) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: "storage_delete requires a key",
})
return
}
await this.simpleStorage.delete(packageName, key)
this.sendResult(packageName, requestId, true)
} catch (err) {
console.error(`${LOG_TAG}: storage_delete error:`, err)
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: err instanceof Error ? err.message : "Storage error",
})
}
}
private async handleStorageList(
packageName: string,
_payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
try {
const keys = await this.simpleStorage.keys(packageName)
this.sendResult(packageName, requestId, true, {keys})
} catch (err) {
console.error(`${LOG_TAG}: storage_list error:`, err)
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: err instanceof Error ? err.message : "Storage error",
})
}
}
private async handleStorageClear(packageName: string, requestId?: string): Promise<void> {
try {
await this.simpleStorage.clear(packageName)
this.sendResult(packageName, requestId, true)
} catch (err) {
console.error(`${LOG_TAG}: storage_clear error:`, err)
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: err instanceof Error ? err.message : "Storage error",
})
}
}
private async handleStorageHas(
packageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
try {
const key = payload.key as string
if (!key) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: "storage_has requires a key",
})
return
}
const has = await this.simpleStorage.has(packageName, key)
this.sendResult(packageName, requestId, true, {has})
} catch (err) {
console.error(`${LOG_TAG}: storage_has error:`, err)
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: err instanceof Error ? err.message : "Storage error",
})
}
}
private async handleStorageGetAll(packageName: string, requestId?: string): Promise<void> {
try {
const values = await this.simpleStorage.getAll(packageName)
this.sendResult(packageName, requestId, true, {values})
} catch (err) {
console.error(`${LOG_TAG}: storage_get_all error:`, err)
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: err instanceof Error ? err.message : "Storage error",
})
}
}
private async handleStorageSetMultiple(
packageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
try {
const values = payload.values as Record<string, unknown> | undefined
if (!values || typeof values !== "object") {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: "storage_set_multiple requires a values object",
})
return
}
await this.simpleStorage.setMultiple(packageName, values)
this.sendResult(packageName, requestId, true)
} catch (err) {
console.error(`${LOG_TAG}: storage_set_multiple error:`, err)
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: err instanceof Error ? err.message : "Storage error",
})
}
}
// ---------------------------------------------------------------------------
// Wi-Fi ADB
// ---------------------------------------------------------------------------
private async handleSetWifiAdbState(
packageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
const result = await handleWifiAdbRequest(packageName, payload, {
isSystemPackage: (candidate) => this.isSystemPackage(candidate),
setWifiAdbState: async (enabled) => {
console.log(`${LOG_TAG}: set_wifi_adb_state enabled=${enabled} from ${packageName}`)
try {
await BluetoothSdk.setWifiAdbState(enabled)
} catch (error) {
console.error(`${LOG_TAG}: set_wifi_adb_state error:`, error)
throw error
}
},
})
if (result.ok) {
this.sendResult(packageName, requestId, true)
return
}
this.sendResult(packageName, requestId, false, undefined, result.error)
}
// ---------------------------------------------------------------------------
// Camera FOV
// ---------------------------------------------------------------------------
private async handleCameraFov(
packageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
const app = this.connectedApps.get(packageName)
const hasCameraPermission = app?.installedManifest?.permissions?.some((p) => p.type === "CAMERA")
if (!hasCameraPermission) {
logPermissionNotDeclared(packageName, "CAMERA", "to set camera FOV", `{"type": "CAMERA"}`)
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.PERMISSION_NOT_DECLARED,
message: `CAMERA permission not declared in miniapp.json. Add {"type": "CAMERA"} to the "permissions" array.`,
permission: "CAMERA",
operation: MiniappRequestType.CAMERA_FOV,
})
return
}
try {
const request = normalizeCameraFovPayload(payload)
const description =
"preset" in request ? `preset=${request.preset}` : `fov=${request.fov} roi=${request.roiPosition ?? "center"}`
console.log(`${LOG_TAG}: camera_fov_set ${description}`)
const result = await phoneCameraFovCoordinator.setOverride(packageName, request)
this.sendResult(packageName, requestId, true, result)
} catch (err) {
console.error(`${LOG_TAG}: camera_fov error:`, err)
this.sendResult(packageName, requestId, false, undefined, {
code: (err as {code?: string}).code || MiniappErrorCode.INTERNAL,
message: err instanceof Error ? err.message : "Camera FOV error",
})
}
}
/**
* Explicit IMU enable/disable from a miniapp (session.imu.setEnabled).
*
* The accel stream already auto-toggles the native IMU on subscribe (see
* {@link recomputeImuSubscription}); this is a direct override. We sync
* `this.imuEnabled` to the requested state so a subsequent subscription
* recompute with the same aggregate doesn't issue a redundant native call.
* Note that a later subscribe/unsubscribe that changes the aggregate will
* still re-derive the sensor state from subscriptions.
*/
private handleImuSetEnabled(packageName: string, payload: Record<string, unknown>, requestId?: string): void {
try {
const enabled = !!payload.enabled
console.log(`${LOG_TAG}: imu_set_enabled ${enabled} (by ${packageName})`)
this.imuEnabled = enabled
void BluetoothSdk.setImuEnabled(enabled)
this.sendResult(packageName, requestId, true)
} catch (err) {
console.error(`${LOG_TAG}: imu_set_enabled error:`, err)
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: err instanceof Error ? err.message : "IMU set-enabled error",
})
}
}
/**
* Lifecycle-scoped glasses-side VAD override from a miniapp
* (session.mic.setVoiceActivityDetectionEnabled). Requires MICROPHONE in the
* miniapp manifest. Mentra Live only today — other models no-op via DeviceStore.
*/
private async handleMicSetVadEnabled(
packageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
const app = this.connectedApps.get(packageName)
const hasMicPermission = app?.installedManifest?.permissions?.some((p) => p.type === "MICROPHONE")
if (!hasMicPermission) {
logPermissionNotDeclared(packageName, "MICROPHONE", "to set VAD enabled", `{"type": "MICROPHONE"}`)
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.PERMISSION_NOT_DECLARED,
message: `MICROPHONE permission not declared in miniapp.json. Add {"type": "MICROPHONE"} to the "permissions" array.`,
permission: "MICROPHONE",
operation: MiniappRequestType.MIC_SET_VAD_ENABLED,
})
return
}
if (typeof payload.enabled !== "boolean") {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INVALID_ARGUMENT,
message: "enabled must be a boolean",
})
return
}
try {
const enabled = payload.enabled
console.log(`${LOG_TAG}: mic_set_vad_enabled ${enabled} (by ${packageName})`)
await micStateCoordinator.setMiniappGateOverride(packageName, "vad", enabled, this.getConfiguredMicGates())
this.sendResult(packageName, requestId, true)
} catch (err) {
console.error(`${LOG_TAG}: mic_set_vad_enabled error:`, err)
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: err instanceof Error ? err.message : "VAD set-enabled error",
})
}
}
/**
* Lifecycle-scoped center-mic loudness gate ("Barrier") override from a miniapp
* (session.mic.setLoudnessGateEnabled). Requires MICROPHONE in the miniapp
* manifest. Mentra Live only today — other models no-op via DeviceStore.
*/
private async handleMicSetLoudnessGateEnabled(
packageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
const app = this.connectedApps.get(packageName)
const hasMicPermission = app?.installedManifest?.permissions?.some((p) => p.type === "MICROPHONE")
if (!hasMicPermission) {
logPermissionNotDeclared(packageName, "MICROPHONE", "to set loudness gate enabled", `{"type": "MICROPHONE"}`)
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.PERMISSION_NOT_DECLARED,
message: `MICROPHONE permission not declared in miniapp.json. Add {"type": "MICROPHONE"} to the "permissions" array.`,
permission: "MICROPHONE",
operation: MiniappRequestType.MIC_SET_LOUDNESS_GATE_ENABLED,
})
return
}
if (typeof payload.enabled !== "boolean") {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INVALID_ARGUMENT,
message: "enabled must be a boolean",
})
return
}
try {
const enabled = payload.enabled
console.log(`${LOG_TAG}: mic_set_loudness_gate_enabled ${enabled} (by ${packageName})`)
await micStateCoordinator.setMiniappGateOverride(
packageName,
"loudnessGate",
enabled,
this.getConfiguredMicGates(),
)
this.sendResult(packageName, requestId, true)
} catch (err) {
console.error(`${LOG_TAG}: mic_set_loudness_gate_enabled error:`, err)
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: err instanceof Error ? err.message : "Loudness gate set-enabled error",
})
}
}
/**
* session.mic.acquire — take a semantic microphone session.
*
* The miniapp names a use case; MicSessionManager and micPolicy decide what that means for the
* hardware. This handler is only the gate: who is allowed to ask for what.
*/
private handleMicAcquire(packageName: string, payload: Record<string, unknown>, requestId?: string): void {
const app = this.connectedApps.get(packageName)
const hasMicPermission = app?.installedManifest?.permissions?.some((p) => p.type === "MICROPHONE")
if (!hasMicPermission) {
logPermissionNotDeclared(packageName, "MICROPHONE", "to acquire a microphone session", `{"type": "MICROPHONE"}`)
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.PERMISSION_NOT_DECLARED,
message: `MICROPHONE permission not declared in miniapp.json. Add {"type": "MICROPHONE"} to the "permissions" array.`,
permission: "MICROPHONE",
operation: MiniappRequestType.MIC_ACQUIRE,
})
return
}
const source = payload.source
const useCase = payload.useCase
if (source !== "glasses" && source !== "phone") {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INVALID_ARGUMENT,
message: `source must be "glasses" or "phone"`,
})
return
}
if (!MIC_USE_CASES.includes(useCase as MicUseCase)) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INVALID_ARGUMENT,
message: `useCase must be one of ${MIC_USE_CASES.join(", ")}`,
})
return
}
// A voice call gets a microphone profile tuned for close-talk speech, so which app may ask for
// one is a product decision, not a permission a manifest can grant itself.
if (useCase === "voice_call" && !VOICE_CALL_PACKAGES.includes(packageName)) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.PERMISSION_DENIED,
message: `${packageName} is not allowed to acquire a voice_call microphone session`,
})
return
}
// Diagnostic leases exist so the mic probe measures what users actually get. Handing one to a
// miniapp would also hand it a glasses lease it could pair with a meeting join.
if (ENGINE_ONLY_USE_CASES.includes(useCase as MicUseCase)) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.PERMISSION_DENIED,
message: `the ${useCase} microphone use case is reserved for the Mentra App`,
})
return
}
try {
const session = micSessionManager.acquire({owner: packageName, source, useCase: useCase as MicUseCase})
this.micSessionsByApp.set(session.id, {packageName, session})
console.log(`${LOG_TAG}: mic_acquire #${session.id} ${useCase}/${source} (by ${packageName})`)
this.sendResult(packageName, requestId, true, {sessionId: session.id})
} catch (err) {
const message = err instanceof Error ? err.message : "mic acquire error"
console.warn(`${LOG_TAG}: mic_acquire failed for ${packageName}:`, message)
this.sendResult(packageName, requestId, false, undefined, {
code: message.startsWith(MIC_SOURCE_CONFLICT)
? MiniappErrorCode.MIC_SOURCE_CONFLICT
: MiniappErrorCode.INTERNAL,
message,
})
}
}
/** session.mic.acquire(...).release() — drop one session, if the caller owns it. */
private handleMicRelease(packageName: string, payload: Record<string, unknown>, requestId?: string): void {
const sessionId = payload.sessionId
const entry = typeof sessionId === "number" ? this.micSessionsByApp.get(sessionId) : undefined
if (!entry || entry.packageName !== packageName) {
// Idempotent by design: a miniapp releasing twice, or releasing after unregister already
// dropped its sessions, is not an error worth failing a teardown path over.
this.sendResult(packageName, requestId, true)
return
}
this.micSessionsByApp.delete(entry.session.id)
entry.session.release()
console.log(`${LOG_TAG}: mic_release #${entry.session.id} (by ${packageName})`)
this.sendResult(packageName, requestId, true)
}
/** Drop the bookkeeping for every session an app owns. The manager is the source of truth. */
private forgetMicSessions(packageName: string): void {
for (const [id, entry] of this.micSessionsByApp) {
if (entry.packageName === packageName) this.micSessionsByApp.delete(id)
}
}
/**
* session.system.scanQr — host camera overlay. Must not clear miniapp
* foreground; the host seam is responsible for presenting a Modal on top.
*/
private async handleScanQr(packageName: string, payload: Record<string, unknown>, requestId?: string): Promise<void> {
try {
const result = await invokeScanQrSeam(getUiSeams().scanQr, payload)
this.sendResult(packageName, requestId, true, result)
} catch (err) {
if (!getUiSeams().scanQr) {
console.warn(`${LOG_TAG}: scanQr seam missing — QR overlay is not registered`)
}
this.sendResult(packageName, requestId, false, undefined, {
code: (err as {code?: string} | null | undefined)?.code || MiniappErrorCode.INTERNAL,
message: err instanceof Error ? err.message : "QR scan failed",
})
}
}
// ---------------------------------------------------------------------------
// System utilities (share, open URL and download are in MiniappSystemActions)
// ---------------------------------------------------------------------------
private async handleCopyClipboard(
packageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
const text = payload.text as string | undefined
if (typeof text !== "string") {
console.warn(`${LOG_TAG}: copy_clipboard missing text`)
return
}
try {
await Clipboard.setStringAsync(text)
this.sendResult(packageName, requestId, true)
} catch (error: any) {
console.error(`${LOG_TAG}: clipboard error:`, error)
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: error?.message || "Clipboard error",
})
}
}
// ===========================================================================
// Photo + streaming handlers (cloud-coordinated)
// ===========================================================================
/**
* Manifest permission gate shared by the camera-and-mic RPCs (streams, meetings).
* Sends PERMISSION_NOT_DECLARED and returns false when the miniapp did not declare
* `permission`; the caller must return without doing the work.
*/
private requireManifestPermission(
packageName: string,
requestId: string | undefined,
permission: "CAMERA" | "PHONE_CAMERA" | "MICROPHONE",
purpose: string,
operation: MiniappRequestType,
): boolean {
const app = this.connectedApps.get(packageName)
if (app?.installedManifest?.permissions?.some((p) => p.type === permission)) return true
logPermissionNotDeclared(packageName, permission, purpose, `{"type": "${permission}"}`)
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.PERMISSION_NOT_DECLARED,
message: `${permission} permission not declared in miniapp.json. Add {"type": "${permission}"} to the "permissions" array.`,
permission,
operation,
})
return false
}
/**
* OS-permission gate: checked, never requested.
*
* The prompt belongs at miniapp-open time, where it can be explained. Requesting here would put
* a system dialog on top of a join that has already started building a hotspot, and a wearer who
* denies it gets a call that half-exists. Missing means the join is refused with the permission
* named, so the miniapp can send them to Settings.
*/
private async requireOsPermission(
packageName: string,
requestId: string | undefined,
feature: string,
label: string,
): Promise<boolean> {
if (await permissions.check(feature)) return true
softapTraceFailure("softap_permission_missing", {packageName, feature})
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.PERMISSION_DENIED,
message: `This phone's ${label} permission is not granted. Grant it in Settings, then try again.`,
permission: feature,
operation: MiniappRequestType.MEETING_JOIN,
})
return false
}
private async handlePhoto(packageName: string, payload: Record<string, unknown>, requestId?: string): Promise<void> {
// Manifest CAMERA permission gate.
const app = this.connectedApps.get(packageName)
const hasCameraPermission = app?.installedManifest?.permissions?.some((p) => p.type === "CAMERA")
if (!hasCameraPermission) {
logPermissionNotDeclared(packageName, "CAMERA", "to take a photo", `{"type": "CAMERA"}`)
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.PERMISSION_NOT_DECLARED,
message: `CAMERA permission not declared in miniapp.json. Add {"type": "CAMERA"} to the "permissions" array.`,
permission: "CAMERA",
operation: MiniappRequestType.PHOTO,
})
return
}
try {
const result = await phonePhotoCoordinator.takePhoto(packageName, {
size: payload.size as "low" | "medium" | "high" | "max" | "small" | "large" | "full" | undefined,
mode: payload.mode as "photo" | "text" | undefined,
transferMethod: payload.transferMethod as "auto" | "direct" | "ble" | undefined,
compress: parsePhotoCompression(payload.compress),
sound: payload.sound as boolean | undefined,
saveToGallery: payload.saveToGallery as boolean | undefined,
exposureTimeNs: payload.exposureTimeNs as number | undefined,
iso: payload.iso as number | null | undefined,
aeExposureDivisor: payload.aeExposureDivisor as number | undefined,
isoCap: payload.isoCap as number | undefined,
noiseReduction: payload.noiseReduction as boolean | undefined,
edgeEnhancement: payload.edgeEnhancement as boolean | undefined,
zsl: payload.zsl as boolean | undefined,
mfnr: payload.mfnr as boolean | undefined,
ispDigitalGain: payload.ispDigitalGain as number | undefined,
ispAnalogGain: payload.ispAnalogGain as string | undefined,
})
this.sendResult(packageName, requestId, true, result)
// The photo reached the miniapp. A call with no request ID has nobody to answer, so nothing was delivered.
if (requestId) fleetEvents.photo({operationId: result.requestId, stage: "delivered"})
} catch (err) {
this.sendResult(packageName, requestId, false, undefined, {
code: (err as {code?: string}).code || MiniappErrorCode.INTERNAL,
message: err instanceof Error ? err.message : "Photo request failed",
stage: (err as {stage?: string}).stage,
transport: (err as {transport?: string}).transport,
})
}
}
private async handleCameraWarmUp(
packageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
// Manifest CAMERA permission gate (same as photo).
const app = this.connectedApps.get(packageName)
const hasCameraPermission = app?.installedManifest?.permissions?.some((p) => p.type === "CAMERA")
if (!hasCameraPermission) {
logPermissionNotDeclared(packageName, "CAMERA", "to warm up the camera", `{"type": "CAMERA"}`)
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.PERMISSION_NOT_DECLARED,
message: `CAMERA permission not declared in miniapp.json. Add {"type": "CAMERA"} to the "permissions" array.`,
permission: "CAMERA",
operation: MiniappRequestType.CAMERA_WARM_UP,
})
return
}
try {
await phonePhotoCoordinator.warmUpCamera(packageName, {
size: payload.size as "low" | "medium" | "high" | "max" | undefined,
mode: payload.mode as "photo" | "text" | undefined,
exposureTimeNs: payload.exposureTimeNs as number | undefined,
durationMs: payload.durationMs as number | undefined,
zsl: payload.zsl as boolean | undefined,
mfnr: payload.mfnr as boolean | undefined,
})
this.sendResult(packageName, requestId, true)
} catch (err) {
this.sendResult(packageName, requestId, false, undefined, {
code: (err as {code?: string}).code || MiniappErrorCode.INTERNAL,
message: err instanceof Error ? err.message : "Camera warm-up failed",
stage: (err as {stage?: string}).stage,
transport: (err as {transport?: string}).transport,
})
}
}
private async handleVideoRecordingStart(
packageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
// Manifest CAMERA permission gate (same as photo).
const app = this.connectedApps.get(packageName)
const hasCameraPermission = app?.installedManifest?.permissions?.some((p) => p.type === "CAMERA")
if (!hasCameraPermission) {
logPermissionNotDeclared(packageName, "CAMERA", "to record video", `{"type": "CAMERA"}`)
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.PERMISSION_NOT_DECLARED,
message: `CAMERA permission not declared in miniapp.json. Add {"type": "CAMERA"} to the "permissions" array.`,
permission: "CAMERA",
operation: MiniappRequestType.VIDEO_RECORDING_START,
})
return
}
try {
const result = await phoneVideoCoordinator.startRecording(packageName, {
width: payload.width as number | undefined,
height: payload.height as number | undefined,
fps: payload.fps as number | undefined,
sound: payload.sound as boolean | undefined,
save: payload.save as boolean | undefined,
})
this.sendResult(packageName, requestId, true, result)
} catch (err) {
this.sendResult(packageName, requestId, false, undefined, {
code: (err as {code?: string}).code || MiniappErrorCode.INTERNAL,
message: err instanceof Error ? err.message : "Video recording start failed",
})
}
}
private async handleVideoRecordingStop(
packageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
try {
await phoneVideoCoordinator.stopRecording(packageName, payload.recordingId as string | undefined, {
uploadUrl: payload.uploadUrl as string | undefined,
uploadAuthToken: payload.uploadAuthToken as string | undefined,
})
this.sendResult(packageName, requestId, true)
} catch (err) {
this.sendResult(packageName, requestId, false, undefined, {
code: (err as {code?: string}).code || MiniappErrorCode.INTERNAL,
message: err instanceof Error ? err.message : "Video recording stop failed",
})
}
}
/**
* Stream handlers — dispatched to PhoneStreamCoordinator on the phone.
* Managed streams also use Cloud V2 REST calls to provision resources,
* poll ingest status, and tear down the managed stream. Miniapp JavaScript
* runs locally in the Mentra App.
*/
private async handleStreamStart(
packageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
const streaming = phoneStreamCoordinator
if (!streaming) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.NOT_IMPLEMENTED,
message: "Streaming is not configured on this host",
})
return
}
// A stream is the glasses camera (and mic) leaving the device; gate it like a photo.
if (
!this.requireManifestPermission(
packageName,
requestId,
"CAMERA",
"to stream the camera",
MiniappRequestType.STREAM_START,
)
) {
return
}
try {
const result = await streaming.startUnmanaged(packageName, {
streamUrl: payload.streamUrl as string,
video: normalizeStreamVideoConfig(payload.video),
audio: normalizeStreamAudioConfig(payload.audio),
sound: payload.sound as boolean | undefined,
authToken: typeof payload.authToken === "string" ? payload.authToken : undefined,
captureAudio: resolveCaptureAudio(payload.captureAudio, resolveAcsAudioSource().source),
})
this.sendResult(packageName, requestId, true, result)
} catch (err) {
this.sendResult(packageName, requestId, false, undefined, {
code: (err as {code?: string}).code || MiniappErrorCode.INTERNAL,
message: err instanceof Error ? err.message : "Stream start failed",
stage: (err as {stage?: string}).stage,
transport: (err as {transport?: string}).transport,
})
}
}
private async handleStreamStop(
packageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
const streaming = phoneStreamCoordinator
if (!streaming) {
// No adapter wired — treat as already-stopped.
this.sendResult(packageName, requestId, true)
return
}
try {
await streaming.stop(packageName, payload.streamId as string | undefined)
this.sendResult(packageName, requestId, true)
} catch (err) {
this.sendResult(packageName, requestId, false, undefined, {
code: (err as {code?: string}).code || MiniappErrorCode.INTERNAL,
message: err instanceof Error ? err.message : "Stream stop failed",
stage: (err as {stage?: string}).stage,
transport: (err as {transport?: string}).transport,
})
}
}
private async handleManagedStreamStart(
packageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
const streaming = phoneStreamCoordinator
if (!streaming) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.NOT_IMPLEMENTED,
message: "Streaming is not configured on this host",
})
return
}
if (
!this.requireManifestPermission(
packageName,
requestId,
"CAMERA",
"to stream the camera",
MiniappRequestType.MANAGED_STREAM_START,
)
) {
return
}
try {
if (payload.ingest === "whip" && !(await permissions.check(PermissionFeatures.LOCAL_WIFI))) {
if (!(await permissions.request(PermissionFeatures.LOCAL_WIFI))) {
throw new Error("Nearby devices permission is required to join the glasses hotspot")
}
}
const result = await streaming.startManaged(packageName, {
restreamDestinations: payload.restreamDestinations as Array<string | {url: string; name?: string}> | undefined,
video: normalizeStreamVideoConfig(payload.video),
audio: normalizeStreamAudioConfig(payload.audio),
sound: payload.sound as boolean | undefined,
ingest: payload.ingest as "srt" | "whip" | "rtmp" | undefined,
captureAudio: normalizeCaptureAudio(payload.captureAudio),
})
this.sendResult(packageName, requestId, true, result)
} catch (err) {
this.sendResult(packageName, requestId, false, undefined, {
code: (err as {code?: string}).code || MiniappErrorCode.INTERNAL,
message: err instanceof Error ? err.message : "Managed stream start failed",
stage: (err as {stage?: string}).stage,
transport: (err as {transport?: string}).transport,
})
}
}
private async handleManagedStreamStop(
packageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
return this.handleStreamStop(packageName, payload, requestId)
}
/** True when the installed manifest of a connected miniapp declares `permission`. */
public hasManifestPermission(packageName: string, permission: string): boolean {
return (
this.connectedApps.get(packageName)?.installedManifest?.permissions?.some((p) => p.type === permission) ?? false
)
}
/**
* Raw decoded-frame preview lease. Authorization, the single-holder rule and the lease's
* lifetime live in the host coordinator; the runtime supplies identity and delivery.
*/
private async handleStreamPreviewStart(
packageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
const app = this.connectedApps.get(packageName)
const previewHost = getStreamPreviewHost()
if (!app || !previewHost) {
this.sendResult(packageName, requestId, false, undefined, {
code: "unsupported",
message: "Stream preview is not available in this Mentra App",
})
return
}
const runtimeId = app.runtimeId
try {
const result = await previewHost.start(
{packageName, runtimeId, source: payload.source, hasCamera: this.hasManifestPermission(packageName, "CAMERA")},
(event) => {
// A respawned background must not hear about its predecessor's lease.
if (this.connectedApps.get(packageName)?.runtimeId !== runtimeId) return
this.sendToMiniapp(packageName, {type: MiniappResponseType.STREAM_PREVIEW_STATUS, ...event})
},
)
this.sendResult(packageName, requestId, true, result)
} catch (err) {
const code = (err as {code?: unknown}).code
this.sendResult(packageName, requestId, false, undefined, {
code: typeof code === "string" ? code : "unsupported",
message: err instanceof Error ? err.message : "Stream preview failed",
})
}
}
private async handleStreamPreviewStop(
packageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
const app = this.connectedApps.get(packageName)
const previewHost = getStreamPreviewHost()
if (app && previewHost && typeof payload.handleId === "string") {
try {
await previewHost.stop({packageName, runtimeId: app.runtimeId, handleId: payload.handleId})
} catch (err) {
console.warn(`${LOG_TAG}: stream preview stop failed for ${packageName}`, err)
}
}
// Releasing is idempotent from the miniapp's side: an unknown or stale handle is already gone.
this.sendResult(packageName, requestId, true)
}
private ensureMeetingStateBridge(): void {
acsMeetingService.setPhotoPauseExpiredHandler((pauseId) => {
const owner = acsMeetingService.ownerPackage()
if (owner) this.notifyPhotoPauseExpired(owner, pauseId)
})
acsMeetingService.setStateHandler((owner, state) => {
const attempt = this.softapAttempt
// While a replacement waits for cleanup, native events still describe its predecessor.
if (attempt?.packageName === owner && !attempt.ownsResources) return
this.sendToMiniapp(owner, {
type: MiniappResponseType.MEETING_STATE,
...state,
...this.softapRecoveryFields(attempt?.packageName === owner ? attempt : null),
})
if (attempt?.ownsResources && attempt.transport?.shouldRepublish(state.mediaSource)) {
void attempt.transport.republish(state.mediaSourceReason ?? "mediaSource failed")
}
})
}
/** Startup owns the hotspot before ACS has an owner. Closing the app must retire both. */
private readonly meetingCredentialRequests = new Map<string, object>()
private async handleMeetingIdentity(packageName: string, requestId?: string): Promise<void> {
try {
this.sendResult(packageName, requestId, true, await meetingIdentity())
} catch (error) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: error instanceof Error ? error.message : "Could not check the meeting identity",
})
}
}
private async handleMeetingCreate(
packageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
try {
// Provider credentials and organizer IDs are host-owned, never copied from the RPC.
const result = await createMeeting({
provider: payload.provider as "acs-teams",
subject: payload.subject as string | undefined,
durationMinutes: payload.durationMinutes as number | undefined,
})
this.sendResult(packageName, requestId, true, result)
} catch (error) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: error instanceof Error ? error.message : "Meeting creation failed",
})
}
}
private async handleMeetingRetire(
packageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
try {
await retireMeeting(payload.meetingRef as string)
this.sendResult(packageName, requestId, true)
} catch (error) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: error instanceof Error ? error.message : "Meeting retirement failed",
})
}
}
private async leaveMeetingForApp(packageName: string): Promise<void> {
this.meetingCredentialRequests.delete(packageName)
const attempt = this.softapAttempt
if (attempt?.packageName === packageName) {
await this.retireSoftapAttempt({attempt})
} else {
await acsMeetingService.leaveIfOwner(packageName)
}
}
private async handleMeetingJoin(
packageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
const credentialRequest = {}
this.meetingCredentialRequests.set(packageName, credentialRequest)
if (!meetingConfiguration().enabled) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.PERMISSION_DENIED,
message: "Native meetings are disabled by this deployment",
})
return
}
this.ensureMeetingStateBridge()
// A meeting puts the glasses camera and mic in front of remote strangers; it
// needs both declared, same as photo/stream and mic capture do individually.
if (
!this.requireManifestPermission(
packageName,
requestId,
"CAMERA",
"to join a meeting",
MiniappRequestType.MEETING_JOIN,
) ||
!this.requireManifestPermission(
packageName,
requestId,
"MICROPHONE",
"to join a meeting",
MiniappRequestType.MEETING_JOIN,
) ||
!this.requireManifestPermission(
packageName,
requestId,
"PHONE_CAMERA",
"to join a meeting",
MiniappRequestType.MEETING_JOIN,
)
) {
return
}
// Defensive only: these are prompted for when the wearer opens the miniapp, so by the time a
// join runs they are either granted or were refused minutes ago on a screen that explained
// them. Checked and never requested — a permission dialog on top of a half-built call is
// asked too late to explain itself, and ACS fails the join outright without the camera.
if (!(await this.requireOsPermission(packageName, requestId, PermissionFeatures.CAMERA, "camera"))) return
if (!(await this.requireOsPermission(packageName, requestId, PermissionFeatures.MICROPHONE, "microphone"))) return
// The wearer's voice rides a microphone session, not the meeting. An app allowed to make voice
// calls must hold one before the sink starts, or it would get a call configured for dictation.
// Other joiners are not required to: without a session the BLE LC3 uplink is simply not
// selected and the audio rides the WHIP capture path, exactly as it did before.
const glassesSession = micSessionManager.hasGlassesSession(packageName)
if (VOICE_CALL_PACKAGES.includes(packageName) && !glassesSession) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.MIC_SESSION_REQUIRED,
message: "acquire a glasses microphone session before joining a meeting",
})
return
}
const meetingUrl = typeof payload.meetingUrl === "string" ? payload.meetingUrl : ""
const legacyToken = typeof payload.token === "string" ? payload.token : undefined
const displayName = typeof payload.displayName === "string" ? payload.displayName : undefined
// Diagnostic only. A miniapp that does not send it gets `unknown`, which is a third answer in
// the comparison rather than a default that would quietly file every old build under "created".
const origin = parseAcsCallOrigin(payload.origin)
if (!meetingUrl) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INVALID_ARGUMENT,
message: "meetingUrl is required",
})
return
}
let videoSource: AcsVideoSource
try {
videoSource = parseAcsVideoSource(payload.videoSource)
} catch (error) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INVALID_ARGUMENT,
message: error instanceof Error ? error.message : "Invalid meeting video source",
})
return
}
try {
let video: ReturnType<typeof parseAcsOutgoingVideo>
try {
video = parseAcsOutgoingVideo(payload.video)
} catch (error) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INVALID_ARGUMENT,
message: error instanceof Error ? error.message : "Invalid meeting video",
})
return
}
const configuration = meetingConfiguration()
if (!configuration.externalBackendAllowed && videoSource.type !== "softap") {
throw new Error("Private meetings require direct glasses video")
}
const credential = await meetingCredential(legacyToken)
if (this.meetingCredentialRequests.get(packageName) !== credentialRequest) {
throw new Error("Meeting join was cancelled")
}
const {token, identityMode, guestReason} = credential
const identity: MeetingIdentity = {identityMode, guestReason}
// SoftAP is a sequence, not a single call: the hotspot and the scoped network have to exist
// before the ACS join binds a listener, and the glasses can only be told where to publish
// after that. The miniapp asks for the transport and the host owns the ordering.
if (videoSource.type === "softap") {
// The miniapp's `requestId` is the only identifier the two logs share until the attempt
// exists, so it is what joins the miniapp's own join line to the host's.
softapTrace("meeting_join_request", {
packageName,
requestId: requestId ?? "none",
transport: videoSource.type,
hasDisplayName: Boolean(displayName),
video: video ? `${video.width}x${video.height}@${video.fps}` : "default",
origin,
})
const startedAt = Date.now()
try {
const state = await this.joinSoftapMeeting(packageName, {
meetingUrl,
token,
identity,
displayName,
video,
origin,
glassesSession,
})
softapTrace("meeting_join_result", {
packageName,
requestId: requestId ?? "none",
state: state.state,
micTransport: state.micTransport ?? "unknown",
durationMs: Date.now() - startedAt,
})
this.sendResult(packageName, requestId, true, state)
} catch (error) {
softapTraceFailure("meeting_join_result", {
packageName,
requestId: requestId ?? "none",
step: error instanceof SoftapCallError ? error.step : "unknown",
code: error instanceof SoftapCallError ? error.code : "INTERNAL",
reason: error instanceof Error ? error.message : String(error),
durationMs: Date.now() - startedAt,
})
throw error
}
return
}
const state = await acsMeetingService.join(packageName, {
meetingUrl,
token,
identity,
videoSource,
displayName,
origin,
glassesSession,
...(video ? {video} : {}),
})
this.sendResult(packageName, requestId, true, state)
} catch (err) {
// A SoftAP failure already knows what it was and where. Flattening every one of them to
// INTERNAL is what left the miniapp unable to tell "your Wi-Fi is off" — a condition with a
// two-tap fix — from an ACS timeout, so it showed the same shrug for both. The step comes
// along too: the same code at `hotspot` and at `scopedJoin` are different stories.
const softap = err instanceof SoftapCallError ? err : undefined
this.sendResult(packageName, requestId, false, undefined, {
code: softap?.code ?? MiniappErrorCode.INTERNAL,
message: err instanceof Error ? err.message : "ACS meeting join failed",
...(softap ? {step: softap.step} : {}),
})
}
}
/**
* Runs the SoftAP call sequence and returns the meeting state it reached.
*
* Everything is hung off one [SoftapAttempt] registered before the first `await`, because the
* cancellable part of this starts immediately and the transport only exists halfway through.
* The attempt is also what `meeting.leave` unwinds: leaving only the ACS call would strand the
* glasses publishing into a listener nobody reads, the phone on a hotspot it no longer needs,
* and this process pinned to cellular.
*/
private async joinSoftapMeeting(
packageName: string,
args: {
meetingUrl: string
token: string
identity?: MeetingIdentity
displayName?: string
video?: AcsOutgoingVideo
origin?: AcsCallOrigin
glassesSession: boolean
},
): Promise<MeetingState> {
// Reserve before awaiting retirement: a second Start or Cancel must see this request,
// including while it is waiting for its predecessor's native cleanup.
const previous = this.softapAttempt
const attempt = this.createSoftapAttempt(packageName)
this.softapAttempt = attempt
const body = this.runSoftapAttempt(attempt, previous, args)
// Settled, never rejected: this exists so the *next* attempt can tell when this one's native
// work has actually stopped, and a rejection here is already handled below.
attempt.body = body.then(
() => undefined,
() => undefined,
)
try {
return await body
} catch (error) {
softapTraceFailure("softap_attempt_failed", {
attempt: attempt.id,
step: error instanceof SoftapCallError ? error.step : "unknown",
code: error instanceof SoftapCallError ? error.code : "INTERNAL",
reason: error instanceof Error ? error.message : String(error),
attemptAgeMs: Date.now() - attempt.startedAt,
})
// Unwind whatever the attempt reached — including the preflight-owned agent and cellular
// pin, which the transport never sees — before the failure surfaces.
await this.retireSoftapAttempt({attempt}).catch(() => undefined)
throw error
}
}
private createSoftapAttempt(packageName: string): SoftapAttempt {
const id = ++this.softapAttemptSeq
let resolveSettled!: () => void
const settled = new Promise<void>((resolve) => {
resolveSettled = resolve
})
const attempt: SoftapAttempt = {
id,
packageName,
startedAt: Date.now(),
cancelled: false,
ownsResources: false,
transport: null,
progress: {
traceId: `preflight-${id}`,
phase: "starting",
steps: SOFTAP_STEPS.map((step) => ({step, status: "pending" as const})),
elapsedMs: 0,
mediaGeneration: 0,
},
scopedLostUnsub: null,
recovery: null,
recoveryActive: false,
recoveryDeadlineAt: null,
body: null,
teardown: null,
settled,
settledDone: false,
markSettled: () => {
if (attempt.settledDone) return
attempt.settledDone = true
softapTrace("softap_attempt_settled", {attempt: id, attemptAgeMs: Date.now() - attempt.startedAt})
resolveSettled()
},
}
softapTrace("softap_attempt_created", {attempt: id, packageName})
return attempt
}
/**
* Throws if this attempt has been cancelled or superseded.
*
* Called after every `await` in the join. The wearer's Cancel cannot interrupt a native call
* that is already in flight, so the next best thing — and the thing that actually makes Cancel
* work — is to refuse to take another step once they have asked.
*
* @param after the await this checkpoint follows. The whole join surfaces as one CANCELLED
* error, so without a name in the log there is no way to tell a Cancel during the permission
* prompt from one during a 35-second Teams sign-in.
*/
private checkpointSoftapAttempt(attempt: SoftapAttempt, after: string): void {
if (attempt.cancelled || this.softapAttempt !== attempt) {
softapTraceFailure("softap_attempt_cancelled", {
attempt: attempt.id,
after,
attemptAgeMs: Date.now() - attempt.startedAt,
// Two different causes with one outcome: the wearer asked to leave, or a second join
// took the slot. They need different fixes, so they are not collapsed here.
cause: attempt.cancelled ? "retired" : "superseded",
current: this.softapAttempt?.id ?? "none",
})
throw new SoftapCallError("hotspot", "CANCELLED", "The call was cancelled while it was starting")
}
}
/** Publishes a checklist snapshot, unless this attempt has already been superseded. */
private emitSoftapProgress(attempt: SoftapAttempt, progress: SoftapProgress): void {
if (this.softapAttempt !== attempt || attempt.cancelled) {
// A dropped checklist is why a stalled join used to look like a stuck UI: the wearer's last
// row was written by an attempt that no longer owned the call, and nothing said so.
softapTrace("softap_progress_dropped", {
attempt: attempt.id,
phase: progress.phase,
traceId: progress.traceId,
cause: attempt.cancelled ? "retired" : "superseded",
current: this.softapAttempt?.id ?? "none",
})
return
}
attempt.progress = progress
// A reservation waiting behind another call must not inherit that call's connected state.
const current = attempt.transport ? acsMeetingService.getState() : {state: "connecting", muted: false}
this.sendToMiniapp(attempt.packageName, {
type: MiniappResponseType.MEETING_STATE,
...current,
// Before the ACS join there is no native state yet, so the phase reads `connecting`: the
// join *is* in progress, and `idle` would make the miniapp think the call ended.
state: current.state === "idle" ? "connecting" : current.state,
softap: progress,
...this.softapRecoveryFields(attempt),
})
}
private softapRecoveryFields(attempt: SoftapAttempt | null | undefined): {
recovery?: {
active: boolean
generation?: number
deadlineAt?: number
phase?: string
}
} {
if (!attempt?.recoveryDeadlineAt) return {}
return {
recovery: {
active: attempt.recoveryActive,
generation: attempt.transport?.currentMediaGeneration(),
deadlineAt: attempt.recoveryDeadlineAt,
phase: attempt.transport?.currentPhase(),
},
}
}
/**
* Narrates preflight work on the first row while it is still pending.
*
* Permissions, mobile data, and the ACS sign-in take most of a minute between them and happen
* before the transport exists, so without this the wearer watches five pending rows and
* concludes the app has hung. No new step and no protocol change: it is the `hotspot` row's
* detail, which the connecting screen renders as its one sub-line until step 1 starts.
*/
private narrateSoftapPreflight(attempt: SoftapAttempt, detail: string): void {
this.emitSoftapProgress(attempt, {
...attempt.progress,
elapsedMs: Date.now() - attempt.startedAt,
steps: attempt.progress.steps.map((step) => (step.step === "hotspot" ? {...step, detail} : step)),
})
}
private async runSoftapAttempt(
attempt: SoftapAttempt,
previous: SoftapAttempt | null,
args: {
meetingUrl: string
token: string
identity?: MeetingIdentity
displayName?: string
video?: AcsOutgoingVideo
origin?: AcsCallOrigin
glassesSession: boolean
},
): Promise<MeetingState> {
const packageName = attempt.packageName
if (previous) {
this.narrateSoftapPreflight(attempt, "Finishing the previous call’s cleanup…")
softapTrace("softap_join_superseding", {
previousAttempt: previous.id,
previousAgeMs: Date.now() - previous.startedAt,
previousPhase: previous.progress.phase,
packageName,
})
await this.retireSoftapAttempt({attempt: previous}).catch(() => undefined)
await awaitCleanupBarrier({
settled: previous.settled,
settledDone: previous.settledDone,
narrate: (detail) => this.narrateSoftapPreflight(attempt, detail),
narrateAfterMs: SOFTAP_CLEANUP_NARRATE_AFTER_MS,
attempt: attempt.id,
waitingFor: `attempt ${previous.id} teardown`,
})
}
this.checkpointSoftapAttempt(attempt, "cleanup barrier")
const cleanupError = this.softapCleanupError
if (cleanupError) {
// Cleared on read, so this refuses at most once and the next attempt always gets through —
// which is why the wearer is told to retry rather than to go power-cycle anything. The
// native reason stays in the trace: it names a leaked port, not something they can act on.
this.softapCleanupError = null
softapTraceFailure("softap_join_refused", {packageName, reason: cleanupError})
throw new Error("Previous call cleanup has not finished yet. Please try joining again.")
}
attempt.releaseHotspot = acquireGlassesHotspot()
attempt.ownsResources = true
this.narrateSoftapPreflight(attempt, "Checking the Nearby devices permission…")
const permissionStartedAt = Date.now()
if (!(await permissions.check(PermissionFeatures.LOCAL_WIFI))) {
this.checkpointSoftapAttempt(attempt, "permission check")
softapTrace("softap_permission_prompt", {attempt: attempt.id, permission: "LOCAL_WIFI"})
const granted = await permissions.request(PermissionFeatures.LOCAL_WIFI)
this.checkpointSoftapAttempt(attempt, "permission prompt")
softapTrace("softap_permission_result", {
attempt: attempt.id,
granted,
// The prompt is modal, so this is the wearer's own reaction time and the single largest
// unexplained gap in a first-run join.
durationMs: Date.now() - permissionStartedAt,
})
if (!granted) {
throw new Error("Nearby devices permission is required to join the glasses hotspot")
}
}
this.checkpointSoftapAttempt(attempt, "permissions")
const transport = new SoftapCallTransport({
...createSoftapCallDeps({
packageName,
meetingUrl: args.meetingUrl,
token: args.token,
displayName: args.displayName,
video: args.video,
awaitFirstFrame: (_report, options) => acsMeetingService.waitForFirstFrame(SOFTAP_FIRST_FRAME_MS, options),
waitUntilLive: (timeoutMs) => acsMeetingService.waitUntilMediaLive(timeoutMs),
subsystems: {
setHotspotState: async (enabled) => {
const status = await this.setGlassesHotspotState(enabled)
if (status.state === "enabled") {
return {state: status.state, ssid: status.ssid, password: status.password, localIp: status.localIp}
}
return {state: status.state}
},
isWifiEnabled: async () => {
// A host that cannot answer reports "on" so the preflight stands aside; the native
// throw at scopedJoin is what covers those platforms.
const enabled = await acsMeetingService.isWifiEnabled()
return enabled ?? true
},
joinScopedNetwork: (ssid, passphrase, gateway, report) =>
acsMeetingService.joinScopedNetwork(ssid, passphrase, gateway, report),
leaveScopedNetwork: () => acsMeetingService.leaveScopedNetwork(),
cancelScopedNetworkJoin: () => acsMeetingService.cancelScopedNetworkJoin(),
probeGateway: async () => {
const verdict = await acsMeetingService.probeScopedGateway()
// No native probe means no verdict, and the orchestrator must not read that as "down".
return verdict ?? {reachable: true, detail: "probe unsupported on this host"}
},
awaitValidatedDefaultNetwork: () => acsMeetingService.awaitValidatedDefaultNetwork(),
onGlassesStreamStatus: (listener) => {
const sub = BluetoothSdk.addListener("stream_status", (event) => {
// The glasses narrate over BLE, which is slow enough that a status from the previous
// publish can land after this attempt was retired — and it is narration, so it would
// be written straight onto the new call's checklist as if it were happening now.
if (this.softapAttempt !== attempt || attempt.cancelled) {
softapTrace("softap_stale_callback", {
source: "glasses_stream_status",
attempt: attempt.id,
status: event.status,
current: this.softapAttempt?.id ?? "none",
})
return
}
listener({
status: event.status,
streamId: event.streamId,
reason: "reason" in event && typeof event.reason === "string" ? event.reason : undefined,
error: "error" in event && typeof event.error === "string" ? event.error : undefined,
})
})
return () => sub.remove()
},
joinMeeting: (pkg, options) =>
acsMeetingService.join(pkg, {
meetingUrl: options.meetingUrl,
token: options.token,
identity: args.identity,
videoSource: options.videoSource,
displayName: options.displayName,
origin: args.origin,
glassesSession: args.glassesSession,
...(args.video ? {video: args.video} : {}),
}),
leaveMeeting: (pkg) => acsMeetingService.leave(pkg),
endMeeting: async (pkg) => {
await acsMeetingService.endForEveryone(pkg)
},
ingestUrl: () => acsMeetingService.softApIngestUrl(),
glassesLc3Uplink: () => acsMeetingService.glassesLc3UplinkActive(),
startPublishing: (pkg, options) => phoneStreamCoordinator.startUnmanaged(pkg, options),
stopPublishing: (pkg) => phoneStreamCoordinator.stop(pkg),
discardPendingBleStop: () => phoneStreamCoordinator.discardPendingBleStop(),
rebindIngest: async (report) => {
report?.("Rebinding the glasses video receiver on the hotspot")
const ingestUrl = await acsMeetingService.rebindSoftApIngest()
if (!ingestUrl) throw new Error("the rebound meeting reported no ingest URL")
report?.(`Receiver rebound at ${ingestUrl}`)
return {ingestUrl}
},
},
}),
onPublisherPauseExpired: (pauseId) => {
acsMeetingService.clearPhotoPause(pauseId)
this.notifyPhotoPauseExpired(packageName, pauseId)
},
})
attempt.transport = transport
// A hotspot that vanishes mid-call is a real failure and a normal teardown is not, so both
// guards are checked: the attempt must still be the current one (a stale event from a finished
// call must never touch the next one) and it must not already be terminating. The unsubscribe
// lives on the attempt, so retiring attempt N cannot clear attempt N+1's listener. Teardown
// itself is left to the miniapp's terminal path, which calls `meeting.leave` — one owner.
attempt.scopedLostUnsub = acsMeetingService.onScopedNetworkLost((error) => {
if (this.softapAttempt !== attempt || attempt.cancelled) {
console.log("[LocalMiniappRuntime] scoped loss for a superseded SoftAP call; ignoring", error)
softapTrace("softap_scoped_loss_dropped", {
attempt: attempt.id,
code: error.code,
cause: attempt.cancelled ? "retired" : "superseded",
current: this.softapAttempt?.id ?? "none",
})
return
}
if (transport.isTerminating()) {
console.log("[LocalMiniappRuntime] scoped loss during teardown; expected", error)
softapTrace("softap_scoped_loss_dropped", {attempt: attempt.id, code: error.code, cause: "terminating"})
return
}
console.warn("[LocalMiniappRuntime] SoftAP hotspot lost mid-call", error)
softapTraceFailure("softap_scoped_loss_reported", {
attempt: attempt.id,
code: error.code,
reason: error.message,
attemptAgeMs: Date.now() - attempt.startedAt,
})
this.beginSoftapRecovery(attempt, transport, error)
})
// Sign in on the phone's current internet *before* the glasses hotspot takes DNS. On device,
// createCallAgent after the scoped join timed out at 20s and only finished once SoftAP was
// released. It also waits for validated mobile data, which is why the wearer is told one
// honest thing about the whole window rather than nothing at all.
this.narrateSoftapPreflight(attempt, "Signing in to Teams…")
const prepareStartedAt = Date.now()
softapTrace("softap_prepare_agent_begin", {attempt: attempt.id})
try {
await acsMeetingService.prepareAgent({
token: args.token,
displayName: args.displayName,
identityMode: args.identity?.identityMode,
})
} catch (error) {
softapTraceFailure("softap_prepare_agent_failed", {
attempt: attempt.id,
reason: error instanceof Error ? error.message : String(error),
durationMs: Date.now() - prepareStartedAt,
})
throw error
}
softapTrace("softap_prepare_agent_done", {attempt: attempt.id, durationMs: Date.now() - prepareStartedAt})
this.checkpointSoftapAttempt(attempt, "prepareAgent")
await transport.start({
// What the wearer has been reading for the last minute, so the first snapshot does not
// blank it.
initialSteps: attempt.progress.steps,
// Every transition reaches the miniapp as a meeting-state event carrying the checklist.
onProgress: (progress) => this.emitSoftapProgress(attempt, progress),
})
this.checkpointSoftapAttempt(attempt, "transport.start")
const state = acsMeetingService.getState()
softapTrace("softap_attempt_live", {
attempt: attempt.id,
state: state.state,
micTransport: state.micTransport ?? "unknown",
attemptAgeMs: Date.now() - attempt.startedAt,
})
return state
}
/**
* SoftAP loss is a media outage. Keep ACS, destroy generation N, wait for the glasses,
* then build generation N+1. Duplicate losses do not renew the deadline.
*/
private beginSoftapRecovery(
attempt: SoftapAttempt,
transport: SoftapCallTransport,
error: {code: string; message: string},
): void {
// Gate on the live flag, not the promise: a settled Promise is still truthy, so a second
// walk-away after a successful re-arm was dropped as "in-flight" and the glasses kept
// POSTing WHIP at a hotspot the phone had already left.
if (attempt.recoveryActive) {
softapTrace("softap_recovery_dropped", {attempt: attempt.id, cause: "in-flight"})
return
}
if (attempt.cancelled || this.softapAttempt !== attempt) {
softapTrace("softap_recovery_dropped", {
attempt: attempt.id,
cause: attempt.cancelled ? "retired" : "superseded",
})
return
}
const lostAt = Date.now()
attempt.recoveryDeadlineAt = lostAt + RETURN_DEADLINE_MS
attempt.recoveryActive = true
this.emitSoftapProgress(attempt, transport.progress())
softapTrace("softap_recovery_begin", {
attempt: attempt.id,
deadlineAt: attempt.recoveryDeadlineAt,
mediaGeneration: transport.currentMediaGeneration(),
reason: error.message,
})
let run!: Promise<void>
run = (async () => {
try {
await transport.recover(`${error.code}: ${error.message}`, {
wait: async () => {
const remaining = (attempt.recoveryDeadlineAt ?? 0) - Date.now()
if (remaining <= 0) {
throw new SoftapCallError("hotspot", "RETURN_DEADLINE", "The glasses did not return in time")
}
const ready = await this.waitForGlassesReturn(remaining, () => attempt.cancelled)
if (attempt.cancelled || this.softapAttempt !== attempt) {
throw new SoftapCallError("hotspot", "CANCELLED", "SoftAP recovery was cancelled")
}
if (!ready) {
throw new SoftapCallError("hotspot", "RETURN_DEADLINE", "The glasses did not return in time")
}
},
})
if (attempt.cancelled || this.softapAttempt !== attempt) return
this.emitSoftapProgress(attempt, transport.progress())
const current = acsMeetingService.getState()
this.sendToMiniapp(attempt.packageName, {
type: MiniappResponseType.MEETING_STATE,
...current,
softap: transport.progress(),
...this.softapRecoveryFields(attempt),
})
softapTrace("softap_recovery_live", {
attempt: attempt.id,
mediaGeneration: transport.currentMediaGeneration(),
elapsedMs: Date.now() - lostAt,
})
} catch (recoveryError) {
if (attempt.cancelled || this.softapAttempt !== attempt) return
const message = recoveryError instanceof Error ? recoveryError.message : String(recoveryError)
softapTraceFailure("softap_recovery_failed", {
attempt: attempt.id,
reason: message,
elapsedMs: Date.now() - lostAt,
})
const current = acsMeetingService.getState()
this.sendToMiniapp(attempt.packageName, {
type: MiniappResponseType.MEETING_STATE,
...current,
state: "error",
error: `SOFTAP_NETWORK_LOST: ${error.message}`,
softap: transport.progress(),
recovery: {
active: false,
generation: transport.currentMediaGeneration(),
deadlineAt: attempt.recoveryDeadlineAt ?? undefined,
phase: transport.currentPhase(),
},
})
} finally {
attempt.recoveryActive = false
if (attempt.recovery === run) attempt.recovery = null
}
})()
attempt.recovery = run
}
/**
* Wait for a link the hotspot commands can actually use.
*
* The hotspot goes away a couple of seconds before the phone declares the BLE link dead, so the
* snapshot at loss time still reads "ready". Taking that at face value sent `set_hotspot_state`
* into a dying link twice, and each one burned its full timeout before the wearer was even back.
* Requiring the link to hold steady turns that into waiting, which is what the budget is for.
*/
private async waitForGlassesReturn(timeoutMs: number, cancelled: () => boolean): Promise<boolean> {
const deadlineAt = Date.now() + timeoutMs
while (!cancelled()) {
const remaining = deadlineAt - Date.now()
if (remaining <= 0) return false
if (
!isGlassesReady(useGlassesStore.getState().connection) &&
!(await this.awaitGlassesReady(remaining, cancelled))
) {
return false
}
const settleMs = Math.min(GLASSES_LINK_SETTLE_MS, Math.max(0, deadlineAt - Date.now()))
if (await this.glassesLinkHoldsSteady(settleMs, cancelled)) return true
}
return false
}
private awaitGlassesReady(timeoutMs: number, cancelled: () => boolean): Promise<boolean> {
const controller = new AbortController()
const poll = setInterval(() => {
if (cancelled()) controller.abort()
}, 250)
return waitForGlassesReady({
getConnection: () => useGlassesStore.getState().connection,
subscribe: (listener) => useGlassesStore.subscribe((state) => state.connection, listener),
timeoutMs,
signal: controller.signal,
}).finally(() => clearInterval(poll))
}
/** True when the link stays ready for [ms]; false the moment it drops again. */
private glassesLinkHoldsSteady(ms: number, cancelled: () => boolean): Promise<boolean> {
if (ms <= 0) return Promise.resolve(isGlassesReady(useGlassesStore.getState().connection))
return new Promise<boolean>((resolve) => {
let done = false
const settle = (steady: boolean) => {
if (done) return
done = true
clearTimeout(timer)
clearInterval(poll)
unsubscribe()
resolve(steady)
}
const unsubscribe = useGlassesStore.subscribe(
(state) => state.connection,
(connection) => {
if (!isGlassesReady(connection)) settle(false)
},
)
const poll = setInterval(() => {
if (cancelled()) settle(false)
}, 250)
const timer = setTimeout(() => settle(true), ms)
})
}
/**
* Cancels a SoftAP attempt and does not return until everything it owns has been released.
*
* This is the barrier the whole design rests on: "leave returned" has to mean "nothing from that
* call is still in flight", or the next Start races the previous call's cleanup through the same
* hotspot. There is deliberately no deadline — a native call that never returns holds the next
* call back rather than letting it race — and a watchdog only says so in the log.
*
* Safe to call when there is no attempt, and safe to call twice: the teardown is single-flight
* per attempt, so a leave and the join's own failure path share one unwind.
*/
private async retireSoftapAttempt(options: {attempt?: SoftapAttempt; mode?: SoftapTeardownMode} = {}): Promise<void> {
const attempt = options.attempt ?? this.softapAttempt
if (!attempt) {
// Not an error — every terminal path calls this without checking — but a Leave that found
// nothing to retire and a Leave that tore a call down are very different log entries.
softapTrace("softap_retire_noop", {mode: options.mode ?? "leave"})
return
}
attempt.cancelled = true
// Keep the retiring attempt discoverable until both its join and cleanup settle.
// A newer reservation replaces it immediately, but must still wait on its barrier.
softapTrace("softap_retire_begin", {
attempt: attempt.id,
mode: options.mode ?? "leave",
attemptAgeMs: Date.now() - attempt.startedAt,
phase: attempt.progress.phase,
// Second and later callers join the first one's teardown rather than running their own, and
// that sharing is what makes a leave racing a failed join safe.
teardownAlreadyRunning: Boolean(attempt.teardown),
})
if (!attempt.teardown) {
attempt.teardown = this.teardownSoftapAttempt(attempt, options.mode)
// The barrier closes over the join body as well as the teardown, and opens only when both
// have stopped. A watchdog reports a cleanup that is taking too long; it never declares one
// finished, because "probably done by now" is exactly the assumption that broke restarts.
const stallWatchdog = setTimeout(() => {
console.warn("[LocalMiniappRuntime] softap_cleanup_stalled", {
attempt: attempt.id,
afterMs: SOFTAP_CLEANUP_STALL_LOG_MS,
})
}, SOFTAP_CLEANUP_STALL_LOG_MS)
void Promise.allSettled([
attempt.teardown,
attempt.body ?? Promise.resolve(),
attempt.recovery ?? Promise.resolve(),
]).then(() => {
clearTimeout(stallWatchdog)
attempt.markSettled()
if (this.softapAttempt === attempt) this.softapAttempt = null
})
}
const awaitedFrom = Date.now()
try {
await attempt.teardown
} catch (error) {
// Only a refused End reaches here; the local unwind has completed either way, which is the
// distinction the wearer's copy depends on.
softapTraceFailure("softap_retire_done", {
attempt: attempt.id,
waitedMs: Date.now() - awaitedFrom,
reason: error instanceof Error ? error.message : String(error),
})
throw error
}
softapTrace("softap_retire_done", {attempt: attempt.id, waitedMs: Date.now() - awaitedFrom})
}
/**
* Releases everything one attempt could own, in the reverse of the order it was taken.
*
* The scoped network and the ACS agent are released unconditionally, not only when the transport
* built them: `prepareAgent` signs in and pins this whole process to cellular *before* the
* transport exists, so a Cancel during sign-in would otherwise leave both behind. Both releases
* are idempotent.
*
* Failures are collected rather than swallowed. Reporting a clean teardown that did not happen
* is what lets the next call start on leaked state.
*/
private async teardownSoftapAttempt(attempt: SoftapAttempt, mode?: SoftapTeardownMode): Promise<void> {
// A cancelled reservation waiting behind another call never acquired any shared resources.
// Its cleanup must not release the preceding call's native agent or network.
if (!attempt.ownsResources) return
// Terminal intent before the first release, so the scoped network we are about to drop cannot
// be reported as a hotspot that walked away.
acsMeetingService.beginScopedTeardown()
const failures: string[] = []
let endFailure: unknown = null
const teardownStartedAt = Date.now()
softapTrace("softap_teardown_begin", {
attempt: attempt.id,
mode: mode ?? "leave",
hasTransport: Boolean(attempt.transport),
steps: attempt.transport?.activeSteps().join(",") ?? "",
})
/**
* One line per resource, whether it released or not.
*
* The releases below are sequential and every one of them can block on a native call, so a
* teardown that takes half a minute is only readable if each step says how long it took. A
* step that never reports is the one that hung.
*/
const releaseStep = async (step: string, release: () => Promise<void>): Promise<unknown> => {
const startedAt = Date.now()
try {
await release()
softapTrace("softap_teardown_step", {
attempt: attempt.id,
step,
outcome: "ok",
durationMs: Date.now() - startedAt,
})
return null
} catch (error) {
softapTraceFailure("softap_teardown_step", {
attempt: attempt.id,
step,
outcome: "failed",
durationMs: Date.now() - startedAt,
reason: error instanceof Error ? error.message : String(error),
})
return error
}
}
const transport = attempt.transport
if (transport) {
// The only thing `stop()` throws is a refused End — the local teardown still completed,
// so this is the caller's business, not a reason to block the next call.
endFailure = await releaseStep("transport.stop", () => transport.stop(mode ? {mode} : {}))
const undoFailures = transport.lastTeardownFailures()
// A hotspot that did not ACK off is leftover ON — the next join wants it on and will
// call setHotspotState(true). Refusing that join is how we got hotspot_off_ack_timeout
// as a wearer-facing "power-cycle the glasses" dead end.
const blockingUndos = undoFailures.filter((step) => step !== "hotspot")
if (blockingUndos.length > 0) failures.push(`could not release ${blockingUndos.join(", ")}`)
if (undoFailures.includes("hotspot")) {
console.warn("[LocalMiniappRuntime] glasses hotspot undo timed out; next join will raise it again", {
attempt: attempt.id,
})
}
}
const scopedFailure = await releaseStep("leaveScopedNetwork", () => acsMeetingService.leaveScopedNetwork())
if (scopedFailure) {
failures.push(
`leaveScopedNetwork: ${scopedFailure instanceof Error ? scopedFailure.message : String(scopedFailure)}`,
)
}
// Stay pinned across this wait. Unpinning onto a leftover glasses AP is what made the next
// Start Call's `teams:create` return `Request failed (503)` — Cloudflare, no internet, not a
// Teams configuration problem.
const defaultNetworkStartedAt = Date.now()
let defaultNetworkOk = false
try {
const network = await acsMeetingService.awaitDefaultNetworkAfterHotspot()
defaultNetworkOk = true
softapTrace("softap_teardown_step", {
attempt: attempt.id,
step: "awaitValidatedDefaultNetwork",
outcome: "ok",
durationMs: Date.now() - defaultNetworkStartedAt,
// Null is "this host cannot tell", which is a different fact from an unusable route, and
// the cellular pin is dropped on the strength of this answer.
network: network?.detail ?? "unknown",
usable: network?.usable ?? "unknown",
})
} catch (error) {
console.warn("[LocalMiniappRuntime] default network after SoftAP teardown is unverified", {
attempt: attempt.id,
error: error instanceof Error ? error.message : String(error),
})
softapTraceFailure("softap_teardown_step", {
attempt: attempt.id,
step: "awaitValidatedDefaultNetwork",
outcome: "failed",
durationMs: Date.now() - defaultNetworkStartedAt,
reason: error instanceof Error ? error.message : String(error),
})
}
const defaultNetworkMs = Date.now() - defaultNetworkStartedAt
const acsLeaveStartedAt = Date.now()
let acsLeaveOk = false
try {
const outcome = await acsMeetingService.leaveAndAwait(attempt.packageName)
acsLeaveOk = outcome.completed
softapTrace("softap_teardown_step", {
attempt: attempt.id,
step: "acsLeaveAndAwait",
// `completed=false` is not a failure and is not recorded as one: the build simply cannot
// confirm its own cleanup, so the next call's barrier is the only guarantee left.
outcome: outcome.completed ? "ok" : "unconfirmed",
reason: outcome.reason ?? "",
durationMs: Date.now() - acsLeaveStartedAt,
})
if (!outcome.completed) {
console.warn("[LocalMiniappRuntime] ACS cleanup completion is unverified on this build", {
attempt: attempt.id,
reason: outcome.reason,
})
}
} catch (error) {
softapTraceFailure("softap_teardown_step", {
attempt: attempt.id,
step: "acsLeaveAndAwait",
outcome: "failed",
durationMs: Date.now() - acsLeaveStartedAt,
reason: error instanceof Error ? error.message : String(error),
})
failures.push(`ACS leave: ${error instanceof Error ? error.message : String(error)}`)
}
const hadScopedLostListener = Boolean(attempt.scopedLostUnsub)
attempt.scopedLostUnsub?.()
attempt.scopedLostUnsub = null
softapTrace("softap_teardown_step", {
attempt: attempt.id,
step: "scopedLostListener",
outcome: hadScopedLostListener ? "ok" : "not taken",
})
failures.push(
...(await this.settleSoftapTeardown(attempt, {
acsLeave: {ok: acsLeaveOk, durationMs: Date.now() - acsLeaveStartedAt},
defaultNetwork: {ok: defaultNetworkOk, durationMs: defaultNetworkMs},
})),
)
if (failures.length > 0) {
this.softapCleanupError = failures.join("; ")
console.warn("[LocalMiniappRuntime] softap_cleanup_failed", {attempt: attempt.id, failures})
}
// The recorded failures are what the *next* join refuses on, so they are logged as the list
// that will be quoted back to the wearer rather than only as the individual step failures.
softapTrace("softap_teardown_done", {
attempt: attempt.id,
durationMs: Date.now() - teardownStartedAt,
refusesNextCall: failures.length > 0,
failures: failures.join("; "),
endRefused: Boolean(endFailure),
})
attempt.releaseHotspot?.()
attempt.releaseHotspot = undefined
if (endFailure) throw endFailure
}
/**
* Send one hotspot command, re-sending it once if a session refresh cancelled it.
*
* The retry lives inside the unit chained onto [glassesHotspotCommand] rather than around it,
* which is what holds the invariant: one logical hotspot operation issues at most two native
* commands, and no later operation runs between them. A retry outside the queue would let an
* `on` land between the two halves of an `off` and leave the glasses in the opposite state.
*
* Re-sending is free because ASG compares against current state first and answers a same-state
* command with its current status instead of cycling the AP.
*/
private setGlassesHotspotState(enabled: boolean) {
const send = async () => {
try {
return await BluetoothSdk.setHotspotState(enabled)
} catch (error) {
const code = (error as {code?: string} | null | undefined)?.code
if (!code || !HOTSPOT_SESSION_REFRESH_CODES.has(code)) throw error
softapTrace("softap_hotspot_session_retry", {enabled, code})
await new Promise<void>((resolve) => setTimeout(resolve, HOTSPOT_SESSION_RETRY_DELAY_MS))
return await BluetoothSdk.setHotspotState(enabled)
}
}
const run = this.glassesHotspotCommand.then(send, send)
this.glassesHotspotCommand = run.then(
() => undefined,
() => undefined,
)
return run
}
/**
* The last two gates, and the point where a timeout stops being treated as consent.
*
* Four things have to be true before the next call may start: this device is out of the ACS
* call, the WHIP listener's port is released, the glasses have acknowledged their hotspot off,
* and the phone has a validated default route again. The first and last already ran; this adds
* the two that were never waited for at all, and the ones that produced the stop-then-start
* failure — the listener was still inside its 3s tombstone and the glasses AP was still up.
*
* A bound that expires is not success. It means the resource is still held by a call nobody is
* in any more, so it is taken by force and re-verified. An ingest port that is still held
* refuses the next join. A glasses hotspot that missed its off-ack does not — the next join
* wants the AP up and will raise it again.
*
* @returns failures to record; a non-empty list refuses the next join.
*/
private async settleSoftapTeardown(
attempt: SoftapAttempt,
earlier: {acsLeave: {ok: boolean; durationMs: number}; defaultNetwork: {ok: boolean; durationMs: number}},
): Promise<string[]> {
const ingestStartedAt = Date.now()
let ingestClosed = false
try {
ingestClosed = await acsMeetingService.awaitIngestClosed(SOFTAP_INGEST_CLOSE_WAIT_MS)
} catch (error) {
softapTraceFailure("softap_teardown_step", {
attempt: attempt.id,
step: "awaitIngestClosed",
outcome: "failed",
reason: error instanceof Error ? error.message : String(error),
})
}
const ingestMs = Date.now() - ingestStartedAt
const hotspotStartedAt = Date.now()
let hotspotOff = false
let hotspotReason = ""
try {
// Idempotent by design — the command asks for "disabled" rather than toggling — so sending
// it again after the transport's own stop costs nothing and is the only way to get an ack
// that is bound to a deadline we chose.
const status = await withTimeout(
this.setGlassesHotspotState(false),
SOFTAP_HOTSPOT_OFF_ACK_MS,
"hotspot_off_ack_timeout",
)
hotspotOff = status.state === "disabled"
hotspotReason = status.state
} catch (error) {
hotspotReason = error instanceof Error ? error.message : String(error)
}
const hotspotMs = Date.now() - hotspotStartedAt
softapTrace("softap_teardown_settled", {
attempt: attempt.id,
acsLeaveMs: earlier.acsLeave.durationMs,
acsLeaveOk: earlier.acsLeave.ok,
ingestClosedMs: ingestMs,
ingestClosed,
hotspotOffMs: hotspotMs,
hotspotOff,
hotspotDetail: hotspotReason,
defaultNetworkMs: earlier.defaultNetwork.durationMs,
defaultNetworkOk: earlier.defaultNetwork.ok,
})
if (ingestClosed && hotspotOff) return []
return this.forceSoftapCleanup(attempt, {ingestClosed, hotspotOff, hotspotReason})
}
/**
* Take back what the bounded waits could not confirm was released.
*
* Runs only after a gate timed out, and re-verifies rather than assuming: the whole reason the
* barrier exists is that "it has probably finished by now" is what broke restarts.
*/
private async forceSoftapCleanup(
attempt: SoftapAttempt,
gates: {ingestClosed: boolean; hotspotOff: boolean; hotspotReason: string},
): Promise<string[]> {
const failures: string[] = []
softapTraceFailure("softap_teardown_forced", {
attempt: attempt.id,
ingestClosed: gates.ingestClosed,
hotspotOff: gates.hotspotOff,
hotspotDetail: gates.hotspotReason,
})
if (!gates.ingestClosed) {
try {
await acsMeetingService.forceCloseIngest()
// Re-asked, not assumed: `forceCloseIngest` skips the tombstone, so the latch should be
// open immediately. A short bound here is enough and a failure is real.
const closed = await acsMeetingService.awaitIngestClosed(SOFTAP_FORCED_VERIFY_MS)
if (!closed) failures.push("the video receiver did not release its port")
} catch (error) {
failures.push(`forced ingest close: ${error instanceof Error ? error.message : String(error)}`)
}
}
if (!gates.hotspotOff) {
try {
const status = await withTimeout(
this.setGlassesHotspotState(false),
SOFTAP_HOTSPOT_OFF_ACK_MS,
"hotspot_off_ack_timeout",
)
if (status.state !== "disabled") {
console.warn("[LocalMiniappRuntime] glasses hotspot still reported after disable; next join will raise it", {
attempt: attempt.id,
state: status.state,
})
}
} catch (error) {
console.warn("[LocalMiniappRuntime] glasses hotspot off ack missed; next join will raise it", {
attempt: attempt.id,
reason: error instanceof Error ? error.message : String(error),
})
}
}
softapTrace("softap_teardown_forced_done", {
attempt: attempt.id,
recovered: failures.length === 0,
failures: failures.join("; "),
})
return failures
}
private async handleMeetingLeave(packageName: string, requestId?: string): Promise<void> {
this.meetingCredentialRequests.delete(packageName)
const startedAt = Date.now()
softapTrace("meeting_leave_request", {
packageName,
requestId: requestId ?? "none",
attempt: this.softapAttempt?.id ?? "none",
})
try {
// A SoftAP call owns the hotspot, the scoped network, and the cellular pin as well as the
// ACS call, and retiring the attempt releases all of them. Returning before that finishes is
// what let the next Start race this teardown.
if (this.softapAttempt) {
await this.retireSoftapAttempt()
softapTrace("meeting_leave_result", {
packageName,
requestId: requestId ?? "none",
path: "softap",
durationMs: Date.now() - startedAt,
})
this.sendResult(packageName, requestId, true)
return
}
await acsMeetingService.leave(packageName)
softapTrace("meeting_leave_result", {
packageName,
requestId: requestId ?? "none",
path: "acs",
durationMs: Date.now() - startedAt,
})
this.sendResult(packageName, requestId, true)
} catch (err) {
softapTraceFailure("meeting_leave_result", {
packageName,
requestId: requestId ?? "none",
reason: err instanceof Error ? err.message : String(err),
durationMs: Date.now() - startedAt,
})
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: err instanceof Error ? err.message : "ACS meeting leave failed",
})
}
}
/**
* End the meeting for everyone, then tear this device down.
*
* A rejection here always means "the others may still be in the meeting", never "you are still in
* it": both paths below complete local teardown before the error surfaces.
*/
private async handleMeetingEnd(packageName: string, requestId?: string): Promise<void> {
const startedAt = Date.now()
const softap = Boolean(this.softapAttempt)
softapTrace("meeting_end_request", {
packageName,
requestId: requestId ?? "none",
attempt: this.softapAttempt?.id ?? "none",
})
try {
if (this.softapAttempt) {
await this.retireSoftapAttempt({mode: "end"})
} else {
await acsMeetingService.endForEveryone(packageName)
}
softapTrace("meeting_end_result", {
packageName,
requestId: requestId ?? "none",
path: softap ? "softap" : "acs",
durationMs: Date.now() - startedAt,
})
this.sendResult(packageName, requestId, true)
} catch (err) {
// A rejection here always means the others may still be in the meeting, never that this
// device is — the log has to be readable that way round or it accuses the wrong side.
softapTraceFailure("meeting_end_result", {
packageName,
requestId: requestId ?? "none",
reason: err instanceof Error ? err.message : String(err),
durationMs: Date.now() - startedAt,
})
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: err instanceof Error ? err.message : "Could not end the meeting for everyone",
})
}
}
private async handleMeetingAdmit(
packageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
try {
if (typeof payload.participantId !== "string") throw new Error("A participant ID is required")
await acsMeetingService.admitParticipant(packageName, payload.participantId)
this.sendResult(packageName, requestId, true)
} catch (error) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: error instanceof Error ? error.message : "Could not admit this guest",
})
}
}
private async handleMeetingSetMuted(
packageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
const startedAt = Date.now()
try {
const state = await acsMeetingService.setMuted(packageName, Boolean(payload.muted))
softapTrace("meeting_set_muted", {
packageName,
requestId: requestId ?? "none",
requested: Boolean(payload.muted),
muted: state.muted,
durationMs: Date.now() - startedAt,
})
this.sendResult(packageName, requestId, true, state)
} catch (err) {
softapTraceFailure("meeting_set_muted", {
packageName,
requestId: requestId ?? "none",
requested: Boolean(payload.muted),
reason: err instanceof Error ? err.message : String(err),
durationMs: Date.now() - startedAt,
})
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: err instanceof Error ? err.message : "ACS mute failed",
})
}
}
private async handleMeetingSetVideoEnabled(
packageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
if (typeof payload.enabled !== "boolean") {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INVALID_ARGUMENT,
message: "enabled must be a boolean",
})
return
}
const startedAt = Date.now()
try {
const state = await acsMeetingService.setVideoEnabled(packageName, payload.enabled)
softapTrace("meeting_set_video_enabled", {
packageName,
requestId: requestId ?? "none",
requested: payload.enabled,
videoEnabled: state.videoEnabled ?? "unknown",
durationMs: Date.now() - startedAt,
})
this.sendResult(packageName, requestId, true, state)
} catch (err) {
softapTraceFailure("meeting_set_video_enabled", {
packageName,
requestId: requestId ?? "none",
requested: payload.enabled,
reason: err instanceof Error ? err.message : String(err),
durationMs: Date.now() - startedAt,
})
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: err instanceof Error ? err.message : "ACS camera toggle failed",
})
}
}
private async handleMeetingUpdateVideoSource(
packageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
const videoSource = payload.videoSource as {type?: string; url?: string} | undefined
const whepUrl = videoSource?.type === "whep" ? (videoSource.url ?? "") : ""
if (!whepUrl) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INVALID_ARGUMENT,
message: "videoSource must be a WHEP URL",
})
return
}
try {
await acsMeetingService.updateVideoSource(packageName, whepUrl)
this.sendResult(packageName, requestId, true)
} catch (err) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: err instanceof Error ? err.message : "ACS video source update failed",
})
}
}
private notifyPhotoPauseExpired(packageName: string, pauseId: string): void {
this.sendToMiniapp(packageName, {
type: MiniappResponseType.MEETING_VIDEO_PUBLISHER,
pauseId,
status: "expired",
})
}
private async handleMeetingPauseVideoPublisher(
packageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
if (payload.reason !== "photo") {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INVALID_ARGUMENT,
message: "reason must be photo",
})
return
}
try {
const attempt = this.softapAttempt?.packageName === packageName ? this.softapAttempt : null
if (attempt && !attempt.transport) throw new Error("The glasses publisher is not ready")
const paused = attempt?.transport
? await attempt.transport.pauseVideoPublisher()
: await acsMeetingService.pauseCloudflarePublisher(packageName)
if (attempt?.transport) acsMeetingService.notePhotoPause(paused.pauseId)
this.sendResult(packageName, requestId, true, {pauseId: paused.pauseId})
} catch (err) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: err instanceof Error ? err.message : "Could not pause the camera",
})
}
}
private async handleMeetingResumeVideoPublisher(
packageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
const pauseId = typeof payload.pauseId === "string" ? payload.pauseId : ""
if (!pauseId) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INVALID_ARGUMENT,
message: "pauseId is required",
})
return
}
try {
const attempt = this.softapAttempt?.packageName === packageName ? this.softapAttempt : null
if (attempt?.transport) await attempt.transport.resumeVideoPublisher(pauseId)
else await acsMeetingService.resumeCloudflarePublisher(pauseId)
acsMeetingService.clearPhotoPause(pauseId)
this.sendResult(packageName, requestId, true)
} catch (err) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: err instanceof Error ? err.message : "Could not resume the camera",
})
}
}
private async handleMeetingShowCard(
packageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
if (payload.kind !== "taking-photo") {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INVALID_ARGUMENT,
message: "kind must be taking-photo",
})
return
}
if (!acsMeetingService.meetingAcceptsPhoto(packageName)) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: "The meeting has already ended",
})
return
}
try {
await acsMeetingService.holdOutgoing("card")
this.sendResult(packageName, requestId, true)
} catch (err) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: err instanceof Error ? err.message : "Could not show the photo card",
})
}
}
private async handleMeetingShowImage(
packageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
const imageUrl = typeof payload.imageUrl === "string" ? payload.imageUrl : ""
const durationMs = payload.durationMs
if (!imageUrl || typeof durationMs !== "number" || !Number.isFinite(durationMs) || durationMs < 0) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INVALID_ARGUMENT,
message: "imageUrl and durationMs are required",
})
return
}
if (!acsMeetingService.meetingAcceptsPhoto(packageName)) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: "The meeting has already ended",
})
return
}
try {
const imageBase64 = await loadOutgoingStill(imageUrl)
if (!acsMeetingService.meetingAcceptsPhoto(packageName)) {
throw new Error("The meeting has already ended")
}
await acsMeetingService.holdOutgoing("image", imageBase64)
this.sendResult(packageName, requestId, true, {shownAt: Date.now()})
} catch (err) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: err instanceof Error ? err.message : "Could not show the photo",
})
}
}
private async handleMeetingShowLive(packageName: string, requestId?: string): Promise<void> {
if (!acsMeetingService.meetingAcceptsPhoto(packageName)) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: "The meeting has already ended",
})
return
}
try {
await acsMeetingService.holdOutgoing("live")
this.sendResult(packageName, requestId, true)
} catch (err) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: err instanceof Error ? err.message : "Could not return to live video",
})
}
}
/**
* Direct link HD photo that never stops the glasses publisher: card, still, live, all host-side.
* `NOT_IMPLEMENTED` with `reason: "unsupported"` tells the miniapp to use its pause-based path.
*/
private async handleMeetingCaptureStill(
packageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
const durationMs = payload.durationMs
if (
typeof durationMs !== "number" ||
!Number.isFinite(durationMs) ||
durationMs < 0 ||
durationMs > STILL_MAX_DURATION_MS
) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INVALID_ARGUMENT,
message: `durationMs must be between 0 and ${STILL_MAX_DURATION_MS}`,
})
return
}
const attempt = this.softapAttempt?.packageName === packageName ? this.softapAttempt : null
if (!attempt?.transport || !acsMeetingService.stillCaptureSupported()) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.NOT_IMPLEMENTED,
message: attempt?.transport
? "This Mentra App cannot share a Direct link photo without pausing the camera"
: "Only a Direct link call can capture a still without pausing the camera",
reason: "unsupported" satisfies MeetingStillFailure,
})
return
}
if (!attempt.transport.stillCaptureReady()) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: `The glasses camera is not live (${attempt.transport.currentPhase()})`,
reason: "not_live" satisfies MeetingStillFailure,
})
return
}
const startedAt = Date.now()
const stillId = typeof payload.stillId === "string" ? payload.stillId : ""
try {
const result = await acsMeetingService.captureStill(packageName, {
durationMs,
onProgress: (phase) => {
softapTrace("meeting_capture_still_progress", {packageName, phase, elapsedMs: Date.now() - startedAt})
if (stillId) this.sendToMiniapp(packageName, {type: MiniappResponseType.MEETING_STILL, stillId, phase})
},
})
softapTrace("meeting_capture_still", {
packageName,
requestId: result.requestId,
bytes: result.bytes,
cardMs: result.timings.cardMs,
stillMs: result.timings.stillMs,
heldMs: result.timings.heldMs,
totalMs: result.timings.totalMs,
})
this.sendResult(packageName, requestId, true, result)
} catch (err) {
const reason: MeetingStillFailure = err instanceof MeetingStillError ? err.reason : "glasses_rejected"
softapTraceFailure("meeting_capture_still", {
packageName,
reason,
message: err instanceof Error ? err.message : String(err),
durationMs: Date.now() - startedAt,
})
this.sendResult(packageName, requestId, false, undefined, {
code:
reason === "unsupported"
? MiniappErrorCode.NOT_IMPLEMENTED
: reason === "cancelled"
? MiniappErrorCode.REQUEST_ABORTED
: MiniappErrorCode.INTERNAL,
message: err instanceof Error ? err.message : "Could not share the photo",
reason,
})
}
}
private async handleMeetingGetState(packageName: string, requestId?: string): Promise<void> {
// No meeting and no join in flight means nothing to adopt. Native keeps reading `connecting`
// from a retired SoftAP attempt's `prepareAgent` until its teardown reaches the ACS leave; a
// respawned Mentra Call adopted that as its own join and, with no owner to push it a terminal
// state, sat on "Starting call…" until the wearer cancelled.
if (acsMeetingService.ownerPackage() !== packageName && !this.hasLiveSoftapAttempt(packageName)) {
this.sendResult(packageName, requestId, true, {state: "idle", muted: false})
return
}
try {
const state = await acsMeetingService.readState(packageName)
this.sendResult(packageName, requestId, true, state)
} catch (err) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: err instanceof Error ? err.message : "ACS getState failed",
})
}
}
/**
* Phone Wi-Fi requests use host seams and never change miniapp foreground.
*/
private async handlePhoneWifiRequest(
packageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
try {
const result = await invokePhoneWifiSeam(getUiSeams(), payload)
this.sendResult(packageName, requestId, true, result)
} catch (err) {
this.sendResult(packageName, requestId, false, undefined, {
code: (err as {code?: string} | null)?.code || MiniappErrorCode.INTERNAL,
message: err instanceof Error ? err.message : "Phone Wi-Fi request failed",
})
}
}
/**
* session.glasses.requestWifiSetup — open the phone's glasses Wi-Fi setup
* flow. The host owns the actual UI via the `engine.configure({ui})` seam;
* this just forwards the request and reports success/failure.
*/
private async handleRequestWifiSetup(
packageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
const requestWifiSetup = getUiSeams().requestWifiSetup
if (!requestWifiSetup) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.NOT_IMPLEMENTED,
message: "Wi-Fi setup is not configured on this host",
})
return
}
try {
await requestWifiSetup(payload.reason as string | undefined, packageName)
this.sendResult(packageName, requestId, true)
} catch (err) {
this.sendResult(packageName, requestId, false, undefined, {
code: (err as {code?: string}).code || MiniappErrorCode.INTERNAL,
message: err instanceof Error ? err.message : "Wi-Fi setup failed",
})
}
}
/**
* Wire the PhoneStreamCoordinator's status callback so coordinator-emitted
* updates become `EVENT { streamType: "stream_status" }` envelopes on the
* subscribing miniapp(s).
*/
public wireStreamingStatusFanout(): void {
const streaming = phoneStreamCoordinator
if (!streaming) return
streaming.setStatusSubscriber((packageName, update) => {
this.sendToMiniapp(packageName, {
type: MiniappResponseType.EVENT,
streamType: "stream_status",
data: {
streamId: update.streamId,
status: update.status,
source: update.source,
...(update.data || {}),
},
})
})
}
// ===========================================================================
// Public subscribe helper
// ===========================================================================
/**
* Standalone subscribe — lets external code subscribe a registered miniapp to
* streams without going through the envelope protocol.
*
* Returns `{ok: true}` on success, or `{ok: false, error}` on failure.
*/
public subscribe(packageName: string, streams: string[]): {ok: boolean; error?: string} {
const app = this.connectedApps.get(packageName)
if (!app) {
return {ok: false, error: `App ${packageName} is not registered`}
}
if (!Array.isArray(streams)) {
return {ok: false, error: "streams must be an array"}
}
console.log(`${LOG_TAG}: subscribe(${packageName}, [${streams.join(", ")}])`)
// Check microphone permission for mic-requiring streams
const micStreams = ["transcription", "translation", "audio_chunk", "vad", "wake_word"]
const needsMic = streams.some((s: string) => micStreams.some((m) => s.startsWith(m) || s === m))
if (needsMic) {
const hasMicPermission = app.installedManifest?.permissions?.some((p) => p.type === "MICROPHONE")
if (!hasMicPermission) {
return {ok: false, error: "MICROPHONE permission not declared in miniapp.json"}
}
}
// Add new subscriptions
const previousSubscriptions = app.subscriptions
app.subscriptions = new Set(streams)
app.transcriptionListeners.replace(
transcriptionRegistrations(undefined, streams, new Map()),
cloudClientService.getAudioPosition(),
)
this.replaceStreamSubscribers(packageName, previousSubscriptions, app.subscriptions)
this.recomputeMicRequirements()
this.updateCloudSubscriptions()
return {ok: true}
}
// ===========================================================================
// Mic requirements
// ===========================================================================
private getConfiguredMicGates(): {vadEnabled: boolean | null; loudnessGateEnabled: boolean | null} {
const bluetoothSettings = useSettingsStore.getState().getBluetoothSettings()
const configuredVad = bluetoothSettings.voice_activity_detection_enabled
const configuredLoudnessGate = bluetoothSettings.loudness_gate_enabled
return {
vadEnabled: typeof configuredVad === "boolean" ? configuredVad : null,
loudnessGateEnabled: typeof configuredLoudnessGate === "boolean" ? configuredLoudnessGate : null,
}
}
private recomputeMicRequirements(): void {
let anyPcm = false
let anyLc3 = false
for (const [stream, subscribers] of this.streamSubscribers) {
if (subscribers.size === 0) continue
// The wake word and voice activity run natively on phone-side PCM.
if (stream === "audio_chunk" || stream === "wake_word" || stream === "vad") anyPcm = true
if (stream.startsWith("transcription:") || stream.startsWith("translation:")) anyLc3 = true
}
wakeWordService.setSubscribed(this.hasStreamSubscribers("wake_word"), (event) =>
this.forwardEvent("wake_word", event),
)
speechActivityService.setEnabled(this.hasStreamSubscribers("vad"))
micStateCoordinator.setLocalRequirements({
pcm: anyPcm,
lc3: anyLc3,
...this.getConfiguredMicGates(),
})
}
/**
* Recompute the aggregated v2 cloud subscription list across all local miniapps.
*
* Cloud-dependent streams (transcription:*, translation:*) only flow if the
* v2 runtime knows the phone wants them. Local-only streams (button_press, etc.)
* are NOT sent — they come from the Bluetooth SDK, not from cloud.
*/
private updateCloudSubscriptions(): void {
// The on-device recognizer reports its state back synchronously from
// setDemand; that report asks for another pass instead of nesting one.
if (this.updatingCloudSubscriptions) {
this.cloudSubscriptionsDirty = true
return
}
this.updatingCloudSubscriptions = true
try {
do {
this.cloudSubscriptionsDirty = false
this.applyCloudSubscriptions()
} while (this.cloudSubscriptionsDirty)
} finally {
this.updatingCloudSubscriptions = false
}
}
private updatingCloudSubscriptions = false
private cloudSubscriptionsDirty = false
private applyCloudSubscriptions(): void {
const cloudStreams = new Set<string>()
for (const [stream, subscribers] of this.streamSubscribers) {
if (subscribers.size === 0) continue
// Only transcription / translation need cloud delivery. Location and
// notifications are sourced natively on the phone — no cloud hop.
if (stream.startsWith("translation:")) {
cloudStreams.add(stream)
}
}
// A transcription stream goes to the cloud only while a listener on it
// needs the cloud; on-device transcription runs only while one needs it.
this.refreshTranscriptionRouting()
let localDemand = false
for (const [packageName, app] of this.connectedApps) {
const state = this.transcriptionRoutingState(packageName)
for (const route of app.transcriptionListeners.routes()) {
if (needsCloud(route, route.source, route.target)) cloudStreams.add(route.stream)
if (needsLocal(route, route.source, state)) localDemand = true
}
}
// Mirror the same set as typed AudioSubscription[] and push it to the cloud
// runtime.
this.ensureCloudResultsWired()
const subs = this.buildCloudAudioSubscriptions(cloudStreams)
const nextKey = this.audioSubscriptionKey(subs)
if (this.cloudAudioSubscriptionSync.begin(nextKey)) {
console.log(
`${LOG_TAG}: updateCloudSubscriptions streams=[${Array.from(cloudStreams).join(", ")}] cloudSubs=${subs.length}`,
)
cloudClientService
.setSubscriptions(subs)
.then(() => {
this.cloudAudioSubscriptionSync.succeeded(nextKey)
})
.catch((err) => {
// Best-effort: the cloud may not be connected yet. Keep failed writes
// retryable; otherwise a reconnect that recomputes the same desired
// transcription set gets deduped and local captions never recover.
this.cloudAudioSubscriptionSync.failed(nextKey)
console.warn(`${LOG_TAG}: cloud setSubscriptions failed: ${(err as Error)?.message ?? err}`)
})
}
// On-device transcription always runs the Speech-page model; its language,
// not the subscription's, decides what local transcripts are tagged with.
localSttFallbackCoordinator.setDemand(localDemand)
this.broadcastTranscriptionModelStatus()
}
// ===========================================================================
// Transcription routing (cloud or on-device, per listener)
// ===========================================================================
/** When each transcript source last spoke, to switch listeners only where both have settled. */
private readonly utterances = new UtteranceTracker()
/** Which sources were up at the last routing pass, to notice one starting. */
private sourcesUp = {cloud: false, local: false}
/** Cloud audio position at the last on-device final. */
private localFinalWatermark: AudioPosition | null = null
/** Bumped whenever the on-device recognizer starts or stops: a drain holds only for the run it drained. */
private localGeneration = 0
/** A drain that just completed, for the routing pass it triggers only; and whether one is running. */
private localDrain: {generation: number; watermark: AudioPosition | null} | null = null
private localDrainRunning = false
/** Re-routes once a waiting switch's sources settle, since silence brings no transcript to do it. */
private handoffTimer: {id: number; at: number} | null = null
/** Cloud transcription is allowed by this deployment and connected. */
private cloudSpeechUp(): boolean {
return isFeatureEnabled("cloudSpeech") && cloudClientService.isConnected()
}
/** What one miniapp's listeners can be transcribed with right now. */
private transcriptionRoutingState(packageName: string): TranscriptionRoutingState {
return {
cloudConnected: this.cloudSpeechUp(),
onDevice: isFeatureEnabled("onDeviceSpeech"),
localLanguage: localSttFallbackCoordinator.getActiveLanguage(),
pickedLanguage: sttModelManager.getBcp47ForLanguage(),
hints: this.transcriptionHintsByApp.get(packageName) ?? [],
}
}
/**
* Moves every transcription listener toward the source it should use now
* (see TranscriptionRouting: a planned switch waits for a settled pause and
* a drain of the on-device recognizer). Returns true when any listener's
* source or target changed, which can change what must run.
*/
private refreshTranscriptionRouting(): boolean {
const cloudConnected = this.cloudSpeechUp()
const localActive = localSttFallbackCoordinator.isActive()
const now = Date.now()
// A source that stopped reports nothing more; one that started may be
// working on speech it has not reported yet.
for (const [source, up] of [
["cloud", cloudConnected],
["local", localActive],
] as const) {
if (up && !this.sourcesUp[source]) this.utterances.started(source, now)
if (!up) this.utterances.clear(source)
if (source === "local" && up !== this.sourcesUp.local) this.localGeneration++
this.sourcesUp[source] = up
}
const drained = this.localDrain !== null && this.localDrain.generation === this.localGeneration
let changed = false
let needsDrain = false
for (const [packageName, app] of this.connectedApps) {
const state = this.transcriptionRoutingState(packageName)
const routed = app.transcriptionListeners.route({
target: (listener) => targetSource(listener, state),
canDeliver: (source) => (source === "cloud" ? cloudConnected : localActive),
busy: (source, stream) => this.utterances.busy(source, stream, now),
drained,
plannedWatermark: this.localDrain?.watermark ?? null,
forcedWatermark: this.localFinalWatermark,
})
if (routed.changed) changed = true
if (routed.needsDrain) needsDrain = true
}
if (needsDrain) this.drainLocalRecognizer()
this.scheduleHandoff(now)
return changed
}
/**
* Has the on-device recognizer report everything it has heard and start
* over (finishTranscription): the boundary of a planned switch. What it
* reports goes to the listeners still on-device. The drain then serves the
* switches ready in the routing pass it triggers, and only those: the
* recognizer keeps hearing audio, so any later switch drains again. A model
* that cannot finish early reports nothing, and the quiet window is the
* boundary.
*/
private drainLocalRecognizer(): void {
if (this.localDrainRunning) return
this.localDrainRunning = true
const generation = this.localGeneration
const watermark = cloudClientService.getAudioPosition()
void this.finishLocalUtterance()
.catch((error) => console.warn(`${LOG_TAG}: draining on-device transcription failed`, error))
.then(() => {
this.localDrainRunning = false
// Everything the recognizer had is reported; its next words are new speech.
this.utterances.clear("local")
this.localDrain = {generation, watermark}
const changed = this.refreshTranscriptionRouting()
this.localDrain = null
if (changed) this.updateCloudSubscriptions()
})
}
/**
* Arms a timer for the moment the next busy source settles while any
* listener waits to switch, so the switch (and dropping what it no longer
* needs, such as a cloud stream) happens during silence too.
*/
private scheduleHandoff(now: number): void {
const waiting = [...this.connectedApps.values()].some((app) => app.transcriptionListeners.switching())
const at = waiting ? this.utterances.nextSettle(now) : null
if (this.handoffTimer && at !== null && this.handoffTimer.at <= at) return
if (this.handoffTimer) BgTimer.clearTimeout(this.handoffTimer.id)
this.handoffTimer = null
if (at === null) return
const id = BgTimer.setTimeout(() => {
if (this.handoffTimer?.id !== id) return
this.handoffTimer = null
if (this.refreshTranscriptionRouting()) this.updateCloudSubscriptions()
}, at - now)
this.handoffTimer = {id, at}
}
/**
* Build the cloud `AudioSubscription[]` from the miniapp cloud-stream key set.
*
* Stream keys: `transcription:<lang>` (lang may be `auto`, `en-US`, …) and
* `translation:<source>:<target>` (3 colon-parts; source/target may be `*`
* or `auto` wildcards, target may also be `*`). The cloud protocol requires a
* concrete `target: string` for translation, so wildcard-target translation
* keys (`translation:<source>:*`, `translation:*:*`, `translation:auto`) have
* no cloud equivalent and are skipped. Wildcard/`auto` SOURCE maps to
* `{mode: "auto"}`.
*/
private buildCloudAudioSubscriptions(cloudStreams: Set<string>): AudioSubscription[] {
const subs: AudioSubscription[] = []
// Union of every connected app's TRANSCRIPTION_CONFIG hints. Hints only
// apply to the auto-mode TRANSCRIPTION subscription (the wire schema has
// no hints field on specific-language sources — the language IS the hint
// there), and are deliberately NOT attached to translation sources.
const hintUnion = [...new Set([...this.transcriptionHintsByApp.values()].flat())].sort()
const langSource = (code: string): LanguageSource =>
code === "auto" || code === "*" ? {mode: "auto"} : {mode: "specific", code}
for (const stream of cloudStreams) {
if (stream.startsWith("transcription:")) {
const lang = stream.substring("transcription:".length)
const source = langSource(lang)
subs.push({
kind: "transcription",
language: source.mode === "auto" && hintUnion.length > 0 ? {mode: "auto", hints: hintUnion} : source,
})
} else if (stream.startsWith("translation:")) {
const parts = stream.split(":")
// Only `translation:<source>:<target>` maps cleanly; a concrete target
// is required by the cloud schema.
if (parts.length === 3) {
const [, source, target] = parts
if (target === "*") continue
subs.push({kind: "translation", source: langSource(source), target})
}
}
}
return subs
}
private audioSubscriptionKey(subs: AudioSubscription[]): string {
return JSON.stringify(
subs
.map((sub) => {
if (sub.kind === "transcription") {
return {
kind: sub.kind,
language: sub.language,
}
}
return {
kind: sub.kind,
source: sub.source,
target: sub.target,
}
})
.sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b))),
)
}
/**
* Wire the cloud's transcription/translation results into the existing
* miniapp fan-out exactly once. Maps each cloud result back to the
* cloud-to-app data shape `forwardEvent` already forwards, keyed on the
* `transcription:<lang>` / `translation:<source>:<target>` stream strings, so
* subscribed miniapps receive identical envelopes.
*/
private ensureCloudResultsWired(): void {
if (this.cloudResultsWired) return
this.cloudResultsWired = true
cloudClientService.onTranscript((d: TranscriptionData) => {
const receivedAt = Date.now()
if (TRANSCRIPT_TIMING_TELEMETRY) {
console.log(
`${LOG_TAG}: transcript cloud_recv t=${receivedAt} final=${d.isFinal} lang=${
d.resolvedLanguage
} text="${d.text.slice(0, 48)}"`,
)
}
this.forwardEvent(
`transcription:${d.resolvedLanguage}`,
{
type: "transcription",
text: d.text,
isFinal: d.isFinal,
utteranceId: d.utteranceId,
transcribeLanguage: d.resolvedLanguage,
detectedLanguage: d.languageDetected ? d.resolvedLanguage : undefined,
startTime: d.startMs,
endTime: d.endMs,
speakerId: d.speakerId,
duration: d.durationMs,
provider: d.provider,
confidence: d.confidence,
__hostReceivedAt: receivedAt,
},
"cloud",
d.provider === "soniox" && (d.frameTimelineVersion === 1 || d.tokens.some((token) => token.audioPosition))
? d.tokens
: undefined,
)
})
cloudClientService.onTranslation((d: TranslationData) => {
this.forwardEvent(`translation:${d.source.language}:${d.target.language}`, {
type: "translation",
text: d.text,
originalText: d.originalText,
isFinal: d.isFinal,
utteranceId: d.utteranceId,
startTime: d.startMs,
endTime: d.endMs,
speakerId: d.speakerId,
duration: d.durationMs,
transcribeLanguage: d.source.language,
translateLanguage: d.target.language,
didTranslate: true,
provider: d.provider,
confidence: d.confidence,
})
})
}
private ensureCloudStatusWired(): void {
if (this.cloudStatusWired) return
this.cloudStatusWired = true
cloudClientService.onStatusChanged((status) => {
if (status.status === "connected") {
for (const app of this.connectedApps.values()) {
app.transcriptionListeners?.observe(cloudClientService.getAudioPosition())
}
// A miniapp that connected before the cloud client was ready never got
// its auth token; now that we're connected, mint it without waiting for
// the retry backoff (or a full manual reconnect).
this.redriveMiniappAuthDelivery()
}
// A disconnect can hand cloud Captions back to the shared native model.
// Recompute ownership on both disconnect and reconnect.
this.updateCloudSubscriptions()
this.broadcastCloudStatus()
})
sttModelManager.onSelectionChanged(() => this.updateCloudSubscriptions())
// On-device transcription starting or stopping moves preferLocal and fallback listeners.
localSttFallbackCoordinator.onModelStatusChanged(() => this.updateCloudSubscriptions())
useSettingsStore.subscribe(
(s) => s.getSetting(ISLAND_SETTINGS_KEYS.localSttFallbackActive),
() => {
this.broadcastCloudStatus()
},
)
}
// ===========================================================================
// On-device transcription model status (session.transcription.onModelStatus)
// ===========================================================================
/**
* The on-device model state as one miniapp sees it. Its on-device listeners
* are the localOnly and preferLocal ones, and every listener while the cloud
* is down. The phone runs one model, the one picked on the Speech page, so a
* miniapp whose on-device listeners all ask for another language is told
* it's unavailable.
*/
private transcriptionModelStatusFor(packageName: string): {
language: string
state: "downloading" | "loading" | "ready" | "unavailable"
progress?: number
reason?: string
} {
const status = localSttFallbackCoordinator.getModelStatus()
const language = status.language || sttModelManager.getBcp47ForLanguage()
if (!isFeatureEnabled("onDeviceSpeech")) {
return {language, state: "unavailable", reason: "On-device speech is disabled by this deployment"}
}
const cloudConnected = this.cloudSpeechUp()
const onDeviceListeners = (this.connectedApps.get(packageName)?.transcriptionListeners.routes() ?? []).filter(
(listener) => listener.processing !== "preferCloud" || !cloudConnected,
)
if (onDeviceListeners.length === 0) {
return {language, state: "unavailable", reason: "No on-device transcription subscription"}
}
// "auto" follows the picked model; any other language must be the picked one.
const hints = this.transcriptionHintsByApp.get(packageName) ?? []
if (!onDeviceListeners.some((listener) => onDeviceServes(listener, language, hints))) {
return {
language,
state: "unavailable",
reason: `The on-device speech model is ${language}; choose another language on the Speech page`,
}
}
switch (status.state) {
case "downloading":
return {language, state: "downloading", progress: status.progress ?? 0}
case "ready":
return {language, state: "ready"}
case "unavailable":
return {language, state: "unavailable", reason: status.reason ?? "The on-device speech model is unavailable"}
default:
// "idle" only lasts until the coordinator picks up this subscription.
return {language, state: "loading"}
}
}
private sendTranscriptionModelStatus(packageName: string, force = false): void {
const app = this.connectedApps.get(packageName)
if (!app) return
const data = this.transcriptionModelStatusFor(packageName)
const key = JSON.stringify(data)
if (!force && app.lastTranscriptionModelStatus === key) return
app.lastTranscriptionModelStatus = key
this.sendToMiniapp(packageName, {
type: MiniappResponseType.EVENT,
streamType: MiniappStreamType.TRANSCRIPTION_MODEL_STATUS,
data,
})
}
private broadcastTranscriptionModelStatus(): void {
for (const packageName of this.streamSubscribers.get(MiniappStreamType.TRANSCRIPTION_MODEL_STATUS) ?? []) {
this.sendTranscriptionModelStatus(packageName)
}
}
/** Bumped after each final local transcript reaches miniapps; finishUtterance waits on it. */
private localFinalSeq = 0
private readonly localFinalWaiters = new Set<() => void>()
/**
* End the current on-device utterance. Resolves with its final text only
* after that final transcript has gone out to miniapps, "" when nothing was
* pending, or null when no streaming model is active or it can't finish early.
*/
private async finishLocalUtterance(): Promise<string | null> {
if (!["android", "ios"].includes(Platform.OS) || typeof BluetoothSdk.finishTranscription !== "function") return null
if (!localSttFallbackCoordinator.isActive()) return null
const before = this.localFinalSeq
const result: unknown = await BluetoothSdk.finishTranscription()
if (typeof result !== "string") return null
if (result && this.localFinalSeq === before) {
// Native emits the final event before resolving, but the event and the
// promise reach JavaScript separately; wait briefly for the event.
await new Promise<void>((resolve) => {
const done = () => {
BgTimer.clearTimeout(timer)
this.localFinalWaiters.delete(done)
resolve()
}
const timer = BgTimer.setTimeout(done, LocalMiniappRuntime.FINISH_DELIVERY_WAIT_MS)
this.localFinalWaiters.add(done)
})
}
return result
}
private static readonly FINISH_DELIVERY_WAIT_MS = 1000
private noteLocalFinalDelivered(): void {
this.localFinalSeq++
for (const waiter of [...this.localFinalWaiters]) waiter()
}
private currentCloudStatus(): CloudClientStatusSnapshot {
const base = cloudClientService.getStatus()
const fallbackActive =
(useSettingsStore.getState().getSetting(ISLAND_SETTINGS_KEYS.localSttFallbackActive) as boolean | undefined) ===
true
return {
status: base.status,
audioTransport: fallbackActive ? "offline" : base.audioTransport,
}
}
private broadcastCloudStatus(): void {
const status = this.currentCloudStatus()
for (const packageName of this.connectedApps.keys()) {
this.sendCloudStatusToMiniapp(packageName, status)
}
}
private sendCloudStatusToMiniapp(packageName: string, status = this.currentCloudStatus()): void {
this.sendToMiniapp(packageName, {
type: MiniappResponseType.EVENT,
streamType: CLOUD_STATUS_STREAM,
data: status,
})
}
// ===========================================================================
// Stream fan-out
// ===========================================================================
/** Whether any miniapp subscribes to `stream`. */
public hasStreamSubscribers(stream: string): boolean {
return (this.streamSubscribers.get(stream)?.size ?? 0) > 0
}
/**
* Forward a streamed event to all miniapps subscribed to the given stream.
*
* Event name translation:
* - Incoming "head_up" → miniapp protocol uses "head_position" (HEAD_POSITION)
* - Incoming "VAD" (uppercase) → miniapp protocol uses "vad" (lowercase)
*/
public forwardEvent(
streamType: string,
data: unknown,
transcriptionSource?: TranscriptionEventSource,
tokens?: TranscriptionData["tokens"],
): void {
// Normalize incoming event names to miniapp protocol stream types
const normalizedStream = this.normalizeStreamType(streamType)
// Collect all subscribers: exact match, plus wildcard matches for streams
// that carry a language tag. A miniapp subscribed to "transcription:auto"
// should receive any "transcription:<lang>" event (the detected language
// is conveyed in the event data, not the stream key).
//
// Translation streams support cloud v3's wildcard patterns. Incoming
// events are keyed `translation:<source>:<target>` and we match against
// any of:
// translation:*:* — all-pairs (TranslationModule.on)
// translation:*:<target> — any-source → target (TranslationModule.to)
// translation:<source>:* — source → any-target (rare)
// translation:<source>:<target> — exact (TranslationModule.fromTo)
// translation:auto — back-compat alias for *:*
const matchedSubs = new Set<string>()
const exact = this.streamSubscribers.get(normalizedStream)
if (exact) for (const p of exact) matchedSubs.add(p)
if (normalizedStream.startsWith("transcription:")) {
const autoSubs = this.streamSubscribers.get("transcription:auto")
if (autoSubs) for (const p of autoSubs) matchedSubs.add(p)
} else if (normalizedStream.startsWith("translation:")) {
// translation:<source>:<target> — match each wildcard variant.
const parts = normalizedStream.split(":")
// parts[0] = "translation", parts[1] = source, parts[2] = target
if (parts.length === 3) {
const [, source, target] = parts
const patterns = [
"translation:auto", // legacy alias for *:*
"translation:*:*", // cloud v3 "all pairs"
`translation:*:${target}`, // cloud v3 "to <target>"
`translation:${source}:*`, // cloud v3 "from <source>"
]
for (const pat of patterns) {
const subs = this.streamSubscribers.get(pat)
if (subs) for (const p of subs) matchedSubs.add(p)
}
} else {
// Malformed stream key — still honor the legacy auto alias.
const autoSubs = this.streamSubscribers.get("translation:auto")
if (autoSubs) for (const p of autoSubs) matchedSubs.add(p)
}
}
if (normalizedStream.startsWith("transcription:") && transcriptionSource) {
this.forwardTranscription(normalizedStream, data, transcriptionSource, tokens, matchedSubs)
return
}
// Touch event per-gesture fan-out. SDK-side dispatch is keyed on the
// exact streamType, so per-gesture subscribers (`touch_event:single_tap`,
// etc.) need their own EVENT envelope with the gesture-tagged streamType.
// The bare `touch_event` stream above still catches `onTouch(handler)`.
let perGestureStream: string | null = null
let outboundData = data
if (normalizedStream === MiniappStreamType.GLASSES_CONNECTION) {
const connection = toMiniappConnectionData(data)
if (!connection) return
outboundData = connection
}
if (normalizedStream === MiniappStreamType.TOUCH_EVENT) {
// The Bluetooth SDK delivers the gesture under `gestureName` (single_tap /
// double_tap / triple_tap / long_press / swipe_up / swipe_down). Surface it
// to miniapps as `TouchData.kind` and tag a per-gesture stream so
// onTouch("single_tap", ...) routes correctly.
const touch = data as {gestureName?: string; kind?: string} | null
const gesture = touch?.gestureName ?? touch?.kind
if (typeof gesture === "string" && gesture.length > 0) {
outboundData = {...(touch as object), kind: gesture}
perGestureStream = `${MiniappStreamType.TOUCH_EVENT}:${gesture}`
}
}
if (matchedSubs.size === 0 && !perGestureStream) return
for (const packageName of matchedSubs) {
// While a nav trip is active the Nav SDK's road-snapped fixes are
// already being forwarded via addLocationListener (see NAV_START handler).
// Suppress the raw background-GPS forward for that miniapp so the two
// streams don't interleave and cause the position to jump back to the
// real-phone location during simulation.
if (normalizedStream === MiniappStreamType.LOCATION_UPDATE && this.navigationHandlers.isTripActive(packageName)) {
continue
}
this.sendToMiniapp(packageName, {
type: MiniappResponseType.EVENT,
streamType: normalizedStream,
data: outboundData,
})
}
// Send a separate envelope to per-gesture subscribers tagged with the
// gesture-specific streamType so SDK-side dispatch routes correctly.
if (perGestureStream) {
const gestureSubs = this.streamSubscribers.get(perGestureStream)
if (gestureSubs) {
for (const packageName of gestureSubs) {
this.sendToMiniapp(packageName, {
type: MiniappResponseType.EVENT,
streamType: perGestureStream,
data: outboundData,
})
}
}
}
}
/**
* Sends one transcript to each listener that hears its stream and currently
* gets its text from its source, tagged with that source. Then records where
* the source is in its utterance: a final can complete a listener's switch
* that waited for it.
*/
private forwardTranscription(
stream: string,
data: unknown,
source: TranscriptionEventSource,
tokens: TranscriptionData["tokens"] | undefined,
packageNames: Set<string>,
): void {
const transcript = (data ?? {}) as {text?: string; isFinal?: boolean; __hostReceivedAt?: number}
const isFinal = transcript.isFinal === true
// A switch that waited only on an utterance that went stale happens before this transcript.
let moved = this.refreshTranscriptionRouting()
const audioPosition = cloudClientService.getAudioPosition()
for (const packageName of packageNames) {
const app = this.connectedApps.get(packageName)
if (!app) continue
const deliveries = app.transcriptionListeners.deliveries(
stream,
source,
transcript.text ?? "",
tokens,
audioPosition,
)
if (TRANSCRIPT_TIMING_TELEMETRY && deliveries.length > 0) {
const now = Date.now()
console.log(
`${LOG_TAG}: transcript fanout t=${now} app=${packageName} source=${source} final=${isFinal} hostDelta=${
transcript.__hostReceivedAt ? now - transcript.__hostReceivedAt : -1
}ms text="${(transcript.text ?? "").slice(0, 48)}"`,
)
}
for (const delivery of deliveries) {
this.sendToMiniapp(packageName, {
type: MiniappResponseType.EVENT,
streamType: stream,
data: {...transcript, text: delivery.text, source},
transcriptionRoute: delivery.route,
...(delivery.listenerId ? {listenerId: delivery.listenerId} : {}),
})
}
}
if (source === "local" && isFinal) {
this.localFinalWatermark = audioPosition ?? this.localFinalWatermark
this.noteLocalFinalDelivered()
}
this.utterances.note(source, stream, isFinal, Date.now())
if (this.refreshTranscriptionRouting()) moved = true
if (moved) this.updateCloudSubscriptions()
}
/**
* Normalize incoming event names to miniapp stream type values.
*/
private normalizeStreamType(cloudEventName: string): string {
// Incoming event names → miniapp protocol translations.
// Bluetooth SDK event names don't always match the miniapp wire values.
switch (cloudEventName) {
case "head_up":
return MiniappStreamType.HEAD_POSITION // head_up → head_position
case "accel_event":
return MiniappStreamType.ACCEL_DATA // accel_event (native) → accel_data
case "VAD":
return MiniappStreamType.VAD // VAD (uppercase) → vad (lowercase)
case "glasses_battery_update":
return MiniappStreamType.GLASSES_BATTERY // glasses_battery_update → glasses_battery
case "glasses_connection_state":
return MiniappStreamType.GLASSES_CONNECTION // glasses_connection_state → glasses_connection
default:
// Preserve case for typed streams like "transcription:en-US" / "translation:en-US:fr-FR"
// whose language tags are case-sensitive (BCP-47). Lowercase only plain names.
if (cloudEventName.includes(":")) return cloudEventName
return cloudEventName.toLowerCase()
}
}
// ===========================================================================
// Outbound helpers
// ===========================================================================
/**
* Send a payload to a connected miniapp, wrapped in an envelope.
*/
/**
* Push a speaker-state transition to the owning miniapp. Idempotent: if
* the new state matches the cached one (and isn't an error), no envelope
* is sent. Error events are always sent — they're transient and the SDK
* settles back to a non-error state immediately after.
*/
private setSpeakerState(
packageName: string,
next: SpeakerStateValue,
extra?: {errorCode?: string; errorMessage?: string; durationMs?: number},
): void {
const app = this.connectedApps.get(packageName)
if (!app) return
if (app.speakerState === next && next !== "error") return
app.speakerState = next === "error" ? "error" : next
this.sendToMiniapp(packageName, {
type: MiniappResponseType.SPEAKER_STATE,
state: next,
...(extra?.errorCode !== undefined ? {errorCode: extra.errorCode} : {}),
...(extra?.errorMessage !== undefined ? {errorMessage: extra.errorMessage} : {}),
...(extra?.durationMs !== undefined ? {durationMs: extra.durationMs} : {}),
})
// After an error event, immediately transition to "stopped" so the
// SDK's isPlaying getter reads false and a new play()/speak() call
// starts cleanly from idle/stopped.
if (next === "error") {
app.speakerState = "stopped"
this.sendToMiniapp(packageName, {
type: MiniappResponseType.SPEAKER_STATE,
state: "stopped",
})
}
}
private sendToMiniapp(packageName: string, payload: Record<string, unknown>, requestId?: string): void {
const app = this.connectedApps.get(packageName)
if (!app) {
console.warn(`${LOG_TAG}: sendToMiniapp — ${packageName} not connected`)
return
}
const envelope: MiniappEnvelope = {
payload,
requestId,
}
const serialized = serializeEnvelope(envelope)
if ((payload as Record<string, unknown>)?.streamType?.toString().startsWith("transcription")) {
// console.log(
// `${LOG_TAG}: sendToMiniapp → ${packageName} streamType=${(payload as Record<string, unknown>).streamType}`,
// )
}
try {
app.sendMessage(serialized)
} catch (err) {
console.error(`${LOG_TAG}: sendToMiniapp error for ${packageName}:`, err)
}
}
/**
* Send a REQUEST_RESULT response.
*/
// ===========================================================================
// Inter-miniapp interop (session.miniapps + session.actions.invoke)
// ===========================================================================
/** Max serialized size of an action call's params / result (256 KB). */
private static readonly ACTION_PAYLOAD_CAP = 256 * 1024
/** Outstanding action invocations, keyed by host-generated callId. */
private actionCalls = new Map<
string,
{
targetPackageName: string
timer: number
resolve: (value: unknown) => void
reject: (error: Error & {code?: string}) => void
releaseWake?: () => Promise<void>
}
>()
private actionCallSeq = 0
/** Bumped by cleanup(): an install requested before sign-out or a deployment switch never activates. */
private installSessionEpoch = 0
/** Changes at cleanup: an install started earlier belongs to the ended session. */
public installSession(): number {
return this.installSessionEpoch
}
private interopApps(): ClientApp[] {
return useAppStatusStore.getState().apps
}
private isSystemPackage(packageName: string): boolean {
// A local or development build never gets system privileges, whatever name it claims.
if (isLocalBuildContext(packageName) || !SYSTEM_MINIAPP_PACKAGE_SET.has(packageName)) return false
const app = this.interopApps().find((candidate) => candidate.packageName === packageName)
if (app?.offline) return true
if (!app?.local || !app.version) return false
// The bundled release, or a compatible update of it from a Mentra host.
const identity = appRegistry.getReleaseIdentity(packageName, app.version)
return identity?.source === "bundled_asset" || isHostTrustedSystemMiniapp(packageName, identity)
}
private async startInteropApp(packageName: string): Promise<boolean> {
const app = this.interopApps().find((a) => a.packageName === packageName)
if (!app) return false
// An update in progress refuses every launch path, not only Home taps.
if (useAppStatusStore.getState().updatingPackages.has(packageName)) return false
if (app.local) {
await miniappLauncher.ensureConnected(packageName)
return true
}
return useAppStatusStore.getState().start(app, {skipNavigation: true})
}
private stopInteropApp(packageName: string): Promise<void> {
return useAppStatusStore.getState().stop(packageName)
}
/** Emit an interop audit event (best-effort — never let telemetry break a call). */
private auditInterop(event: InteropAuditEvent): void {
try {
getAnalytics()?.("miniapp_interop", {
caller: event.caller,
op: event.op,
target: event.target ?? "",
actionId: event.actionId ?? "",
ok: event.ok,
errorCode: event.errorCode ?? "",
})
} catch {
/* telemetry must never break an interop call */
}
}
/** Reject the request with NOT_PERMITTED unless the caller is a system app. */
private requireSystemCaller(
packageName: string,
requestId: string | undefined,
op: InteropAuditEvent["op"],
target?: string,
): boolean {
if (this.isSystemPackage(packageName)) return true
this.auditInterop({caller: packageName, op, target, ok: false, errorCode: MiniappErrorCode.NOT_PERMITTED})
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.NOT_PERMITTED,
message: "Inter-miniapp APIs are restricted to system apps",
})
return false
}
/** Project a host ClientApp into the SDK's MiniappInfo shape (JSON over the wire). */
private buildMiniappInfo(app: ClientApp): Record<string, unknown> {
const compatibility = app.compatibility ?? {
isCompatible: true,
missingRequired: [],
missingOptional: [],
warnings: [],
}
return {
packageName: app.packageName,
name: app.name,
version: app.version ?? "",
running: app.running,
compatibility,
system: isSystemMiniappPackage(app.packageName),
actions: projectSystemActions(app.actions ?? []),
}
}
private handleMiniappsList(packageName: string, payload: Record<string, unknown>, requestId?: string): void {
if (!this.requireSystemCaller(packageName, requestId, "list")) return
const includeIncompatible = payload.includeIncompatible === true
const infos = this.interopApps()
.filter(
(a) =>
a.packageName &&
a.packageName !== packageName &&
!a.packageName.includes("@empty") &&
(includeIncompatible || a.compatibility?.isCompatible !== false),
)
.map((a) => this.buildMiniappInfo(a))
this.sendResult(packageName, requestId, true, infos)
this.auditInterop({caller: packageName, op: "list", ok: true})
}
private async handleMiniappsStart(
packageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
const target = payload.packageName as string | undefined
if (!this.requireSystemCaller(packageName, requestId, "start", target)) return
const app = target ? this.interopApps().find((a) => a.packageName === target) : undefined
if (!target || !app) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.APP_NOT_FOUND,
message: `Miniapp not found: ${target ?? "(missing packageName)"}`,
})
this.auditInterop({
caller: packageName,
op: "start",
target,
ok: false,
errorCode: MiniappErrorCode.APP_NOT_FOUND,
})
return
}
// Pre-flight the hardware gate so the caller gets a precise reason rather
// than a generic rejection (start()'s own gate would refuse it silently).
if (app.compatibility && app.compatibility.isCompatible === false) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.APP_NOT_COMPATIBLE,
message: `${target} is not compatible with the connected glasses`,
})
islandNotifications.emit({
kind: "version_incompatible",
packageName: target,
reason: `${target} is not compatible with the connected glasses`,
metadata: {missingRequired: app.compatibility.missingRequired ?? [], via: "miniapps.start"},
timestamp: Date.now(),
})
this.auditInterop({
caller: packageName,
op: "start",
target,
ok: false,
errorCode: MiniappErrorCode.APP_NOT_COMPATIBLE,
})
return
}
try {
// startInteropApp resolves to false when the app-store gate rejected the
// launch or the background context failed to spawn — don't report success.
const started = await this.startInteropApp(target)
if (started) {
// `session.miniapps.open` also brings the phone UI forward.
if (payload.foreground === true && app.local) await useAppStatusStore.getState().setForeground(target)
this.sendResult(packageName, requestId, true)
this.auditInterop({caller: packageName, op: "start", target, ok: true})
} else {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: `start of ${target} was rejected by the host (gated, updating, or failed to spawn)`,
})
this.auditInterop({
caller: packageName,
op: "start",
target,
ok: false,
errorCode: MiniappErrorCode.INTERNAL,
})
}
} catch (e) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: (e as Error)?.message ?? "start failed",
})
this.auditInterop({
caller: packageName,
op: "start",
target,
ok: false,
errorCode: MiniappErrorCode.INTERNAL,
})
}
}
private async handleMiniappsStop(
packageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
const target = payload.packageName as string | undefined
if (!this.requireSystemCaller(packageName, requestId, "stop", target)) return
if (!target) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.APP_NOT_FOUND,
message: "stop requires a packageName",
})
return
}
try {
await this.stopInteropApp(target)
this.sendResult(packageName, requestId, true)
this.auditInterop({caller: packageName, op: "stop", target, ok: true})
} catch (e) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: (e as Error)?.message ?? "stop failed",
})
}
}
// ---------------------------------------------------------------------------
// Installing miniapps (system-list miniapps only)
// ---------------------------------------------------------------------------
/**
* Installing and uninstalling miniapps: only a miniapp on the system list, running the release the host installed
* for it. Both the live context's provenance and the installed release count: a development build, or another
* context that only reuses a system package's name, may not, and neither may any other miniapp.
*/
private requireSystemListCaller(
packageName: string,
requestId: string | undefined,
op: InteropAuditEvent["op"],
target?: string,
): boolean {
if (
SYSTEM_MINIAPP_PACKAGE_SET.has(packageName) &&
this.connectedApps.get(packageName)?.hostTrustedSystem === true &&
this.isSystemPackage(packageName)
) {
return true
}
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.NOT_PERMITTED,
message: "Installing miniapps is restricted to the Mentra App's system miniapps",
})
this.auditInterop({caller: packageName, op, target, ok: false, errorCode: MiniappErrorCode.NOT_PERMITTED})
return false
}
/** The host's compatibility policy for installs and updates, or null until configured. */
public currentInstallCompatibilityPolicy(): MiniappCompatibilityPolicy | null {
const {hostVersion, supportedMiniappSdkRange} = getConfigValues()
if (!hostVersion || !supportedMiniappSdkRange) return null
const defaultWearable = useSettingsStore.getState().getSetting(ISLAND_SETTINGS_KEYS.defaultWearable) as
| DeviceTypes
| undefined
return {
hostVersion,
supportedSdkRange: supportedMiniappSdkRange,
hardwareCapabilities: getModelCapabilities(defaultWearable || DeviceTypes.NONE),
}
}
private evaluateInstallCompatibility(payload: Record<string, unknown>): MiniappInstallCompatibility {
const policy = this.currentInstallCompatibilityPolicy()
if (!policy) {
return {compatible: false, blocker: "host", reason: "Host miniapp compatibility policy is not configured"}
}
return checkMiniappInstallCompatibility(
{
minHostVersion: typeof payload.minHostVersion === "string" ? payload.minHostVersion.trim() : undefined,
sdkVersion: typeof payload.sdkVersion === "string" ? payload.sdkVersion.trim() : undefined,
hardwareRequirements: payload.hardwareRequirements,
},
policy,
)
}
/** A QR-selected build or snapshot is the user's choice; automatic updates leave it alone. */
public hasDevelopmentSelection(packageName: string): boolean {
return (
this.interopApps().some((app) => app.packageName === packageName && app.isMiniappDev) ||
getDevAppRecords().some((record) => record.packageName === packageName) ||
appRegistry.getSelectedDevSnapshot(packageName) !== null
)
}
/**
* Install the miniapp at a miniapp URL through `installMiniapp`, headlessly: the system miniapp asks the person
* first, in its own conversation. It registers the URL like every install.
*/
private async handleMiniappsInstall(
callerPackageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
if (!this.requireSystemListCaller(callerPackageName, requestId, "install")) return
const fail = (code: MiniappErrorCode, message: string, reason?: InstallMiniappErrorCode) => {
this.sendResult(callerPackageName, requestId, false, undefined, {code, message, ...(reason ? {reason} : {})})
this.auditInterop({caller: callerPackageName, op: "install", ok: false, errorCode: code})
}
const url = typeof payload.url === "string" ? payload.url.trim() : ""
if (!url) {
fail(MiniappErrorCode.INVALID_ARGUMENT, "install requires the miniapp's url")
return
}
// The package the caller agreed to; the URL must serve exactly that one.
const expected = payload.packageName === undefined ? undefined : payload.packageName
if (expected !== undefined && (typeof expected !== "string" || !expected.trim())) {
fail(MiniappErrorCode.INVALID_ARGUMENT, "install's packageName must be a package name")
return
}
try {
const {status, packageName, version} = await installMiniapp(url, {
source: "system",
...(expected !== undefined ? {expectedPackageName: expected.trim()} : {}),
})
this.sendResult(callerPackageName, requestId, true, {status, packageName, version})
this.auditInterop({caller: callerPackageName, op: "install", target: packageName, ok: true})
} catch (error) {
if (error instanceof InstallMiniappError) fail(MiniappErrorCode.INSTALL_FAILED, error.message, error.code)
else fail(MiniappErrorCode.INSTALL_FAILED, (error as Error)?.message ?? "miniapp installation failed")
}
}
private handleMiniappsInstallCheck(
callerPackageName: string,
payload: Record<string, unknown>,
requestId?: string,
): void {
if (!this.requireSystemListCaller(callerPackageName, requestId, "install")) return
this.sendResult(callerPackageName, requestId, true, this.evaluateInstallCompatibility(payload))
}
/**
* Why a system miniapp may not uninstall `target`, or null. It may uninstall a miniapp installed from a miniapp URL,
* by the person or a system miniapp. A miniapp this build bundles, one a workspace manages (its deployment manifest
* or a Fleet assignment), a release QR's and a development build stay: they belong to the build, the workspace or
* the person.
*/
private uninstallRefusal(target: string): {code: MiniappErrorCode; message: string} | null {
if (isSystemMiniappPackage(target)) {
return {code: MiniappErrorCode.NOT_PERMITTED, message: `${target} is bundled with the Mentra App`}
}
const version = appRegistry.getActiveReleaseVersion(target)
if (!version) return {code: MiniappErrorCode.APP_NOT_FOUND, message: `${target} is not installed`}
const identity = appRegistry.getReleaseIdentity(target, version)
const fromUrlOnly = appRegistry.getInstallReasons(target).every((reason) => reason === "explicit")
if (identity?.source !== "url" || !fromUrlOnly || this.hasDevelopmentSelection(target)) {
return {code: MiniappErrorCode.NOT_PERMITTED, message: `${target} wasn't installed from a miniapp URL`}
}
return null
}
private async handleMiniappsUninstall(
callerPackageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
const target = typeof payload.packageName === "string" ? payload.packageName : undefined
if (!this.requireSystemListCaller(callerPackageName, requestId, "uninstall", target)) return
const fail = (code: MiniappErrorCode, message: string) => {
this.sendResult(callerPackageName, requestId, false, undefined, {code, message})
this.auditInterop({caller: callerPackageName, op: "uninstall", target, ok: false, errorCode: code})
}
if (!target) {
fail(MiniappErrorCode.INVALID_ARGUMENT, "uninstall requires a packageName")
return
}
const refused = this.uninstallRefusal(target)
if (refused) {
fail(refused.code, refused.message)
return
}
const session = this.installSessionEpoch
const late: {refusal?: {code: MiniappErrorCode; message: string}} = {}
try {
const app = this.interopApps().find((candidate) => candidate.packageName === target)
if (app?.running) await this.stopInteropApp(target)
// Checked again inside the serialized uninstall: a Fleet assignment, a workspace release or a development build
// may have arrived while the miniapp stopped, and nothing is removed once the engine session has ended.
const result = await useAppStatusStore.getState().uninstall(target, undefined, {
beforeRemove: () => {
late.refusal =
session === this.installSessionEpoch
? (this.uninstallRefusal(target) ?? undefined)
: {code: MiniappErrorCode.INTERNAL, message: `The uninstall of ${target} was cancelled`}
if (late.refusal) throw new Error(late.refusal.message)
},
})
if (result.is_error()) throw result.error
this.sendResult(callerPackageName, requestId, true)
this.auditInterop({caller: callerPackageName, op: "uninstall", target, ok: true})
} catch (error) {
if (late.refusal) fail(late.refusal.code, late.refusal.message)
else fail(MiniappErrorCode.INTERNAL, (error as Error)?.message ?? "miniapp uninstall failed")
}
}
// ---------------------------------------------------------------------------
// Declared actions
// ---------------------------------------------------------------------------
/** True iff `value` serializes larger than the action payload cap. */
private actionPayloadTooLarge(value: unknown): boolean {
try {
return JSON.stringify(value ?? null).length > LocalMiniappRuntime.ACTION_PAYLOAD_CAP
} catch {
// Unserializable — let it through; the transport's own serialize handles it.
return false
}
}
private actionError(
code: string,
message: string,
details?: Record<string, unknown>,
): Error & {code: string; details?: Record<string, unknown>} {
return Object.assign(new Error(message), {code, ...(details ? {details} : {})})
}
/**
* The action broker shared by `session.actions.invoke` and host scheduling.
* A transient action runs in an invisible, invocation-scoped wake; a
* persistent one starts the target as normal user activity. Host-audience
* actions, and every action of a background-only miniapp, are reachable only
* from the host.
*/
private async invokeDeclaredAction(
callerPackageName: string,
target: string,
actionId: string,
params: Record<string, unknown>,
timeoutMs: number,
allowHostAudience: boolean,
): Promise<unknown> {
if (this.actionPayloadTooLarge(params)) {
throw this.actionError(MiniappErrorCode.PAYLOAD_TOO_LARGE, "action params exceeded the 256 KB cap")
}
// Background-only packages stay out of every user/miniapp-facing list. The
// host resolves their installed declarations without exposing them.
const backgroundOnly = !isMiniappAvailable(target)
const app =
backgroundOnly && allowHostAudience
? (await appRegistry.getInstalledMiniapps({includeBackgroundOnly: true})).find(
(candidate) => candidate.packageName === target,
)
: this.interopApps().find((candidate) => candidate.packageName === target)
if (!app) throw this.actionError(MiniappErrorCode.APP_NOT_FOUND, `Miniapp not found: ${target}`)
if (app.compatibility && app.compatibility.isCompatible === false) {
islandNotifications.emit({
kind: "version_incompatible",
packageName: target,
reason: `${target} is not compatible with the connected glasses`,
metadata: {missingRequired: app.compatibility.missingRequired ?? [], via: "miniapps.invoke"},
timestamp: Date.now(),
})
throw this.actionError(
MiniappErrorCode.APP_NOT_COMPATIBLE,
`${target} is not compatible with the connected glasses`,
)
}
const action = (app.actions ?? []).find((candidate) => candidate.id === actionId)
if (
!action ||
(action.audience === "host" && !allowHostAudience) ||
(backgroundOnly && (!allowHostAudience || action.audience !== "host" || action.lifecycle !== "transient"))
) {
throw this.actionError(MiniappErrorCode.ACTION_NOT_FOUND, `${target} does not declare action "${actionId}"`)
}
let releaseWake: (() => Promise<void>) | undefined
try {
if (action.lifecycle === "transient") {
if (!app.local) {
throw this.actionError(
MiniappErrorCode.WAKE_FAILED,
`transient action wake is unavailable for non-local miniapp ${target}`,
)
}
releaseWake = await this.transientActionWakes.acquire(target)
} else if (!(await this.startInteropApp(target))) {
throw this.actionError(MiniappErrorCode.WAKE_FAILED, `failed to start ${target}`)
}
} catch (error) {
if ((error as {code?: string}).code) throw error
throw this.actionError(MiniappErrorCode.WAKE_FAILED, (error as Error)?.message ?? `failed to wake ${target}`)
}
// The wake waited for CONNECT, but the target could have dropped in the gap
// before delivery — fail fast rather than arming a timer for a call that
// sendToMiniapp would silently drop.
if (!this.connectedApps.has(target)) {
await releaseWake?.()
throw this.actionError(
MiniappErrorCode.WAKE_FAILED,
`${target} disconnected before the action could be delivered`,
)
}
const callId = `act-${Date.now().toString(36)}-${this.actionCallSeq++}`
return new Promise<unknown>((resolve, reject) => {
const timer = BgTimer.setTimeout(() => {
void this.finalizeActionCall(
callId,
false,
undefined,
this.actionError(MiniappErrorCode.ACTION_TIMEOUT, `action "${actionId}" timed out after ${timeoutMs}ms`),
)
}, timeoutMs)
this.actionCalls.set(callId, {targetPackageName: target, timer, resolve, reject, releaseWake})
this.sendToMiniapp(target, {
type: MiniappResponseType.ACTION_CALL,
callId,
actionId,
params,
callerPackageName,
})
})
}
/** The host invokes a miniapp's action, host-only actions included. The host is not represented as a miniapp. */
public invokeActionFromHost(
targetPackageName: string,
actionId: string,
params: Record<string, unknown> = {},
timeoutMs = 10 * 60_000,
): Promise<unknown> {
const boundedTimeout = Math.min(Math.max(timeoutMs, 6_000), 15 * 60_000)
return this.invokeDeclaredAction(HOST_ACTION_CALLER, targetPackageName, actionId, params, boundedTimeout, true)
}
/** `session.actions.invoke` adapter around the shared broker. */
private async handleActionInvoke(
callerPackageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
const target = payload.targetPackageName as string | undefined
if (!this.requireSystemCaller(callerPackageName, requestId, "invoke", target)) return
const actionId = payload.actionId as string | undefined
if (!target || !actionId) {
this.sendResult(callerPackageName, requestId, false, undefined, {
code: !target ? MiniappErrorCode.APP_NOT_FOUND : MiniappErrorCode.ACTION_NOT_FOUND,
message: !target ? "invoke requires a targetPackageName" : "invoke requires an actionId",
})
return
}
// Floor the timeout at 6s so the host never rejects with ACTION_TIMEOUT before
// the target SDK's handler-registration window closes. A freshly-woken miniapp
// buffers an undelivered ACTION_CALL for HANDLER_WAIT_MS (5s in @mentra/miniapp's
// actions module) waiting for session.actions.handle; a shorter host timeout
// could fire while the target is still registering, then the action would run
// with no caller left to receive its result. 6s = that 5s buffer + 1s for the
// ACTION_RESULT/NO_ACTION_HANDLER reply to travel back. Keep these in sync.
const timeoutMs = Math.min(Math.max(Number(payload.timeoutMs) || 30_000, 6_000), 120_000)
const params = (payload.params as Record<string, unknown> | undefined) ?? {}
try {
const result = await this.invokeDeclaredAction(callerPackageName, target, actionId, params, timeoutMs, false)
this.sendResult(callerPackageName, requestId, true, result ?? null)
this.auditInterop({caller: callerPackageName, op: "invoke", target, actionId, ok: true})
} catch (error) {
const code = (error as {code?: string}).code ?? MiniappErrorCode.INTERNAL
// A target's own error carries its extra fields through to the caller.
this.sendResult(callerPackageName, requestId, false, undefined, {
...((error as {details?: Record<string, unknown>}).details ?? {}),
code,
message: (error as Error)?.message ?? "action invocation failed",
})
this.auditInterop({caller: callerPackageName, op: "invoke", target, actionId, ok: false, errorCode: code})
}
}
/** The target's context is gone: fail its pending invocations and forget its wake leases. */
private clearActionState(packageName: string): void {
this.transientActionWakes.forget(packageName)
for (const [callId, pending] of this.actionCalls) {
if (pending.targetPackageName !== packageName) continue
void this.finalizeActionCall(
callId,
false,
undefined,
this.actionError(MiniappErrorCode.WAKE_FAILED, `${packageName} disconnected during action execution`),
)
}
}
private async finalizeActionCall(
callId: string,
ok: boolean,
result?: unknown,
error?: Error & {code?: string},
): Promise<void> {
const pending = this.actionCalls.get(callId)
if (!pending) return
this.actionCalls.delete(callId)
BgTimer.clearTimeout(pending.timer)
try {
await pending.releaseWake?.()
} catch (releaseError) {
console.warn(`${LOG_TAG}: failed to release transient action wake`, releaseError)
}
if (ok) pending.resolve(result ?? null)
else pending.reject(error ?? this.actionError(MiniappErrorCode.INTERNAL, "action handler error"))
}
/** Target → host: resolve the correlated action invocation. */
private handleActionResult(targetPackageName: string, payload: Record<string, unknown>): void {
const callId = payload.callId as string | undefined
if (!callId) return
const pending = this.actionCalls.get(callId)
// Only the invoked target may resolve this call. callIds are guessable
// (timestamp + seq), so a different connected miniapp must not be able to
// spoof a result/error for someone else's invoke.
if (!pending || pending.targetPackageName !== targetPackageName) return
if (payload.ok === true) {
const result = payload.result
if (this.actionPayloadTooLarge(result)) {
void this.finalizeActionCall(
callId,
false,
undefined,
this.actionError(MiniappErrorCode.PAYLOAD_TOO_LARGE, "action result exceeded the 256 KB cap"),
)
return
}
void this.finalizeActionCall(callId, true, result)
return
}
const payloadError = payload.error as ({code?: string; message?: string} & Record<string, unknown>) | undefined
void this.finalizeActionCall(
callId,
false,
undefined,
this.actionError(
payloadError?.code ?? MiniappErrorCode.INTERNAL,
payloadError?.message ?? "action handler error",
payloadError,
),
)
}
private sendResult(
packageName: string,
requestId: string | undefined,
ok: boolean,
data?: unknown,
error?: {code: string; message: string} & Record<string, unknown>,
): void {
if (!requestId) return
this.sendToMiniapp(
packageName,
{
type: MiniappResponseType.REQUEST_RESULT,
requestId,
ok,
...(data !== undefined ? {data} : {}),
...(error ? {error} : {}),
},
requestId,
)
}
/**
* Send a VISIBILITY_CHANGE push to a miniapp.
*/
public sendVisibilityChange(packageName: string, visibility: "foreground" | "background"): void {
this.sendToMiniapp(packageName, {
type: MiniappResponseType.VISIBILITY_CHANGE,
visibility,
})
}
/**
* Fast foreground liveness check used when a local miniapp UI is opened or
* resumed. The normal watchdog intentionally waits ~30s to avoid killing a
* healthy-but-busy background script. When the user is actively looking at a
* WebView, a stale JSContext reads as "cloud offline" / no captions, so probe
* immediately and reuse the crash-respawn path if no message comes back.
*/
public probeForegroundLiveness(
packageName: string,
reason = "foreground-open",
timeoutMs = FOREGROUND_LIVENESS_PROBE_TIMEOUT_MS,
): void {
const app = this.connectedApps.get(packageName)
if (!app) return
this.clearForegroundProbe(packageName)
const probeStartedAt = Date.now()
this.sendToMiniapp(packageName, {
type: MiniappRequestType.PING,
})
const timerId = BgTimer.setTimeout(() => {
this.foregroundProbeTimers.delete(packageName)
const current = this.connectedApps.get(packageName)
if (!current) return
if (current.lastPongAt >= probeStartedAt) return
// Respawning tears down an ACS call and its hotspot. A busy background during a join
// misses one short ping; leave it to the regular ping loop, which needs several misses.
// Nobody owns the meeting until the `acsJoin` step, so a live SoftAP attempt counts as well:
// respawning during the hotspot or scoped Wi-Fi join cancels the join outright.
if (acsMeetingService.ownerPackage() === packageName || this.hasLiveSoftapAttempt(packageName)) {
console.warn(`${LOG_TAG}: ${packageName} missed a foreground probe (${reason}) during a call; not respawning`)
return
}
console.warn(`${LOG_TAG}: ${packageName} failed foreground liveness probe (${reason}), respawning`)
this.unregisterApp(packageName)
this.onLivenessTimeout?.(packageName)
}, timeoutMs)
this.foregroundProbeTimers.set(packageName, timerId)
}
// ===========================================================================
// Ping / pong liveness
// ===========================================================================
private ensurePingLoop(): void {
if (this.pingIntervalId !== null) return
this.pingIntervalId = BgTimer.setInterval(() => {
this.doPingRound()
}, PING_INTERVAL_MS)
}
private stopPingLoop(): void {
if (this.pingIntervalId !== null) {
BgTimer.clearInterval(this.pingIntervalId)
this.pingIntervalId = null
}
}
private doPingRound(): void {
const toRemove: string[] = []
for (const [packageName, app] of this.connectedApps) {
if (!this.hasLiveSoftapAttempt(packageName)) {
const liveness = advanceMiniappPingLiveness(app.unansweredPingRounds, PING_TIMEOUT_THRESHOLD)
if (liveness.shouldUnregister) {
console.warn(`${LOG_TAG}: ${packageName} missed ${PING_TIMEOUT_THRESHOLD} pings, unregistering`)
toRemove.push(packageName)
continue
}
app.unansweredPingRounds = liveness.unansweredPingRounds
}
// Send PING — SDK auto-replies with PONG
this.sendToMiniapp(packageName, {
type: MiniappRequestType.PING,
})
}
for (const pkg of toRemove) {
this.unregisterApp(pkg)
// Hand the package to the router's respawn machinery — a missed-pings
// death is treated like a crash so the background script comes back.
this.onLivenessTimeout?.(pkg)
}
}
/**
* Called when a PONG is received from a miniapp (or any message, really).
* Updates lastPongAt to keep the app alive.
*/
public handlePong(packageName: string): void {
const app = this.connectedApps.get(packageName)
if (app) {
app.lastPongAt = Date.now()
app.unansweredPingRounds = 0
this.clearForegroundProbe(packageName)
}
}
/** This miniapp's SoftAP join is in flight and has not been cancelled. */
private hasLiveSoftapAttempt(packageName: string): boolean {
return shouldHoldMiniappPingLiveness({
packageName,
softapPackageName: this.softapAttempt?.packageName,
softapCancelled: this.softapAttempt?.cancelled,
})
}
private clearForegroundProbe(packageName: string): void {
const timerId = this.foregroundProbeTimers.get(packageName)
if (timerId == null) return
BgTimer.clearTimeout(timerId)
this.foregroundProbeTimers.delete(packageName)
}
// ===========================================================================
// Lifecycle
// ===========================================================================
public cleanup(): void {
console.log(`${LOG_TAG}: cleanup()`)
// Installs already in flight belong to the ending session: they must
// not activate afterwards, and their open update prompts close unanswered.
this.installSessionEpoch += 1
dismissRunningUpdatePrompts()
this.visibilityUnsubscribe?.()
this.visibilityUnsubscribe = null
this.appStateSubscription?.remove()
this.appStateSubscription = null
this.visiblePackage = null
this.initialized = false
this.stopPingLoop()
// Copy keys since unregisterApp mutates the map
const packageNames = [...this.connectedApps.keys()]
for (const pkg of packageNames) {
this.unregisterApp(pkg)
}
// Belt-and-suspenders: clear any remaining state
const hadButtonPressSubscribers = this.getButtonPressSubscribers().length > 0
this.streamSubscribers.clear()
if (hadButtonPressSubscribers) {
for (const listener of this.buttonPressSubscriberListeners) {
try {
listener([])
} catch (error) {
console.warn(`${LOG_TAG}: button press subscriber listener threw during cleanup:`, error)
}
}
}
this.connectedApps.clear()
this.lastAppliedLocationRate = null
this.recomputeLocationTier()
for (const timerId of this.foregroundProbeTimers.values()) {
BgTimer.clearTimeout(timerId)
}
this.foregroundProbeTimers.clear()
LocalMiniappRuntime.instance = null
}
/**
* Number of currently connected miniapps (for diagnostics).
*/
public get connectedAppCount(): number {
return this.connectedApps.size
}
}
const localMiniappRuntime = LocalMiniappRuntime.getInstance()
export default localMiniappRuntime
|