Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 | 'use client' import React, { useCallback, useEffect, useRef, useState } from 'react' import { useQueryClient } from '@tanstack/react-query' import * as DropdownMenu from '@radix-ui/react-dropdown-menu' import { useSession } from 'next-auth/react' import { AppNavBar } from '@/components/AppNavBar' import { AdminNav } from '@/components/AdminNav' import { TtsTestPanel } from '@/components/admin/TtsTestPanel' import { ClipRecorder } from '@/components/admin/ClipRecorder' import { MicLevelMeter } from '@/components/admin/MicLevelMeter' import { useBackgroundTask } from '@/hooks/useBackgroundTask' import { useCollectedClips, useGenerateCollectedClips, collectedClipKeys, } from '@/hooks/useCollectedClips' import type { CollectedClipGenerateOutput } from '@/lib/tasks/collected-clip-generate' import { isHashClipId } from '@/lib/audio/clipHash' import { ALL_VOICES, VOICE_PROVIDERS, getVoiceMeta } from '@/lib/audio/voices' import { Z_INDEX } from '@/constants/zIndex' import { css } from '../../../../styled-system/css' import type { VoiceSourceData } from '@/lib/audio/voiceSource' interface AudioStatus { activeVoice: string voices: Record<string, { total: number; existing: number }> totalCollectedClips: number voiceClipCounts: Record<string, number> } export default function AdminAudioPage() { const [status, setStatus] = useState<AudioStatus | null>(null) const [loading, setLoading] = useState(true) const [error, setError] = useState<string | null>(null) const [voiceChain, setVoiceChain] = useState<VoiceSourceData[]>([]) const [voiceChainDirty, setVoiceChainDirty] = useState(false) const [showVoiceChain, setShowVoiceChain] = useState(false) const [showTtsTest, setShowTtsTest] = useState(false) const [showClipManagement, setShowClipManagement] = useState(false) const [ccGenVoice, setCcGenVoice] = useState<string>('onyx') const [ccGenTaskId, setCcGenTaskId] = useState<string | null>(null) const [ccPlayingClipId, setCcPlayingClipId] = useState<string | null>(null) const [newCustomVoiceName, setNewCustomVoiceName] = useState<string | null>(null) const [recordingClipId, setRecordingClipId] = useState<string | null>(null) const [audioDevices, setAudioDevices] = useState<MediaDeviceInfo[]>([]) const [selectedDeviceId, setSelectedDeviceId] = useState<string>('') const [micStream, setMicStream] = useState<MediaStream | null>(null) const ccAudioRef = useRef<HTMLAudioElement | null>(null) const [reportingVoice, setReportingVoice] = useState<string | null>(null) const reportAudioRef = useRef<HTMLAudioElement | null>(null) const queryClient = useQueryClient() const { data: session } = useSession() // React Query: collected clips with per-voice generation status const { data: ccData, isLoading: collectedClipsLoading } = useCollectedClips(ccGenVoice, { enabled: showClipManagement, }) const collectedClips = ccData?.clips ?? [] const ccGeneratedFor = ccData?.generatedFor ?? {} const ccDeactivatedFor = ccData?.deactivatedFor ?? {} // React Query: mutation for triggering collected clip generation const ccGenerateMutation = useGenerateCollectedClips(ccGenVoice) // Background task subscription for collected clip generation const { state: ccTaskState, cancel: cancelCcTask } = useBackgroundTask<CollectedClipGenerateOutput>(ccGenTaskId) const fetchStatus = useCallback(async () => { try { const res = await fetch('/api/admin/audio') if (!res.ok) throw new Error('Failed to fetch') const data = await res.json() setStatus({ activeVoice: data.activeVoice, voices: data.voices, totalCollectedClips: data.totalCollectedClips ?? 0, voiceClipCounts: data.voiceClipCounts ?? {}, }) } catch (err) { setError(err instanceof Error ? err.message : 'Unknown error') } finally { setLoading(false) } }, []) useEffect(() => { fetchStatus() }, [fetchStatus]) // Fetch voice chain config on mount useEffect(() => { fetch('/api/settings/voice-chain') .then((res) => (res.ok ? res.json() : null)) .then((data) => { if (data?.voiceChain) setVoiceChain(data.voiceChain) }) .catch(() => {}) }, []) const handleSaveVoiceChain = async () => { try { const res = await fetch('/api/settings/voice-chain', { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ voiceChain }), }) if (!res.ok) throw new Error('Failed to save') setVoiceChainDirty(false) } catch (err) { setError(err instanceof Error ? err.message : 'Failed to save voice chain') } } const moveVoiceChainEntry = (index: number, direction: -1 | 1) => { const next = [...voiceChain] const target = index + direction if (target < 0 || target >= next.length) return ;[next[index], next[target]] = [next[target], next[index]] setVoiceChain(next) setVoiceChainDirty(true) } const removeVoiceChainEntry = (index: number) => { setVoiceChain((prev) => prev.filter((_, i) => i !== index)) setVoiceChainDirty(true) } const addToVoiceChain = (source: VoiceSourceData) => { setVoiceChain((prev) => [...prev, source]) setVoiceChainDirty(true) } const handleReportIn = useCallback(async (voiceName: string) => { if (reportAudioRef.current) { reportAudioRef.current.pause() reportAudioRef.current = null } setReportingVoice(voiceName) try { const res = await fetch('/api/admin/audio/preview', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ voice: voiceName, text: `Hey! I'm ${voiceName}, reporting for duty. You picked me, great choice.`, tone: 'Sassy, confident, and a little cheeky. Short punchy delivery with loads of personality. Have fun with it.', }), }) if (!res.ok) { let detail = `HTTP ${res.status}` try { const body = await res.json() if (body.error) detail = body.error } catch { // response wasn't JSON } setError(`Report-in failed for ${voiceName}: ${detail}`) setReportingVoice(null) return } const blob = await res.blob() const url = URL.createObjectURL(blob) const audio = new Audio(url) reportAudioRef.current = audio audio.onended = () => { setReportingVoice(null) URL.revokeObjectURL(url) } audio.onerror = () => { setError(`Report-in audio playback failed for ${voiceName}`) setReportingVoice(null) URL.revokeObjectURL(url) } audio.play() } catch (err) { setError( `Report-in network error for ${voiceName}: ${err instanceof Error ? err.message : String(err)}` ) setReportingVoice(null) } }, []) const isCcGenerating = ccTaskState?.status === 'pending' || ccTaskState?.status === 'running' // Determine if selected voice is custom const isCustomVoice = voiceChain.some((s) => s.type === 'custom' && s.name === ccGenVoice) // Request mic permission, acquire stream, and enumerate devices when custom voice is selected. // getUserMedia must be called BEFORE enumerateDevices — browsers withhold real // deviceIds/labels until permission is granted, which causes { exact: id } to fail. useEffect(() => { if (!isCustomVoice) { // Clean up stream when leaving custom voice setMicStream((prev) => { if (prev) prev.getTracks().forEach((t) => t.stop()) return null }) setAudioDevices([]) setSelectedDeviceId('') setRecordingClipId(null) return } let cancelled = false // 1. Request mic permission with default device → gives us a working stream immediately navigator.mediaDevices .getUserMedia({ audio: true }) .then(async (defaultStream) => { if (cancelled) { defaultStream.getTracks().forEach((t) => t.stop()) return } // Set the default stream so recording works right away setMicStream((prev) => { if (prev) prev.getTracks().forEach((t) => t.stop()) return defaultStream }) // 2. Now that permission is granted, enumerate returns real deviceIds/labels const devices = await navigator.mediaDevices.enumerateDevices() if (cancelled) return const audioInputs = devices.filter((d) => d.kind === 'audioinput') setAudioDevices(audioInputs) // Pre-select the device that matches the active stream track const activeTrack = defaultStream.getAudioTracks()[0] const activeSettings = activeTrack?.getSettings() const matchingDevice = audioInputs.find((d) => d.deviceId === activeSettings?.deviceId) setSelectedDeviceId(matchingDevice?.deviceId ?? audioInputs[0]?.deviceId ?? '') }) .catch((err) => { console.error('Failed to acquire mic:', err) if (!cancelled) setError('Failed to access microphone. Check browser permissions.') }) return () => { cancelled = true } // eslint-disable-next-line react-hooks/exhaustive-deps }, [isCustomVoice]) // Switch mic stream when user picks a different device from the dropdown useEffect(() => { if (!isCustomVoice || !selectedDeviceId) return // Skip if the current stream already uses this device const currentTrack = micStream?.getAudioTracks()[0] if (currentTrack?.getSettings().deviceId === selectedDeviceId) return let cancelled = false navigator.mediaDevices .getUserMedia({ audio: { deviceId: { ideal: selectedDeviceId } } }) .then((stream) => { if (cancelled) { stream.getTracks().forEach((t) => t.stop()) return } setMicStream((prev) => { if (prev) prev.getTracks().forEach((t) => t.stop()) return stream }) }) .catch((err) => { console.error('Failed to switch mic:', err) if (!cancelled) setError('Failed to switch microphone') }) return () => { cancelled = true } // eslint-disable-next-line react-hooks/exhaustive-deps }, [selectedDeviceId]) // Clean up mic stream on unmount useEffect(() => { return () => { setMicStream((prev) => { if (prev) prev.getTracks().forEach((t) => t.stop()) return null }) } }, []) // Custom clip management handlers const handleDeactivateClip = async (clipId: string) => { try { const res = await fetch( `/api/admin/audio/custom-clips/${encodeURIComponent(ccGenVoice)}/${encodeURIComponent(clipId)}`, { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'deactivate' }), } ) if (!res.ok) throw new Error('Failed to deactivate') queryClient.invalidateQueries({ queryKey: collectedClipKeys.list(ccGenVoice) }) } catch (err) { setError(err instanceof Error ? err.message : 'Failed to deactivate clip') } } const handleReactivateClip = async (clipId: string) => { try { const res = await fetch( `/api/admin/audio/custom-clips/${encodeURIComponent(ccGenVoice)}/${encodeURIComponent(clipId)}`, { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'reactivate' }), } ) if (!res.ok) throw new Error('Failed to reactivate') queryClient.invalidateQueries({ queryKey: collectedClipKeys.list(ccGenVoice) }) } catch (err) { setError(err instanceof Error ? err.message : 'Failed to reactivate clip') } } const handleDeleteCustomClip = async (clipId: string) => { if (!confirm(`Delete this recording for "${clipId}"?`)) return try { const res = await fetch( `/api/admin/audio/custom-clips/${encodeURIComponent(ccGenVoice)}/${encodeURIComponent(clipId)}`, { method: 'DELETE' } ) if (!res.ok) throw new Error('Failed to delete') queryClient.invalidateQueries({ queryKey: collectedClipKeys.list(ccGenVoice) }) fetchStatus() } catch (err) { setError(err instanceof Error ? err.message : 'Failed to delete clip') } } const handleRemoveVoice = async (voice: string) => { if (!confirm(`Remove all clips for voice "${voice}"?`)) return try { const res = await fetch(`/api/admin/audio/voice/${encodeURIComponent(voice)}`, { method: 'DELETE', }) if (!res.ok) { const errData = await res.json() throw new Error(errData.error || 'Failed to remove') } await fetchStatus() } catch (err) { setError(err instanceof Error ? err.message : 'Failed to remove voice') } } // Collected clip generation handler (uses mutation) const handleCcGenerate = (clipIds: string[]) => { ccGenerateMutation.mutate( { voice: ccGenVoice, clipIds }, { onSuccess: ({ taskId }) => setCcGenTaskId(taskId), onError: (err) => setError(err instanceof Error ? err.message : 'Generation failed'), } ) } const handleCcPlayClip = (clipId: string) => { if (ccAudioRef.current) { ccAudioRef.current.pause() } const audio = new Audio(`/api/audio/clips/${ccGenVoice}/${clipId}`) ccAudioRef.current = audio setCcPlayingClipId(clipId) audio.play() audio.onended = () => setCcPlayingClipId(null) audio.onerror = () => setCcPlayingClipId(null) } // Invalidate collected clips query and refresh status when cc task completes useEffect(() => { if (ccTaskState?.status === 'completed' || ccTaskState?.status === 'failed') { queryClient.invalidateQueries({ queryKey: collectedClipKeys.list(ccGenVoice), }) fetchStatus() } }, [ccTaskState?.status, ccGenVoice, queryClient, fetchStatus]) return ( <> <AppNavBar navSlot={null} /> <div className={css({ paddingTop: '56px' })}> <AdminNav /> </div> <div data-component="AdminAudioPage" className={css({ backgroundColor: '#0d1117', minHeight: '100vh', color: '#c9d1d9', padding: '24px', })} > <div className={css({ maxWidth: '1200px', margin: '0 auto' })}> <div className={css({ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '24px', })} > <h1 className={css({ fontSize: '24px', fontWeight: '600', color: '#f0f6fc', })} > Audio Management </h1> <button data-action="nuke-all-clips" disabled={isCcGenerating} onClick={async () => { if ( !confirm( 'Delete ALL generated mp3s AND collected clip records? This cannot be undone.' ) ) return if ( !confirm('Are you really sure? This removes every mp3 AND clears the database.') ) return try { const res = await fetch('/api/admin/audio/voices', { method: 'DELETE' }) if (!res.ok) { const data = await res.json() throw new Error(data.error || 'Failed to remove') } const data = await res.json() setError(null) await fetchStatus() queryClient.invalidateQueries({ queryKey: collectedClipKeys.list(ccGenVoice) }) alert( `Removed ${data.removedDirs} voice director${data.removedDirs === 1 ? 'y' : 'ies'} and cleared all collected clips from database.` ) } catch (err) { setError(err instanceof Error ? err.message : 'Failed to nuke clips') } }} className={css({ fontSize: '12px', backgroundColor: 'transparent', color: '#f85149', border: '1px solid #f85149', borderRadius: '6px', padding: '4px 12px', cursor: 'pointer', fontWeight: '600', flexShrink: 0, '&:hover': { backgroundColor: '#f8514922' }, '&:disabled': { opacity: 0.5, cursor: 'not-allowed' }, })} > Nuke All Clips + DB </button> </div> {error && ( <div data-element="error-banner" className={css({ backgroundColor: '#3d1f28', border: '1px solid #f85149', borderRadius: '6px', padding: '12px 16px', marginBottom: '16px', color: '#f85149', })} > {error} <button onClick={() => setError(null)} className={css({ marginLeft: '12px', color: '#8b949e', cursor: 'pointer', background: 'none', border: 'none', })} > dismiss </button> </div> )} {loading && <p className={css({ color: '#8b949e' })}>Loading...</p>} {status && ( <> {/* Voice Chain Configuration — collapsible */} <section data-element="voice-chain-config" className={css({ backgroundColor: '#161b22', border: '1px solid #30363d', borderRadius: '6px', marginBottom: '8px', })} > <button data-action="toggle-voice-chain" onClick={() => setShowVoiceChain((p) => !p)} className={css({ width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '12px 16px', background: 'none', border: 'none', cursor: 'pointer', color: '#f0f6fc', })} > <span className={css({ fontSize: '15px', fontWeight: '600' })}> Voice Chain (Fallback Order) </span> <span className={css({ display: 'flex', alignItems: 'center', gap: '8px' })}> <span className={css({ color: '#8b949e', fontSize: '12px' })}> {voiceChain .map((s) => s.type === 'pregenerated' ? s.name : s.type === 'custom' ? `${s.name} (mic)` : s.type === 'generate' ? 'generate' : s.type === 'subtitle' ? 'subtitle' : 'browser' ) .join(' \u2192 ')} </span> <span className={css({ color: '#8b949e', fontSize: '12px' })}> {showVoiceChain ? '\u25B2' : '\u25BC'} </span> </span> </button> {showVoiceChain && ( <div className={css({ padding: '0 16px 16px' })}> <p className={css({ color: '#8b949e', fontSize: '13px', marginBottom: '12px' })} > Audio plays through each voice in order. If a clip is missing from the first voice, the next voice is tried. </p> {voiceChain.length === 0 && ( <p className={css({ color: '#8b949e', fontSize: '13px', fontStyle: 'italic' })} > No voice chain configured. Add a voice below. </p> )} <div className={css({ display: 'flex', flexDirection: 'column', gap: '6px', marginBottom: '16px', })} > {voiceChain.map((source, idx) => ( <div key={idx} data-element="voice-chain-entry" className={css({ display: 'flex', alignItems: 'center', gap: '8px', backgroundColor: '#0d1117', border: '1px solid #30363d', borderRadius: '6px', padding: '8px 12px', })} > <span className={css({ color: '#8b949e', fontSize: '12px', width: '20px' })} > {idx + 1}. </span> <span className={css({ color: '#f0f6fc', fontWeight: '600', flex: 1 })}> {source.type === 'pregenerated' ? source.name : source.type === 'custom' ? source.name : source.type === 'generate' ? 'Auto-generate' : source.type === 'subtitle' ? 'Subtitles' : 'Browser TTS'} </span> <span className={css({ display: 'flex', alignItems: 'center', flexShrink: 0, fontSize: '11px', })} > {source.type === 'pregenerated' ? ( (() => { const meta = getVoiceMeta(source.name) const providerLabel = meta ? `${meta.provider.name} ${meta.model.name}` : 'unknown' const formatLabel = meta?.model.format ?? 'unknown' return ( <> <span className={css({ padding: '2px 10px 2px 8px', backgroundColor: '#1f6feb33', color: '#58a6ff', clipPath: 'polygon(0 0, calc(100% - 6px) 0, 100% 50%, calc(100% - 6px) 100%, 0 100%)', borderRadius: '8px 0 0 8px', })} > {providerLabel} </span> <span className={css({ padding: '2px 8px 2px 10px', backgroundColor: '#8b949e1a', color: '#8b949e', clipPath: 'polygon(6px 0, 100% 0, 100% 100%, 6px 100%, 0 50%)', borderRadius: '0 8px 8px 0', })} > {formatLabel} on disk </span> </> ) })() ) : source.type === 'custom' ? ( <span className={css({ padding: '2px 8px', borderRadius: '8px', backgroundColor: '#a371f733', color: '#a371f7', })} > Custom (microphone) </span> ) : source.type === 'generate' ? ( <span className={css({ padding: '2px 8px', borderRadius: '8px', backgroundColor: '#d2992233', color: '#d29922', })} > On-demand via API </span> ) : source.type === 'subtitle' ? ( <span className={css({ padding: '2px 8px', borderRadius: '8px', backgroundColor: '#e3b34133', color: '#e3b341', })} > On-screen text </span> ) : ( <span className={css({ padding: '2px 8px', borderRadius: '8px', backgroundColor: '#23863633', color: '#3fb950', })} > Web Speech API </span> )} </span> {source.type === 'pregenerated' && ( <button data-action={`report-in-${source.name}`} onClick={() => handleReportIn(source.name)} disabled={reportingVoice === source.name} className={css({ background: 'none', border: '1px solid #30363d', borderRadius: '6px', color: reportingVoice === source.name ? '#58a6ff' : '#8b949e', cursor: reportingVoice === source.name ? 'wait' : 'pointer', fontSize: '11px', padding: '2px 8px', whiteSpace: 'nowrap', '&:hover': { borderColor: '#58a6ff', color: '#58a6ff' }, '&:disabled': { opacity: 0.7 }, })} title={`Hear ${source.name} introduce itself`} > {reportingVoice === source.name ? '\u25B6 ...' : '\u{1F399} Report in'} </button> )} <button data-action="chain-move-up" onClick={() => moveVoiceChainEntry(idx, -1)} disabled={idx === 0} className={css({ background: 'none', border: 'none', color: idx === 0 ? '#30363d' : '#8b949e', cursor: idx === 0 ? 'not-allowed' : 'pointer', fontSize: '14px', padding: '2px 4px', })} title="Move up" > ▲ </button> <button data-action="chain-move-down" onClick={() => moveVoiceChainEntry(idx, 1)} disabled={idx === voiceChain.length - 1} className={css({ background: 'none', border: 'none', color: idx === voiceChain.length - 1 ? '#30363d' : '#8b949e', cursor: idx === voiceChain.length - 1 ? 'not-allowed' : 'pointer', fontSize: '14px', padding: '2px 4px', })} title="Move down" > ▼ </button> <button data-action="chain-remove" onClick={() => removeVoiceChainEntry(idx)} className={css({ background: 'none', border: 'none', color: '#f85149', cursor: 'pointer', fontSize: '14px', padding: '2px 4px', })} title="Remove" > ✕ </button> </div> ))} </div> <div className={css({ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '12px', })} > <DropdownMenu.Root> <DropdownMenu.Trigger asChild> <button data-element="add-chain-voice" type="button" className={css({ backgroundColor: '#0d1117', color: '#f0f6fc', border: '1px solid #30363d', borderRadius: '6px', padding: '6px 12px', fontSize: '13px', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: '6px', '&:hover': { borderColor: '#8b949e' }, })} > Add voice... <span className={css({ color: '#8b949e', fontSize: '10px' })}> ▾ </span> </button> </DropdownMenu.Trigger> <DropdownMenu.Portal> <DropdownMenu.Content data-element="voice-dropdown-content" sideOffset={5} className={css({ backgroundColor: '#161b22', border: '1px solid #30363d', borderRadius: '8px', padding: '4px', minWidth: '280px', maxHeight: '400px', overflowY: 'auto', zIndex: Z_INDEX.DROPDOWN, boxShadow: '0 8px 24px rgba(0,0,0,0.4)', })} > {(() => { const hasSubtitle = voiceChain.some((vc) => vc.type === 'subtitle') const hasBrowser = voiceChain.some((vc) => vc.type === 'browser-tts') const hasGenerate = voiceChain.some((vc) => vc.type === 'generate') const chainPregenNames = new Set( voiceChain .filter((vc) => vc.type === 'pregenerated') .map((vc) => (vc as { type: 'pregenerated'; name: string }).name) ) const total = status?.totalCollectedClips ?? 0 // Build grouped provider sections, filtering out voices already in chain const providerGroups = VOICE_PROVIDERS.map((provider) => { const modelGroups = provider.models .map((model) => { const available = model.voices.filter( (v) => !chainPregenNames.has(v) ) const sorted = [...available].sort((a, b) => { const genA = status?.voiceClipCounts?.[a] ?? 0 const genB = status?.voiceClipCounts?.[b] ?? 0 const pctA = total > 0 ? genA / total : 0 const pctB = total > 0 ? genB / total : 0 return pctB - pctA }) return { model, voices: sorted } }) .filter((g) => g.voices.length > 0) return { provider, modelGroups } }).filter((g) => g.modelGroups.length > 0) const hasAnyAvailable = providerGroups.length > 0 || !hasBrowser || !hasGenerate if (!hasAnyAvailable) { return ( <DropdownMenu.Label className={css({ padding: '8px 12px', color: '#8b949e', fontSize: '13px', fontStyle: 'italic', })} > All voices added </DropdownMenu.Label> ) } const multipleProviders = VOICE_PROVIDERS.length > 1 const sectionSep = ( <DropdownMenu.Separator className={css({ height: '1px', backgroundColor: '#30363d', margin: '4px 0', })} /> ) const voiceItem = (v: string, format: string, isEmpty: boolean) => { const generated = status?.voiceClipCounts?.[v] ?? 0 const pct = total > 0 ? Math.round((generated / total) * 100) : 0 const barColor = pct >= 100 ? '#3fb950' : pct > 0 ? '#d29922' : 'transparent' return ( <DropdownMenu.Item key={v} data-action={`add-voice-${v}`} onSelect={() => addToVoiceChain({ type: 'pregenerated', name: v }) } style={{ opacity: isEmpty ? 0.45 : 1 }} className={css({ padding: '8px 12px', borderRadius: '6px', cursor: 'pointer', outline: 'none', '&:hover': { backgroundColor: '#21262d' }, '&:focus': { backgroundColor: '#21262d' }, })} > <div className={css({ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '4px', })} > <span className={css({ display: 'flex', alignItems: 'center', gap: '6px', })} > <span className={css({ color: isEmpty ? '#8b949e' : '#f0f6fc', fontWeight: '600', fontSize: '13px', })} > {v} </span> <span className={css({ fontSize: '10px', padding: '0px 5px', borderRadius: '4px', backgroundColor: '#8b949e15', color: '#8b949e', fontFamily: 'monospace', })} > {format} </span> </span> <span className={css({ color: '#8b949e', fontFamily: 'monospace', fontSize: '12px', })} > {generated === 0 ? 'none' : `${generated} / ${total}`} </span> </div> <div className={css({ height: '4px', backgroundColor: '#30363d', borderRadius: '2px', overflow: 'hidden', })} > {pct > 0 && ( <div style={{ width: `${Math.min(pct, 100)}%`, backgroundColor: barColor, }} className={css({ height: '100%', borderRadius: '2px', transition: 'width 0.3s', })} /> )} </div> </DropdownMenu.Item> ) } const sections: React.ReactNode[] = [] // Auto-generate — on-demand via OpenAI API if (!hasGenerate) { sections.push( <DropdownMenu.Item key="generate" data-action="add-voice-generate" onSelect={() => addToVoiceChain({ type: 'generate' })} className={css({ padding: '8px 12px', borderRadius: '6px', cursor: 'pointer', outline: 'none', '&:hover': { backgroundColor: '#21262d' }, '&:focus': { backgroundColor: '#21262d' }, })} > <div className={css({ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '4px', })} > <span className={css({ color: '#f0f6fc', fontWeight: '600', fontSize: '13px', })} > Auto-generate </span> <span className={css({ fontSize: '11px', padding: '1px 6px', borderRadius: '8px', backgroundColor: '#d2992233', color: '#d29922', })} > on-demand via API </span> </div> <div className={css({ color: '#8b949e', fontSize: '12px' })}> Generates missing clips via OpenAI when needed </div> </DropdownMenu.Item> ) } // Browser TTS — always first (always healthy) if (!hasBrowser) { sections.push( <DropdownMenu.Item key="browser-tts" data-action="add-voice-browser-tts" onSelect={() => addToVoiceChain({ type: 'browser-tts' })} className={css({ padding: '8px 12px', borderRadius: '6px', cursor: 'pointer', outline: 'none', '&:hover': { backgroundColor: '#21262d' }, '&:focus': { backgroundColor: '#21262d' }, })} > <div className={css({ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '4px', })} > <span className={css({ color: '#f0f6fc', fontWeight: '600', fontSize: '13px', })} > Browser TTS </span> <span className={css({ fontSize: '11px', padding: '1px 6px', borderRadius: '8px', backgroundColor: '#23863633', color: '#3fb950', })} > always available </span> </div> <div className={css({ height: '4px', backgroundColor: '#30363d', borderRadius: '2px', overflow: 'hidden', })} > <div style={{ width: '100%' }} className={css({ height: '100%', borderRadius: '2px', backgroundColor: '#3fb950', })} /> </div> </DropdownMenu.Item> ) } // Subtitles — show text on screen as last-resort fallback if (!hasSubtitle) { sections.push( <DropdownMenu.Item key="subtitle" data-action="add-voice-subtitle" onSelect={() => addToVoiceChain({ type: 'subtitle' })} className={css({ padding: '8px 12px', borderRadius: '6px', cursor: 'pointer', outline: 'none', '&:hover': { backgroundColor: '#21262d' }, '&:focus': { backgroundColor: '#21262d' }, })} > <div className={css({ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '4px', })} > <span className={css({ color: '#f0f6fc', fontWeight: '600', fontSize: '13px', })} > Subtitles </span> <span className={css({ fontSize: '11px', padding: '1px 6px', borderRadius: '8px', backgroundColor: '#e3b34133', color: '#e3b341', })} > always available </span> </div> <div className={css({ color: '#8b949e', fontSize: '12px' })}> Shows text on screen instead of speaking </div> </DropdownMenu.Item> ) } // Provider groups for (const { provider, modelGroups } of providerGroups) { const multipleModels = modelGroups.length > 1 if (sections.length > 0) sections.push( <React.Fragment key={`sep-${provider.id}`}> {sectionSep} </React.Fragment> ) if (multipleProviders || multipleModels) { // Show provider group header when multiple providers or models for (const { model, voices } of modelGroups) { sections.push( <React.Fragment key={`group-${provider.id}-${model.id}`}> <DropdownMenu.Label className={css({ padding: '6px 12px 2px', color: '#8b949e', fontSize: '11px', fontWeight: '500', })} > {provider.name} {model.name} </DropdownMenu.Label> {voices.map((v) => voiceItem( v, model.format, (status?.voiceClipCounts?.[v] ?? 0) === 0 && total === 0 ) )} </React.Fragment> ) } } else { // Single provider, single model: show inline header const { model, voices } = modelGroups[0] sections.push( <React.Fragment key={`group-${provider.id}-${model.id}`}> <DropdownMenu.Label className={css({ padding: '6px 12px 2px', color: '#8b949e', fontSize: '11px', fontWeight: '500', })} > Voices by {provider.name} · {model.name} </DropdownMenu.Label> {voices.map((v) => voiceItem( v, model.format, (status?.voiceClipCounts?.[v] ?? 0) === 0 && total === 0 ) )} </React.Fragment> ) } } return <>{sections}</> })()} </DropdownMenu.Content> </DropdownMenu.Portal> </DropdownMenu.Root> {/* New Custom Voice button/input */} {newCustomVoiceName === null ? ( <button data-action="new-custom-voice" onClick={() => setNewCustomVoiceName(session?.user?.name ?? 'custom')} className={css({ backgroundColor: '#0d1117', color: '#a371f7', border: '1px solid #a371f744', borderRadius: '6px', padding: '6px 12px', fontSize: '13px', cursor: 'pointer', '&:hover': { borderColor: '#a371f7' }, })} > + Custom Voice </button> ) : ( <div data-element="new-custom-voice-input" className={css({ display: 'flex', alignItems: 'center', gap: '6px', })} > <input type="text" value={newCustomVoiceName} onChange={(e) => setNewCustomVoiceName(e.target.value)} onKeyDown={(e) => { if (e.key === 'Enter') { const name = newCustomVoiceName.trim() if (!name) return if ( ALL_VOICES.includes(name) || voiceChain.some( (s) => (s.type === 'pregenerated' || s.type === 'custom') && s.name === name ) ) { setError( `Voice name "${name}" already exists in chain or is a built-in voice` ) return } setVoiceChain((prev) => [ { type: 'custom', name } as VoiceSourceData, ...prev, ]) setVoiceChainDirty(true) setNewCustomVoiceName(null) } else if (e.key === 'Escape') { setNewCustomVoiceName(null) } }} placeholder="Voice name" autoFocus className={css({ backgroundColor: '#0d1117', color: '#f0f6fc', border: '1px solid #a371f7', borderRadius: '6px', padding: '5px 10px', fontSize: '13px', width: '140px', })} /> <button onClick={() => { const name = newCustomVoiceName.trim() if (!name) return if ( ALL_VOICES.includes(name) || voiceChain.some( (s) => (s.type === 'pregenerated' || s.type === 'custom') && s.name === name ) ) { setError( `Voice name "${name}" already exists in chain or is a built-in voice` ) return } setVoiceChain((prev) => [ { type: 'custom', name } as VoiceSourceData, ...prev, ]) setVoiceChainDirty(true) setNewCustomVoiceName(null) }} className={css({ backgroundColor: '#238636', color: '#fff', border: 'none', borderRadius: '6px', padding: '5px 10px', fontSize: '12px', cursor: 'pointer', '&:hover': { backgroundColor: '#2ea043' }, })} > Add </button> <button onClick={() => setNewCustomVoiceName(null)} className={css({ background: 'none', border: 'none', color: '#8b949e', cursor: 'pointer', fontSize: '14px', })} > ✕ </button> </div> )} </div> {voiceChainDirty && ( <button data-action="save-voice-chain" onClick={handleSaveVoiceChain} className={css({ backgroundColor: '#238636', color: '#fff', border: 'none', borderRadius: '6px', padding: '8px 20px', fontSize: '14px', fontWeight: '600', cursor: 'pointer', '&:hover': { backgroundColor: '#2ea043' }, })} > Save Voice Chain </button> )} </div> )} </section> {/* TTS Test Panel — collapsible */} <section data-element="tts-test-panel" className={css({ backgroundColor: '#161b22', border: '1px solid #30363d', borderRadius: '6px', marginBottom: '8px', })} > <button data-action="toggle-tts-test" onClick={() => setShowTtsTest((p) => !p)} className={css({ width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '12px 16px', background: 'none', border: 'none', cursor: 'pointer', color: '#f0f6fc', })} > <span className={css({ fontSize: '15px', fontWeight: '600' })}> TTS Test Panel </span> <span className={css({ color: '#8b949e', fontSize: '12px' })}> {showTtsTest ? '\u25B2' : '\u25BC'} </span> </button> {showTtsTest && <TtsTestPanel voiceChain={voiceChain} />} </section> {/* Clip Management — collapsible */} <section data-element="clip-management" className={css({ backgroundColor: '#161b22', border: '1px solid #30363d', borderRadius: '6px', marginBottom: '8px', })} > <button data-action="toggle-clip-management" onClick={() => setShowClipManagement((p) => !p)} className={css({ width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '12px 16px', background: 'none', border: 'none', cursor: 'pointer', color: '#f0f6fc', })} > <span className={css({ fontSize: '15px', fontWeight: '600' })}> Clip Management </span> <span className={css({ display: 'flex', alignItems: 'center', gap: '8px' })}> <span className={css({ color: '#8b949e', fontSize: '12px' })}> {(() => { const generated = status?.voiceClipCounts?.[ccGenVoice] ?? 0 const total = status?.totalCollectedClips ?? 0 if (total === 0) return '' return `${total} clips \u00b7 viewing ${ccGenVoice} (${generated}/${total})` })()} </span> <span className={css({ color: '#8b949e', fontSize: '12px' })}> {showClipManagement ? '\u25B2' : '\u25BC'} </span> </span> </button> {showClipManagement && ( <div className={css({ padding: '0 16px 16px' })}> <p className={css({ color: '#8b949e', fontSize: '13px', marginBottom: '12px' })} > Clips collected from app usage. Generate mp3s for a voice, then add the voice to the chain above. </p> {/* Voice selector + controls */} <div data-element="cc-controls" className={css({ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '12px', flexWrap: 'wrap', })} > <label className={css({ color: '#8b949e', fontSize: '13px' })}>Voice:</label> <select data-element="cc-voice-select" value={ccGenVoice} onChange={(e) => { setCcGenVoice(e.target.value) setRecordingClipId(null) }} className={css({ backgroundColor: '#0d1117', color: '#f0f6fc', border: '1px solid #30363d', borderRadius: '6px', padding: '4px 10px', fontSize: '13px', })} > {ALL_VOICES.map((v) => ( <option key={v} value={v}> {v} </option> ))} {(() => { const customVoices = voiceChain .filter((s) => s.type === 'custom') .map((s) => (s as { type: 'custom'; name: string }).name) return customVoices.length > 0 ? ( <optgroup label="Custom"> {customVoices.map((v) => ( <option key={v} value={v}> {v} </option> ))} </optgroup> ) : null })()} </select> {!isCustomVoice && (() => { const missingCount = collectedClips.filter( (c) => !ccGeneratedFor[c.id] ).length return missingCount > 0 ? ( <button data-action="cc-generate-all-missing" onClick={() => { const missingIds = collectedClips .filter((c) => !ccGeneratedFor[c.id]) .map((c) => c.id) handleCcGenerate(missingIds) }} disabled={isCcGenerating} className={css({ fontSize: '12px', backgroundColor: '#238636', color: '#fff', border: 'none', borderRadius: '6px', padding: '4px 12px', cursor: 'pointer', fontWeight: '600', '&:hover': { backgroundColor: '#2ea043' }, '&:disabled': { opacity: 0.5, cursor: 'not-allowed' }, })} > Generate {missingCount} Missing </button> ) : null })()} <button data-action="refresh-collected" onClick={() => queryClient.invalidateQueries({ queryKey: collectedClipKeys.list(ccGenVoice), }) } disabled={collectedClipsLoading} className={css({ fontSize: '12px', background: 'none', border: '1px solid #30363d', color: '#8b949e', borderRadius: '6px', padding: '4px 10px', cursor: 'pointer', '&:hover': { borderColor: '#8b949e' }, '&:disabled': { opacity: 0.5, cursor: 'not-allowed' }, })} > Refresh </button> {/* Remove clips — only when voice has clips on disk and is NOT in voice chain */} {(() => { const hasClips = !!status?.voices?.[ccGenVoice] const inChain = voiceChain.some( (s) => s.type === 'pregenerated' && s.name === ccGenVoice ) return hasClips && !inChain && !isCcGenerating ? ( <button data-action="remove-voice-clips" onClick={() => handleRemoveVoice(ccGenVoice)} className={css({ fontSize: '12px', background: 'none', border: 'none', color: '#f85149', cursor: 'pointer', padding: '4px 8px', '&:hover': { textDecoration: 'underline' }, })} > Remove clips for “{ccGenVoice}” </button> ) : null })()} </div> {/* Mic selector bar — shown when custom voice selected */} {isCustomVoice && ( <div data-element="mic-selector-bar" className={css({ display: 'flex', alignItems: 'center', gap: '10px', backgroundColor: '#0d1117', border: '1px solid #30363d', borderRadius: '6px', padding: '10px 14px', marginBottom: '12px', })} > <MicLevelMeter stream={micStream} /> <label className={css({ color: '#8b949e', fontSize: '13px', flexShrink: 0 })} > Microphone: </label> <select data-element="mic-device-select" value={selectedDeviceId} onChange={(e) => setSelectedDeviceId(e.target.value)} className={css({ flex: 1, backgroundColor: '#161b22', color: '#f0f6fc', border: '1px solid #30363d', borderRadius: '6px', padding: '4px 10px', fontSize: '13px', })} > {audioDevices.length === 0 && ( <option value="">No microphones found</option> )} {audioDevices.map((d) => ( <option key={d.deviceId} value={d.deviceId}> {d.label || `Microphone ${d.deviceId.slice(0, 8)}`} </option> ))} </select> </div> )} {/* Voice Health Banner */} {(() => { const meta = getVoiceMeta(ccGenVoice) const generated = status?.voiceClipCounts?.[ccGenVoice] ?? 0 const total = status?.totalCollectedClips ?? 0 const pct = total > 0 ? Math.round((generated / total) * 100) : 0 const barColor = pct >= 100 ? '#3fb950' : pct > 0 ? '#d29922' : '#484f58' const chainIndex = voiceChain.findIndex( (s) => s.type === 'pregenerated' && s.name === ccGenVoice ) const positionLabel = chainIndex >= 0 ? `Position #${chainIndex + 1} in voice chain` : 'Not in voice chain' return ( <div data-element="voice-health-banner" className={css({ backgroundColor: '#0d1117', border: '1px solid #30363d', borderRadius: '6px', padding: '12px', marginBottom: '12px', })} > <div className={css({ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '6px', })} > <span className={css({ color: '#f0f6fc', fontSize: '13px', fontWeight: '600', })} > {ccGenVoice} {meta && ( <span className={css({ color: '#8b949e', fontWeight: '400' })}> {' '} · {meta.provider.name} {meta.model.name} ·{' '} {meta.model.format} </span> )} </span> <span className={css({ fontSize: '11px', color: chainIndex >= 0 ? '#58a6ff' : '#8b949e', fontStyle: chainIndex >= 0 ? 'normal' : 'italic', })} > {positionLabel} </span> </div> <div className={css({ display: 'flex', alignItems: 'center', gap: '8px' })} > <div className={css({ flex: 1, height: '6px', backgroundColor: '#30363d', borderRadius: '3px', overflow: 'hidden', })} > <div style={{ width: `${Math.min(pct, 100)}%` }} className={css({ height: '100%', borderRadius: '3px', backgroundColor: barColor, transition: 'width 0.3s', })} /> </div> <span className={css({ color: '#8b949e', fontSize: '12px', fontFamily: 'monospace', flexShrink: 0, })} > {generated} / {total} ({pct}%) </span> </div> </div> ) })()} {/* CC generation progress */} {ccTaskState && ( <div data-element="cc-gen-progress" className={css({ backgroundColor: '#0d1117', border: '1px solid #30363d', borderRadius: '6px', padding: '12px', marginBottom: '12px', })} > <div className={css({ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '8px', })} > <span className={css({ color: '#f0f6fc', fontSize: '13px', fontWeight: '600', })} > Generation {isCcGenerating ? 'in progress...' : ccTaskState.status} </span> {isCcGenerating && ( <button data-action="cancel-cc-gen" onClick={cancelCcTask} className={css({ fontSize: '11px', background: 'none', border: '1px solid #f85149', color: '#f85149', borderRadius: '6px', padding: '2px 8px', cursor: 'pointer', })} > Cancel </button> )} </div> {isCcGenerating && ( <div> <div className={css({ backgroundColor: '#30363d', borderRadius: '4px', height: '6px', overflow: 'hidden', })} > <div className={css({ backgroundColor: '#58a6ff', height: '100%', transition: 'width 0.3s', })} style={{ width: `${ccTaskState.progress}%` }} /> </div> <p className={css({ color: '#8b949e', fontSize: '11px', marginTop: '4px', })} > {ccTaskState.progressMessage || `${ccTaskState.progress}%`} </p> </div> )} {ccTaskState.output && ( <p className={css({ color: '#8b949e', fontSize: '12px' })}> Generated: {ccTaskState.output.generated}, Errors:{' '} {ccTaskState.output.errors}, Total: {ccTaskState.output.total} </p> )} {ccTaskState.error && ( <div data-element="cc-task-error-banner" className={css({ backgroundColor: '#3d1f28', border: '1px solid #f85149', borderRadius: '6px', padding: '10px 14px', marginTop: '8px', color: '#f85149', fontSize: '13px', lineHeight: '1.5', })} > {ccTaskState.error} </div> )} {/* Per-clip event log */} {(() => { const ccClipEvents = (ccTaskState.events ?? []).filter( (e) => e.eventType === 'cc_clip_done' || e.eventType === 'cc_clip_error' ) return ccClipEvents.length > 0 ? ( <div data-element="cc-clip-events" className={css({ maxHeight: '150px', overflowY: 'auto', fontSize: '12px', fontFamily: 'monospace', marginTop: '8px', })} > {ccClipEvents.map((e, i) => { const payload = e.payload as { clipId?: string error?: string } return ( <div key={i} className={css({ color: e.eventType === 'cc_clip_error' ? '#f85149' : '#3fb950', padding: '1px 0', })} > {e.eventType === 'cc_clip_done' ? '\u2713' : '\u2717'}{' '} {payload.clipId} {payload.error && ` \u2014 ${payload.error}`} </div> ) })} </div> ) : null })()} </div> )} {collectedClipsLoading && ( <p className={css({ color: '#8b949e', fontSize: '13px' })}>Loading...</p> )} {!collectedClipsLoading && collectedClips.length === 0 && ( <p className={css({ color: '#8b949e', fontSize: '13px', fontStyle: 'italic' })} > No clips collected yet. Use the app with audio enabled to populate this list. </p> )} {collectedClips.length > 0 && (() => { const clipsWithoutSay = collectedClips.filter( (c) => !c.say || Object.keys(c.say).length === 0 ) // Group clips by their text content const getClipText = (clip: (typeof collectedClips)[0]) => clip.say ? (Object.values(clip.say)[0] ?? null) : null const groups: { text: string | null clips: typeof collectedClips }[] = [] const groupMap = new Map<string, typeof collectedClips>() for (const clip of collectedClips) { const text = getClipText(clip) const key = text ?? `__no_say__${clip.id}` let group = groupMap.get(key) if (!group) { group = [] groupMap.set(key, group) groups.push({ text, clips: group }) } group.push(clip) } return ( <> {clipsWithoutSay.length > 0 && ( <div data-element="cc-missing-say-warning" className={css({ backgroundColor: '#3b2e00', border: '1px solid #d29922', borderRadius: '6px', padding: '10px 14px', marginBottom: '12px', color: '#d29922', fontSize: '13px', lineHeight: '1.5', })} > <strong> {clipsWithoutSay.length} clip {clipsWithoutSay.length > 1 ? 's' : ''} </strong>{' '} missing{' '} <code className={css({ fontSize: '12px', backgroundColor: '#d2992220', padding: '1px 4px', borderRadius: '3px', })} > say </code>{' '} text. These will use the clip ID as the spoken text, which may not sound natural. Register clips with a{' '} <code className={css({ fontSize: '12px', backgroundColor: '#d2992220', padding: '1px 4px', borderRadius: '3px', })} > say </code>{' '} map in{' '} <code className={css({ fontSize: '12px', backgroundColor: '#d2992220', padding: '1px 4px', borderRadius: '3px', })} > useTTS() </code>{' '} to provide proper text. </div> )} <table data-element="cc-grouped-table" className={css({ width: '100%', borderCollapse: 'collapse', fontSize: '13px', })} > <thead> <tr> {['Status', 'Tone', 'Clip ID', 'Plays', 'Play', 'Actions'].map( (header, idx) => ( <th key={header} className={css({ textAlign: idx === 1 || idx === 2 ? 'left' : 'center', padding: '6px 8px', color: '#8b949e', borderBottom: '1px solid #30363d', fontWeight: '500', backgroundColor: '#161b22', width: idx === 0 || idx === 4 ? '50px' : idx === 5 ? '90px' : undefined, })} > {header} </th> ) )} </tr> </thead> <tbody> {groups.map((group, groupIdx) => { const groupGenerated = group.clips.filter( (c) => !!ccGeneratedFor[c.id] ).length const allGenerated = groupGenerated === group.clips.length return ( <React.Fragment key={groupIdx}> {/* Group header row */} <tr data-element="cc-group-header"> <td colSpan={6} className={css({ padding: '10px 8px 6px', borderBottom: '1px solid #30363d', backgroundColor: '#0d1117', })} > <div className={css({ display: 'flex', alignItems: 'center', gap: '8px', })} > {group.text ? ( <span className={css({ color: '#f0f6fc', fontWeight: '600', fontSize: '13px', })} > “{group.text}” </span> ) : ( <span className={css({ display: 'flex', alignItems: 'center', gap: '4px', })} > <span className={css({ color: '#d29922', fontSize: '13px', })} > ⚠ </span> <span className={css({ color: '#d29922', fontStyle: 'italic', fontSize: '13px', })} > "{group.clips[0].id}" (no say text) </span> </span> )} <span className={css({ color: '#8b949e', fontSize: '11px', })} > {group.clips.length} tone {group.clips.length !== 1 ? 's' : ''} </span> <span className={css({ display: 'inline-block', width: '6px', height: '6px', borderRadius: '50%', backgroundColor: allGenerated ? '#3fb950' : groupGenerated > 0 ? '#d29922' : '#484f58', flexShrink: 0, })} title={`${groupGenerated}/${group.clips.length} generated`} /> </div> </td> </tr> {/* Individual tone rows */} {group.clips.map((clip) => { const isGenerated = !!ccGeneratedFor[clip.id] const isDeactivated = !!ccDeactivatedFor[clip.id] return ( <React.Fragment key={clip.id}> <tr data-element="cc-clip-row"> <td className={css({ padding: '6px 8px', borderBottom: '1px solid #21262d', textAlign: 'center', })} > <span title={ isDeactivated ? 'Deactivated' : isGenerated ? `Generated for ${ccGenVoice}` : 'Not generated' } className={css({ display: 'inline-block', width: '8px', height: '8px', borderRadius: '50%', backgroundColor: isDeactivated ? '#d29922' : isGenerated ? '#3fb950' : '#484f58', })} /> </td> <td className={css({ padding: '6px 8px', borderBottom: '1px solid #21262d', fontSize: '12px', color: '#c9d1d9', maxWidth: '200px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', })} title={clip.tone} > {clip.tone} </td> <td className={css({ padding: '6px 8px', borderBottom: '1px solid #21262d', color: '#8b949e', fontFamily: 'monospace', fontSize: '11px', })} > {clip.id} {isHashClipId(clip.id) && ( <span data-element="hash-badge" title="Content-addressed clip ID (auto-generated from text + tone)" className={css({ marginLeft: '6px', fontSize: '10px', padding: '1px 5px', borderRadius: '8px', backgroundColor: '#8b949e22', color: '#8b949e', })} > hash </span> )} </td> <td className={css({ padding: '6px 8px', borderBottom: '1px solid #21262d', textAlign: 'center', fontFamily: 'monospace', color: clip.playCount > 0 ? '#3fb950' : '#8b949e', })} > {clip.playCount} </td> <td className={css({ padding: '6px 8px', borderBottom: '1px solid #21262d', textAlign: 'center', })} > <button data-action="play-cc-clip" onClick={() => handleCcPlayClip(clip.id)} disabled={!isGenerated} className={css({ background: 'none', border: 'none', color: ccPlayingClipId === clip.id ? '#58a6ff' : '#c9d1d9', cursor: isGenerated ? 'pointer' : 'not-allowed', fontSize: '16px', opacity: isGenerated ? 1 : 0.3, })} title={ isGenerated ? 'Play clip' : 'Not generated yet' } > {ccPlayingClipId === clip.id ? '\u23F8' : '\u25B6'} </button> </td> <td className={css({ padding: '6px 8px', borderBottom: '1px solid #21262d', textAlign: 'center', })} > {isCustomVoice ? ( <div className={css({ display: 'flex', gap: '4px', justifyContent: 'center', flexWrap: 'wrap', })} > {!isGenerated && !isDeactivated && ( <button data-action="record-clip" onClick={() => setRecordingClipId( recordingClipId === clip.id ? null : clip.id ) } className={css({ fontSize: '11px', backgroundColor: '#238636', color: '#fff', border: 'none', borderRadius: '6px', padding: '2px 8px', cursor: 'pointer', '&:hover': { backgroundColor: '#2ea043', }, })} > Record </button> )} {isGenerated && !isDeactivated && ( <> <button data-action="re-record-clip" onClick={() => setRecordingClipId( recordingClipId === clip.id ? null : clip.id ) } className={css({ fontSize: '11px', backgroundColor: 'transparent', color: '#d29922', border: '1px solid #d29922', borderRadius: '6px', padding: '2px 6px', cursor: 'pointer', })} > Re-record </button> <button data-action="deactivate-clip" onClick={() => handleDeactivateClip(clip.id) } className={css({ fontSize: '11px', background: 'none', border: 'none', color: '#8b949e', cursor: 'pointer', '&:hover': { color: '#d29922' }, })} title="Deactivate" > Deact. </button> </> )} {isDeactivated && ( <> <button data-action="re-record-clip" onClick={() => setRecordingClipId( recordingClipId === clip.id ? null : clip.id ) } className={css({ fontSize: '11px', backgroundColor: 'transparent', color: '#d29922', border: '1px solid #d29922', borderRadius: '6px', padding: '2px 6px', cursor: 'pointer', })} > Re-record </button> <button data-action="reactivate-clip" onClick={() => handleReactivateClip(clip.id) } className={css({ fontSize: '11px', background: 'none', border: 'none', color: '#3fb950', cursor: 'pointer', })} > Reactivate </button> </> )} {(isGenerated || isDeactivated) && ( <button data-action="delete-clip" onClick={() => handleDeleteCustomClip(clip.id) } className={css({ fontSize: '11px', background: 'none', border: 'none', color: '#f85149', cursor: 'pointer', '&:hover': { textDecoration: 'underline', }, })} title="Delete recording" > Del </button> )} </div> ) : ( <button data-action="generate-cc-clip" onClick={() => handleCcGenerate([clip.id])} disabled={isCcGenerating} className={css({ fontSize: '11px', backgroundColor: isGenerated ? 'transparent' : '#238636', color: isGenerated ? '#d29922' : '#fff', border: isGenerated ? '1px solid #d29922' : 'none', borderRadius: '6px', padding: '2px 8px', cursor: 'pointer', '&:disabled': { opacity: 0.5, cursor: 'not-allowed', }, })} > {isGenerated ? 'Regen' : 'Generate'} </button> )} </td> </tr> {/* ClipRecorder inline row */} {isCustomVoice && recordingClipId === clip.id && ( <tr data-element="clip-recorder-row"> <td colSpan={6} className={css({ padding: '8px', borderBottom: '1px solid #21262d', })} > <ClipRecorder voice={ccGenVoice} clipId={clip.id} promptText={ clip.say ? (Object.values(clip.say)[0] ?? clip.id) : clip.id } tone={clip.tone} hasExistingClip={isGenerated || isDeactivated} isDeactivated={isDeactivated} stream={micStream} onSaved={() => { setRecordingClipId(null) queryClient.invalidateQueries({ queryKey: collectedClipKeys.list(ccGenVoice), }) fetchStatus() }} onCancel={() => setRecordingClipId(null)} /> </td> </tr> )} </React.Fragment> ) })} </React.Fragment> ) })} </tbody> </table> </> ) })()} </div> )} </section> </> )} </div> </div> </> ) } |