chore(electron): repoint legacy guard tests and retire the unreachable shared UI (#2603)

This commit is contained in:
debpalash committed 2026-11-14 02:38:07 +05:30
1 parent 4670882c72
commit ce37930c0c
208 files changed
+230 -86730

No files matched your search

+5 -7
View File
@@ -89,11 +89,10 @@ reviews:
every user-visible failure has an actionable, non-technical error
message; loading/disabled states during long operations. Every new
user-facing string must be an i18n t('...') key present in ALL 21
locale files of the catalog the code imports from —
electron/src/shared/i18n/locales/*.json (tests/test_locale_parity.py)
or electron/src/renderer/src/i18n/locales/*.json (electron
locale:check) — flag hardcoded UI strings and keys missing from any
locale.
locale files of the catalog —
electron/src/renderer/src/i18n/locales/*.json (tests/test_locale_parity.py
and electron locale:check) — flag hardcoded UI strings and keys missing
from any locale.
- path: "electron/**/*.{ts,tsx}"
instructions: >-
Electron is the only maintained desktop; Tauri is sunset and archived.
@@ -163,8 +162,7 @@ reviews:
mode: warning
instructions: >-
For every new or changed t('...') key in Electron UI code, verify the
key exists in all 21 files of the catalog it uses:
electron/src/shared/i18n/locales/ or
key exists in all 21 files of the catalog:
electron/src/renderer/src/i18n/locales/. List any locale files
missing the key. Also flag hardcoded user-facing strings
that bypass i18n entirely.
+3 -4
View File
@@ -558,10 +558,9 @@ test-only PR. Docker Hub overview edits still publish through the small
Platform-only features go behind an explicit opt-in (Settings toggle, env
var, or CLI flag).
- **i18n — every locale (hard rule):** every user-facing string goes through
`t('...')` and the key must exist in **every** file of the catalog the code
uses: `electron/src/shared/i18n/locales/` (checked by
`tests/test_locale_parity.py`) or `electron/src/renderer/src/i18n/locales/`
(checked by `bun run --cwd electron locale:check`, which also fails on an
`t('...')` and the key must exist in **every** file of the catalog:
`electron/src/renderer/src/i18n/locales/` (checked by
`tests/test_locale_parity.py` and `bun run --cwd electron locale:check`, which also fails on an
`en.json` key no code references; delete it from every locale, or add a
prefix to `ALLOWED_PREFIXES` in `electron/tests/locale-source-keys.mjs` if code
builds it dynamically). Translate; don't copy
+1 -1
View File
@@ -3,7 +3,7 @@
Everything VoiceStudio renders into a bug report or diagnostic dump goes
through ``scrub_text()`` before it can reach a prefilled GitHub Issues URL
(the only outbound path — see CLAUDE.md Capability 2). The scrubber is the
backend twin of ``electron/src/shared/utils/bugReport.js``'s ``scrubText`` and
backend twin of ``electron/src/shared/utils/scrub.js``'s ``scrubText`` and
must stay at least as strict:
- home directories → ``~`` (macOS ``/Users/<name>``, Linux ``/home/<name>``,
+1 -103
View File
@@ -19,15 +19,6 @@
"@electron-toolkit/utils": "^4.0.0",
"@fontsource-variable/inter": "^5.3.0",
"@lobehub/icons-static-svg": "^1.95.0",
"@radix-ui/react-dialog": "^1.1.23",
"@radix-ui/react-dropdown-menu": "^2.1.24",
"@radix-ui/react-progress": "^1.1.16",
"@radix-ui/react-slider": "^1.4.7",
"@radix-ui/react-slot": "^1.3.3",
"@radix-ui/react-tabs": "^1.1.21",
"@radix-ui/react-toggle": "^1.1.18",
"@radix-ui/react-toggle-group": "^1.1.19",
"@radix-ui/react-tooltip": "^1.2.16",
"@scalar/api-reference-react": "^0.9.67",
"@tanstack/react-form": "^1.33.5",
"@tanstack/react-pacer": "^0.23.0",
@@ -39,7 +30,6 @@
"@vidstack/react": "1.15.6",
"@xyflow/react": "^12.12.0",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"cn": "^0.3.0",
"country-flag-icons": "^1.6.20",
"dashjs": "^5.2.1",
@@ -47,7 +37,6 @@
"hls.js": "^1.7.3",
"html-entities": "^2.6.0",
"i18next": "^26.4.2",
"i18next-browser-languagedetector": "^8.2.1",
"lucide-react": "^1.46.0",
"proxy-agent": "6.5.0",
"qrcode": "^1.5.4",
@@ -57,7 +46,6 @@
"react-i18next": "^17.0.14",
"shadcn": "^4.21.0",
"sonner": "^2.0.8",
"tailwind-merge": "^3.6.0",
"tw-animate-css": "^1.4.0",
"wavesurfer.js": "^7.12.12",
"word-extractor": "1.0.4",
@@ -485,78 +473,6 @@
"@quansync/fs": ["@quansync/fs@1.0.0", "", { "dependencies": { "quansync": "^1.0.0" } }, "sha512-4TJ3DFtlf1L5LDMaM6CanJ/0lckGNtJcMjQ1NAV6zDmA0tEHKZtxNKin8EgPaVX1YzljbxckyT2tJrpQKAtngQ=="],
"@radix-ui/number": ["@radix-ui/number@1.1.3", "", {}, "sha512-Road2bidD0uu/1BGDOWNdPI06g0lIRy6IF9GZcIrDK2KGItfor8IQwQa+yM2ERgHM1MmHxaxpTzk0/Jp42lNfA=="],
"@radix-ui/primitive": ["@radix-ui/primitive@1.1.7", "", {}, "sha512-rqWnm76nYT8HoNNqEjpgJ7Pw/DrBj5iBTrmEPo6HTX5+VJyBNOqTdv4g89G63HuR5g0AaENoAcH7Is5fF2kZ8Q=="],
"@radix-ui/react-arrow": ["@radix-ui/react-arrow@1.1.15", "", { "dependencies": { "@radix-ui/react-primitive": "2.1.10" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-v4zggRcjadnI+ClKDuijlQEW4tw3NoaeHc/PwpKnLoLLKNUG4InLegkstooLcRIUWCs+8L22dGURCVuFfOKfnA=="],
"@radix-ui/react-collection": ["@radix-ui/react-collection@1.1.15", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-slot": "1.3.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-9W+B9NPF0NaaPh/1NJd3+KqsnlLqU9H7T2rvww+fp+T/evVXdNAyYcnfRQZFOjkR1ajQp3yORlqnI8soawLvNA=="],
"@radix-ui/react-compose-refs": ["@radix-ui/react-compose-refs@1.1.5", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA=="],
"@radix-ui/react-context": ["@radix-ui/react-context@1.2.2", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-RHCUGwKHDr0hDGg4X7ma4JG4/+12qxw8rkh5QKdDldlCvtja6nUx1Ef/8HVrJze81lEsgLQlqjzjGNHantgnQA=="],
"@radix-ui/react-dialog": ["@radix-ui/react-dialog@1.1.23", "", { "dependencies": { "@radix-ui/primitive": "1.1.7", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-dismissable-layer": "1.1.19", "@radix-ui/react-focus-guards": "1.1.6", "@radix-ui/react-focus-scope": "1.1.16", "@radix-ui/react-id": "1.1.4", "@radix-ui/react-portal": "1.1.17", "@radix-ui/react-presence": "1.1.10", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-slot": "1.3.3", "@radix-ui/react-use-controllable-state": "1.2.6", "@radix-ui/react-use-layout-effect": "1.1.4", "aria-hidden": "^1.2.4", "react-remove-scroll": "^2.7.2" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-Ksw4WeROkO4rC9k/onilX/Ao2Cr1ku1unMNH+XSCcP4jSXYu7HDsg9n4ojMjVb22XpYjAQ9qfrFlVbru1vXDUA=="],
"@radix-ui/react-direction": ["@radix-ui/react-direction@1.1.4", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-5pzg4FGQNpExhnhT2zlrP1wZFaYCd1K0nYWoFAdcYoYK868IEigqMX3B3f8yIoRlAhAeDWciLI6ZdCKHF9P4Vg=="],
"@radix-ui/react-dismissable-layer": ["@radix-ui/react-dismissable-layer@1.1.19", "", { "dependencies": { "@radix-ui/primitive": "1.1.7", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-use-callback-ref": "1.1.4", "@radix-ui/react-use-effect-event": "0.0.5" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-8g4pfOL9HoKKLWGiypT+dphVqjFfmcXO5GBnhsG6zI+lxAx/8feQpr+1LSN8Re3hiZ+XkLNS4O9ztK11/LzQ6w=="],
"@radix-ui/react-dropdown-menu": ["@radix-ui/react-dropdown-menu@2.1.24", "", { "dependencies": { "@radix-ui/primitive": "1.1.7", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-id": "1.1.4", "@radix-ui/react-menu": "2.1.24", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-use-controllable-state": "1.2.6" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-geq8l2rJkxvkXsT9RMgtUE3P8pITFpTsvYpbySi1IH4fZEABD/Gp85myayFgxk0ktljGMJnCbeFkyTusvSvv7g=="],
"@radix-ui/react-focus-guards": ["@radix-ui/react-focus-guards@1.1.6", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-RNOJjfZMTyBM6xYmV3IVGXkPjIhcBAuv48POevAXwrGJhkWZ9p1rFoIS1JFooPuT193AZmRsCPhpoVJxx6OPoQ=="],
"@radix-ui/react-focus-scope": ["@radix-ui/react-focus-scope@1.1.16", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-use-callback-ref": "1.1.4" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-wmRZ2WWLvmt6KHy2rNPOdPUjwq5xOHY02+m+udwJTn0aNIox/rkskAvJTyTLGhPK6KgrUjlJUJpgmx/+wFiFIQ=="],
"@radix-ui/react-id": ["@radix-ui/react-id@1.1.4", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.4" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-TMQp2llA+RYn7JcjnrMnz7wN4pcVttPZnRZo52PLQsoLVKzNlVwUeHmfePgTgRluXFvlD3GD5g5MOVVTJCO0qA=="],
"@radix-ui/react-menu": ["@radix-ui/react-menu@2.1.24", "", { "dependencies": { "@radix-ui/primitive": "1.1.7", "@radix-ui/react-collection": "1.1.15", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-direction": "1.1.4", "@radix-ui/react-dismissable-layer": "1.1.19", "@radix-ui/react-focus-guards": "1.1.6", "@radix-ui/react-focus-scope": "1.1.16", "@radix-ui/react-id": "1.1.4", "@radix-ui/react-popper": "1.3.7", "@radix-ui/react-portal": "1.1.17", "@radix-ui/react-presence": "1.1.10", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-roving-focus": "1.1.19", "@radix-ui/react-slot": "1.3.3", "@radix-ui/react-use-callback-ref": "1.1.4", "aria-hidden": "^1.2.4", "react-remove-scroll": "^2.7.2" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-uW7RVuU6Lp/ZtfeY4b3kL32zccgEWvPv1+cf17ubYzHa9cL8AHokmk36cG/XEiH/smbQvumnieXX9j/e9RqJWA=="],
"@radix-ui/react-popper": ["@radix-ui/react-popper@1.3.7", "", { "dependencies": { "@floating-ui/react-dom": "^2.0.0", "@radix-ui/react-arrow": "1.1.15", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-use-callback-ref": "1.1.4", "@radix-ui/react-use-layout-effect": "1.1.4", "@radix-ui/react-use-rect": "1.1.4", "@radix-ui/react-use-size": "1.1.4", "@radix-ui/rect": "1.1.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-UsJrrd7w4wuKKTdvd/DNERVlwSlUcyXzjhyDwBk+3aPOsCjOY6ZSbxuw8E6lZTjjfP8Cpd0J8VVkrYUWyGYXyg=="],
"@radix-ui/react-portal": ["@radix-ui/react-portal@1.1.17", "", { "dependencies": { "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-use-layout-effect": "1.1.4" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-vKQLcWypUnwZVvfV7UkGahH2g6ySe8M8R+zYBwPrv5byZ9QAW6cQVvNKo7GgmD+p8aYb6D9JBuvy8/WhOno2wQ=="],
"@radix-ui/react-presence": ["@radix-ui/react-presence@1.1.10", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.4" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-3wyzCQ6+ubRA+D4uv9m95JYLXxmOHp05qjrkjeA7uKHHtjpPggQzc6DAb0URl7j67oR0K2foO4ip27TiX037Bw=="],
"@radix-ui/react-primitive": ["@radix-ui/react-primitive@2.1.10", "", { "dependencies": { "@radix-ui/react-slot": "1.3.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-MucOnzh6hR5mid6VpkbglRAMYMjKLqRnGBbjXkzjK52fuQDd1qbkx78a5P40mkcnVXJdEVxm26E9OPAiUq7nBg=="],
"@radix-ui/react-progress": ["@radix-ui/react-progress@1.1.16", "", { "dependencies": { "@radix-ui/react-context": "1.2.2", "@radix-ui/react-primitive": "2.1.10" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-5XnomAsoZZCY+KNTxbIghpGqPruZvKFNlvcAljVAOdDRDsH4/OZQxhtwo5wdtoDM5R6MhJBb2sPnDuRFep3lzg=="],
"@radix-ui/react-roving-focus": ["@radix-ui/react-roving-focus@1.1.19", "", { "dependencies": { "@radix-ui/primitive": "1.1.7", "@radix-ui/react-collection": "1.1.15", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-direction": "1.1.4", "@radix-ui/react-id": "1.1.4", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-use-callback-ref": "1.1.4", "@radix-ui/react-use-controllable-state": "1.2.6", "@radix-ui/react-use-is-hydrated": "0.1.3", "@radix-ui/react-use-layout-effect": "1.1.4" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-V9jI6hDjT7l3jsCQD9bLNvDLM3tH/gdbOTp7Tefp3hbbgCGQoK7tUvrWiRlcoBHIZ809ElXwNQwVo0B98LuTXQ=="],
"@radix-ui/react-slider": ["@radix-ui/react-slider@1.4.7", "", { "dependencies": { "@radix-ui/number": "1.1.3", "@radix-ui/primitive": "1.1.7", "@radix-ui/react-collection": "1.1.15", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-direction": "1.1.4", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-use-controllable-state": "1.2.6", "@radix-ui/react-use-layout-effect": "1.1.4", "@radix-ui/react-use-previous": "1.1.4", "@radix-ui/react-use-size": "1.1.4" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-mTSLf1GC/C0moWjTbvCM6Qn/gBjvlFt1azuWF2v7MN5C3Zq2U2J2lN3ZEYkpujuOU5Ro7A28wkviSxaKnG0BYg=="],
"@radix-ui/react-slot": ["@radix-ui/react-slot@1.3.3", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.5" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-qx7oqnYbxnK9kYI9m317qmFmEgo6ywqWvbTogdj7cL9p3/yx4M48p7Rnw5z3H890cL/ow/EeWJsuTykeZVXP5Q=="],
"@radix-ui/react-tabs": ["@radix-ui/react-tabs@1.1.21", "", { "dependencies": { "@radix-ui/primitive": "1.1.7", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-direction": "1.1.4", "@radix-ui/react-id": "1.1.4", "@radix-ui/react-presence": "1.1.10", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-roving-focus": "1.1.19", "@radix-ui/react-use-controllable-state": "1.2.6" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-UKxJlZid7FVtsk/WTxj4i4uSEgj2Au+KBbS7SQyTlzMhhn+86Cz3tISZdTa87bfEfcuvZezf2ZsxD4xuEKtkog=="],
"@radix-ui/react-toggle": ["@radix-ui/react-toggle@1.1.18", "", { "dependencies": { "@radix-ui/primitive": "1.1.7", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-use-controllable-state": "1.2.6" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-7lonPlKfSacd20GlOBx2ltuVKz9oqWYZz+oMQyOltw6t1y2nyftj2ZmwwUHYn49kqfDWcp8dNZm5NgV+5Z+mug=="],
"@radix-ui/react-toggle-group": ["@radix-ui/react-toggle-group@1.1.19", "", { "dependencies": { "@radix-ui/primitive": "1.1.7", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-direction": "1.1.4", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-roving-focus": "1.1.19", "@radix-ui/react-toggle": "1.1.18", "@radix-ui/react-use-controllable-state": "1.2.6" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-OtnwuSVjd1Ofi+AdnvhsjQdyuhCDwYs1w9RyB5BN/OavXOVQo42SYqQjwUnbPnaiPFBpQ9aX70dWeee+v2oBLA=="],
"@radix-ui/react-tooltip": ["@radix-ui/react-tooltip@1.2.16", "", { "dependencies": { "@radix-ui/primitive": "1.1.7", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-dismissable-layer": "1.1.19", "@radix-ui/react-id": "1.1.4", "@radix-ui/react-popper": "1.3.7", "@radix-ui/react-portal": "1.1.17", "@radix-ui/react-presence": "1.1.10", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-slot": "1.3.3", "@radix-ui/react-use-controllable-state": "1.2.6", "@radix-ui/react-use-layout-effect": "1.1.4", "@radix-ui/react-visually-hidden": "1.2.11" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-6EamKFRRnlpdadndbZ6LMwycfwkwPte1B42hs6QA0gYhjaOKqW4PZ4pjaW9UrlDX5eVt/OjncE7BFTPL5nmZhg=="],
"@radix-ui/react-use-callback-ref": ["@radix-ui/react-use-callback-ref@1.1.4", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-R6OUY2e2fA6Yn6s+VSx5KBV6Nx8LQEhu+cz7LCej18rQ1HLyg9PSC9jP/ZNx0o6FAIK9c0F1kHylzSxKsdlkrQ=="],
"@radix-ui/react-use-controllable-state": ["@radix-ui/react-use-controllable-state@1.2.6", "", { "dependencies": { "@radix-ui/primitive": "1.1.7", "@radix-ui/react-use-effect-event": "0.0.5", "@radix-ui/react-use-layout-effect": "1.1.4" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-uEQJGT97ZA/TgP/Hydw47lHu+/vQj6z/0jA+WeTbK1o9Rx45GImjpD0tc3W5ad3D6XTSR6e1yEO0FvGq6WQfVQ=="],
"@radix-ui/react-use-effect-event": ["@radix-ui/react-use-effect-event@0.0.5", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.4" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-7cshFL8HGS/7HEiHH+9kL9HBwp2sa9yX18Knwek6KYWmXwM7pegMgta2AXMQKI+rq3JnfSj9x8wYqFMTdG1Jgg=="],
"@radix-ui/react-use-is-hydrated": ["@radix-ui/react-use-is-hydrated@0.1.3", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-umO/aJ+82CpOnhDZUTbILCQf7kU/g0iv+oGs/Q8jw7IkhWBzaEP4sA268PhFAJTFetbwp3ICc6ktpI4TqtxcIw=="],
"@radix-ui/react-use-layout-effect": ["@radix-ui/react-use-layout-effect@1.1.4", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-K20DkRkUwDnxEYMBPcg3Y6voLkEy5p5QQmszZgLngKKiC7dzBR/aEuK3w1qlx2JWDUNH6FluahYdgR3BP+QbYw=="],
"@radix-ui/react-use-previous": ["@radix-ui/react-use-previous@1.1.4", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-XoSLhbRbqxFtgJoi2fNHA3C6pDlY34x508vUpUGoFZfvePfHXHbE1lC4FYFMnJWgiCRroSTw6fOsXQoVS9RwZg=="],
"@radix-ui/react-use-rect": ["@radix-ui/react-use-rect@1.1.4", "", { "dependencies": { "@radix-ui/rect": "1.1.3" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-cSOCh6JlkmfjLyNcLiu2nB4v+nm+dkZ+Q5KHWk/soo4U7ZLiEQFKHK9/YmtBHjfCEaU43IBKQOc4/uJmCaiCTQ=="],
"@radix-ui/react-use-size": ["@radix-ui/react-use-size@1.1.4", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.4" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-D3anSY15EJoxrihpsXI6SMrmmonnQtR2ni7arO+Lfdg3O95b9hNXxONk8jA5C8ANdF/h5HMAxejgs8PWJ6rlhw=="],
"@radix-ui/react-visually-hidden": ["@radix-ui/react-visually-hidden@1.2.11", "", { "dependencies": { "@radix-ui/react-primitive": "2.1.10" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-NFS86RYYZb4/exihaESBGOpMJFz8MGLAfu3mOBSGByVnVPC9JPASfYubxd/8KbkQK0sYAv8lVQDEQukDX/qXvQ=="],
"@radix-ui/rect": ["@radix-ui/rect@1.1.3", "", {}, "sha512-JtyZR+mqgBibTo8xea3B6ZRmzZiM/YeVBtUkas6zMuXjAlfIFIW2FgqeM9eLyvEaYX66vr6DJMK+4U6LV0KhNw=="],
"@replit/codemirror-css-color-picker": ["@replit/codemirror-css-color-picker@6.3.0", "", { "peerDependencies": { "@codemirror/language": "^6.0.0", "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.0.0" } }, "sha512-19biDANghUm7Fz7L1SNMIhK48tagaWuCOHj4oPPxc7hxPGkTVY2lU/jVZ8tsbTKQPVG7BO2CBDzs7CBwb20t4A=="],
"@rolldown/binding-android-arm-eabi": ["@rolldown/binding-android-arm-eabi@1.2.7", "", { "os": "android", "cpu": "arm" }, "sha512-EypzgnYCwyVY4NDHKzGmNJT5b+XaQEBniHxsMdeIQLB/tcCzZnhqrzHpZFbX9iaxx+5RiB8caATBtfvZP7zVxQ=="],
@@ -1203,8 +1119,6 @@
"detect-node": ["detect-node@2.1.0", "", {}, "sha512-T0NIuQpnTvFDATNuHN5roPwSBG83rFsuO+MXXH9/3N1eFbn4wcPjttvjMLEPWJ0RGUYgQE7cGgS3tNxbqCGM7g=="],
"detect-node-es": ["detect-node-es@1.1.0", "", {}, "sha512-ypdmJU/TbBby2Dxibuv7ZLW3Bs1QEmM7nHjEANfohJLvE0XVujisn1qPJcZxg+qDucsr+bP6fLD1rPS3AhJ7EQ=="],
"devlop": ["devlop@1.1.0", "", { "dependencies": { "dequal": "^2.0.0" } }, "sha512-RWmIqhcFf1lRYBvNmr7qTNuyCt/7/ns2jbpp1+PalgE/rDQcBT0fioSMUpJ93irlUhC5hrg4cYqe6U+0ImW0rA=="],
"diff": ["diff@8.0.4", "", {}, "sha512-DPi0FmjiSU5EvQV0++GFDOJ9ASQUVFh5kD+OzOnYdi7n3Wpm9hWWGfB/O2blfHcMVTL5WkQXSnRiK9makhrcnw=="],
@@ -1373,8 +1287,6 @@
"get-intrinsic": ["get-intrinsic@1.3.0", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.2", "es-define-property": "^1.0.1", "es-errors": "^1.3.0", "es-object-atoms": "^1.1.1", "function-bind": "^1.1.2", "get-proto": "^1.0.1", "gopd": "^1.2.0", "has-symbols": "^1.1.0", "hasown": "^2.0.2", "math-intrinsics": "^1.1.0" } }, "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ=="],
"get-nonce": ["get-nonce@1.0.1", "", {}, "sha512-FJhYRoDaiatfEkUK8HKlicmu/3SGFD51q3itKDGoSTysQJBnfOcxU5GxnhE1E6soB76MbT0MBtnKJuXyAx+96Q=="],
"get-own-enumerable-keys": ["get-own-enumerable-keys@1.0.0", "", {}, "sha512-PKsK2FSrQCyxcGHsGrLDcK0lx+0Ke+6e8KFFozA9/fIQLhQzPaRvJFdcz7+Axg3jUH/Mq+NI4xa5u/UT2tQskA=="],
"get-proto": ["get-proto@1.0.1", "", { "dependencies": { "dunder-proto": "^1.0.1", "es-object-atoms": "^1.0.0" } }, "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g=="],
@@ -1479,8 +1391,6 @@
"i18next": ["i18next@26.4.2", "", { "peerDependencies": { "typescript": "^5 || ^6 || ^7" }, "optionalPeers": ["typescript"] }, "sha512-RX+R0VLg13IbvRuJSxnqykUFS9vQZTl8wYpWPCIUDWVrSGjsQywB5Y+pjzrkboxGAuYfJZVH1InFTdgBdxq6ug=="],
"i18next-browser-languagedetector": ["i18next-browser-languagedetector@8.2.1", "", { "dependencies": { "@babel/runtime": "^7.23.2" } }, "sha512-bZg8+4bdmaOiApD7N7BPT9W8MLZG+nPTOFlLiJiT8uzKXFjhxw4v2ierCXOwB5sFDMtuA5G4kgYZ0AznZxQ/cw=="],
"iconv-lite": ["iconv-lite@0.7.3", "", { "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" } }, "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ=="],
"identifier-regex": ["identifier-regex@1.1.0", "", { "dependencies": { "reserved-identifiers": "^1.0.0" } }, "sha512-SLX4H/vtcYlYnL7XqnuJKHU7Z8517TgsW9nmQiGOgMCjQ8V/deLYu6bEmbGoXe7WMMhc9+EUGyFFneHja8KabA=="],
@@ -1961,12 +1871,6 @@
"react-is": ["react-is@17.0.2", "", {}, "sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w=="],
"react-remove-scroll": ["react-remove-scroll@2.7.2", "", { "dependencies": { "react-remove-scroll-bar": "^2.3.7", "react-style-singleton": "^2.2.3", "tslib": "^2.1.0", "use-callback-ref": "^1.3.3", "use-sidecar": "^1.1.3" }, "peerDependencies": { "@types/react": "*", "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-Iqb9NjCCTt6Hf+vOdNIZGdTiH1QSqr27H/Ek9sv/a97gfueI/5h1s3yRi1nngzMUaOOToin5dI1dXKdXiF+u0Q=="],
"react-remove-scroll-bar": ["react-remove-scroll-bar@2.3.8", "", { "dependencies": { "react-style-singleton": "^2.2.2", "tslib": "^2.0.0" }, "peerDependencies": { "@types/react": "*", "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" }, "optionalPeers": ["@types/react"] }, "sha512-9r+yi9+mgU33AKcj6IbT9oRCO78WriSj6t/cF8DWBZJ9aOGPOTEDvdUDz1FwKim7QXWwmHqtdHnRJfhAxEG46Q=="],
"react-style-singleton": ["react-style-singleton@2.2.3", "", { "dependencies": { "get-nonce": "^1.0.0", "tslib": "^2.0.0" }, "peerDependencies": { "@types/react": "*", "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-b6jSvxvVnyptAiLjbkWLE/lOnR4lfTtDAl+eUC7RZy+QQWc6wRzIV2CE6xBuMmDxc2qIihtDCZD5NPOFl7fRBQ=="],
"read-binary-file-arch": ["read-binary-file-arch@1.0.6", "", { "dependencies": { "debug": "^4.3.4" }, "bin": { "read-binary-file-arch": "cli.js" } }, "sha512-BNg9EN3DD3GsDXX7Aa8O4p92sryjkmzYYgmgTAc6CA4uGLEDzFfxOxugu21akOxpcXHiEgsYkC6nPsQvLLLmEg=="],
"readable-stream": ["readable-stream@2.3.8", "", { "dependencies": { "core-util-is": "~1.0.0", "inherits": "~2.0.3", "isarray": "~1.0.0", "process-nextick-args": "~2.0.0", "safe-buffer": "~5.1.1", "string_decoder": "~1.1.1", "util-deprecate": "~1.0.1" } }, "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA=="],
@@ -2153,7 +2057,7 @@
"tagged-tag": ["tagged-tag@1.0.0", "", {}, "sha512-yEFYrVhod+hdNyx7g5Bnkkb0G6si8HJurOoOEgC8B/O0uXLHlaey/65KRv6cuWBNhBgHKAROVpc7QyYqE5gFng=="],
"tailwind-merge": ["tailwind-merge@3.7.0", "", {}, "sha512-XPPUyAc+cvspz3lHTcR/QgPfW2A0lv/xQNIjX3HGhLR+Nq2lHaLq5MtTesHn8GUr3W3DguT2KT5x3NVgRtYwmA=="],
"tailwind-merge": ["tailwind-merge@3.5.0", "", {}, "sha512-I8K9wewnVDkL1NTGoqWmVEIlUcB9gFriAEkXkfCjX5ib8ezGxtR3xD7iZIxrfArjEsH7F1CHD4RFUtxefdqV/A=="],
"tailwindcss": ["tailwindcss@4.3.3", "", {}, "sha512-gOhV3P7ufE62QDGg1zVaTgCR+EtPv92k2nIhVcVKcLmxT1sUBsQGhnZj175j+MqRt4zLF7ic+sCYjfhxMxj7YQ=="],
@@ -2263,10 +2167,6 @@
"update-browserslist-db": ["update-browserslist-db@1.3.2", "", { "dependencies": { "escalade": "^3.2.0", "picocolors": "^1.1.1" }, "peerDependencies": { "browserslist": ">= 4.21.0" }, "bin": { "update-browserslist-db": "cli.js" } }, "sha512-UQ+MSxlhRm1bzjhU+DcuXfjFO1FzNtqhK5+9Yvlp90ItDLk5vT932A0rFu619nf7RVS+Y/VeaUW1jaRDqZ8VJw=="],
"use-callback-ref": ["use-callback-ref@1.3.3", "", { "dependencies": { "tslib": "^2.0.0" }, "peerDependencies": { "@types/react": "*", "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-jQL3lRnocaFtu3V00JToYz/4QkNWswxijDaCVNZRiRTO3HQDLsdu1ZtmIUvV4yPp+rvWm5j0y0TG/S61cuijTg=="],
"use-sidecar": ["use-sidecar@1.1.3", "", { "dependencies": { "detect-node-es": "^1.1.0", "tslib": "^2.0.0" }, "peerDependencies": { "@types/react": "*", "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-Fedw0aZvkhynoPYlA5WXrMCAMm+nSWdZt6lzJQ7Ok8S6Q+VsHmHpRWndVRJ8Be0ZbkfPc5LRYH+5XrzXcEeLRQ=="],
"use-sync-external-store": ["use-sync-external-store@1.6.0", "", { "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-Pp6GSwGP/NrPIrxVFAIkOQeyw8lFenOHijQWkUTrDvrF4ALqylP2C/KCkeS9dpUM3KvYRQhna5vt7IL95+ZQ9w=="],
"utf8-byte-length": ["utf8-byte-length@1.0.5", "", {}, "sha512-Xn0w3MtiQ6zoz2vFyUVruaCL53O/DwUvkEeOvj+uulMm0BkUGYWmBYVyElqZaSLhY6ZD0ulfU3aBra2aVT4xfA=="],
@@ -2445,8 +2345,6 @@
"@scalar/types/zod": ["zod@4.5.4", "", {}, "sha512-sC95tT5iHHH9gtpj6A81kh+NEaRAUFN+qlUPDUbRfOMvNf5QCBqsb3WgvnpVtK5Y+4UfA6KqufotuTvMGiTlsA=="],
"@scalar/use-hooks/tailwind-merge": ["tailwind-merge@3.5.0", "", {}, "sha512-I8K9wewnVDkL1NTGoqWmVEIlUcB9gFriAEkXkfCjX5ib8ezGxtR3xD7iZIxrfArjEsH7F1CHD4RFUtxefdqV/A=="],
"@scalar/workspace-store/yaml": ["yaml@2.9.0", "", { "bin": { "yaml": "bin.mjs" } }, "sha512-2AvhNX3mb8zd6Zy7INTtSpl1F15HW6Wnqj0srWlkKLcpYl/gMIMJiyuGq2KeI2YFxUPjdlB+3Lc10seMLtL4cA=="],
"@tailwindcss/node/lightningcss": ["lightningcss@1.32.0", "", { "dependencies": { "detect-libc": "^2.0.3" }, "optionalDependencies": { "lightningcss-android-arm64": "1.32.0", "lightningcss-darwin-arm64": "1.32.0", "lightningcss-darwin-x64": "1.32.0", "lightningcss-freebsd-x64": "1.32.0", "lightningcss-linux-arm-gnueabihf": "1.32.0", "lightningcss-linux-arm64-gnu": "1.32.0", "lightningcss-linux-arm64-musl": "1.32.0", "lightningcss-linux-x64-gnu": "1.32.0", "lightningcss-linux-x64-musl": "1.32.0", "lightningcss-win32-arm64-msvc": "1.32.0", "lightningcss-win32-x64-msvc": "1.32.0" } }, "sha512-NXYBzinNrblfraPGyrbPoD19C1h9lfI/1mzgWYvXUTe414Gz/X1FD2XBZSZM7rRTrMA8JL3OtAaGifrIKhQ5yQ=="],
+2 -2
View File
@@ -54,8 +54,8 @@ VoiceStudio/
│ ├── src/main/ lifecycle, backend supervisor, runtime setup, updater, native IPC
│ ├── src/preload/ typed contextBridge → window.voicestudio
│ ├── src/renderer/ desktop React app: routes/, features/, components/, i18n/locales/
│ ├── src/shared/ modules shared by the desktop and browser builds (api/, i18n/,
│ │ store/, ui/, utils/) — not a runnable app
│ ├── src/shared/ modules shared by the desktop and browser builds (api/, store/,
│ │ utils/) — not a runnable app
│ ├── tests/ packaged-app, installer and workflow smoke tests
│ ├── build/ packaging inputs: icons, entitlements, Info.plist
│ ├── scripts/ dev launcher, AppImage update-info embedding
+1 -2
View File
@@ -10,7 +10,6 @@ spark identifies creation. The product voice is clear, calm, and direct.
| Primary vector mark | `docs/logo.svg` |
| README mark | `docs/logo.png` and `docs/logo-256.png` |
| Browser icon | `electron/public/favicon.svg` |
| In-app mark | `electron/src/shared/components/brand/VoiceStudioMark.jsx` |
| Desktop/platform icons | `electron/build/icons/` |
| macOS menu-bar templates | `electron/build/icons/trayTemplate.svg` and `trayRecordingTemplate.svg` |
| Electron sidebar and browser icon | `electron/public/favicon.svg` via `electron/src/renderer/src/lib/brand.ts` |
@@ -50,7 +49,7 @@ macOS artwork (`icon.icns` and `icon-macos.png`) keeps Apple's icon grid: the ti
spans the centred 824 px of a 1024 px canvas, so it matches other apps in the Dock,
Launchpad and Finder. `tests/test_macos_icon_grid.py` checks it.
Do not redraw the waveform per screen. Use `VoiceStudioMark` in React and the
Do not redraw the waveform per screen. Use `electron/src/renderer/src/lib/brand.ts` in React and the
canonical SVG elsewhere so the silhouette stays recognizable at 16–512 px.
## Palette
-12
View File
@@ -42,15 +42,6 @@
"@electron-toolkit/utils": "^4.0.0",
"@fontsource-variable/inter": "^5.3.0",
"@lobehub/icons-static-svg": "^1.95.0",
"@radix-ui/react-dialog": "^1.1.23",
"@radix-ui/react-dropdown-menu": "^2.1.24",
"@radix-ui/react-progress": "^1.1.16",
"@radix-ui/react-slider": "^1.4.7",
"@radix-ui/react-slot": "^1.3.3",
"@radix-ui/react-tabs": "^1.1.21",
"@radix-ui/react-toggle": "^1.1.18",
"@radix-ui/react-toggle-group": "^1.1.19",
"@radix-ui/react-tooltip": "^1.2.16",
"@scalar/api-reference-react": "^0.9.67",
"@tanstack/react-form": "^1.33.5",
"@tanstack/react-pacer": "^0.23.0",
@@ -62,7 +53,6 @@
"@vidstack/react": "1.15.6",
"@xyflow/react": "^12.12.0",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"cn": "^0.3.0",
"country-flag-icons": "^1.6.20",
"dashjs": "^5.2.1",
@@ -70,7 +60,6 @@
"hls.js": "^1.7.3",
"html-entities": "^2.6.0",
"i18next": "^26.4.2",
"i18next-browser-languagedetector": "^8.2.1",
"lucide-react": "^1.46.0",
"proxy-agent": "6.5.0",
"qrcode": "^1.5.4",
@@ -80,7 +69,6 @@
"react-i18next": "^17.0.14",
"shadcn": "^4.21.0",
"sonner": "^2.0.8",
"tailwind-merge": "^3.6.0",
"tw-animate-css": "^1.4.0",
"wavesurfer.js": "^7.12.12",
"word-extractor": "1.0.4",
@@ -0,0 +1,18 @@
import { describe, expect, it } from 'vitest';
import { licensedEngine } from './engine-license';
// A license-gated engine must always offer its Accept flow until the backend
// reports it accepted; the gate keys off the structured flags, never off the
// wording of the unavailable reason.
describe('licensedEngine', () => {
it.each(['supertonic3', 'pockettts'])('offers the license for %s until accepted', (id) => {
expect(licensedEngine(id, true, false)).toBe(id);
expect(licensedEngine(id, true, undefined)).toBe(id);
});
it('offers nothing once accepted, when not required, or for other engines', () => {
expect(licensedEngine('supertonic3', true, true)).toBeNull();
expect(licensedEngine('pockettts', undefined, false)).toBeNull();
expect(licensedEngine('kokoro', true, false)).toBeNull();
});
});
@@ -0,0 +1,22 @@
import { describe, expect, it } from 'vitest';
import { refineFailureNoteKey } from '@shared/components/settings/refineStatus';
import en from '@/i18n/locales/en.json';
const dictation = en.dictation as Record<string, string>;
describe('refineFailureNoteKey', () => {
it('is silent without a status or after a successful refinement', () => {
expect(refineFailureNoteKey(null)).toBeNull();
expect(refineFailureNoteKey(undefined)).toBeNull();
expect(refineFailureNoteKey({ ok: true })).toBeNull();
});
it('maps a timeout and any other failure to distinct, translated notes', () => {
const timeout = refineFailureNoteKey({ ok: false, reason: 'timeout' });
const failed = refineFailureNoteKey({ ok: false, reason: 'RuntimeError' });
expect(timeout).toBe('dictation.refine_timeout_note');
expect(failed).toBe('dictation.refine_failed_note');
expect(dictation.refine_timeout_note).toMatch(/timed out/i);
expect(dictation.refine_failed_note).toMatch(/failed/i);
});
});
@@ -0,0 +1,70 @@
import { afterEach, describe, expect, it } from 'vitest';
import en from './locales/en.json';
import i18n, { APP_LANGUAGES, SUPPORTED_LOCALES } from './index';
const catalogs = import.meta.glob<{ default: Record<string, unknown> }>('./locales/*.json', {
eager: true,
});
describe('selectable UI languages', () => {
it('lists every supported locale with a language name and English first', () => {
expect(SUPPORTED_LOCALES[0]).toBe('en');
expect(APP_LANGUAGES.map(({ code }) => code)).toEqual([...SUPPORTED_LOCALES]);
expect(APP_LANGUAGES.every(({ label }) => label.trim().length > 0)).toBe(true);
});
it('ships a catalog file for each supported locale', () => {
for (const code of SUPPORTED_LOCALES)
expect(catalogs[`./locales/${code}.json`], code).toBeTruthy();
expect(Object.keys(catalogs)).toHaveLength(SUPPORTED_LOCALES.length);
});
});
describe('document direction follows the active locale', () => {
afterEach(async () => {
await i18n.changeLanguage('en');
});
it('switching to Arabic sets <html dir="rtl" lang="ar">', async () => {
await i18n.changeLanguage('ar');
expect(document.documentElement.dir).toBe('rtl');
expect(document.documentElement.lang).toBe('ar');
});
it('switching back to English restores <html dir="ltr" lang="en">', async () => {
await i18n.changeLanguage('ar');
await i18n.changeLanguage('en');
expect(document.documentElement.dir).toBe('ltr');
expect(document.documentElement.lang).toBe('en');
});
it('left-to-right locales stay left-to-right', async () => {
await i18n.changeLanguage('de');
expect(document.documentElement.dir).toBe('ltr');
expect(document.documentElement.lang).toBe('de');
});
});
describe('failure copy keeps the real error', () => {
it('gallery.use_failed interpolates the backend message', () => {
expect((en.gallery as Record<string, string>).use_failed).toContain('{{message}}');
});
it.each([
['it', 'Altre righe: 1', 'Altre righe: 2'],
['nl', 'Extra rijen: 1', 'Extra rijen: 2'],
['pl', 'Dodatkowe wiersze: 1', 'Dodatkowe wiersze: 2'],
['pt', 'Linhas adicionais: 1', 'Linhas adicionais: 2'],
['ru', 'Дополнительных строк: 1', 'Дополнительных строк: 2'],
])('%s keeps the pasted-translation row count readable', async (locale, one, other) => {
const catalog = catalogs[`./locales/${locale}.json`]!.default;
const instance = i18n.createInstance();
await instance.init({
lng: locale,
fallbackLng: false,
resources: { [locale]: { translation: catalog } },
});
expect(instance.t('dub.paste_translation_more_rows', { count: 1 })).toBe(one);
expect(instance.t('dub.paste_translation_more_rows', { count: 2 })).toBe(other);
});
});
-203
View File
@@ -1,203 +0,0 @@
import { apiFetch } from './client';
interface AudiobookSpan {
voice_id: string | null;
text: string;
pause_ms_after: number;
}
interface AudiobookChapter {
title: string;
char_count: number;
spans: AudiobookSpan[];
}
export interface AudiobookPlan {
chapters: AudiobookChapter[];
chapter_count: number;
char_count: number;
}
/** Parse a script into a chapter/span plan (pure preview, no synthesis). */
export async function audiobookPlan(body: {
text: string;
default_voice?: string | null;
}): Promise<AudiobookPlan> {
const res = await apiFetch('/audiobook/plan', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
return res.json();
}
export interface AudiobookPreview {
output: string; // path under OUTPUTS_DIR, served via /audio
duration_s: number;
cached: boolean;
title: string;
}
/**
* Expressive/quality knobs shared by the audiobook synth + per-chapter preview
* (#1208). All optional — an omitted field reproduces today's exact render on
* the backend. Preview MUST carry the same fields as the full render so a
* previewed chapter warms exactly the cache slot the render reuses.
*/
export interface ExpressiveRequestFields {
num_step?: number | null;
guidance_scale?: number | null;
position_temperature?: number | null;
class_temperature?: number | null;
postprocess_output?: boolean | null;
seed?: number | null;
emo_vector?: number[] | null;
emo_text?: string | null;
emo_alpha?: number | null;
vary_repeats?: boolean;
}
/** Render a single chapter to audition it (also warms the resume cache). */
export async function audiobookPreviewChapter(
body: {
text: string;
chapter_index: number;
default_voice?: string | null;
language?: string | null;
lexicon?: Record<string, string> | null;
// Cast map {[voice:NAME] → profile id} — must match the render's (#1217).
voice_map?: Record<string, string> | null;
} & ExpressiveRequestFields,
): Promise<AudiobookPreview> {
const res = await apiFetch('/audiobook/preview', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
return res.json();
}
/** Global tags embedded in the output file (player-visible). */
interface AudiobookMetadata {
title?: string;
author?: string;
narrator?: string;
year?: string;
genre?: string;
description?: string;
}
export interface AudiobookGenerateBody extends ExpressiveRequestFields {
text: string;
default_voice?: string | null;
// #1208 / #505: the backend AudiobookRequest has always accepted `language`,
// but this body omitted it, so an audiobook language pick could never reach
// the backend. Now threaded through ('Auto' → the profile's language).
language?: string | null;
bitrate?: string;
format?: 'm4b' | 'mp3';
loudness?: 'off' | 'acx' | 'podcast' | null;
cover_path?: string | null;
metadata?: AudiobookMetadata | null;
lexicon?: Record<string, string> | null;
// Multi-voice cast map {[voice:NAME] → profile id} (#1217). Absent/empty
// reproduces today's single-voice render + cache keys.
voice_map?: Record<string, string> | null;
}
/**
* Start the synth job. Returns the raw streaming Response; the caller reads
* `response.body` with a reader + the sseParse helpers. (apiFetch throws on a
* non-2xx status, so a returned Response is always a live stream.)
*
* `opts.signal` wires an AbortController into the fetch so a Stop cancels the
* request end-to-end (#1216): aborting closes the connection, the backend's
* `is_disconnected()` poll trips, and it stops scheduling further chapters
* instead of rendering the whole book into a stream nobody is reading.
*/
export async function audiobookGenerate(
body: AudiobookGenerateBody,
opts: { signal?: AbortSignal } = {},
): Promise<Response> {
return apiFetch('/audiobook', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
signal: opts.signal,
});
}
export interface ResumableAudiobookJob {
job_id: string;
type: 'audiobook' | 'longform';
status: string;
title: string;
total_chapters: number;
chapters_done: number;
created_at: number | null;
}
/** Fetch the renders the backend has on disk that can still be resumed. */
export async function audiobookListJobs(): Promise<{ jobs: ResumableAudiobookJob[] }> {
const res = await apiFetch('/audiobook/jobs', { method: 'GET' });
return res.json();
}
/** Ask the backend to continue one render; consumers read events from the response body. */
export async function audiobookResume(
jobId: string,
opts: { signal?: AbortSignal } = {},
): Promise<Response> {
const route = ['/audiobook/resume', encodeURIComponent(jobId)].join('/');
const requestOptions: RequestInit = { method: 'POST' };
if (opts.signal) requestOptions.signal = opts.signal;
return apiFetch(route, requestOptions);
}
/** Upload a cover image; returns the server-side path to pass as `cover_path`. */
export async function audiobookUploadCover(file: File): Promise<{ path: string }> {
const form = new FormData();
form.append('cover', file);
const res = await apiFetch('/audiobook/cover', { method: 'POST', body: form });
return res.json();
}
/** Import a .txt/.md/.epub/.pdf into a chapter-delimited script. */
export async function audiobookImport(file: File): Promise<{ text: string; chapters: number }> {
const form = new FormData();
form.append('file', file);
const res = await apiFetch('/audiobook/import', { method: 'POST', body: form });
return res.json();
}
export interface LongformRenderBody extends ExpressiveRequestFields {
chapters: Array<{
title?: string;
spans: Array<{
voice_id: string | null;
text: string;
pause_ms_after: number;
speed?: number | null;
}>;
}>;
default_voice?: string | null;
language?: string | null;
bitrate?: string;
format?: 'm4b' | 'mp3';
loudness?: 'off' | 'acx' | 'podcast' | null;
cover_path?: string | null;
metadata?: AudiobookMetadata | null;
voice_map?: Record<string, string> | null;
}
/**
* Render a pre-built chapter/span plan through the shared chapterized renderer
* (the convergence endpoint Stories posts to). Returns the raw SSE stream
* Response — read `response.body` with the sseParse helpers, same as
* `audiobookGenerate`.
*/
export async function longformRender(body: LongformRenderBody): Promise<Response> {
return apiFetch('/longform/render', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
}
-112
View File
@@ -1,112 +0,0 @@
/**
* Contract test for the batch API client: /batch/enqueue receives uploaded
* File BYTES only. Filesystem paths must never appear in the request — the
* watch-folder feature (and everything else) rides the same guarantee.
*/
import { beforeEach, describe, expect, it, vi } from 'vitest';
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const invoke = vi.fn();
vi.mock('@tauri-apps/api/core', () => ({ invoke: (...args) => invoke(...args) }));
vi.mock('./client', () => ({
ApiError: class ApiError extends Error {
constructor(message, init = {}) {
super(message);
Object.assign(this, init);
}
},
apiJson: vi.fn(),
apiPost: vi.fn(async () => ({ job_id: 'j1', status: 'queued', queue_position: 0 })),
apiDelete: vi.fn(),
API: 'http://127.0.0.1:3900',
}));
import { apiPost } from './client';
import { enqueueBatchJob } from './batch';
describe('enqueueBatchJob', () => {
beforeEach(() => vi.clearAllMocks());
it('uploads the File itself — no filesystem path in any form field', async () => {
const file = new File(['bytes'], 'clip.mp4', { type: 'video/mp4' });
// Desktop-flavored File objects sometimes carry a path property; even if
// one sneaks in, the client must not serialize it.
Object.defineProperty(file, 'path', { value: '/Users/me/Watched/clip.mp4' });
await enqueueBatchJob(file, ['es', 'fr'], 'voice-1', false);
expect(apiPost).toHaveBeenCalledTimes(1);
const [url, form] = apiPost.mock.calls[0];
expect(url).toBe('/batch/enqueue');
expect(form).toBeInstanceOf(FormData);
expect([...form.keys()].sort()).toEqual(['langs', 'preserve_bg', 'video', 'voice_id']);
expect(form.get('video')).toBeInstanceOf(File);
expect(form.get('video').name).toBe('clip.mp4');
expect(form.get('langs')).toBe('es,fr');
expect(form.get('voice_id')).toBe('voice-1');
expect(form.get('preserve_bg')).toBe('false');
for (const [, value] of form.entries()) {
if (typeof value === 'string') {
expect(value).not.toContain('/Users/me');
}
}
});
it('streams native watch entries without constructing FormData in the renderer', async () => {
const watched = {
__voiceStudioNativeWatchUpload: /** @type {const} */ (true),
token: 'a'.repeat(64),
name: 'large.mkv',
size: 8 * 1024 * 1024 * 1024,
mtime: 1234,
};
invoke.mockResolvedValueOnce({
status: 200,
body: { job_id: 'native-1', status: 'queued', queue_position: 1 },
});
await expect(enqueueBatchJob(watched, ['es'], '', true)).resolves.toMatchObject({
job_id: 'native-1',
});
expect(invoke).toHaveBeenCalledWith('watch_folder_enqueue', {
token: watched.token,
name: 'large.mkv',
expectedSize: watched.size,
expectedMtime: watched.mtime,
langs: ['es'],
voiceId: '',
preserveBg: true,
});
expect(apiPost).not.toHaveBeenCalled();
});
it('preserves structured backend errors from native watch uploads', async () => {
const detail = { error: 'asr_model_missing', recommended: { repo_id: 'model/repo' } };
invoke.mockResolvedValueOnce({ status: 409, body: { detail } });
const watched = {
__voiceStudioNativeWatchUpload: /** @type {const} */ (true),
token: 'b'.repeat(64),
name: 'clip.mp4',
size: 4,
mtime: 1,
};
await expect(enqueueBatchJob(watched, ['es'])).rejects.toMatchObject({ status: 409, detail });
});
it('the batch client source never touches a path at all', () => {
const source = fs.readFileSync(
path.join(path.dirname(fileURLToPath(import.meta.url)), 'batch.ts'),
'utf-8',
);
// No `path` identifier anywhere: not a form field, not a query param, not
// a property read. (Regression guard for the watch-folder rule that the
// backend only ever receives uploaded bytes.)
expect(source).not.toMatch(/[^A-Za-z]path/i);
});
});
-100
View File
@@ -1,100 +0,0 @@
/**
* Batch dubbing API — wraps the /batch/* backend endpoints.
*
* Used by BatchQueue and BatchAddDialog to enqueue, monitor, and
* manage batch dub jobs.
*/
import { apiJson, apiPost, apiDelete, ApiError } from './client';
export interface BatchJob {
id: string;
status: 'queued' | 'running' | 'done' | 'failed' | 'cancelled';
filename: string;
langs: string[];
voice_id?: string;
preserve_bg: boolean;
created_at: number;
started_at?: number;
finished_at?: number;
error?: string;
progress?: {
stage: string;
percent: number;
current_lang?: string;
current_segment?: number;
total_segments?: number;
segments_count?: number;
};
outputs?: Record<string, string>;
}
interface NativeWatchUpload {
__voiceStudioNativeWatchUpload: true;
token: string;
name: string;
size: number;
mtime: number;
}
function isNativeWatchUpload(file: File | NativeWatchUpload): file is NativeWatchUpload {
return !(file instanceof File) && file.__voiceStudioNativeWatchUpload === true;
}
/** List batch jobs, optionally filtered by status. */
export async function listBatchJobs(status?: string, limit = 50): Promise<BatchJob[]> {
const qs = new URLSearchParams();
if (status) qs.set('status', status);
qs.set('limit', String(limit));
return apiJson<BatchJob[]>(`/batch/jobs?${qs.toString()}`);
}
/** Get a single batch job (used to resolve why a job left the active list). */
export async function getBatchJob(id: string): Promise<BatchJob> {
return apiJson<BatchJob>(`/batch/jobs/${id}`);
}
/** Enqueue a video for batch dubbing. */
export async function enqueueBatchJob(
file: File | NativeWatchUpload,
langs: string[],
voiceId?: string,
preserveBg = true,
): Promise<{ job_id: string; status: string; queue_position: number }> {
if (isNativeWatchUpload(file)) {
const { invoke } = await import('@tauri-apps/api/core');
const reply = await invoke<{ status: number; body: unknown }>('watch_folder_enqueue', {
token: file.token,
name: file.name,
expectedSize: file.size,
expectedMtime: file.mtime,
langs,
voiceId,
preserveBg,
});
if (reply.status < 200 || reply.status >= 300) {
const detail = (reply.body as { detail?: unknown })?.detail ?? reply.body;
throw new ApiError(`Watch-folder upload failed (${reply.status})`, {
status: reply.status,
detail,
});
}
return reply.body as { job_id: string; status: string; queue_position: number };
}
const form = new FormData();
form.append('video', file);
form.append('langs', langs.join(','));
if (voiceId) form.append('voice_id', voiceId);
form.append('preserve_bg', String(preserveBg));
return apiPost('/batch/enqueue', form);
}
/** Cancel a batch job. */
export async function cancelBatchJob(id: string): Promise<unknown> {
return apiPost(`/batch/jobs/${id}/cancel`, {});
}
/** Delete a batch job and its files. */
export async function deleteBatchJob(id: string): Promise<unknown> {
const res = await apiDelete(`/batch/jobs/${id}`);
return res.json();
}
-21
View File
@@ -1,21 +0,0 @@
import { apiJson, apiPost } from './client';
export async function listExportHistory(): Promise<unknown> {
return apiJson('/export/history');
}
export async function exportAction(body: Record<string, unknown>): Promise<unknown> {
return apiPost('/export', body);
}
export async function exportReveal(body: Record<string, unknown>): Promise<unknown> {
if (typeof window !== 'undefined' && '__TAURI_INTERNALS__' in window) {
const { invoke } = await import('@tauri-apps/api/core');
return invoke('reveal_host_path', { path: body.path });
}
return apiPost('/export/reveal', body);
}
export async function exportRecord(body: Record<string, unknown>): Promise<unknown> {
return apiPost('/export/record', body);
}
-15
View File
@@ -1,15 +0,0 @@
import { apiFetch } from './client';
/**
* Transcode a client-stitched WAV blob to a compressed format via the backend
* ffmpeg endpoint. Same-origin + PIN-aware (apiFetch). Throws on failure so the
* caller can fall back to the raw WAV.
*/
export async function encodeAudio(wavBlob: Blob, format = 'mp3', bitrate = '192k'): Promise<Blob> {
const fd = new FormData();
fd.append('file', wavBlob, 'story.wav');
fd.append('format', format);
fd.append('bitrate', bitrate);
const res = await apiFetch('/stories/encode', { method: 'POST', body: fd });
return res.blob();
}
@@ -1,155 +0,0 @@
/**
* AsrModelChooser — the "no speech-to-text model installed" empty state's
* model picker.
*
* The page used to offer exactly one button: download the backend's
* recommended model. That hid the six other catalogue models — the English
* Parakeet that is markedly more accurate, the 25–44 MB streaming models that
* show text while you speak, the bilingual zh/en ones — behind Settings, and
* a user who already had one of them on disk still saw "download Whisper
* Tiny". This lists the whole sherpa-onnx catalogue grouped by what the user
* is choosing between (accuracy vs latency), with languages and size on every
* row, and lets them install any of them, or switch to one already installed.
*
* Falls back to the single recommended-download button when the catalogue
* can't be read (backend restarting, older backend), so the page is never
* left without a way forward.
*/
import React, { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Check, Download } from 'lucide-react';
import { apiJson } from '../api/client';
import { Badge, Button } from '../ui';
function fmtSize(sizeGb) {
if (sizeGb == null) return '';
if (sizeGb < 1) return `${Math.round(sizeGb * 1000)} MB`;
return `${sizeGb.toFixed(sizeGb < 10 ? 1 : 0)} GB`;
}
// Offline models transcribe once you stop (best accuracy); streaming ones emit
// partial text as you speak (lowest latency). That is the real trade-off, so
// it is the grouping — not the engine's internal `kind`.
const GROUPS = [
{ tag: 'offline', title: 'asr_missing.group_offline' },
{ tag: 'streaming', title: 'asr_missing.group_streaming' },
];
export default function AsrModelChooser({ fallback, onInstall, onSelect, disabled = false }) {
const { t } = useTranslation();
// null = loading, [] = catalogue unavailable.
const [models, setModels] = useState(null);
useEffect(() => {
let live = true;
apiJson('/dictation/models')
.then((data) => {
if (live) setModels(Array.isArray(data?.models) ? data.models : []);
})
.catch(() => {
if (live) setModels([]);
});
return () => {
live = false;
};
}, []);
if (models === null) return null;
if (models.length === 0) {
if (!fallback?.repo_id) return null;
return (
<Button
size="sm"
variant="primary"
leading={<Download size={13} />}
disabled={disabled}
onClick={() => onInstall(fallback)}
>
{t('asr_missing.download', { label: fallback.label, size: fallback.size_gb })}
</Button>
);
}
const desc = (m) => t(`voicePanel.model_desc.${m.id}`, { defaultValue: m.languages || '' });
return (
<div className="flex flex-col gap-3" data-testid="asr-model-chooser">
<p className="m-0 text-xs text-fg-muted">{t('asr_missing.choose')}</p>
{GROUPS.map(({ tag, title }) => {
const rows = models
.filter((m) => m.tag === tag)
.sort((a, b) => Number(b.recommended) - Number(a.recommended));
if (rows.length === 0) return null;
return (
<section key={tag} aria-labelledby={`asr-group-${tag}`} className="flex flex-col gap-1">
<h3
id={`asr-group-${tag}`}
className="m-0 text-[11px] font-semibold uppercase tracking-[0.06em] text-fg-muted"
>
{t(title)}
</h3>
<ul className="m-0 flex list-none flex-col gap-1 p-0">
{rows.map((m) => (
<li
key={m.id}
data-testid={`asr-choice-${m.id}`}
className="flex flex-wrap items-center gap-2 rounded-md border border-border bg-bg px-3 py-2"
>
<div className="min-w-0 flex-1">
<div className="flex flex-wrap items-center gap-1.5">
<span className="text-sm font-semibold text-fg">{m.label}</span>
{m.recommended && (
<Badge tone="success" size="xs">
{t('voicePanel.badge_recommended')}
</Badge>
)}
{m.installed && (
<Badge tone="neutral" size="xs">
{t('asr_missing.installed')}
</Badge>
)}
<span className="text-xs tabular-nums text-fg-muted">
{fmtSize(m.size_gb)}
</span>
</div>
<p className="m-0 text-xs text-fg-muted">
{desc(m)}
{m.languages && (
<>
{' · '}
<span className="whitespace-nowrap">{m.languages}</span>
</>
)}
</p>
</div>
{m.installed ? (
<Button
size="sm"
variant="subtle"
leading={<Check size={13} />}
disabled={disabled}
onClick={() => onSelect(m)}
>
{t('asr_missing.use', { label: m.label })}
</Button>
) : (
<Button
size="sm"
variant={m.recommended ? 'primary' : 'subtle'}
leading={<Download size={13} />}
disabled={disabled}
onClick={() => onInstall(m)}
>
{t('asr_missing.download', { label: m.label, size: m.size_gb })}
</Button>
)}
</li>
))}
</ul>
</section>
);
})}
</div>
);
}
File diff suppressed because it is too large. Load diff
@@ -1,365 +0,0 @@
/**
* DictationDemo — guided walkthrough for the real-time dictation feature.
*
* What this surfaces:
* 1. Active hotkey display (including a portal-selected Wayland shortcut).
* 2. Three script cards — short utterances the user can read aloud OR
* replay from a bundled WAV. The replay path posts the bundled audio
* to POST /transcribe and renders the recognized text below the card
* so dictation can be demoed even when the user hasn't granted mic
* permission yet, or is on a headless / VM / CI box.
* 3. Hotkey verification status — subscribes to the `tray-dictate` and
* `tray-dictate-stop` Tauri events so we can show "verified" the
* moment the user presses the shortcut for the first time.
*
* Cross-platform: the replay path uses the existing backend transcribe
* endpoint and works identically on macOS / Windows / Linux. The hotkey
* verification path requires Tauri (gracefully no-ops in the web UI).
*
* Where this is mounted:
* - Settings → Capture & Dictation (above HotkeyTab) — always available
* - SetupWizard step 4 — first-run onboarding
*/
import { useEffect, useRef, useState } from 'react';
import { Play, Pause, Keyboard, Mic, CheckCircle2, AlertTriangle } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { API, apiFetch } from '../api/client';
import { asrMissingPayload, toastAsrModelMissing } from '../utils/asrModelMissing';
import { useEffectiveDictationShortcut } from '../hooks/useEffectiveDictationShortcut';
import { useDictationReadiness } from '../hooks/useDictationReadiness';
import AsrModelChooser from './AsrModelChooser';
import { Button } from '../ui';
// Shared status-pill base; per-state color/bg/border appended below. The gruvbox
// status hues are intentionally preserved (palette kept) as arbitrary utilities.
const STATUS_BASE =
'inline-flex items-center gap-[6px] text-[11px] px-[8px] py-[3px] rounded-[999px] border';
const SCRIPTS = [
{
id: 'en_conversational',
labelKey: 'demo.script_conversational',
language: 'English',
text: 'Schedule a meeting with Pat for Tuesday at three PM and remind me to bring the quarterly report.',
wav: '/demo_audio/dictation/en_conversational.wav',
},
{
id: 'en_technical',
labelKey: 'demo.script_technical',
language: 'English',
text: 'Patch the WebGPU shader in renderer.tsx, then bump pnpm to nine point fifteen and rerun the Vitest suite.',
wav: '/demo_audio/dictation/en_technical.wav',
},
{
id: 'fr_reservation',
labelKey: 'demo.script_french',
language: 'French',
text: 'Bonjour, je voudrais réserver une table pour deux personnes à vingt heures.',
wav: '/demo_audio/dictation/fr_reservation.wav',
},
];
function isTauri() {
return typeof window !== 'undefined' && '__TAURI_INTERNALS__' in window;
}
export default function DictationDemo({ embedded = false }) {
const { t } = useTranslation();
const [hotkeyState, setHotkeyState] = useState('unknown'); // unknown | registered | verified
const desktop = isTauri();
const { info: shortcut } = useEffectiveDictationShortcut(desktop);
// Transcribing a sample needs a speech-to-text model, and the mandatory-only
// install path ships none. Rendering the cards regardless meant the final
// onboarding step opened with one hard error per card and invited the user
// to press a hotkey that could not work (#1856). Probed for the same reason
// the demo already probes for its sample WAVs below.
const readiness = useDictationReadiness();
const [playingId, setPlayingId] = useState(null);
const [transcripts, setTranscripts] = useState({}); // {scriptId: {state, text, error}}
// null = probing, true/false once the demo assets are confirmed present.
// The sample WAVs are rendered by scripts/build_demos.sh and may be absent
// (e.g. source checkout without a render step). When absent we hide the demo
// rather than show cards that fail on click (#119/#124 follow-up).
const [assetsAvailable, setAssetsAvailable] = useState(null);
const audioRef = useRef(null);
// Probe whether the bundled dictation samples actually exist; hide the whole
// demo if not, mirroring DubbingDemo's missing-manifest behavior.
useEffect(() => {
let cancelled = false;
apiFetch(`${API}${SCRIPTS[0].wav}`, { method: 'HEAD' })
.then(() => {
if (!cancelled) setAssetsAvailable(true);
})
.catch(() => {
if (!cancelled) setAssetsAvailable(false);
});
return () => {
cancelled = true;
};
}, []);
useEffect(() => {
if (!desktop) return;
// `unregistered` is its own state, not a flavour of `unknown`: the OS
// refused the accelerator, usually because another app already holds it
// (the default collides with 1Password Quick Access on macOS). Saying
// "no hotkey registered" there would read as "we have not checked yet",
// when what the user needs to know is that this specific combination is
// taken and they should pick another (#1858).
setHotkeyState((current) => {
if (shortcut.backend === 'unregistered') return 'unregistered';
if (current === 'verified') return current;
return shortcut.backend === 'focused' ? 'unknown' : 'registered';
});
}, [desktop, shortcut.backend]);
// Subscribe to dictation events: the moment the user presses their
// hotkey while this panel is mounted, flip to verified.
useEffect(() => {
if (!isTauri()) return;
let unlistenStart, unlistenStop;
(async () => {
try {
const { listen } = await import('@tauri-apps/api/event');
unlistenStart = await listen('tray-dictate', () => {
setHotkeyState('verified');
});
unlistenStop = await listen('tray-dictate-stop', () => {
setHotkeyState('verified');
});
} catch {
// Tauri event API unavailable — leave state alone.
}
})();
return () => {
try {
unlistenStart && unlistenStart();
} catch {
/* noop */
}
try {
unlistenStop && unlistenStop();
} catch {
/* noop */
}
};
}, []);
const togglePlay = (script) => {
const audio = audioRef.current;
if (!audio) return;
if (playingId === script.id) {
audio.pause();
setPlayingId(null);
return;
}
audio.src = `${API}${script.wav}`;
audio.currentTime = 0;
audio
.play()
.then(() => setPlayingId(script.id))
.catch((e) => {
console.warn('Sample playback failed:', e);
setPlayingId(null);
});
};
// Replay path: fetch the bundled WAV, post it to the transcribe endpoint,
// render what the engine heard. Demonstrates the full dictation pipeline
// without requiring mic permission or a hotkey press.
const replay = async (script) => {
setTranscripts((prev) => ({
...prev,
[script.id]: { state: 'loading', text: '', error: '' },
}));
try {
const wavRes = await apiFetch(`${API}${script.wav}`);
const blob = await wavRes.blob();
const fd = new FormData();
fd.append('audio', blob, `${script.id}.wav`);
const tRes = await apiFetch(`${API}/transcribe`, { method: 'POST', body: fd });
const json = await tRes.json();
setTranscripts((prev) => ({
...prev,
[script.id]: { state: 'ok', text: json.text || '', error: '' },
}));
} catch (e) {
// Typed 409 on a TTS-only install: no ASR model on disk. Render the
// human message + the one-click download CTA instead of the raw
// "409 Conflict: …" string.
const missing = asrMissingPayload(e);
if (missing) toastAsrModelMissing(missing);
setTranscripts((prev) => ({
...prev,
[script.id]: {
state: 'fail',
text: '',
error: missing ? t('asr_missing.message') : e?.message || String(e),
},
}));
}
};
const statusBadge = (() => {
switch (hotkeyState) {
case 'verified':
return (
<span
className={`${STATUS_BASE} border-transparent bg-[rgba(152,151,26,0.12)] text-[#b8bb26]`}
>
<CheckCircle2 size={12} /> {t('demo.dictation_status_ok')}
</span>
);
case 'unregistered':
return (
<span
className={`${STATUS_BASE} border-transparent bg-[rgba(204,36,29,0.12)] text-[#fb4934]`}
>
<AlertTriangle size={12} />{' '}
{t('demo.dictation_status_taken', {
defaultValue:
'Another app already uses this shortcut — pick a different one in Settings.',
})}{' '}
<code className="font-mono text-[10px] px-[4px] py-[1px] bg-[rgba(0,0,0,0.3)] rounded-[3px]">
{shortcut.display}
</code>
</span>
);
case 'registered':
return (
<span
className={`${STATUS_BASE} border-transparent bg-[rgba(215,153,33,0.10)] text-[#fabd2f]`}
>
<Keyboard size={12} /> {t('demo.dictation_status_pending')}{' '}
<code className="font-mono text-[10px] px-[4px] py-[1px] bg-[rgba(0,0,0,0.3)] rounded-[3px]">
{shortcut.display}
</code>
</span>
);
default:
return (
<span
className={`${STATUS_BASE} border-transparent bg-[rgba(204,36,29,0.10)] text-[#fb4934]`}
>
<AlertTriangle size={12} /> {t('demo.dictation_status_warn')}
</span>
);
}
})();
// The hotkey card always has something real to teach (the registered
// shortcut + live press-to-verify) — only the replayable script cards
// depend on the bundled WAVs, which installs don't always ship. Hiding
// the whole panel left the wizard's "Try dictation" act completely
// blank on every such install (#119/#124 follow-up, refined).
// `checking` still shows the cards: the probe resolves in well under a
// second and flashing the install panel first would be worse than a brief
// wait. Only a confirmed-missing model swaps them out.
const asrMissing = readiness.phase === 'missing';
const showScripts = assetsAvailable !== false && !asrMissing;
return (
<section
className={`dictation-demo flex flex-col gap-[10px] ${
embedded
? 'mb-[12px]'
: 'p-[14px] rounded-[10px] border border-border bg-[rgba(255,255,255,0.02)] mb-[16px]'
}`}
>
<header className="flex items-center justify-between gap-[12px] flex-wrap">
<h3 className="inline-flex items-center gap-[6px] m-0 text-[13px] font-bold text-fg">
<Mic size={14} /> {t('demo.dictation_title')}
</h3>
{statusBadge}
</header>
<p className="m-0 text-[11px] leading-[1.45] text-fg-muted">
{showScripts
? t('demo.dictation_lede')
: t(
'demo.dictation_lede_hotkey_only',
'Hold the shortcut above anywhere on your desktop, speak, release — the text lands in whatever app has focus. Press it now to verify it works.',
)}
</p>
<audio ref={audioRef} onEnded={() => setPlayingId(null)} preload="none" />
{asrMissing && (
<div className="flex flex-col gap-2 rounded-[8px] border border-border bg-[rgba(0,0,0,0.15)] px-[12px] py-[10px]">
<p className="m-0 text-[11px] leading-[1.45] text-fg-muted">{t('asr_missing.message')}</p>
<AsrModelChooser
fallback={readiness.missing?.recommended}
onInstall={readiness.install}
onSelect={readiness.select}
disabled={readiness.phase === 'installing'}
/>
</div>
)}
{showScripts && (
<div className="dictation-demo__scripts grid grid-cols-[repeat(auto-fill,minmax(260px,1fr))] gap-[10px]">
{SCRIPTS.map((s) => {
const isPlaying = playingId === s.id;
const tx = transcripts[s.id] || {};
return (
<div
key={s.id}
className="flex flex-col gap-[6px] px-[12px] py-[10px] rounded-[8px] border border-border bg-[rgba(0,0,0,0.15)]"
>
<div className="flex items-center gap-[8px] text-[10px] text-fg-muted">
<span className="font-mono text-[9px] px-[5px] py-[1px] rounded-sm bg-[rgba(255,255,255,0.06)] uppercase tracking-[0.04em]">
{s.language}
</span>
<span className="font-semibold text-[11px] text-fg normal-case">
{t(s.labelKey)}
</span>
</div>
<blockquote className="m-0 px-[8px] py-[6px] text-[11.5px] leading-[1.45] border-l-2 border-l-transparent bg-[rgba(255,255,255,0.02)] text-fg italic">
{s.text}
</blockquote>
<div className="flex gap-[6px] mt-[2px]">
<Button
size="sm"
variant="subtle"
onClick={() => togglePlay(s)}
leading={isPlaying ? <Pause size={11} /> : <Play size={11} />}
aria-label={
isPlaying
? t('demo.aria_pause', { label: t(s.labelKey) })
: t('demo.aria_hear', { label: t(s.labelKey) })
}
>
{isPlaying ? t('demo.dictation_stop') : t('demo.dictation_hear')}
</Button>
<Button
size="sm"
variant="subtle"
onClick={() => replay(s)}
loading={tx.state === 'loading'}
leading={tx.state !== 'loading' && <Mic size={11} />}
aria-label={t('demo.aria_replay', { label: t(s.labelKey) })}
>
{tx.state === 'loading'
? t('demo.dictation_transcribing')
: t('demo.dictation_replay')}
</Button>
</div>
{tx.state === 'ok' && (
<div className="flex items-start gap-[6px] text-[11px] px-[8px] py-[6px] rounded-lg leading-[1.4] text-[#b8bb26] bg-[rgba(152,151,26,0.08)] border border-transparent">
<CheckCircle2 size={11} /> <em className="not-italic">{tx.text}</em>
</div>
)}
{tx.state === 'fail' && (
<div className="flex items-start gap-[6px] text-[11px] px-[8px] py-[6px] rounded-lg leading-[1.4] text-[#fb4934] bg-[rgba(204,36,29,0.08)] border border-transparent">
<AlertTriangle size={11} /> {tx.error}
</div>
)}
</div>
);
})}
</div>
)}
</section>
);
}
@@ -1,129 +0,0 @@
import React, { useEffect, useState } from 'react';
import { Check, Download, Loader } from 'lucide-react';
import { useQuery } from '@tanstack/react-query';
import { useTranslation } from 'react-i18next';
import { apiJson } from '../api/client';
import { useInstallModel } from '../api/hooks';
import { useAppStore } from '../store';
function fmtSize(sizeGb) {
if (sizeGb == null) return '';
if (sizeGb < 1) return `${Math.round(sizeGb * 1000)} MB`;
return `${sizeGb.toFixed(sizeGb < 10 ? 1 : 0)} GB`;
}
/**
* The sherpa-onnx dictation model list, nested under the "Sherpa-ONNX
* dictation" row of the Transcription engine picker. The engine row switches
* the *engine*; this switches which of the seven catalogue models that engine
* (and the live-dictation hotkey) loads — the same `dictation.model_id` pref
* the Settings → Voice panel writes, so both surfaces always agree.
*
* Picking a model that isn't downloaded yet persists the choice and starts
* the download in one click (mirrors VoicePanel.onPick): the user gets the
* model the moment it lands rather than a second "now install it" step.
*/
export default function DictationModelPicker({ embedded = false }) {
const { t } = useTranslation();
const modelId = useAppStore((s) => s.dictationModelId);
const setModelId = useAppStore((s) => s.setDictationModelId);
const loadPrefs = useAppStore((s) => s.loadDictationPrefs);
const dictationLoaded = useAppStore((s) => s.dictationLoaded);
const installMutation = useInstallModel();
const [installing, setInstalling] = useState(() => new Set());
useEffect(() => {
if (!dictationLoaded) loadPrefs();
}, [dictationLoaded, loadPrefs]);
const { data, refetch } = useQuery({
queryKey: ['dictation-models'],
queryFn: () => apiJson('/dictation/models'),
staleTime: 10_000,
retry: false,
// While a download runs, poll so the "installed" state flips without a
// reopen — the quick menu has no SSE progress stream of its own.
refetchInterval: installing.size > 0 ? 2_000 : false,
});
const models = Array.isArray(data?.models) ? data.models : [];
if (models.length === 0) return null;
const selectedId = models.some((m) => m.id === modelId)
? modelId
: (models.find((m) => m.recommended) || models[0]).id;
const pick = async (model) => {
if (model.id !== selectedId) setModelId(model.id);
if (model.installed || installing.has(model.repo_id)) return;
setInstalling((prev) => new Set(prev).add(model.repo_id));
try {
await installMutation.mutateAsync(model.repo_id);
await refetch();
} catch {
// The install surface (Settings → Voice / Model Catalogue) reports the
// failure with full detail; here the row simply returns to "download".
} finally {
setInstalling((prev) => {
const next = new Set(prev);
next.delete(model.repo_id);
return next;
});
}
};
return (
<div
role="group"
aria-label={t('engines.dictation_model')}
title={t('engines.dictation_model_hint')}
data-testid="dictation-model-picker"
className={`ml-[20px] flex flex-col border-l border-transparent pl-1 ${embedded ? 'mb-2' : 'mb-1'}`}
>
<p className="m-0 px-2 pb-[2px] pt-[2px] text-[10px] font-semibold uppercase tracking-[0.06em] text-[var(--chrome-fg-muted)]">
{t('engines.dictation_model')}
</p>
{models.map((m) => {
const isSel = m.id === selectedId;
const busy = installing.has(m.repo_id);
const desc = t(`voicePanel.model_desc.${m.id}`, { defaultValue: m.languages || '' });
return (
<button
key={m.id}
type="button"
onClick={() => pick(m)}
disabled={busy}
aria-pressed={isSel}
data-testid={`dictation-model-${m.id}`}
title={m.installed ? desc : `${desc} — ${t('engines.dictation_not_installed')}`}
className={`flex w-full items-center gap-2 rounded-md border-0 px-2 py-[5px] text-left text-xs text-[color:var(--chrome-fg)] hover:bg-[var(--chrome-hover-bg)] disabled:cursor-default ${isSel ? 'bg-[var(--chrome-accent-bg)]' : 'bg-transparent'}`}
>
<span className="w-[12px] shrink-0">
{isSel && <Check size={12} aria-label={t('engines.active')} />}
</span>
<span className="min-w-0 flex-1 truncate">
<span className="font-medium">{m.label}</span>
<span className="ml-[6px] text-[10px] text-[var(--chrome-fg-muted)]">
{m.tag === 'streaming'
? t('voicePanel.badge_streaming')
: t('voicePanel.badge_offline')}
{m.recommended && ` · ${t('voicePanel.badge_recommended')}`}
</span>
</span>
<span className="flex shrink-0 items-center gap-1 text-[10px] tabular-nums text-[color:var(--chrome-fg-muted)]">
{fmtSize(m.size_gb)}
{busy ? (
<Loader
size={12}
className="animate-spin"
aria-label={t('voicePanel.downloading')}
/>
) : m.installed ? null : (
<Download size={12} aria-hidden="true" />
)}
</span>
</button>
);
})}
</div>
);
}
@@ -1,169 +0,0 @@
import React from 'react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
vi.mock('react-hot-toast', () => ({ toast: { success: vi.fn(), error: vi.fn() } }));
const { listEngines, selectEngine, listLoadedModels, apiJson, apiPost, installMutate } = vi.hoisted(
() => ({
listEngines: vi.fn(),
selectEngine: vi.fn(),
listLoadedModels: vi.fn(),
apiJson: vi.fn(),
apiPost: vi.fn(),
installMutate: vi.fn(),
}),
);
vi.mock('../api/engines', () => ({ listEngines, selectEngine }));
vi.mock('../api/system', () => ({ listLoadedModels }));
vi.mock('../api/client', async (importOriginal) => ({
...(await importOriginal()),
apiJson: (...a) => apiJson(...a),
apiPost: (...a) => apiPost(...a),
}));
vi.mock('../api/hooks', async (importOriginal) => ({
...(await importOriginal()),
useInstallModel: () => ({ mutateAsync: installMutate }),
}));
import EngineQuickSwitch from './EngineQuickSwitch';
import { useAppStore } from '../store';
const ASR_INVENTORY = {
tts: {
active: 'omnivoice',
backends: [{ id: 'omnivoice', display_name: 'OmniVoice', available: true }],
},
asr: {
active: 'whisperx',
backends: [
{ id: 'whisperx', display_name: 'WhisperX (faster-whisper + wav2vec2)', available: true },
{
id: 'sherpa-onnx-asr',
display_name: 'Sherpa-ONNX dictation (live, CPU — streaming + offline)',
available: true,
},
{ id: 'nemo-parakeet', display_name: 'Parakeet TDT (NVIDIA NeMo)', available: false },
],
},
llm: { active: 'off', backends: [] },
};
const MODELS = {
models: [
{
id: 'sherpa-whisper-tiny',
repo_id: 'csukuangfj/sherpa-onnx-whisper-tiny',
label: 'Whisper Tiny',
tag: 'offline',
recommended: true,
size_gb: 0.104,
languages: '90+ languages',
installed: true,
},
{
id: 'sherpa-parakeet-tdt-v3',
repo_id: 'csukuangfj/sherpa-onnx-nemo-parakeet-tdt-0.6b-v3-int8',
label: 'Parakeet TDT v3',
tag: 'offline',
recommended: false,
size_gb: 0.67,
languages: '25 European languages',
installed: true,
},
{
id: 'sherpa-zipformer-en-20m',
repo_id: 'csukuangfj/sherpa-onnx-streaming-zipformer-en-20M-2023-02-17',
label: 'Zipformer Streaming EN',
tag: 'streaming',
recommended: false,
size_gb: 0.044,
languages: 'English',
installed: false,
},
],
default_model_id: 'sherpa-whisper-tiny',
};
function renderSwitch(props = {}) {
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
return render(
<QueryClientProvider client={client}>
<EngineQuickSwitch family="asr" embedded {...props} />
</QueryClientProvider>,
);
}
describe('EngineQuickSwitch → dictation model picker', () => {
beforeEach(() => {
vi.clearAllMocks();
listEngines.mockResolvedValue(ASR_INVENTORY);
listLoadedModels.mockResolvedValue({ models: [] });
apiJson.mockImplementation(async (path) => {
if (path === '/dictation/models') return MODELS;
if (path === '/dictation/prefs')
return { enabled: true, mode: 'toggle', model_id: 'sherpa-whisper-tiny' };
throw new Error(`unexpected GET ${path}`);
});
apiPost.mockImplementation(async (path, body) => {
if (path === '/dictation/prefs')
return { enabled: true, mode: 'toggle', model_id: body.model_id };
throw new Error(`unexpected POST ${path}`);
});
installMutate.mockResolvedValue({});
useAppStore.setState({ dictationModelId: 'sherpa-whisper-tiny', dictationLoaded: true });
});
it('lists the sherpa dictation models under the Sherpa-ONNX engine row only', async () => {
renderSwitch();
const picker = await screen.findByTestId('dictation-model-picker');
expect(picker).toHaveTextContent('Whisper Tiny');
expect(picker).toHaveTextContent('Parakeet TDT v3');
expect(picker).toHaveTextContent('Zipformer Streaming EN');
// Nested directly after the Sherpa row, not after WhisperX.
const sherpaRow = screen.getByText('Sherpa-ONNX dictation').closest('button');
expect(sherpaRow.nextElementSibling).toBe(picker);
// Engine rows themselves are untouched.
expect(screen.getByText('WhisperX').closest('button')).toBeInTheDocument();
expect(screen.getByTestId('dictation-model-sherpa-whisper-tiny')).toHaveAttribute(
'aria-pressed',
'true',
);
});
it('does not render the picker for a family without the Sherpa engine', async () => {
renderSwitch({ family: 'tts' });
expect(await screen.findByText('OmniVoice')).toBeInTheDocument();
expect(screen.queryByTestId('dictation-model-picker')).not.toBeInTheDocument();
});
it('selecting an installed model writes dictation.model_id and does not download', async () => {
renderSwitch();
fireEvent.click(await screen.findByTestId('dictation-model-sherpa-parakeet-tdt-v3'));
await waitFor(() =>
expect(apiPost).toHaveBeenCalledWith('/dictation/prefs', {
model_id: 'sherpa-parakeet-tdt-v3',
}),
);
expect(installMutate).not.toHaveBeenCalled();
expect(useAppStore.getState().dictationModelId).toBe('sherpa-parakeet-tdt-v3');
expect(screen.getByTestId('dictation-model-sherpa-parakeet-tdt-v3')).toHaveAttribute(
'aria-pressed',
'true',
);
});
it('selecting a model that is not installed persists the choice and starts the download', async () => {
renderSwitch();
fireEvent.click(await screen.findByTestId('dictation-model-sherpa-zipformer-en-20m'));
await waitFor(() =>
expect(installMutate).toHaveBeenCalledWith(
'csukuangfj/sherpa-onnx-streaming-zipformer-en-20M-2023-02-17',
),
);
expect(apiPost).toHaveBeenCalledWith('/dictation/prefs', {
model_id: 'sherpa-zipformer-en-20m',
});
});
});
@@ -1,104 +0,0 @@
import React from 'react';
import { useTranslation } from 'react-i18next';
import { openExternal } from '../api/external';
import { KOFI_URL, PAYPAL_URL } from '../utils/donateLinks';
import { DONATE_LINE_COUNT } from '../utils/donationMoments';
/**
* DonateMomentPopover — the friendly "Clippy-like" speech bubble that
* LogsFooter anchors above the donate heart when a donation moment fires
* (see utils/donationMoments.js for the strict eligibility gates).
*
* Deliberately NO backdrop and NO focus trap: it's an aside, not a modal —
* the user can keep working and it auto-dismisses on its own. Bounce-in
* animation collapses to a plain fade under `prefers-reduced-motion`.
* Chrome palette throughout so it reads as part of the footer.
*/
/** How long the popover lingers before quietly dismissing itself. */
export const DONATE_POPOVER_AUTO_DISMISS_MS = 15_000;
// Small pill CTA shared by the Ko-fi / PayPal buttons.
const CTA_BTN =
'inline-flex items-center gap-[5px] px-[10px] h-[24px] rounded-[5px] cursor-pointer ' +
'border border-solid border-transparent text-[11px] font-semibold [font-family:inherit] ' +
'[background:var(--chrome-accent-bg)] [color:var(--chrome-fg)] transition-colors ' +
'hover:[border-color:var(--chrome-accent-border)] hover:[color:var(--chrome-accent)]';
const QUIET_BTN =
'bg-transparent border-0 cursor-pointer p-0 text-[11px] [font-family:inherit] ' +
'[color:var(--chrome-fg-muted)] hover:[color:var(--chrome-fg)] transition-colors';
export default function DonateMomentPopover({ line = 0, onLater, onOptOut }) {
const { t } = useTranslation();
// Rotate through the friendly lines; clamp so a stale/oversized index from
// the event detail can never resolve to a missing i18n key.
const lineKey = `footer_donate.line_${(Math.abs(line | 0) % DONATE_LINE_COUNT) + 1}`;
return (
<div
role="status"
aria-label={t('footer_donate.aria')}
data-testid="donate-moment-popover"
className={
'absolute bottom-[calc(100%+10px)] right-0 z-[60] w-[272px] p-[12px] rounded-[10px] ' +
'flex flex-col gap-[10px] select-none [background:var(--chrome-bg,#1d2021)] ' +
'border border-solid [border-color:var(--chrome-border,rgba(255,255,255,0.08))] ' +
'shadow-[0_8px_24px_rgba(0,0,0,0.45)] ' +
'[animation:donate-pop-in_0.45s_cubic-bezier(0.34,1.56,0.64,1)_both] ' +
'motion-reduce:[animation:donate-fade-in_0.2s_ease-out_both]'
}
>
{/* Speech-bubble tail, pointing down at the heart. */}
<span
aria-hidden="true"
className={
'absolute -bottom-[6px] right-[12px] w-[10px] h-[10px] rotate-45 ' +
'[background:var(--chrome-bg,#1d2021)] ' +
'[border-right:1px_solid_var(--chrome-border,rgba(255,255,255,0.08))] ' +
'[border-bottom:1px_solid_var(--chrome-border,rgba(255,255,255,0.08))]'
}
/>
<p className="m-0 text-[11.5px] leading-[1.55] [color:var(--chrome-fg)]">{t(lineKey)}</p>
<div className="flex items-center gap-[6px]">
<button
type="button"
className={CTA_BTN}
aria-label={t('footer_donate.kofi_aria')}
onClick={() => {
openExternal(KOFI_URL);
onLater();
}}
>
<span aria-hidden="true">☕</span> {t('footer_donate.kofi')}
</button>
<button
type="button"
className={CTA_BTN}
aria-label={t('footer_donate.paypal_aria')}
onClick={() => {
openExternal(PAYPAL_URL);
onLater();
}}
>
<span aria-hidden="true">💳</span> {t('footer_donate.paypal')}
</button>
<span className="flex-1" />
<button type="button" className={QUIET_BTN} onClick={onLater}>
{t('footer_donate.later')}
</button>
</div>
<button
type="button"
onClick={onOptOut}
className={
'self-end bg-transparent border-0 cursor-pointer p-0 text-[10px] [font-family:inherit] ' +
'[color:var(--chrome-fg-dim,var(--chrome-fg-muted))] hover:underline ' +
'hover:[color:var(--chrome-fg-muted)] transition-colors'
}
>
{t('footer_donate.dont_ask')}
</button>
</div>
);
}
@@ -1,679 +0,0 @@
import React, { memo, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import {
CheckCircle,
AlertCircle,
Circle,
Trash2,
Loader,
Headphones,
Scissors,
Merge,
MoreHorizontal,
Minus,
Plus,
Sparkles,
Volume2,
BookOpen,
} from 'lucide-react';
import { formatTime } from '../utils/format';
import { LANG_CODES } from '../utils/languages';
import { MIN_SEG_DUR } from '../utils/timeline';
import { Menu } from '../ui';
import VoiceSelector from './VoiceSelector';
const CHAR_BUDGET_RATIO = 1.3;
const SENTENCE_END = /[.!?。!?]/;
const TIME_EPSILON = 1e-9;
function rowClass(isActive, isDone, selected, isPlaying, timelineSelected) {
return `segment-row${isActive ? ' segment-active' : ''}${isDone ? ' segment-done' : ''}${selected ? ' segment-selected' : ''}${isPlaying ? ' segment-playing' : ''}${timelineSelected ? ' segment-timeline-selected' : ''}`;
}
// Best split point for the Scissors menu when the user hasn't placed a cursor —
// prefer the sentence boundary nearest the middle, then a whitespace boundary,
// then the literal midpoint as a last resort.
function bestSplitPoint(text) {
const mid = Math.floor(text.length / 2);
let best = -1,
bestDist = Infinity;
for (let i = 0; i < text.length; i++) {
if (SENTENCE_END.test(text[i])) {
const d = Math.abs(i + 1 - mid);
if (d < bestDist) {
best = i + 1;
bestDist = d;
}
}
}
if (best > 0 && best < text.length) return best;
for (let r = 0; r < text.length; r++) {
for (const i of [mid - r, mid + r]) {
if (i > 0 && i < text.length && /\s/.test(text[i])) return i;
}
}
return mid;
}
// Accept "m:ss[.s]" or raw seconds; return null on garbage so the field can revert.
function parseTime(s) {
const m = /^\s*(\d+):([0-5]?\d(?:\.\d+)?)\s*$/.exec(s);
if (m) return parseInt(m[1], 10) * 60 + parseFloat(m[2]);
if (String(s).includes(':') || !/^\s*\d+(?:\.\d+)?\s*$/.test(s)) return null;
const n = Number(s);
return Number.isFinite(n) ? n : null;
}
function DubSegmentRow({
seg,
idx,
style,
ariaAttributes,
disabled,
isActive,
isDone,
isPlaying,
previewLoading,
selected,
profiles,
speakerClones,
onEditField,
onDelete,
onRestore,
onPreview,
onSelect,
onSplit,
onMerge,
onInsert,
onMoveResize,
canMerge,
canMergePrev,
onDirect,
onSeek,
timelineSelected,
hasOverlap,
liveEnabled,
liveActive,
onLiveEdit,
onLiveToggle,
}) {
const { t } = useTranslation();
const textInputRef = useRef(null);
// Remember where the caret was inside the text field even after it loses
// focus — Radix's menu trigger steals focus, so by the time the Scissors
// item fires, selectionStart on the input would otherwise read as null.
const lastCursorRef = useRef(null);
const speakerOptions = speakerClones ? Object.keys(speakerClones) : [];
const speakerListId = `seg-speakers-${seg.id}`;
// Truthful per-segment fit badge. The backend's new fit_status object is
// the source of truth — describes exactly what the mix loop did:
// "fits" → audio fit cleanly inside the slot (or its gap).
// "overflows" → concise mode hard-trimmed +Ns past slot; user
// should shorten the text for a cleaner result.
// "video_stretched" → stretch_video mode lengthened the source clip by
// the stretch ratio to fit natural-rate audio.
// We fall back to the legacy sync_ratio bucketing only when fit_status is
// missing (older jobs / partial-regen with no done event yet) — and even
// then we now display the *raw* ratio so it stops claiming 100% when the
// audio was actually compressed at synthesis time.
const fitStatus = seg.fit_status && typeof seg.fit_status === 'object' ? seg.fit_status : null;
let fitBadge = null;
if (fitStatus) {
if (fitStatus.status === 'fits') {
fitBadge = {
color: '#b8bb26',
Icon: CheckCircle,
label: t('segment.fit_fits'),
title: t('segment.fit_fits_title'),
};
} else if (fitStatus.status === 'overflows') {
const over = fitStatus.overflow_s || 0;
fitBadge = {
color: over > 0.5 ? '#fb4934' : '#fabd2f',
Icon: AlertCircle,
label: t('segment.fit_overflows', { seconds: over.toFixed(2) }),
title: t('segment.fit_overflows_title', { seconds: over.toFixed(2) }),
};
} else if (fitStatus.status === 'video_stretched') {
const r = fitStatus.stretch_ratio || 1.0;
fitBadge = {
color: r > 1.18 ? '#fb4934' : r > 1.05 ? '#fabd2f' : '#83a598',
Icon: Circle,
label: t('segment.fit_stretched', { ratio: r.toFixed(2) }),
title: t('segment.fit_stretched_title', { ratio: r.toFixed(2) }),
};
} else if (fitStatus.status === 'audio_slowed') {
// Underrun fill: the line ran shorter than its slot and was slowed
// (pitch-preserved) toward it so speech covers the on-screen mouth time.
const r = fitStatus.audio_rate || 1.0;
fitBadge = {
color: '#83a598',
Icon: Circle,
label: t('segment.fit_slowed', { ratio: r.toFixed(2) }),
title: t('segment.fit_slowed_title', { ratio: r.toFixed(2) }),
};
}
} else if (seg.sync_ratio !== undefined) {
const r = seg.sync_ratio;
if (r > 1.25) {
fitBadge = {
color: '#fb4934',
Icon: AlertCircle,
label: `${Math.round(r * 100)}%`,
title: t('segment.fit_compressed_title', { pct: Math.round(r * 100) }),
};
} else if (r >= 0.95 && r <= 1.05) {
fitBadge = {
color: '#b8bb26',
Icon: CheckCircle,
label: t('segment.fit_fits'),
title: t('segment.fit_audio_title'),
};
} else {
fitBadge = {
color: '#fabd2f',
Icon: Circle,
label: `${Math.round(r * 100)}%`,
title: t('segment.fit_ratio_title', { pct: Math.round(r * 100) }),
};
}
}
const overBudget =
seg.text_original && seg.text.length > Math.ceil(seg.text_original.length * CHAR_BUDGET_RATIO);
// Both time fields commit through the SAME path the timeline drag handles
// use (segmentMoveResize → commitMoveResize), so typing a time and dragging
// its edge produce identical results — including the speed recompute that
// keeps the dubbed audio inside a resized slot. The numeric start field used
// to write `start` raw and skip that compensation, so the two UIs disagreed.
// The fields show tenths, so leaving one untouched must not commit that
// rounding; only a field typed into since it was focused commits.
const editedTimeRef = useRef({});
const timeKeyDown = (edge) => (e) => {
if (e.key === 'Enter') e.target.blur();
if (e.key === 'Escape') {
editedTimeRef.current[edge] = false;
e.target.value = formatTime(seg[edge]);
e.target.blur();
}
};
const commitTime = (edge) => (e) => {
const current = seg[edge];
if (!editedTimeRef.current[edge]) return;
editedTimeRef.current[edge] = false;
const v = parseTime(e.target.value);
const inRange =
edge === 'start'
? v >= 0 && v <= seg.end - MIN_SEG_DUR + TIME_EPSILON
: v >= seg.start + MIN_SEG_DUR - TIME_EPSILON;
if (v == null || !inRange) {
e.target.value = formatTime(current);
return;
}
if (Math.abs(v - current) <= 1e-3) {
e.target.value = formatTime(current);
return;
}
const next = +v.toFixed(3);
onMoveResize(seg.id, {
start: edge === 'start' ? next : seg.start,
end: edge === 'end' ? next : seg.end,
});
};
const nudgeTime = (edge, delta) => {
const current = seg[edge];
const limit = edge === 'start' ? seg.end - MIN_SEG_DUR : seg.start + MIN_SEG_DUR;
const next = +(
edge === 'start'
? Math.max(0, Math.min(limit, current + delta))
: Math.max(limit, current + delta)
).toFixed(3);
if (Math.abs(next - current) <= 1e-3) return;
onMoveResize(seg.id, {
start: edge === 'start' ? next : seg.start,
end: edge === 'end' ? next : seg.end,
});
};
const handleTextKeyDown = (e) => {
if ((e.ctrlKey || e.metaKey) && (e.key === 'd' || e.key === 'D')) {
e.preventDefault();
const pos = e.target.selectionStart ?? seg.text.length;
onSplit(seg.id, pos);
} else if ((e.ctrlKey || e.metaKey) && (e.key === 'm' || e.key === 'M')) {
e.preventDefault();
if (e.shiftKey) {
if (canMergePrev) onMerge(seg.id, 'prev');
} else if (canMerge) onMerge(seg.id, 'next');
}
};
const captureCursor = (e) => {
const pos = e.target.selectionStart;
if (pos != null) lastCursorRef.current = pos;
};
// Row click → seek the player to this segment. We don't fire when the click
// originates in an interactive element (input, button, the actions cluster)
// so per-field editing keeps working.
const handleRowClick = (e) => {
if (!onSeek) return;
if (e.target.closest('input, button, select, textarea, label, [data-noseek]')) return;
onSeek(seg.start);
};
return (
<div
{...ariaAttributes}
style={style}
className={rowClass(isActive, isDone, selected, isPlaying, timelineSelected)}
onClick={handleRowClick}
>
<input
type="checkbox"
checked={!!selected}
onChange={(e) => onSelect(seg.id, idx, e.nativeEvent.shiftKey)}
onClick={(e) => onSelect(seg.id, idx, e.shiftKey)}
disabled={disabled}
className="seg-select cursor-pointer justify-self-center"
title={t('segment.select_title')}
/>
<span className="seg-text-col">
<span className="flex items-center gap-[2px] min-w-0">
<textarea
ref={textInputRef}
rows={2}
className="input-base segment-input"
value={seg.text}
onChange={(e) => {
onEditField(seg.id, 'text', e.target.value);
// Live dub preview (opt-in): debounce-stream the edited line.
if (liveEnabled) onLiveEdit?.(seg, e.target.value);
}}
onKeyDown={handleTextKeyDown}
onKeyUp={captureCursor}
onSelect={captureCursor}
onClick={(e) => {
e.stopPropagation();
captureCursor(e);
}}
disabled={disabled}
title={
seg.translate_error
? t('segment.translate_error_title', { error: seg.translate_error })
: seg.translate_degraded
? t('segment.translate_degraded_title', { reason: seg.translate_degraded })
: overBudget
? t('segment.budget_title', {
pct: Math.round((seg.text.length / seg.text_original.length) * 100),
})
: t('segment.text_title')
}
style={
overBudget
? { background: 'rgba(250,189,47,0.10)' }
: seg.translate_error
? { background: 'rgba(251,73,52,0.10)' }
: undefined
}
/>
{liveEnabled && (
// Tiny live-preview speaker: pulses while this line streams;
// click streams the current text now / stops the active stream.
<button
type="button"
className={`seg-live-btn${liveActive ? ' seg-live-btn--on' : ''}`}
disabled={disabled}
title={t(liveActive ? 'segment.live_stop_title' : 'segment.live_play_title')}
onClick={(e) => {
e.stopPropagation();
onLiveToggle?.(seg);
}}
>
<Volume2 size={14} />
</button>
)}
</span>
{seg.text_original && seg.text_original !== seg.text && (
<span className="seg-original flex items-center gap-[6px] px-[2px] overflow-hidden">
<span className="opacity-80 uppercase font-semibold text-[0.48rem] text-[#7c6f64]">
{t('segment.orig_label')}
</span>
<span
className="flex-1 whitespace-nowrap overflow-hidden text-ellipsis"
title={seg.text_original}
>
{seg.text_original}
</span>
{overBudget && (
<span className="text-[#fabd2f] text-[0.48rem]">
{Math.round((seg.text.length / seg.text_original.length) * 100)}%
</span>
)}
<button
onClick={() => onRestore(seg.id)}
disabled={disabled}
title={t('segment.restore_title')}
className="bg-transparent border-none text-[#83a598] cursor-pointer p-0 text-[0.52rem]"
>
↺
</button>
</span>
)}
</span>
<span className="segment-time flex flex-col min-w-0 overflow-hidden tabular-nums">
{['start', 'end'].map((edge) => (
<span className="seg-time-stepper" key={`${edge}-${seg.id}-${seg[edge]}`}>
<button
type="button"
onClick={() => nudgeTime(edge, -0.1)}
disabled={disabled || (edge === 'start' && seg.start <= 0)}
aria-label={t(`segment.time_nudge_${edge}_earlier`)}
>
<Minus size={10} />
</button>
<input
type="text"
className="seg-time-input"
defaultValue={formatTime(seg[edge])}
disabled={disabled}
title={t(
edge === 'start' ? 'segment.time_edit_title' : 'segment.time_edit_end_title',
)}
onClick={(e) => e.stopPropagation()}
onFocus={() => {
editedTimeRef.current[edge] = false;
}}
onChange={() => {
editedTimeRef.current[edge] = true;
}}
onKeyDown={timeKeyDown(edge)}
onBlur={commitTime(edge)}
/>
<button
type="button"
onClick={() => nudgeTime(edge, 0.1)}
disabled={disabled}
aria-label={t(`segment.time_nudge_${edge}_later`)}
>
<Plus size={10} />
</button>
</span>
))}
{seg.speed && seg.speed !== 1.0 && (
<span
className="text-[0.52rem] ml-[1px]"
style={{ color: seg.speed > 1 ? '#d3869b' : '#8ec07c' }}
>
{seg.speed.toFixed(2)}x
</span>
)}
{hasOverlap && (
<span className="seg-overlap-warning" title={t('timeline.overlap_warning')}>
<AlertCircle size={14} /> {t('timeline.overlap_warning')}
</span>
)}
{fitBadge && (
<span className="seg-status" style={{ color: fitBadge.color }} title={fitBadge.title}>
<fitBadge.Icon size={8} /> {fitBadge.label}
</span>
)}
{seg.qc_flagged && (
// Wave 3.3: second-pass ASR heard something different from the
// target text for this line — worth a re-listen / re-dub.
<span
className="seg-status"
style={{ color: '#fb4934' }}
title={t('segment.qc_verify_title', { heard: seg.qc_recognized || '' })}
>
<AlertCircle size={8} /> {t('segment.qc_verify')}
</span>
)}
{seg.rate_ratio != null && Math.abs(seg.rate_ratio - 1.0) > 0.03 && (
<span
className="seg-status tabular-nums"
style={{
color:
seg.rate_ratio > 1.15 ? '#fb4934' : seg.rate_ratio < 0.85 ? '#83a598' : '#a89984',
}}
title={t('segment.rate_title', {
ratio: seg.rate_ratio.toFixed(2),
error: seg.rate_error || '',
})}
>
<BookOpen size={12} aria-hidden="true" /> {seg.rate_ratio.toFixed(2)}×
</span>
)}
{/* Pre-synthesis duration plan (backend duration_planner): warn about
tight/impossible segments BEFORE GPU time is spent. Informational
only — generation is never blocked. */}
{seg.plan && (seg.plan.status === 'tight' || seg.plan.status === 'impossible') && (
<span
className="seg-status"
style={{ color: seg.plan.status === 'impossible' ? '#fb4934' : '#fabd2f' }}
title={t(
seg.plan.status === 'impossible'
? 'segment.plan_impossible_title'
: 'segment.plan_tight_title',
{
est: (seg.plan.est_dur_s || 0).toFixed(1),
avail: (seg.plan.available_s || 0).toFixed(1),
seconds: (seg.plan.est_overrun_s || 0).toFixed(1),
},
)}
>
<AlertCircle size={8} />{' '}
{seg.plan.status === 'impossible'
? t('segment.plan_impossible', {
seconds: (seg.plan.est_overrun_s || 0).toFixed(1),
})
: t('segment.plan_tight')}
</span>
)}
{seg.plan && seg.plan.suggested_text && seg.plan.suggested_text !== seg.text && (
<button
onClick={() => onEditField(seg.id, 'text', seg.plan.suggested_text)}
disabled={disabled}
title={t('segment.plan_apply_title', { text: seg.plan.suggested_text })}
className="seg-plan-apply"
>
<Scissors size={12} aria-hidden="true" /> {t('segment.plan_apply')}
</button>
)}
</span>
<div className="seg-controls">
<input
className="seg-speaker-input"
value={seg.speaker_id || ''}
onChange={(e) => onEditField(seg.id, 'speaker_id', e.target.value)}
onClick={(e) => e.stopPropagation()}
disabled={disabled}
list={speakerOptions.length ? speakerListId : undefined}
placeholder={speakerOptions.length ? t('segment.speaker_pick') : ''}
title={
speakerOptions.length
? t('segment.speaker_title_detected')
: t('segment.speaker_title_custom')
}
/>
{speakerOptions.length > 0 && (
<datalist id={speakerListId}>
{speakerOptions.map((spk) => (
<option key={spk} value={spk} />
))}
</datalist>
)}
<select
className="input-base seg-lang-select"
aria-label={t('segment.lang')}
value={seg.target_lang || ''}
disabled={disabled}
onChange={(e) => onEditField(seg.id, 'target_lang', e.target.value)}
>
<option value="">{t('segment.lang_default')}</option>
{LANG_CODES.map((lc) => (
<option key={lc.code} value={lc.code}>
{lc.code.toUpperCase()}
</option>
))}
</select>
{/* Shared gallery-enabled picker (#1220). `data-noseek` + stopPropagation
keep a voice pick from also seeking the player (handleRowClick). The
dropdown portals to <body> so it isn't clipped by the react-window
virtualized row's overflow. The from-video `auto:<slug>` options come
through `speakerClones`; the legacy hardcoded design PRESETS group is
intentionally dropped — the Gallery supersedes it (see #1220). */}
<span className="seg-voice-col min-w-0" data-noseek onClick={(e) => e.stopPropagation()}>
<VoiceSelector
value={seg.profile_id || ''}
onChange={(v) => onEditField(seg.id, 'profile_id', v)}
profiles={profiles}
speakerClones={speakerClones}
disabled={disabled}
size="sm"
menuPortal
buttonClassName="input-base seg-profile-select"
defaultLabel={t('segment.voice_default')}
/>
</span>
<input
type="range"
min="0"
max="200"
value={Math.round((seg.gain ?? 1.0) * 100)}
title={`${Math.round((seg.gain ?? 1.0) * 100)}%`}
aria-label={t('segment.vol_title')}
disabled={disabled}
onChange={(e) => onEditField(seg.id, 'gain', Number(e.target.value) / 100)}
className="seg-gain-slider"
style={{
accentColor:
(seg.gain ?? 1.0) > 1.2
? 'var(--color-danger)'
: (seg.gain ?? 1.0) < 0.5
? 'var(--color-info)'
: 'var(--color-fg-muted)',
}}
/>
<div className="seg-actions">
<button
className="segment-play"
disabled={disabled}
title={t('segment.preview_title')}
onClick={(e) => onPreview(seg, e)}
>
{previewLoading ? <Loader className="spinner" size={14} /> : <Headphones size={14} />}
</button>
<Menu
placement="bottom-end"
disabled={disabled}
items={[
{
id: 'direct',
label: seg.direction ? t('segment.edit_direction') : t('segment.set_direction'),
icon: Sparkles,
onSelect: () => onDirect?.(seg),
},
'separator',
{
id: 'split',
label: t('segment.split_label'),
icon: Scissors,
shortcut: '⌘D',
onSelect: () => {
// Prefer the live cursor if the text input still has focus,
// otherwise fall back to the last remembered position, then
// to a sentence-boundary heuristic. Splitting at the literal
// midpoint (the old behaviour) felt random to users.
let pos = textInputRef.current?.selectionStart;
if (pos == null || pos <= 0 || pos >= seg.text.length) {
pos = lastCursorRef.current;
}
if (pos == null || pos <= 0 || pos >= seg.text.length) {
pos = bestSplitPoint(seg.text);
}
onSplit(seg.id, pos);
},
},
{
id: 'merge-prev',
label: t('segment.merge_prev_label'),
icon: Merge,
shortcut: '⇧⌘M',
disabled: !canMergePrev,
onSelect: () => onMerge(seg.id, 'prev'),
},
{
id: 'merge',
label: t('segment.merge_label'),
icon: Merge,
shortcut: '⌘M',
disabled: !canMerge,
onSelect: () => onMerge(seg.id, 'next'),
},
'separator',
{
id: 'insert',
label: t('segment.insert_label'),
icon: Plus,
onSelect: () => onInsert(seg.id),
},
]}
>
<button
className={`segment-play ${seg.direction ? 'has-direction' : ''}`}
disabled={disabled}
title={
seg.direction
? t('segment.direction_title', { dir: seg.direction })
: t('segment.more_actions_title')
}
>
{seg.direction ? <Sparkles size={14} /> : <MoreHorizontal size={14} />}
</button>
</Menu>
<button className="segment-del" disabled={disabled} onClick={() => onDelete(seg.id)}>
<Trash2 size={14} />
</button>
</div>
</div>
</div>
);
}
export default memo(
DubSegmentRow,
(prev, next) =>
prev.style === next.style &&
prev.ariaAttributes === next.ariaAttributes &&
prev.hasOverlap === next.hasOverlap &&
prev.seg === next.seg &&
prev.disabled === next.disabled &&
prev.isActive === next.isActive &&
prev.isDone === next.isDone &&
prev.isPlaying === next.isPlaying &&
prev.timelineSelected === next.timelineSelected &&
prev.previewLoading === next.previewLoading &&
prev.onDirect === next.onDirect &&
prev.onSeek === next.onSeek &&
prev.selected === next.selected &&
prev.canMerge === next.canMerge &&
prev.canMergePrev === next.canMergePrev &&
prev.profiles === next.profiles &&
prev.speakerClones === next.speakerClones &&
prev.liveEnabled === next.liveEnabled &&
prev.liveActive === next.liveActive &&
prev.onLiveEdit === next.onLiveEdit &&
prev.onLiveToggle === next.onLiveToggle &&
prev.idx === next.idx,
);
@@ -1,235 +0,0 @@
import React, { useEffect, useMemo, useRef, useState } from 'react';
import { Check, ChevronRight, Cpu } from 'lucide-react';
import { useQuery } from '@tanstack/react-query';
import { useTranslation } from 'react-i18next';
import { listLoadedModels } from '../api/system';
import { useEngines, useSelectEngine } from '../api/hooks';
import { notifyEngineSelected } from '../utils/engineSelectToast';
import { useAppStore } from '../store';
import { engineDisplayName } from '../utils/engineDisplayName';
import DictationModelPicker from './DictationModelPicker';
const MENU_SURFACE =
'rounded-[8px] border-0 p-1 bg-[color-mix(in_srgb,var(--chrome-fg)_6%,var(--chrome-bg))] ' +
'shadow-[0_8px_24px_rgba(0,0,0,0.45)] [color:var(--chrome-fg)]';
/**
* A compact TTS/ASR/LLM picker for chrome that needs to expose the active
* engine without growing a second engine-management surface. The matrix stays
* the detailed view; this lists only engines that are ready to be used.
*/
export default function EngineQuickSwitch({
family = 'tts',
className = '',
shortcutTarget = false,
// The footer chip opens upward (nothing below the last row on screen);
// workspace-header chips must open downward or the popover clips off the
// top of the viewport.
dropUp = false,
prominent = false,
embedded = false,
}) {
const { t } = useTranslation();
const rootRef = useRef(null);
const [open, setOpen] = useState(false);
const [switchError, setSwitchError] = useState('');
const { data: engines } = useEngines();
const selectMutation = useSelectEngine();
const { data: residency } = useQuery({
queryKey: ['loaded-models'],
queryFn: listLoadedModels,
staleTime: 10_000,
retry: false,
enabled: open || embedded,
});
const familyData = engines?.[family];
const active = familyData?.backends?.find((engine) => engine.id === familyData.active);
const available = useMemo(
() => (familyData?.backends || []).filter((engine) => engine.available),
[familyData],
);
const residentIds = useMemo(
() =>
new Set(
(residency?.models || []).flatMap((model) => (model.engine_id ? [model.engine_id] : [])),
),
[residency],
);
useEffect(() => {
if (!open) return undefined;
const close = (event) => {
if (rootRef.current && !rootRef.current.contains(event.target)) setOpen(false);
};
const escape = (event) => {
if (event.key === 'Escape') setOpen(false);
};
document.addEventListener('mousedown', close);
document.addEventListener('keydown', escape);
return () => {
document.removeEventListener('mousedown', close);
document.removeEventListener('keydown', escape);
};
}, [open]);
// In-webview shortcut bridge. This stays a DOM event (not a Tauri global
// shortcut), so every desktop and browser build behaves the same way.
useEffect(() => {
if (!shortcutTarget) return undefined;
const show = () => {
setSwitchError('');
setOpen(true);
};
window.addEventListener('engine-quick-switch', show);
return () => window.removeEventListener('engine-quick-switch', show);
}, [shortcutTarget]);
if (!active || available.length === 0) return null;
const activeName = engineDisplayName(active.display_name);
const locked = Boolean(familyData.env_override);
const choose = async (backendId) => {
if (backendId === familyData.active || locked) return;
setSwitchError('');
try {
const result = await selectMutation.mutateAsync({ family, backendId });
if (result.env_override) {
setSwitchError(t('settings.llmp_env_override'));
return;
}
notifyEngineSelected(result, t, family);
setOpen(false);
} catch (error) {
setSwitchError(error?.message || t('engines.switch_failed'));
}
};
return (
<div
className={`${embedded ? 'block w-full' : 'relative inline-flex shrink-0 items-center'} ${prominent ? 'self-start max-w-full' : ''} ${className}`}
ref={rootRef}
>
{!embedded && (
<button
type="button"
onClick={() => {
setSwitchError('');
setOpen((value) => !value);
}}
aria-haspopup="dialog"
aria-expanded={open}
title={t('engines.activeEngine', {
family: family.toUpperCase(),
engine: activeName,
})}
aria-label={t('engines.activeEngine', {
family: family.toUpperCase(),
engine: activeName,
})}
className={`inline-flex items-center gap-[5px] rounded-sm border-0 bg-transparent px-[7px] font-medium text-[color:var(--chrome-fg-muted)] transition-[background,color] hover:bg-[var(--chrome-hover-bg)] hover:text-[color:var(--chrome-fg)] ${prominent ? 'min-h-11 text-sm text-left' : 'h-[20px] text-[11px]'}`}
>
<Cpu size={13} aria-hidden="true" />
<span className={prominent ? 'min-w-0 break-words' : 'max-w-[124px] truncate'}>
{activeName}
</span>
</button>
)}
{(open || embedded) && (
<div
role={embedded ? 'group' : 'dialog'}
aria-label={t('engines.engineCompatLabel', { family: family.toUpperCase() })}
className={
embedded
? 'flex w-full min-w-0 flex-col gap-1 py-2'
: `absolute ${prominent ? 'left-0' : 'right-0'} z-[60] flex w-[272px] max-w-[calc(100vw-32px)] flex-col gap-[4px] p-[8px] ${
dropUp ? 'bottom-[calc(100%+8px)]' : 'top-[calc(100%+8px)]'
} ${MENU_SURFACE}`
}
>
{locked && (
<p className="m-[4px] text-[11px] leading-[1.4] text-[color:var(--chrome-fg-muted)]">
{t('settings.llmp_env_override')}
</p>
)}
{available.map((engine) => {
const isActive = engine.id === familyData.active;
const warm = residentIds.has(engine.id);
const displayName = engineDisplayName(engine.display_name);
const parts = displayName.match(/^(.+?)\s*\((.*)\)$/);
// The Sherpa engine is one engine but seven catalogue models; the
// model choice lives right under its row so "which dictation
// model?" is answerable from the same menu that shows the engine.
const nestedPicker =
family === 'asr' && engine.id === 'sherpa-onnx-asr' ? (
<DictationModelPicker embedded={embedded} />
) : null;
return (
<React.Fragment key={engine.id}>
<button
type="button"
disabled={isActive || locked || selectMutation.isPending}
onClick={() => choose(engine.id)}
className={`flex w-full items-center gap-2 rounded-md border-0 px-2 py-3 text-left text-xs text-[color:var(--chrome-fg)] hover:bg-[var(--chrome-hover-bg)] disabled:cursor-default ${embedded && isActive ? 'bg-[var(--chrome-accent-bg)]' : 'bg-transparent'}`}
>
<span className="w-[12px] shrink-0">
{isActive && <Check size={12} aria-label={t('engines.active')} />}
</span>
<span
className={
embedded
? 'min-w-0 flex-1 whitespace-normal break-words'
: 'min-w-0 flex-1 truncate'
}
>
{embedded && parts ? (
<>
<span className="block font-medium text-sm">{parts[1]}</span>
<span className="block mt-1 text-xs leading-relaxed text-[var(--chrome-fg-muted)]">
{parts[2]}
</span>
</>
) : (
displayName
)}
</span>
<span className="shrink-0 text-[10px] text-[color:var(--chrome-fg-muted)]">
{warm
? t('engines.inMemory')
: isActive
? t('engines.active')
: embedded
? ''
: t('engines.available')}
</span>
</button>
{nestedPicker}
</React.Fragment>
);
})}
{switchError && (
<p
role="alert"
className="m-[4px] text-[11px] leading-[1.4] text-[color:var(--chrome-severity-err)]"
>
{switchError}
</p>
)}
{!embedded && (
<button
type="button"
onClick={() => {
setOpen(false);
useAppStore.getState().openCatalogue({ family });
}}
className="mt-[3px] flex items-center gap-[3px] border-0 bg-transparent px-[7px] py-[5px] text-left text-[11px] text-[color:var(--chrome-fg-muted)] hover:text-[color:var(--chrome-fg)]"
>
{t('settings.engines')} <ChevronRight size={12} aria-hidden="true" />
</button>
)}
</div>
)}
</div>
);
}
@@ -1,125 +0,0 @@
import React from 'react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
vi.mock('react-hot-toast', () => ({ toast: { success: vi.fn() } }));
const { listEngines, selectEngine, listLoadedModels } = vi.hoisted(() => ({
listEngines: vi.fn(),
selectEngine: vi.fn(),
listLoadedModels: vi.fn(),
}));
vi.mock('../api/engines', () => ({ listEngines, selectEngine }));
vi.mock('../api/system', () => ({ listLoadedModels }));
import EngineQuickSwitch from './EngineQuickSwitch';
const inventory = (env_override = false) => ({
tts: {
active: 'omnivoice',
env_override,
backends: [
{ id: 'omnivoice', display_name: 'OmniVoice', available: true },
{ id: 'indextts2', display_name: 'IndexTTS 2', available: true },
{ id: 'offline', display_name: 'Offline', available: false },
],
},
asr: { active: 'whisper', backends: [] },
llm: { active: 'off', backends: [] },
});
function renderPicker(props = {}) {
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
return render(
<QueryClientProvider client={client}>
<EngineQuickSwitch {...props} />
</QueryClientProvider>,
);
}
describe('EngineQuickSwitch', () => {
it('embeds engine choices without another popup trigger', async () => {
renderPicker({ embedded: true });
expect(await screen.findByText('IndexTTS 2')).toBeInTheDocument();
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
expect(screen.queryByRole('button', { name: /active tts:/i })).not.toBeInTheDocument();
});
it('anchors the prominent menu to the left-hand engine button', async () => {
renderPicker({ prominent: true });
fireEvent.click(await screen.findByRole('button', { name: /active tts: omnivoice/i }));
expect(screen.getByRole('dialog')).toHaveClass('left-0');
expect(screen.getByRole('dialog')).not.toHaveClass('right-0');
});
beforeEach(() => {
vi.clearAllMocks();
listEngines.mockResolvedValue(inventory());
listLoadedModels.mockResolvedValue({ models: [{ engine_id: 'omnivoice' }] });
});
it.each(['VoiceStudio', 'VoiceStudio TTS', 'VoiceStudio (k2-fsa/OmniVoice)'])(
'formats the active name consistently for %s',
async (name) => {
const data = inventory();
data.tts.backends[0].display_name = name;
listEngines.mockResolvedValue(data);
const expected = name.replace('VoiceStudio', 'OmniVoice');
const { unmount } = renderPicker();
const trigger = await screen.findByRole('button', {
name: `Active TTS: ${expected}`,
});
expect(trigger).toHaveAttribute('title', `Active TTS: ${expected}`);
expect(trigger).toHaveTextContent(expected);
fireEvent.click(trigger);
expect(screen.getByRole('dialog')).not.toHaveTextContent('VoiceStudio');
unmount();
renderPicker({ embedded: true });
expect(await screen.findByRole('group')).not.toHaveTextContent('VoiceStudio');
expect(screen.getByRole('group')).toHaveTextContent('OmniVoice');
},
);
it('lists only available engines and annotates residency', async () => {
renderPicker();
fireEvent.click(await screen.findByRole('button', { name: /active tts: omnivoice/i }));
expect(screen.getByText('IndexTTS 2')).toBeInTheDocument();
expect(screen.queryByText('Offline')).not.toBeInTheDocument();
expect(await screen.findByText('In memory')).toBeInTheDocument();
});
it('selects through the shared mutation', async () => {
selectEngine.mockResolvedValue({ family: 'tts', active: 'indextts2', env_override: false });
renderPicker();
fireEvent.click(await screen.findByRole('button', { name: /active tts: omnivoice/i }));
fireEvent.click(screen.getByText('IndexTTS 2'));
await waitFor(() => expect(selectEngine).toHaveBeenCalledWith('tts', 'indextts2', undefined));
});
it('locks a family owned by an environment variable', async () => {
listEngines.mockResolvedValue(inventory(true));
renderPicker();
fireEvent.click(await screen.findByRole('button', { name: /active tts: omnivoice/i }));
expect(screen.getByText(/set via an environment variable/i)).toBeInTheDocument();
expect(screen.getByText('IndexTTS 2').closest('button')).toBeDisabled();
});
it('opens only the designated picker from the global shortcut bridge', async () => {
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
render(
<QueryClientProvider client={client}>
<EngineQuickSwitch />
<EngineQuickSwitch shortcutTarget />
</QueryClientProvider>,
);
await screen.findAllByRole('button', { name: /active tts: omnivoice/i });
fireEvent(window, new Event('engine-quick-switch'));
expect(await screen.findByRole('dialog')).toBeInTheDocument();
expect(screen.getAllByRole('dialog')).toHaveLength(1);
});
});
@@ -1,915 +0,0 @@
/**
* First-run install setup screen.
*
* Rendered by BootstrapSplash while the Rust side is parked in the
* `awaiting_setup` stage — nothing has been downloaded or installed yet.
* The user picks install mode (installed/portable), storage locations,
* compute variant, network mirrors and update channel; every chosen
* directory is live-checked for free space against the minimum the install
* needs (Rust re-validates on submit — the UI gate is a mirror, not the
* authority). "Start installation" is the only thing that kicks off the
* bootstrap.
*
* Built on standard shadcn primitives (Button/Input/Select/Progress/Badge)
* + Tailwind utilities themed by the VoiceStudio palette tokens. The only
* bespoke CSS left is the breathing-waveform / rise-in keyframes in
* firstrun.css. All motion honors prefers-reduced-motion; every asset is
* bundled — a first run may be on a restricted network.
*/
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { cn } from '@/lib/utils';
import i18n, { LANGUAGES } from '../i18n';
import { useAppStore } from '../store';
import { Badge, Button, Input, Progress, Select } from '../ui';
import UiScaleControl from './UiScaleControl';
const APP_VERSION = __APP_VERSION__ || '0.0.0';
const GIB = 1024 * 1024 * 1024;
const fmtGB = (bytes) =>
bytes == null ? '—' : `${(bytes / GIB).toFixed(bytes < 10 * GIB ? 1 : 0)} GB`;
const invoke = async (...args) => {
const { invoke: tauriInvoke } = await import('@tauri-apps/api/core');
return tauriInvoke(...args);
};
/** Debounced live probe of one install target (free space / writability). */
function useTargetCheck(path) {
const [check, setCheck] = useState(null);
useEffect(() => {
if (!path) {
setCheck(null);
return;
}
let cancelled = false;
const t = setTimeout(async () => {
try {
const res = await invoke('check_install_target', { path });
if (!cancelled) setCheck(res);
} catch {
if (!cancelled) setCheck(null);
}
}, 250);
return () => {
cancelled = true;
clearTimeout(t);
};
}, [path]);
return check;
}
/** Breathing waveform masthead — bar heights are stable per mount. */
function Waveform({ bars = 96 }) {
const heights = useMemo(
() =>
Array.from({ length: bars }, (_, i) => {
// Deterministic pseudo-random silhouette: layered sines read as speech
// cadence (syllables + phrase envelope) rather than white noise.
const t = i / bars;
const v = Math.abs(
Math.sin(t * Math.PI * 7.3) * 0.55 +
Math.sin(t * Math.PI * 2.1 + 1.2) * 0.3 +
Math.sin(t * Math.PI * 17.0 + 0.4) * 0.15,
);
return 0.18 + v * 0.82;
}),
[bars],
);
return (
<div className="fr-wave" aria-hidden="true">
{heights.map((h, i) => (
<span
key={i}
className="fr-wave__bar"
style={{ '--h': h, '--d': `${(i * 73) % 1400}ms` }}
/>
))}
</div>
);
}
/** Capacity meter: how much of the volume's free space this install consumes.
* Switches to the danger tone when the install would overflow the disk. */
function CapacityMeter({ need, free }) {
const ratio = free > 0 ? need / free : 1;
const pct = Math.min(100, Math.max(3, ratio * 100));
return (
<Progress
value={pct}
tone={ratio > 1 ? 'danger' : 'brand'}
size="md"
className="w-full"
aria-label={`${fmtGB(need)} / ${fmtGB(free)}`}
/>
);
}
/** Engraved mono section label with a rule trailing off to the right. */
function SectionLabel({ children }) {
return (
<h2 className="m-0 flex items-center gap-2 font-mono text-[0.62rem] font-semibold uppercase tracking-[0.18em] text-fg-muted">
<span>{children}</span>
<span
className="h-px flex-1 bg-gradient-to-r from-border-strong to-transparent"
aria-hidden="true"
/>
</h2>
);
}
/** One first-run section: rise-in stagger + engraved label + content. */
function Section({ title, delay = 0, className = '', children }) {
return (
<section className={cn('fr-rise flex flex-col gap-2.5', className)} style={{ '--rise': delay }}>
<SectionLabel>{title}</SectionLabel>
{children}
</section>
);
}
/** One storage location row: label, path, space readout, Change… picker. */
function StorageRow({ label, desc, path, need, check, onPick }) {
const { t } = useTranslation();
const lowSpace = check?.freeBytes != null && check.freeBytes < need;
const notWritable = check && !check.writable;
const blocked = lowSpace || notWritable;
const tight = check?.freeBytes != null && need / check.freeBytes > 0.35;
return (
<div
className={cn(
'flex flex-wrap items-center gap-x-4 gap-y-2 rounded-md px-3 py-2 transition-colors hover:bg-bg-elev-3',
blocked &&
'bg-danger/[0.06] shadow-[inset_2px_0_0_var(--color-danger)] hover:bg-danger/[0.06]',
)}
>
<div className="flex min-w-0 flex-1 flex-col gap-0.5" title={desc}>
<span className="text-sm font-semibold">{label}</span>
{/* rtl for a start-side ellipsis; <bdi> keeps the path's own order
(see the preflight detail in SetupWizard.jsx for why). */}
<code className="truncate font-mono text-[0.66rem] text-fg-muted" title={path} dir="rtl">
<bdi>{path}</bdi>
</code>
</div>
<div className="flex min-w-[170px] shrink-0 flex-col items-end gap-1">
{(blocked || tight) && check?.freeBytes != null && (
<CapacityMeter need={need} free={check.freeBytes} />
)}
<span
className={cn(
'whitespace-nowrap font-mono text-[0.64rem] tabular-nums text-fg-muted',
lowSpace && 'font-bold text-danger',
)}
>
{check == null ? (
t('firstrun.checking', 'checking…')
) : notWritable ? (
t('firstrun.not_writable', 'not writable')
) : (
<>
{t('firstrun.needs', { size: fmtGB(need), defaultValue: 'needs ~{{size}}' })}
{' · '}
{t('firstrun.free', { size: fmtGB(check.freeBytes), defaultValue: '{{size}} free' })}
</>
)}
</span>
</div>
{onPick && (
<Button variant="ghost" size="sm" onClick={onPick}>
{t('firstrun.change', 'Change…')}
</Button>
)}
</div>
);
}
/** Arrow-key navigation for a radio group (WAI-ARIA radio pattern):
* Left/Up selects the previous enabled option, Right/Down the next.
* Selection follows focus, exactly like native radios. */
export function radioGroupNav(e, values, current, select) {
let delta = 0;
if (e.key === 'ArrowRight' || e.key === 'ArrowDown') delta = 1;
else if (e.key === 'ArrowLeft' || e.key === 'ArrowUp') delta = -1;
else return;
e.preventDefault();
const idx = Math.max(0, values.indexOf(current));
const next = values[(idx + delta + values.length) % values.length];
select(next);
}
/** Radio option card — used for install mode, compute and update channel.
* Roving tabindex: only the selected option is in the tab order; arrows move
* within the group. The leading dot lights when selected. */
function OptionCard({ active, disabled, onSelect, name, desc, badge }) {
return (
<button
type="button"
role="radio"
aria-checked={active}
tabIndex={active ? 0 : -1}
disabled={disabled}
title={desc}
onClick={() => !disabled && onSelect()}
className={cn(
'flex flex-col gap-1 rounded-md border px-3 py-2.5 text-left transition-colors',
'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring',
active
? 'border-transparent bg-primary/10'
: 'border-border bg-bg-elev-2 hover:bg-bg-elev-1',
disabled && 'cursor-not-allowed opacity-40 hover:bg-bg-elev-2',
)}
>
<span className="flex flex-wrap items-center gap-2">
<span
className={cn(
'h-1.5 w-1.5 shrink-0 rounded-full',
active ? 'bg-primary shadow-[0_0_6px_1px_var(--color-brand-glow)]' : 'bg-fg-subtle/40',
)}
aria-hidden="true"
/>
<span className="text-sm font-semibold">{name}</span>
{badge && (
<Badge tone="success" size="xs">
{badge}
</Badge>
)}
</span>
</button>
);
}
/** Fixed caption slot under a radio group: two reserved lines, the active
* option's description swaps in — the layout never shifts on selection. */
function GroupCaption({ text }) {
return (
<p className="m-0 min-h-[2.4em] text-xs leading-snug text-fg-subtle" aria-live="polite">
{text}
</p>
);
}
/** Mono error block shown for server / submit failures. */
function ErrorBox({ children }) {
return (
<pre className="m-0 overflow-x-auto whitespace-pre-wrap break-words rounded-md bg-danger/10 px-3 py-2 font-mono text-[0.66rem] leading-relaxed text-danger shadow-[inset_2px_0_0_var(--color-danger)]">
{children}
</pre>
);
}
export default function FirstRunSetup() {
const { t } = useTranslation();
const locale = useAppStore((s) => s.locale);
const setLocale = useAppStore((s) => s.setLocale);
const [setup, setSetup] = useState(null); // get_setup_state payload
const [plan, setPlan] = useState(null); // user's editable choices
const [submitting, setSubmitting] = useState(false);
const [serverError, setServerError] = useState(null);
const mounted = useRef(true);
useEffect(
() => () => {
mounted.current = false;
},
[],
);
useEffect(() => {
(async () => {
try {
const s = await invoke('get_setup_state');
if (!mounted.current) return;
setSetup(s);
setPlan({
installMode:
s.portable.available && s.defaults.installMode === 'portable'
? 'portable'
: 'installed',
envDir: s.defaults.envDir,
dataDir: s.defaults.dataDir,
modelsDir: s.defaults.modelsDir,
// Where a portable install would go. Seeded from whatever the app
// currently resolves (default beside the app, or an earlier
// relocation) so the row shows a real path, never "(default)".
portableDir: s.portable.baseDir || '',
region: s.defaults.region,
updateChannel: s.defaults.updateChannel,
// Pre-select ROCm only when Rust verified the ROCm userspace is
// installed (kind === 'rocm'). A bare AMD GPU without the runtime
// reports kind === 'amd': ROCm stays offered but unselected, since
// its wheels would silently fall back to CPU on such machines.
torchVariant: s.hardware?.kind === 'rocm' ? 'rocm' : s.defaults.torchVariant,
mirrors: { pypiIndex: '', hfEndpoint: '', pythonDownloads: '' },
});
} catch (e) {
if (mounted.current) setServerError(String(e));
}
})();
}, []);
const portable = plan?.installMode === 'portable';
const req = setup?.requirements;
const hw = setup?.hardware;
const combinedNeed = req ? req.envBytes + req.modelsBytes + req.dataBytes : 0;
// Live target probes — in portable mode only the anchor folder matters.
const portableBase = plan?.portableDir || setup?.portable?.baseDir || '';
const portableDefault = setup?.portable?.defaultDir || '';
const portableRelocated = Boolean(
portableBase && portableDefault && portableBase !== portableDefault,
);
const portableAnchor = setup?.portable?.anchorDir || '';
// A folder INSIDE the app's own directory is recorded as a RELATIVE path, so
// app + folder move as a unit and the mount path may change. Anywhere else
// only an absolute path can be stored, and the cross-machine promise does not
// hold — say so rather than imply it (CodeRabbit, #1404).
const portableTravelsWithApp =
Boolean(portableAnchor) &&
portableBase.startsWith(portableAnchor.endsWith('/') ? portableAnchor : `${portableAnchor}/`);
const envCheck = useTargetCheck(portable ? null : plan?.envDir);
const dataCheck = useTargetCheck(portable ? null : plan?.dataDir);
const modelsCheck = useTargetCheck(portable ? null : plan?.modelsDir);
const portableCheck = useTargetCheck(portable ? portableBase : null);
// Mirror of the Rust gate: group targets by filesystem, sum requirements,
// block when any volume falls short or isn't writable.
const blockers = useMemo(() => {
if (!plan || !req) return [{ key: 'loading' }];
const targets = portable
? [{ check: portableCheck, need: combinedNeed, label: portableBase }]
: [
{ check: envCheck, need: req.envBytes, label: plan.envDir },
{ check: dataCheck, need: req.dataBytes, label: plan.dataDir },
{ check: modelsCheck, need: req.modelsBytes, label: plan.modelsDir },
];
if (targets.some((x) => x.check == null)) return [{ key: 'loading' }];
const out = [];
for (const { check, label } of targets) {
if (!check.writable) out.push({ key: 'not_writable', label });
}
const byFs = new Map();
for (const { check, need } of targets) {
const k = check.fsKey || check.path;
const cur = byFs.get(k) || { need: 0, free: check.freeBytes };
cur.need += need;
cur.free = Math.min(cur.free ?? Infinity, check.freeBytes ?? Infinity);
byFs.set(k, cur);
}
for (const { need, free } of byFs.values()) {
if (free != null && free < need) out.push({ key: 'space', need, free });
}
return out;
}, [
plan,
req,
portable,
portableBase,
combinedNeed,
envCheck,
dataCheck,
modelsCheck,
portableCheck,
]);
const pickDir = useCallback(
async (field) => {
try {
const { open } = await import('@tauri-apps/plugin-dialog');
const dir = await open({ directory: true, defaultPath: plan?.[field] || undefined });
if (typeof dir === 'string' && dir) setPlan((p) => ({ ...p, [field]: dir }));
} catch (e) {
console.error('folder pick failed', e);
}
},
[plan],
);
const set = useCallback((patch) => setPlan((p) => ({ ...p, ...patch })), []);
const start = useCallback(async () => {
if (!plan || submitting) return;
setSubmitting(true);
setServerError(null);
try {
const clean = (s) => (s && s.trim() ? s.trim() : null);
await invoke('complete_setup', {
plan: {
installMode: plan.installMode,
portableDir: clean(plan.portableDir),
envDir: clean(plan.envDir),
dataDir: clean(plan.dataDir),
modelsDir: clean(plan.modelsDir),
region: plan.region,
locale,
updateChannel: plan.updateChannel,
torchVariant: plan.torchVariant,
mirrors: {
pypiIndex: clean(plan.mirrors.pypiIndex),
hfEndpoint: clean(plan.mirrors.hfEndpoint),
pythonDownloads: clean(plan.mirrors.pythonDownloads),
},
},
});
// Success: the stage poll in App.jsx leaves `awaiting_setup` and the
// normal bootstrap progress UI takes over. Nothing to do here.
} catch (e) {
if (mounted.current) {
const message = e instanceof Error ? e.message : String(e);
setServerError(
message === 'backend_stop_failed'
? t('firstrun.backend_stop_failed')
: message === 'setup_task_failed'
? t('bootstrap.unknown_error')
: message,
);
setSubmitting(false);
}
}
}, [plan, submitting, locale, t]);
if (!setup || !plan) {
return (
<div className="absolute inset-0 z-[9999] flex flex-col items-center justify-center bg-bg px-6 font-sans text-fg">
<UiScaleControl />
{serverError ? (
<ErrorBox>{serverError}</ErrorBox>
) : (
<div className="text-sm text-fg-muted">{t('firstrun.loading', 'Preparing setup…')}</div>
)}
</div>
);
}
const blocked = blockers.length > 0;
const spaceBlocker = blockers.find((b) => b.key === 'space');
// The full machine identity — OS/distro · arch · GPU · CPU · RAM — the
// exact matrix cell this install is for (and what bug reports cite).
const hwLine = hw
? [
[hw.osName, hw.arch].filter(Boolean).join(' '),
hw.gpu,
hw.cpuCores ? `${hw.cpuCores}×CPU` : null,
hw.ramGb ? `${hw.ramGb} GB RAM` : null,
]
.filter(Boolean)
.join(' · ')
: null;
// ROCm wheels are Linux-only — never offer a choice that can't work on
// this platform (Rust clamps it server-side too).
const rocmAvailable = setup.os === 'linux';
return (
<div className="absolute inset-0 z-[9999] flex flex-col items-center overflow-hidden bg-bg px-6 pt-12 font-sans text-fg">
<div className="flex w-full max-w-[1100px] flex-1 flex-col">
<div className="flex flex-1 flex-col gap-5 overflow-y-auto pb-4">
{/* ── Masthead: waveform + headline + language/region ──────────── */}
<header
className="fr-rise flex flex-col gap-3 pb-1"
style={{ '--rise': 0 }}
data-tauri-drag-region
>
<Waveform />
{/* Journey rail: this page is stage 1 of the install flow. */}
<JourneyRail active="setup" t={t} />
<div className="mt-2 flex flex-wrap items-end justify-between gap-6">
<div className="min-w-0">
{/* Version rides beside the app name — same masthead across all
three first-run acts (setup → install → models & engines), so
a screenshot from any of them identifies the build. */}
<div className="flex flex-wrap items-baseline gap-2.5">
<h1 className="m-0 font-serif text-[clamp(1.6rem,3vw,2.2rem)] font-semibold leading-tight tracking-tight">
{t('firstrun.title', 'Set up VoiceStudio')}
</h1>
<span className="font-mono text-[0.62rem] tracking-[0.14em] text-fg-subtle">
v{APP_VERSION}
</span>
</div>
<p className="mt-1.5 max-w-[58ch] text-sm leading-snug text-fg-muted">
{t(
'firstrun.subtitle',
"Nothing's installed yet — review where everything goes, then start. Change it later in Settings.",
)}
</p>
</div>
<div className="flex shrink-0 flex-col items-end gap-2">
{/* Language + download region: the two "where am I" choices. */}
<div className="flex items-center gap-2">
<UiScaleControl />
<Select
size="sm"
value={locale}
onChange={(e) => {
setLocale(e.target.value);
i18n.changeLanguage(e.target.value);
}}
aria-label={t('firstrun.language', 'Language')}
>
{LANGUAGES.map((l) => (
<option key={l.code} value={l.code}>
{l.label}
</option>
))}
</Select>
<Select
size="sm"
value={plan.region}
onChange={(e) => set({ region: e.target.value })}
aria-label={t('firstrun.region_label', 'Download region')}
>
<option value="auto">{t('bootstrap.auto_detect', 'Auto-detect')}</option>
<option value="global">
{t('bootstrap.region_global', 'Global (direct)')}
</option>
<option value="china">{t('bootstrap.region_china', 'China (mirror)')}</option>
<option value="russia">
{t('bootstrap.region_russia', 'Russia (mirror)')}
</option>
<option value="restricted">
{t('bootstrap.region_restricted', 'Restricted (mirror)')}
</option>
</Select>
</div>
<details className="text-right">
<summary className="cursor-pointer select-none font-mono text-[0.62rem] uppercase tracking-wide text-fg-muted hover:text-fg">
{t('firstrun.mirrors_title', 'Custom mirrors (advanced)')}
</summary>
<div className="mt-2 grid min-w-[320px] gap-2 text-left">
{[
[
'pypiIndex',
t('firstrun.mirror_pypi', 'PyPI index URL'),
'https://mirrors.aliyun.com/pypi/simple/',
],
[
'hfEndpoint',
t('firstrun.mirror_hf', 'Hugging Face endpoint'),
'https://hf-mirror.com',
],
[
'pythonDownloads',
t('firstrun.mirror_python', 'Python downloads mirror'),
'https://gh-proxy.com/…',
],
].map(([field, label, ph]) => (
<label key={field} className="flex flex-col gap-1">
<span className="font-mono text-[0.6rem] uppercase tracking-wide text-fg-muted">
{label}
</span>
<Input
size="sm"
type="url"
placeholder={ph}
value={plan.mirrors[field]}
onChange={(e) =>
set({ mirrors: { ...plan.mirrors, [field]: e.target.value } })
}
/>
</label>
))}
</div>
</details>
</div>
</div>
</header>
{/* ── Wide deck: storage rail (left) + decision rail (right) ────── */}
<div className="grid grid-cols-1 items-start gap-5 lg:grid-cols-[7fr_5fr]">
<div className="flex min-w-0 flex-col gap-5">
<Section title={t('firstrun.mode_title', 'Install mode')} delay={1}>
<div
className="grid grid-cols-1 gap-2.5 sm:grid-cols-2"
role="radiogroup"
aria-label={t('firstrun.mode_title', 'Install mode')}
onKeyDown={(e) =>
radioGroupNav(
e,
setup.portable.available ? ['installed', 'portable'] : ['installed'],
plan.installMode,
(v) => set({ installMode: v }),
)
}
>
<OptionCard
active={!portable}
onSelect={() => set({ installMode: 'installed' })}
name={t('firstrun.mode_installed', 'Installed')}
desc={t(
'firstrun.mode_installed_desc',
'Standard system folders. Recommended.',
)}
/>
<OptionCard
active={portable}
disabled={!setup.portable.available}
onSelect={() => set({ installMode: 'portable' })}
name={t('firstrun.mode_portable', 'Portable')}
desc={
setup.portable.available
? t(
'firstrun.mode_portable_desc',
'Everything lives in one folder next to the app — move it to another disk or machine as a unit.',
)
: t(
'firstrun.mode_portable_unavailable',
'Unavailable: the folder next to the app is not writable.',
)
}
/>
</div>
<GroupCaption
text={
portable
? t(
'firstrun.mode_portable_desc',
'Everything lives in one folder next to the app — move it to another disk or machine as a unit.',
)
: t('firstrun.mode_installed_desc', 'Standard system folders. Recommended.')
}
/>
</Section>
<Section title={t('firstrun.storage_title', 'Storage')} delay={2}>
{portable ? (
<>
<StorageRow
label={t('firstrun.portable_folder', 'Portable folder')}
desc={t(
'firstrun.portable_folder_desc',
'App environment, models, and your voice data — one folder, fully movable.',
)}
path={portableBase}
need={combinedNeed}
check={portableCheck}
onPick={() => pickDir('portableDir')}
/>
{portableRelocated && (
<GroupCaption
text={
setup.portable.anchorWritable && portableTravelsWithApp
? t(
'firstrun.portable_moved',
'Recorded beside the app as a relative path, so moving the app and this folder together — even to another machine or drive letter — keeps the install working.',
)
: t(
'firstrun.portable_moved_machine_bound',
'This exact location is remembered on this machine. If the app or this folder moves, or you use another machine, you will have to point the app at it again.',
)
}
/>
)}
</>
) : (
<>
<StorageRow
label={t('firstrun.env_dir', 'App environment')}
desc={t('firstrun.env_dir_desc', 'Python runtime and AI libraries.')}
path={plan.envDir}
need={req.envBytes}
check={envCheck}
onPick={() => pickDir('envDir')}
/>
<StorageRow
label={t('firstrun.data_dir', 'Voice data & projects')}
desc={t(
'firstrun.data_dir_desc',
'Your voices, dubs, outputs and project database.',
)}
path={plan.dataDir}
need={req.dataBytes}
check={dataCheck}
onPick={() => pickDir('dataDir')}
/>
<StorageRow
label={t('firstrun.models_dir', 'Model cache')}
desc={t(
'firstrun.models_dir_desc',
'Downloaded AI models — the largest and most relocatable part.',
)}
path={plan.modelsDir}
need={req.modelsBytes}
check={modelsCheck}
onPick={() => pickDir('modelsDir')}
/>
</>
)}
</Section>
</div>
<div className="flex min-w-0 flex-col gap-5">
<Section title={t('firstrun.compute_title', 'Compute')} delay={2}>
{hwLine && (
<div className="flex min-w-0 items-center gap-2 pb-1" title={hwLine}>
<span
className="h-1.5 w-1.5 shrink-0 rounded-full bg-success shadow-[0_0_6px_1px_color-mix(in_srgb,var(--color-success)_60%,transparent)] fr-pulse"
aria-hidden="true"
/>
<span className="shrink-0 font-mono text-[0.58rem] uppercase tracking-wide text-fg-muted">
{t('firstrun.compute_detected', { defaultValue: 'Detected' })}
</span>
<span className="truncate font-mono text-[0.66rem] tabular-nums text-fg">
{hwLine}
</span>
</div>
)}
<div
className="grid gap-2.5"
role="radiogroup"
aria-label={t('firstrun.compute_title', 'Compute')}
onKeyDown={(e) =>
radioGroupNav(
e,
rocmAvailable ? ['auto', 'rocm'] : ['auto'],
plan.torchVariant,
(v) => set({ torchVariant: v }),
)
}
>
<OptionCard
active={plan.torchVariant === 'auto'}
onSelect={() => set({ torchVariant: 'auto' })}
name={t('firstrun.compute_auto', 'Auto (NVIDIA CUDA / Apple MPS / CPU)')}
desc={t(
'firstrun.compute_auto_desc',
'Best backend picked at runtime — CUDA on NVIDIA, MPS on Apple Silicon, else CPU.',
)}
badge={
hw?.kind === 'cuda' || hw?.kind === 'mps'
? t('firstrun.compute_match', { defaultValue: 'matches this machine' })
: null
}
/>
{rocmAvailable && (
<OptionCard
active={plan.torchVariant === 'rocm'}
onSelect={() => set({ torchVariant: 'rocm' })}
name={t('firstrun.compute_rocm', 'AMD GPU (ROCm, Linux)')}
desc={t(
'firstrun.compute_rocm_desc',
'Installs PyTorch ROCm wheels for AMD graphics cards on Linux. Leave on Auto if unsure.',
)}
badge={
hw?.kind === 'rocm'
? t('firstrun.compute_match', { defaultValue: 'matches this machine' })
: null
}
/>
)}
</div>
<GroupCaption
text={
plan.torchVariant === 'rocm'
? t(
'firstrun.compute_rocm_desc',
'Installs PyTorch ROCm wheels for AMD graphics cards on Linux. Leave on Auto if unsure.',
)
: t(
'firstrun.compute_auto_desc',
'Best backend picked at runtime — CUDA on NVIDIA, MPS on Apple Silicon, else CPU.',
)
}
/>
</Section>
<Section title={t('firstrun.channel_label', 'Update channel')} delay={3}>
<div
className="grid gap-2.5"
role="radiogroup"
aria-label={t('firstrun.channel_label', 'Update channel')}
onKeyDown={(e) =>
radioGroupNav(e, ['stable', 'preview'], plan.updateChannel, (v) =>
set({ updateChannel: v }),
)
}
>
<OptionCard
active={plan.updateChannel === 'stable'}
onSelect={() => set({ updateChannel: 'stable' })}
name={t('firstrun.channel_stable', 'Stable')}
desc={t(
'firstrun.channel_stable_desc',
'Tested releases only, after community validation.',
)}
/>
<OptionCard
active={plan.updateChannel === 'preview'}
onSelect={() => set({ updateChannel: 'preview' })}
name={t('firstrun.channel_preview', 'Preview (latest main)')}
desc={t(
'firstrun.channel_preview_desc',
'Latest main — new engines and fixes first, occasional rough edges.',
)}
/>
</div>
<GroupCaption
text={
plan.updateChannel === 'preview'
? t(
'firstrun.channel_preview_desc',
'Latest main — new engines and fixes first, occasional rough edges.',
)
: t(
'firstrun.channel_stable_desc',
'Tested releases only, after community validation.',
)
}
/>
</Section>
</div>
</div>
</div>
{/* ── Footer: gate + arm ──────────────────────────────────────────── */}
<footer
className="fr-rise flex shrink-0 flex-col gap-2 border-t border-border bg-bg pt-3 pb-6"
style={{ '--rise': 5 }}
>
{serverError && <ErrorBox>{serverError}</ErrorBox>}
{spaceBlocker && (
<p className="m-0 text-sm text-danger">
{t('firstrun.insufficient_space', {
need: fmtGB(spaceBlocker.need),
free: fmtGB(spaceBlocker.free),
defaultValue:
'Not enough free space: this layout needs ~{{need}} on one disk, only {{free}} available. Pick a different location.',
})}
</p>
)}
{blockers.some((b) => b.key === 'not_writable') && (
<p className="m-0 text-sm text-danger">
{t(
'firstrun.blocked_not_writable',
'A chosen folder is not writable — pick a different location.',
)}
</p>
)}
<div className="flex flex-wrap items-center justify-between gap-4">
{/* Version moved up beside the app name (masthead) — the footer now
carries only the download total. */}
<span className="inline-flex flex-wrap items-baseline gap-2 text-xs tabular-nums text-fg-muted">
{t('firstrun.total_required', {
size: fmtGB(combinedNeed),
defaultValue: 'Total disk needed: ~{{size}} (one-time download on first use)',
})}
</span>
<Button variant="primary" disabled={blocked || submitting} onClick={start}>
{submitting
? t('firstrun.starting', 'Starting…')
: t('firstrun.start', 'Start installation')}
</Button>
</div>
{/* The product's whole thesis, said where the user decides. */}
<p className="m-0 text-xs text-fg-subtle">
{t(
'firstrun.trust_line',
'Privacy first: your voices, recordings and projects never leave this machine — no account, no cloud processing.',
)}
</p>
</footer>
</div>
</div>
);
}
/** Three-stage breadcrumb shared by the setup + install acts. */
export function JourneyRail({ active, t }) {
const stages = [
['setup', t('firstrun.stage_setup', 'Setup')],
['installing', t('firstrun.installing_title', 'Installing')],
['models', t('firstrun.stage_models', 'Models & engines')],
];
const activeIdx = stages.findIndex(([id]) => id === active);
return (
<nav
className="flex flex-wrap items-center gap-x-5 gap-y-2"
aria-label={t('firstrun.title', 'Set up VoiceStudio')}
>
{stages.map(([id, label], i) => {
const isActive = i === activeIdx;
const isDone = i < activeIdx;
return (
<span
key={id}
className={cn(
'inline-flex items-center gap-1.5 font-mono text-[0.62rem] font-semibold uppercase tracking-[0.14em]',
isActive ? 'text-fg' : isDone ? 'text-fg-muted' : 'text-fg-subtle/60',
)}
>
<span
className={cn(
'h-1.5 w-1.5 rounded-full',
isActive
? 'bg-primary shadow-[0_0_6px_1px_var(--color-brand-glow)]'
: isDone
? 'bg-success'
: 'bg-fg-subtle/40',
)}
aria-hidden="true"
/>
{label}
</span>
);
})}
</nav>
);
}
-639
View File
@@ -1,639 +0,0 @@
import React, { useState, useRef, useEffect, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import EngineQuickSwitch from './EngineQuickSwitch';
import { engineDisplayName } from '../utils/engineDisplayName';
import { Tabs, TabsList, TabsTrigger, TabsContent } from './ui/tabs';
import { createPortal } from 'react-dom';
import {
Globe,
Fingerprint,
Wand2,
Film,
FolderOpen,
RefreshCw,
Settings2,
ChevronRight,
ChevronDown,
Zap,
Building2,
Library,
FileText,
Boxes,
Trash2,
Minus,
Square,
X,
} from 'lucide-react';
import { Button, Badge } from '../ui';
import NotificationPanel from './NotificationPanel';
import TitleTabs from './TitleTabs';
import VoiceStudioMark from './brand/VoiceStudioMark';
import { useAppStore } from '../store';
import { useSysinfo, useEngines } from '../api/hooks';
import { reloadAfterApplicationPersistence } from '../utils/persistenceLifecycle';
const VIEW_META = {
launchpad: {
labelKey: 'header.label_launchpad',
Icon: Globe,
accent: '#f3a5b6',
kickerKey: 'header.kicker_studio',
},
studio: {
labelKey: 'nav.voice',
Icon: Fingerprint,
accent: '#d3869b',
kickerKey: 'header.kicker_studio',
},
// Legacy ids — kept so a not-yet-shimmed persisted 'clone'/'design' mode
// still renders a sensible header (voice-studio-unification P4).
clone: {
labelKey: 'header.label_clone',
Icon: Fingerprint,
accent: '#d3869b',
kickerKey: 'header.kicker_studio',
},
design: {
labelKey: 'header.label_design',
Icon: Wand2,
accent: '#8ec07c',
kickerKey: 'header.kicker_studio',
},
dub: {
labelKey: 'header.label_dub',
Icon: Film,
accent: '#fe8019',
kickerKey: 'header.kicker_studio',
},
projects: {
labelKey: 'header.label_projects',
Icon: FolderOpen,
accent: '#83a598',
kickerKey: 'header.kicker_library',
},
gallery: {
labelKey: 'header.label_gallery',
Icon: Library,
accent: '#b8bb26',
kickerKey: 'header.kicker_library',
},
transcriptions: {
labelKey: 'header.label_transcriptions',
Icon: FileText,
accent: '#d3869b',
kickerKey: 'header.kicker_library',
},
catalogue: {
labelKey: 'header.label_catalogue',
Icon: Boxes,
accent: '#689d6a',
kickerKey: 'header.kicker_preferences',
},
settings: {
labelKey: 'header.label_settings',
Icon: Settings2,
accent: '#fabd2f',
kickerKey: 'header.kicker_preferences',
},
enterprise: {
labelKey: 'header.label_enterprise',
Icon: Building2,
accent: '#fe8019',
kickerKey: 'header.kicker_licensing',
},
};
function WaveBars({ color = '#f3a5b6', active }) {
const heights = [4, 9, 5, 11, 6, 10, 5, 8];
return (
<div
data-testid="header-wave-bars"
className={`inline-flex items-center gap-[2px] h-[16px] px-[6px] transition-opacity duration-200 max-[1351px]:hidden ${active ? 'opacity-100' : 'opacity-[0.35]'}`}
aria-hidden="true"
>
{heights.map((h, i) => (
<span
key={i}
className={`inline-block w-[2.5px] rounded-[2px] transition-opacity duration-200 ${active ? '[animation:hqBounce_1.3s_ease-in-out_infinite]' : ''}`}
style={{
// Height + color are per-instance; animation-delay is per-bar.
// These three are genuinely dynamic so stay inline.
height: h,
background: color,
animationDelay: `${i * 0.08}s`,
}}
/>
))}
</div>
);
}
async function runWindowAction(action) {
try {
const { getCurrentWindow } = await import('@tauri-apps/api/window');
const appWindow = getCurrentWindow();
if (action === 'minimize') await appWindow.minimize();
else if (action === 'maximize') await appWindow.toggleMaximize();
else if (action === 'close') await appWindow.close();
} catch {
console.warn('Window control action failed');
}
}
export default function Header({
mode,
setMode,
navStyle = 'rail',
modelStatus,
doubleClickMaximize,
activeProjectName,
onFlushMemory,
}) {
// Titlebar-tabs mode puts the workspace switcher in this row, where the
// breadcrumb + wordmark normally sit — the tabs already say where you are,
// and two answers to that question in one bar is one too many.
const tabsInTitlebar = navStyle === 'tabs';
// The macOS platform config enables decorated overlay chrome. Its native
// traffic lights provide the same window actions as our custom desktop row.
const isDesktop = typeof window !== 'undefined' && '__TAURI_INTERNALS__' in window;
const hasMacTrafficLights =
isDesktop && typeof navigator !== 'undefined' && (navigator.platform || '').startsWith('Mac');
const showWindowControls = isDesktop && !hasMacTrafficLights;
const { t } = useTranslation();
// Sysinfo is subscribed here (not in App via useAppData) so the 5s poll
// only re-renders the header chrome, not the whole App tree.
const sysQuery = useSysinfo();
const sysStats = sysQuery.data ?? null;
// Default OFF — chrome shouldn't double as a resource monitor. Power users
// flip this on via Settings → Performance. Idle/Ready/Loading badge +
// Flush button stay visible regardless (action-relevant).
const showLiveStats = useAppStore((s) => s.showHeaderLiveStats);
const [flushing, setFlushing] = useState(false);
const [flushOpen, setFlushOpen] = useState(false);
const [engineFamily, setEngineFamily] = useState('tts');
const { data: engines } = useEngines();
const [engineLabelIndex, setEngineLabelIndex] = useState(0);
const [engineLabelPaused, setEngineLabelPaused] = useState(false);
const activeEngines = ['tts', 'asr', 'llm'].flatMap((family) => {
const inventory = engines?.[family];
const active = inventory?.backends?.find((engine) => engine.id === inventory.active);
return active ? [{ family, name: engineDisplayName(active.display_name) }] : [];
});
const displayedEngine = activeEngines[engineLabelIndex % (activeEngines.length || 1)];
const activeEngineName = displayedEngine?.name;
const activeEngineShortName = activeEngineName?.split(' (')[0];
useEffect(() => {
if (flushOpen || engineLabelPaused || activeEngines.length < 2) return;
const timer = setInterval(() => setEngineLabelIndex((index) => index + 1), 4000);
return () => clearInterval(timer);
}, [flushOpen, engineLabelPaused, activeEngines.length]);
const [loadedModels, setLoadedModels] = useState([]);
const [unloading, setUnloading] = useState(null);
const flushRef = useRef(null);
const flushBtnRef = useRef(null);
const [dropdownPos, setDropdownPos] = useState({ top: 0, left: 0 });
// Dynamically compute dropdown position from button rect
const computePos = useCallback(() => {
if (!flushBtnRef.current) return;
const rect = flushBtnRef.current.getBoundingClientRect();
const dropW = Math.min(420, window.innerWidth - 16);
const dropH = Math.min(640, window.innerHeight - 80);
const pad = 6;
// Default: below button, right-aligned
let top = rect.bottom + pad;
let left = rect.right - dropW;
// Flip up if too close to bottom
if (top + dropH > window.innerHeight - 10) {
top = Math.max(8, rect.top - dropH - pad);
}
// Clamp left so it doesn't go off-screen
if (left < 8) left = 8;
if (left + dropW > window.innerWidth - 8) left = window.innerWidth - dropW - 8;
setDropdownPos({ top, left, width: dropW });
}, []);
// Recompute on open, resize, and scroll
useEffect(() => {
if (!flushOpen) return;
computePos();
window.addEventListener('resize', computePos);
window.addEventListener('scroll', computePos, true);
return () => {
window.removeEventListener('resize', computePos);
window.removeEventListener('scroll', computePos, true);
};
}, [flushOpen, computePos]);
const view = VIEW_META[mode] || VIEW_META.launchpad;
const ViewIcon = view.Icon;
// Fetch loaded models when dropdown opens
useEffect(() => {
if (!flushOpen) return;
const fetchModels = async () => {
try {
const { apiFetch } = await import('../api/client');
const res = await apiFetch('/model/loaded');
const data = await res.json();
setLoadedModels(data.models || []);
} catch {}
};
fetchModels();
}, [flushOpen]);
// Click outside to close (must check both the button wrapper AND the portal dropdown)
const dropdownRef = useRef(null);
useEffect(() => {
if (!flushOpen) return;
const frame = requestAnimationFrame(() =>
dropdownRef.current?.querySelector('button')?.focus(),
);
return () => cancelAnimationFrame(frame);
}, [flushOpen]);
useEffect(() => {
const show = () => setFlushOpen(true);
window.addEventListener('engine-quick-switch', show);
return () => window.removeEventListener('engine-quick-switch', show);
}, []);
useEffect(() => {
if (!flushOpen) return;
const handler = (e) => {
const inBtn = flushRef.current && flushRef.current.contains(e.target);
const inDrop = dropdownRef.current && dropdownRef.current.contains(e.target);
if (!inBtn && !inDrop) setFlushOpen(false);
};
document.addEventListener('mousedown', handler);
const escape = (event) => {
if (event.key === 'Escape') {
setFlushOpen(false);
flushBtnRef.current?.focus();
}
};
document.addEventListener('keydown', escape);
return () => {
document.removeEventListener('mousedown', handler);
document.removeEventListener('keydown', escape);
};
}, [flushOpen]);
const unloadModel = async (modelId) => {
setUnloading(modelId);
try {
const { apiFetch } = await import('../api/client');
await apiFetch(`/model/unload/${modelId}`, { method: 'POST' });
setLoadedModels((prev) => prev.filter((m) => m.id !== modelId));
} catch {
} finally {
setUnloading(null);
}
};
// Dynamic accent color must stay inline — it's driven by the current view.
const dotStyle = { background: view.accent, boxShadow: `0 0 10px ${view.accent}90` };
const labelStyle = { color: view.accent };
return (
<div
className={`header-area ${tabsInTitlebar ? 'header-area--tabs' : ''}`}
data-tauri-drag-region
onDoubleClick={doubleClickMaximize}
>
{tabsInTitlebar ? (
<div className="header-area__tabs min-w-0">
<TitleTabs mode={mode} setMode={setMode} />
</div>
) : (
/* Left: view title + breadcrumb. On macOS the native traffic lights
float over this corner, so the block gets an extra start inset. */
<div
className={`flex items-center gap-[14px] justify-self-start min-w-0${
hasMacTrafficLights ? ' header-area__lead--mac-inset' : ''
}`}
>
<div className="inline-flex items-center gap-[6px] h-[var(--chrome-pill-h)] [font-family:var(--font-sans)] max-[961px]:gap-[5px]">
<span
/* Decorative pulse: stop it when the OS asks for reduced motion. */
className="w-[7px] h-[7px] rounded-full shrink-0 [animation:hqPulse_2.4s_ease-in-out_infinite] motion-reduce:[animation:none] max-[821px]:hidden"
style={dotStyle}
/>
<span className="text-[length:var(--chrome-label-size)] font-semibold tracking-[var(--chrome-label-track)] uppercase text-[var(--chrome-fg-muted)] max-[1501px]:hidden">
{t(view.kickerKey)}
</span>
<ChevronRight size={10} color="#504945" className="mx-[2px] max-[1501px]:hidden" />
<span
className="inline-flex items-center gap-1 [font-family:var(--font-sans)] text-[0.72rem] font-semibold tracking-[0.02em] max-[961px]:text-[0.78rem]"
style={labelStyle}
>
<ViewIcon size={12} className="mr-1 align-[-1px]" />
{t(view.labelKey)}
</span>
{activeProjectName ? (
<>
<ChevronRight size={10} color="#504945" className="mx-[2px]" />
<span
className="[font-family:var(--font-sans)] text-[0.68rem] font-medium text-[var(--chrome-fg-muted)] max-w-[180px] overflow-hidden text-ellipsis whitespace-nowrap max-[1201px]:hidden"
title={activeProjectName}
>
{activeProjectName}
</span>
</>
) : null}
</div>
{import.meta.env.DEV && (
<Button
variant="ghost"
size="sm"
title={t('common.reload')}
onClick={() => void reloadAfterApplicationPersistence()}
leading={<RefreshCw size={9} />}
className="shrink-0"
>
{t('common.reload')}
</Button>
)}
</div>
)}
{/* Center: logo — the tabs take this room in titlebar-tabs mode. */}
{!tabsInTitlebar && (
<div
className="flex items-center gap-2 justify-self-center pointer-events-none whitespace-nowrap"
translate="no"
>
<VoiceStudioMark
data-testid="voice-studio-logo"
className="size-7 overflow-visible text-[var(--chrome-accent)]"
/>
<span className="text-[0.92rem] font-semibold text-[var(--chrome-fg)] tracking-[0.02em] [font-family:var(--font-sans)] not-italic">
Voice<span className="text-[var(--chrome-accent)]">Studio</span>
</span>
</div>
)}
{/* Right: wave + sys stats. UI scale (S/M/L) lives in the bottom
LogsFooter bar so all app-wide chrome sits together. */}
<div className="flex items-center justify-end gap-3 justify-self-end min-w-0 overflow-visible">
<NotificationPanel onNavigate={setMode} />
<WaveBars color={view.accent} active={modelStatus === 'loading'} />
{sysStats && (
<div className="flex items-center gap-2 [font-family:var(--chrome-font-mono)] text-[10.5px] text-[var(--chrome-fg-dim)] bg-transparent h-[var(--chrome-pill-h)] whitespace-nowrap shrink-0 tabular-nums slashed-zero">
{showLiveStats && (
<>
<span className="max-[1081px]:hidden">
<b className="text-[var(--chrome-fg-muted)] font-semibold">RAM</b>{' '}
{sysStats.ram.toFixed(1)}/{sysStats.total_ram.toFixed(0)}G
</span>
<span className="max-[1081px]:hidden">
<b className="text-[var(--chrome-fg-muted)] font-semibold">CPU</b>{' '}
{sysStats.cpu.toFixed(0)}%
</span>
<span
className="[border-left:1px_solid_var(--chrome-border)] pl-[6px]"
aria-label={`VRAM usage: ${sysStats.vram.toFixed(1)} gigabytes`}
>
<b
className={`font-semibold ${sysStats.gpu_active ? 'text-[var(--chrome-severity-ok)]' : 'text-[var(--chrome-fg-muted)]'}`}
>
VRAM
</b>{' '}
{sysStats.vram.toFixed(1)}G
</span>
</>
)}
<span className="[border-left:1px_solid_var(--chrome-border)] pl-[6px] flex items-center gap-1">
<Badge
tone={
modelStatus === 'ready'
? 'success'
: modelStatus === 'loading'
? 'warn'
: 'neutral'
}
size="xs"
dot
className={`[border:none]! bg-transparent! p-0! normal-case! tracking-normal! font-semibold! ${modelStatus === 'loading' ? 'ui-badge--pulse' : ''}`}
>
{modelStatus === 'ready'
? t('header.status_ready')
: modelStatus === 'loading'
? t('header.status_loading')
: t('header.status_idle')}
</Badge>
</span>
{onFlushMemory && (
<div ref={flushRef} style={{ position: 'relative' }}>
<Button
ref={flushBtnRef}
variant="subtle"
size="sm"
title={activeEngineName || t('header.memory_management')}
aria-label={t('settings.engines')}
aria-haspopup="dialog"
aria-expanded={flushOpen}
loading={flushing}
leading={!flushing && <Zap size={8} />}
trailing={<ChevronDown size={8} />}
onMouseEnter={() => setEngineLabelPaused(true)}
onMouseLeave={() => setEngineLabelPaused(false)}
onFocus={() => setEngineLabelPaused(true)}
onBlur={() => setEngineLabelPaused(false)}
onClick={() => {
if (!flushOpen && displayedEngine) setEngineFamily(displayedEngine.family);
setFlushOpen((o) => !o);
}}
className="ml-[2px]"
>
<span
key={displayedEngine?.family}
className="engine-title-label flex w-[112px] items-center justify-between gap-1 max-[600px]:w-[77px]"
>
{displayedEngine && (
<span className="shrink-0 text-left text-[var(--chrome-fg-dim)]">
{t(`models.role_${displayedEngine.family}`)} ·{' '}
</span>
)}
<span className="min-w-0 flex-1 truncate text-right">
{activeEngineShortName || t('settings.engines')}
</span>
</span>
</Button>
{flushOpen &&
createPortal(
<div
role="dialog"
aria-label={t('settings.engines')}
className="fixed overflow-y-auto bg-[var(--color-bg)] border border-transparent rounded-[var(--radius-lg)] shadow-xl z-[9999] p-3"
style={{
top: dropdownPos.top,
left: dropdownPos.left,
width: dropdownPos.width,
maxHeight: `calc(100vh - ${dropdownPos.top + 8}px)`,
}}
ref={dropdownRef}
>
<div className="flex items-center justify-between gap-2 pb-2">
<span className="text-sm font-semibold">{t('settings.engines')}</span>
<button
type="button"
aria-label={t('common.close')}
onClick={() => {
setFlushOpen(false);
flushBtnRef.current?.focus();
}}
className="inline-flex h-8 w-8 items-center justify-center rounded-md border-0 bg-transparent text-[var(--chrome-fg-muted)] cursor-pointer hover:bg-[var(--chrome-hover-bg)] focus-visible:outline-2 focus-visible:outline-[var(--chrome-accent)]"
>
<X size={16} />
</button>
</div>
<Tabs value={engineFamily} onValueChange={setEngineFamily}>
<TabsList
aria-label={t('settings.engines')}
className="w-full h-auto grid grid-cols-3 bg-[var(--chrome-hover-bg)]"
>
{['tts', 'asr', 'llm'].map((family) => (
<TabsTrigger
key={family}
value={family}
className="min-h-11 cursor-pointer whitespace-normal bg-transparent text-xs text-[var(--chrome-fg-muted)] data-[state=active]:bg-[var(--chrome-accent-bg)] data-[state=active]:text-[var(--chrome-accent)] dark:data-[state=active]:bg-[var(--chrome-accent-bg)] dark:data-[state=active]:text-[var(--chrome-accent)] hover:data-[state=inactive]:bg-[var(--chrome-hover-bg)]"
>
{family === 'tts'
? t('header.speech')
: family === 'asr'
? t('projects.transcription')
: t('models.role_llm')}
</TabsTrigger>
))}
</TabsList>
<TabsContent value={engineFamily}>
<EngineQuickSwitch key={engineFamily} family={engineFamily} embedded />
</TabsContent>
</Tabs>
<button
type="button"
className="flex items-center gap-1 border-0 bg-transparent p-2 text-xs text-[var(--chrome-fg-muted)] cursor-pointer hover:text-[var(--chrome-fg)]"
onClick={() => {
setFlushOpen(false);
useAppStore.getState().openCatalogue({ family: engineFamily });
}}
>
{t('header.label_catalogue')} <ChevronRight size={12} />
</button>
<div className="h-px bg-[var(--color-border)] my-2" />
<div className="text-[10px] font-semibold text-[var(--color-fg-subtle)] uppercase tracking-[0.5px] pt-[6px] px-[12px] pb-[4px]">
{t('header.loaded_models')}
</div>
{loadedModels.length === 0 ? (
<div className="p-[12px] text-[11px] text-[var(--color-fg-muted)] text-center">
{t('header.no_models')}
</div>
) : (
loadedModels.map((m) => (
<div
key={m.id}
className="flex items-center justify-between py-[6px] px-[12px] gap-2 hover:bg-[rgba(255,255,255,0.03)]"
>
<div className="flex flex-col gap-[1px] min-w-0">
<span className="text-[12px] text-[var(--color-fg)] font-medium">
{engineDisplayName(m.name)}
{/* Resident-but-not-routed engine (e.g. VoiceStudio still in
VRAM after switching to another backend) — say so. */}
{m.is_active_engine === false && (
<span className="ml-[6px] text-[10px] font-normal text-[var(--color-fg-subtle)] [font-family:var(--font-mono)]">
{t('header.model_not_active')}
</span>
)}
</span>
<span className="text-[10px] text-[var(--color-fg-subtle)] [font-family:var(--font-mono)]">
{m.device} {m.vram_mb > 0 ? `· ${m.vram_mb.toFixed(0)} MB` : ''}
</span>
</div>
{m.unloadable && (
<button
className="text-[10px] font-semibold text-[var(--color-brand)] bg-[rgba(211,134,155,0.1)] [border:1px_solid_rgba(211,134,155,0.2)] rounded-[var(--radius-pill)] py-[2px] px-[8px] cursor-pointer shrink-0 hover:bg-[rgba(211,134,155,0.2)]"
onClick={() => unloadModel(m.id)}
disabled={unloading === m.id}
aria-label={`Unload ${m.name}`}
>
{unloading === m.id ? '…' : t('header.unload')}
</button>
)}
</div>
))
)}
<div className="h-[1px] bg-[var(--color-border)] my-[4px]" />
<button
className="flex items-center gap-[6px] w-full py-[6px] px-[12px] text-[12px] text-[var(--color-fg)] bg-transparent border-none cursor-pointer text-left hover:bg-[rgba(255,255,255,0.04)]"
onClick={async () => {
setFlushing(true);
setFlushOpen(false);
try {
await onFlushMemory(false);
} finally {
setFlushing(false);
}
}}
>
<Zap size={10} /> {t('header.flush_caches')}
</button>
<details>
<summary className="cursor-pointer px-3 py-2 text-xs text-[var(--chrome-fg-muted)]">
{t('header.memory_management')}
</summary>
<button
className="flex items-center gap-[6px] w-full py-[6px] px-[12px] text-[12px] text-[#fb4934] bg-transparent border-none cursor-pointer text-left hover:bg-[rgba(251,73,52,0.08)]"
onClick={async () => {
setFlushing(true);
setFlushOpen(false);
try {
await onFlushMemory(true);
} finally {
setFlushing(false);
}
}}
>
<Trash2 size={10} /> {t('header.unload_all_flush')}
</button>
</details>
</div>,
document.body,
)}
</div>
)}
</div>
)}
{showWindowControls && (
<div className="ml-1 flex h-full shrink-0 items-stretch" data-testid="window-controls">
<button
type="button"
className="flex h-7 w-9 items-center justify-center border-0 bg-transparent text-[var(--chrome-fg-muted)] hover:bg-[var(--chrome-hover-bg)] hover:text-[var(--chrome-fg)]"
aria-label={t('common.minimize_window')}
title={t('common.minimize_window')}
onClick={() => void runWindowAction('minimize')}
>
<Minus size={13} />
</button>
<button
type="button"
className="flex h-7 w-9 items-center justify-center border-0 bg-transparent text-[var(--chrome-fg-muted)] hover:bg-[var(--chrome-hover-bg)] hover:text-[var(--chrome-fg)]"
aria-label={t('common.maximize_restore_window')}
title={t('common.maximize_restore_window')}
onClick={() => void runWindowAction('maximize')}
>
<Square size={10} />
</button>
<button
type="button"
className="flex h-7 w-9 items-center justify-center border-0 bg-transparent text-[var(--chrome-fg-muted)] hover:bg-[#c42b1c] hover:text-white"
aria-label={t('common.close_window')}
title={t('common.close_window')}
onClick={() => void runWindowAction('close')}
>
<X size={13} />
</button>
</div>
)}
</div>
</div>
);
}
@@ -1,866 +0,0 @@
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { copyText } from '../utils/copyText';
import {
ChevronUp,
ChevronDown,
RefreshCw,
Trash2,
Copy,
Bug,
X,
AlertTriangle,
AlertCircle,
Info,
FileText,
Heart,
Mail,
Sparkles,
Braces,
Gem,
} from 'lucide-react';
import toast from 'react-hot-toast';
import { clearSystemLogs, clearTauriLogs } from '../api/system';
import {
useSystemLogs,
useTauriLogs,
useVisibleNotifications,
isDismissibleNotification,
} from '../api/hooks';
import { getFrontendLogs, clearFrontendLogs } from '../utils/consoleBuffer';
import { useTranslation } from 'react-i18next';
import { useAppStore } from '../store';
import NetworkToggle from './NetworkToggle';
import { APP_VERSION, whatsNewPending } from '../utils/appVersion';
import DonateMomentPopover, { DONATE_POPOVER_AUTO_DISMISS_MS } from './DonateMomentPopover';
import { DONATION_MOMENT_EVENT, optOutOfDonationMoments } from '../utils/donationMoments';
/**
* VSCode-style bottom panel for logs. Always-visible 28 px collapsed bar
* shows error/warning counts per source (Backend, Frontend, Tauri); click
* any pill or the chevron to expand into a resizable panel. State — which
* tab is active, is it collapsed, panel height — persists in localStorage
* so the panel remembers where the user left it across launches.
*/
const SOURCES = [
{ id: 'backend', label: 'Backend', icon: FileText },
{ id: 'frontend', label: 'Frontend', icon: FileText },
{ id: 'tauri', label: 'Tauri', icon: FileText },
// Notifications used to live here as a 4th pill but that duplicated the
// header's bell+badge (single source of truth for notifications). The
// footer is logs-only now; bell handles notifications.
// Updates tab moved to Settings → Updates (see Settings.jsx).
];
const LS_HEIGHT = 'omnivoice.logs.height';
const LS_ACTIVE = 'omnivoice.logs.active';
const MIN_H = 180;
const MAX_H = 720;
// Severity heuristics. We scan each line for these keywords so the UI
// can show badge counts per source without waiting for a structured
// logger. Matches word-boundary to avoid false positives on identifiers
// like `warning_count` or `error_handler`.
const RE_ERROR = /\b(error|fatal|exception|traceback)\b/i;
const RE_WARN = /\b(warn(ing)?|deprecated)\b/i;
function classifyLine(raw) {
const text = typeof raw === 'string' ? raw : (raw?.msg ?? String(raw));
if (RE_ERROR.test(text)) return 'error';
if (RE_WARN.test(text)) return 'warn';
return 'info';
}
function countLevels(lines) {
let error = 0,
warn = 0;
for (const l of lines) {
const sev = classifyLine(l);
if (sev === 'error') error++;
else if (sev === 'warn') warn++;
}
return { error, warn, total: lines.length };
}
function formatFrontendLine(entry) {
const ts = new Date(entry.t).toISOString().slice(11, 23);
return `[${ts}] ${entry.level.toUpperCase()} ${entry.msg}`;
}
function SeverityIcon({ level, size = 11 }) {
if (level === 'error') return <AlertCircle size={size} color="#fb4934" />;
if (level === 'warn') return <AlertTriangle size={size} color="#fabd2f" />;
return <Info size={size} color="#7c6f64" />;
}
// UiScaleToggle and ThemePicker used to live here as always-visible
// controls in the footer chrome. Moved to Settings → Appearance (see
// AppearancePanel) so the footer can stay focused on logs. The store
// fields (uiScale, theme, setUiScale, setTheme) are unchanged; only the
// rendering moved.
// ── Tailwind utility-string presets (replacing the old `logs-footer__*` BEM
// classes). Chrome palette is referenced via `--chrome-*` arbitrary values so
// the footer keeps its fixed dark-chrome look (same tokens Header uses).
// Severity colors stay as literal arbitrary values (#fb4934 / #fabd2f /
// #83a598) — NOT text-danger/text-accent — so the footer chrome stays fixed
// across themes (the token utilities recolor per [data-theme]).
const ICON_BTN =
'flex items-center justify-center w-[var(--chrome-icon-btn)] h-[var(--chrome-icon-btn)] ' +
'rounded-[3px] bg-transparent border-0 cursor-pointer transition-all ' +
'[color:var(--chrome-fg-muted)] hover:[color:var(--chrome-fg)] hover:[background:var(--chrome-hover-bg)] ' +
'disabled:opacity-40 disabled:cursor-not-allowed';
// Report button: same shell but hovers warn-yellow instead of chrome-fg.
const ICON_BTN_REPORT =
'flex items-center justify-center w-[var(--chrome-icon-btn)] h-[var(--chrome-icon-btn)] ' +
'rounded-[3px] bg-transparent border-0 cursor-pointer transition-all ' +
'[color:var(--chrome-fg-muted)] hover:[color:#fabd2f] hover:[background:var(--chrome-hover-bg)]';
const PILL_BASE =
'inline-flex items-center gap-[6px] px-[8px] py-[2px] h-[var(--chrome-pill-h)] rounded-[3px] ' +
'bg-transparent border text-[11px] cursor-pointer transition-all [font-family:inherit] ' +
'hover:[background:var(--chrome-hover-bg)] hover:[color:var(--chrome-fg)]';
// Count-badge layout/typography (severity bg+color appended per case).
const BADGE_LAYOUT =
'inline-flex items-center justify-center min-w-[18px] px-[5px] h-[14px] rounded-[7px] ' +
'text-[10px] font-semibold [font-family:var(--chrome-font-mono)]';
const BADGE_NEUTRAL = `${BADGE_LAYOUT} [background:rgba(255,255,255,0.08)] [color:var(--chrome-fg)]`;
const BADGE_ERROR = `${BADGE_LAYOUT} [background:rgba(251,73,52,0.2)] [color:#fb4934]`;
const BADGE_WARN = `${BADGE_LAYOUT} [background:rgba(250,189,47,0.2)] [color:#fabd2f]`;
const DISCORD_BTN =
'flex items-center justify-center w-[var(--chrome-icon-btn)] h-[var(--chrome-icon-btn)] shrink-0 ' +
'rounded-[4px] bg-transparent border-0 cursor-pointer [color:#7289da] opacity-60 ' +
'transition-[color,opacity,transform] duration-150 hover:opacity-100 hover:[color:#5865F2] hover:scale-110';
// API-reference button: same compact footer-icon shell as Discord/Mail but on
// the neutral chrome-muted palette, hovering to the theme accent.
const API_REF_BTN =
'flex items-center justify-center w-[var(--chrome-icon-btn)] h-[var(--chrome-icon-btn)] shrink-0 ' +
'rounded-[4px] bg-transparent border-0 cursor-pointer [color:var(--chrome-fg-muted)] opacity-70 ' +
'transition-[color,opacity,transform] duration-150 hover:opacity-100 hover:[color:var(--chrome-accent)] hover:scale-110';
const DONATE_BTN =
'flex items-center justify-center w-[var(--chrome-icon-btn)] h-[var(--chrome-icon-btn)] shrink-0 ' +
'rounded-[4px] bg-transparent border-0 cursor-pointer [color:#d3869b] ' +
'transition-[color,transform] duration-150 hover:[color:var(--chrome-accent)] hover:scale-[1.15]';
// Idle glow vs. the gentle attention pulse while the donation-moment popover
// is open. Split from DONATE_BTN so exactly one animation applies at a time.
const HEART_GLOW =
'[animation:heart-glow_2.5s_ease-in-out_infinite] motion-reduce:[animation:none]';
const HEART_PULSE =
'[animation:donate-heart-pulse_1.1s_ease-in-out_infinite] motion-reduce:[animation:none]';
function SourcePill({ source, counts, active, onClick, icon: Icon }) {
const hasErrors = counts.error > 0;
const hasWarns = counts.warn > 0;
// Severity color wins over active wins over muted (matches old cascade).
const colorClass = hasErrors
? '[color:#fb4934]'
: hasWarns
? '[color:#fabd2f]'
: active
? '[color:var(--chrome-accent)]'
: '[color:var(--chrome-fg-muted)]';
const activeClass = active
? '[background:var(--chrome-accent-bg)] [border-color:var(--chrome-accent-border)]'
: 'border-transparent';
return (
<button
type="button"
className={`${PILL_BASE} ${activeClass} ${colorClass}`}
onClick={onClick}
aria-label={`${source.label} logs${hasErrors ? `, ${counts.error} errors` : hasWarns ? `, ${counts.warn} warnings` : ''}`}
>
{Icon && <Icon size={12} className="shrink-0" aria-hidden="true" />}
<span className="font-medium">{source.label}</span>
{hasErrors && <span className={BADGE_ERROR}>{counts.error}</span>}
{!hasErrors && hasWarns && <span className={BADGE_WARN}>{counts.warn}</span>}
{!hasErrors && !hasWarns && counts.total > 0 && (
<span className={BADGE_NEUTRAL}>{counts.total}</span>
)}
</button>
);
}
// ── Seasonal / random donate heart ──────────────────────────────────────
// Christmas (Dec), Diwali (~Oct-Nov), Valentine's (Feb), Eid (~Mar-Apr),
// default pool rotates daily based on day-of-year.
const HEART_POOL = ['❤️', '🩷', '💜', '💙', '🧡', '💛', '🩵', '💖', '💗'];
const SEASONAL = [
{ month: 12, emoji: '🎄', color: '#e74c3c', title: 'Merry Christmas! Support this project' },
{ month: 2, emoji: '💝', color: '#ff6b81', title: "Happy Valentine's! Support this project" },
// Diwali window — roughly Kartik Amavasya (Oct–Nov)
{ month: 10, emoji: '🪔', color: '#f5a623', title: 'Happy Diwali! Support this project' },
{ month: 11, emoji: '✨', color: '#f5a623', title: 'Happy Diwali! Support this project' },
];
function DonateHeart() {
const now = new Date();
const month = now.getMonth() + 1;
const dayOfYear = Math.floor((now - new Date(now.getFullYear(), 0, 0)) / 86400000);
const seasonal = SEASONAL.find((s) => s.month === month);
if (seasonal) {
return (
<span style={{ fontSize: 14, lineHeight: 1 }} title={seasonal.title}>
{seasonal.emoji}
</span>
);
}
// Rotate through the pool daily
const pick = HEART_POOL[dayOfYear % HEART_POOL.length];
return <span style={{ fontSize: 14, lineHeight: 1 }}>{pick}</span>;
}
export default function LogsFooter() {
// Always start collapsed on every launch — per-session toggling works
// but nothing persists. Kill the legacy key on the way out so users
// who had it stored as "open" before aren't stuck on the next load.
if (typeof localStorage !== 'undefined') {
localStorage.removeItem('omnivoice.logs.collapsed');
}
const [collapsed, setCollapsed] = useState(true);
const { t } = useTranslation();
// Update availability drives the footer version badge's notification dot.
const updateStatus = useAppStore((s) => s.updateStatus);
const updateVersion = useAppStore((s) => s.updateVersion);
const updateReady = updateStatus === 'available' || updateStatus === 'ready';
// One-time "What's new" affordance after an update (feat/safe-updates):
// non-blocking footer pill, never a startup modal. First run with no
// recorded version baselines silently; after an update the pill shows
// until the user opens the notes (or clicks it away).
const whatsNewSeen = useAppStore((s) => s.whatsNewSeenVersion);
useEffect(() => {
if (whatsNewSeen == null && APP_VERSION !== 'unknown') {
useAppStore.getState().setWhatsNewSeenVersion(APP_VERSION);
}
}, [whatsNewSeen]);
const showWhatsNew = whatsNewPending(whatsNewSeen, APP_VERSION);
const openWhatsNew = useCallback(() => {
useAppStore.getState().setWhatsNewSeenVersion(APP_VERSION);
useAppStore.getState().openSettingsTab?.('updates');
}, []);
const [height, setHeight] = useState(() => {
const v = Number(localStorage.getItem(LS_HEIGHT));
return Number.isFinite(v) && v >= MIN_H && v <= MAX_H ? v : 300;
});
const [active, setActive] = useState(() => {
const v = localStorage.getItem(LS_ACTIVE);
return SOURCES.some((s) => s.id === v) ? v : 'backend';
});
// Only the local console ring needs state; HTTP logs render from their query.
const [frontendLines, setFrontendLines] = useState(() =>
getFrontendLogs().map(formatFrontendLine),
);
const [loading, setLoading] = useState(false);
const scrollRef = useRef(null);
useEffect(() => localStorage.setItem(LS_HEIGHT, String(height)), [height]);
useEffect(() => localStorage.setItem(LS_ACTIVE, active), [active]);
// Expose the current footer height as a CSS variable on :root. Inside the
// studio shell the footer is a grid ROW (index.css .app-container), so
// content clearance needs no variable — but the fixed toasts/previews that
// anchor above the footer (VoicePreview, ExportModal, …) and the
// setup-wizard wrapper still position off --logs-footer-height.
useEffect(() => {
const h = collapsed ? 28 : height;
document.documentElement.style.setProperty('--logs-footer-height', `${h}px`);
return () => {
document.documentElement.style.setProperty('--logs-footer-height', '28px');
};
}, [collapsed, height]);
// ── TanStack Query for backend + tauri logs ────────────────────────────
// While collapsed only the count badge is visible, so poll lazily (45s);
// tighten to 10s when the panel is open (same throttle idea as pullFrontend).
const backendLogs = useSystemLogs(300, true, collapsed ? 45_000 : 10_000);
const tauriLogs = useTauriLogs(300, true, collapsed ? 45_000 : 10_000);
const lines = useMemo(
() => ({
backend: backendLogs.data?.lines || [],
frontend: frontendLines,
tauri: tauriLogs.data?.lines || [],
}),
[backendLogs.data, tauriLogs.data, frontendLines],
);
// Skip the state update (and the re-render it forces) when the console ring
// buffer hasn't changed since the last pull — same length + same last
// timestamp means nothing new arrived.
const lastFrontendPull = useRef({ len: -1, t: 0 });
const pullFrontend = useCallback(() => {
const raw = getFrontendLogs();
const lastT = raw.length ? raw[raw.length - 1].t : 0;
const seen = lastFrontendPull.current;
if (raw.length === seen.len && lastT === seen.t) return;
lastFrontendPull.current = { len: raw.length, t: lastT };
setFrontendLines(raw.map(formatFrontendLine));
}, []);
const refreshAll = useCallback(async () => {
setLoading(true);
backendLogs.refetch();
tauriLogs.refetch();
pullFrontend();
setLoading(false);
}, [backendLogs, tauriLogs, pullFrontend]);
// Frontend logs still need a local interval (no API, reads from buffer)
useEffect(() => {
pullFrontend();
const iv = setInterval(pullFrontend, collapsed ? 8000 : 3000);
return () => clearInterval(iv);
}, [pullFrontend, collapsed]);
// ── Notifications (shared TanStack Query cache with the header bell) ────
// Already filtered to what the user hasn't dismissed — badge and tab agree.
const { notifications, isSuccess: notificationsReady } = useVisibleNotifications();
const allSourcesReady = backendLogs.isSuccess && tauriLogs.isSuccess && notificationsReady;
const dismissNotification = useAppStore((s) => s.dismissNotification);
// ── Donation moment popover (see utils/donationMoments.js) ─────────────
// The eligibility engine dispatches DONATION_MOMENT_EVENT after a rare,
// gated value-creation success; the footer just renders the speech bubble
// above the heart and auto-dismisses it. null = closed.
const [donateMoment, setDonateMoment] = useState(null);
useEffect(() => {
const onMoment = (e) => setDonateMoment({ line: e?.detail?.line ?? 0 });
window.addEventListener(DONATION_MOMENT_EVENT, onMoment);
return () => window.removeEventListener(DONATION_MOMENT_EVENT, onMoment);
}, []);
useEffect(() => {
if (!donateMoment) return undefined;
const timer = setTimeout(() => setDonateMoment(null), DONATE_POPOVER_AUTO_DISMISS_MS);
return () => clearTimeout(timer);
}, [donateMoment]);
// Allow header bell to open notifications tab
useEffect(() => {
const handler = () => {
setActive('notifications');
setCollapsed(false);
};
window.addEventListener('omni:open-notifications', handler);
return () => window.removeEventListener('omni:open-notifications', handler);
}, []);
// Auto-scroll to bottom when new lines arrive and panel is open.
useEffect(() => {
if (collapsed) return;
const el = scrollRef.current;
if (!el) return;
const atBottom = el.scrollTop + el.clientHeight >= el.scrollHeight - 40;
if (atBottom) el.scrollTop = el.scrollHeight;
}, [lines, active, collapsed]);
const counts = useMemo(
() => ({
backend: countLevels(lines.backend),
frontend: countLevels(lines.frontend),
tauri: countLevels(lines.tauri),
notifications: {
error: notifications.filter((n) => n.level === 'error').length,
warn: notifications.filter((n) => n.level === 'warn').length,
total: notifications.length,
},
}),
[lines, notifications],
);
const openTo = (id) => {
setActive(id);
setCollapsed(false);
};
// Combined backend+frontend+tauri counts for the single collapsed "Logs" tab.
const mergedCounts = useMemo(() => {
const acc = { error: 0, warn: 0, total: 0 };
for (const s of SOURCES) {
const c = counts[s.id] || { error: 0, warn: 0, total: 0 };
acc.error += c.error;
acc.warn += c.warn;
acc.total += c.total;
}
return acc;
}, [counts]);
// ── Resize handle (drag the top edge) ───────────────────────────────
const dragRef = useRef(null);
const onDragStart = (e) => {
e.preventDefault();
const startY = e.clientY;
const startH = height;
const move = (ev) => {
const dy = startY - ev.clientY;
const next = Math.min(MAX_H, Math.max(MIN_H, startH + dy));
setHeight(next);
};
const up = () => {
window.removeEventListener('mousemove', move);
window.removeEventListener('mouseup', up);
};
window.addEventListener('mousemove', move);
window.addEventListener('mouseup', up);
};
// ── Actions ─────────────────────────────────────────────────────────
const onClear = async () => {
try {
if (active === 'backend') {
await clearSystemLogs();
await backendLogs.refetch({ throwOnError: true });
} else if (active === 'tauri') {
await clearTauriLogs();
await tauriLogs.refetch({ throwOnError: true });
} else if (active === 'frontend') {
clearFrontendLogs();
pullFrontend();
}
toast.success(t('logs.log_cleared', { source: active }));
} catch (e) {
toast.error(t('logs.clear_failed', { message: e?.message || e }));
}
};
const onCopy = async () => {
try {
const raw = (lines[active] || []).join('\n');
await copyText(raw);
toast.success(t('logs.log_copied', { source: active }));
} catch (e) {
toast.error(t('logs.copy_failed', { message: e?.message || e }));
}
};
const onReportIssue = async () => {
// Collate a short diagnostic dump — last 80 lines per source + counts
// + user agent — onto the clipboard so the user can paste into a
// GitHub issue without hand-collecting files.
const header = [
`VoiceStudio — diagnostic report`,
`When: ${new Date().toISOString()}`,
`UA: ${navigator.userAgent}`,
`Counts: backend err=${counts.backend.error}/warn=${counts.backend.warn}, ` +
`frontend err=${counts.frontend.error}/warn=${counts.frontend.warn}, ` +
`tauri err=${counts.tauri.error}/warn=${counts.tauri.warn}`,
'',
].join('\n');
const body = SOURCES.map((s) => {
const l = lines[s.id] || [];
return (
`── ${s.label} (last ${Math.min(l.length, 80)} of ${l.length}) ──────────────\n` +
l.slice(-80).join('\n')
);
}).join('\n\n');
try {
await copyText(header + body);
toast.success(t('logs.report_copied'));
} catch (e) {
toast.error(t('logs.report_failed', { message: e?.message || e }));
}
};
// ── Render ──────────────────────────────────────────────────────────
const current = lines[active] || [];
return (
<div
className={['logs-footer', collapsed ? 'logs-footer--collapsed' : 'logs-footer--open'].join(
' ',
)}
style={collapsed ? undefined : { height }}
>
{!collapsed && (
<div
ref={dragRef}
className="absolute top-[-2px] left-0 right-0 h-[5px] cursor-ns-resize z-[1] hover:[background:var(--chrome-accent-border)]"
onMouseDown={onDragStart}
title={t('logs.drag_resize')}
/>
)}
<div className="flex items-center justify-between h-[28px] px-[8px] gap-[8px] [border-bottom:1px_solid_rgba(255,255,255,0.04)] shrink-0">
<div className="flex items-center gap-[8px] min-w-0 flex-1 overflow-hidden">
{/* UI scale + theme picker moved to Settings → Appearance.
Footer is logs-focused now; rarely-used display prefs don't
belong in always-visible chrome. */}
<button
type="button"
className={ICON_BTN}
onClick={() => setCollapsed((c) => !c)}
title={collapsed ? t('logs.expand') : t('logs.collapse')}
aria-label={collapsed ? t('logs.expand_aria') : t('logs.collapse_aria')}
aria-expanded={!collapsed}
>
{collapsed ? <ChevronUp size={12} /> : <ChevronDown size={12} />}
</button>
{collapsed ? (
/* Collapsed: a single merged "Logs" tab with the combined count.
Expanding reveals the per-source filter tabs below. */
<SourcePill
source={{ id: 'logs', label: t('logs.title') }}
icon={FileText}
counts={mergedCounts}
active={false}
onClick={() => openTo(SOURCES.some((s) => s.id === active) ? active : 'backend')}
/>
) : (
<>
<span className="[color:var(--chrome-fg-muted)] text-[11px] uppercase tracking-[0.06em] mr-[4px]">
{t('logs.title')}
</span>
{SOURCES.map((s) => (
<SourcePill
key={s.id}
source={s}
counts={counts[s.id]}
active={active === s.id}
onClick={() => setActive(s.id)}
/>
))}
</>
)}
</div>
<div className="flex items-center gap-[4px] shrink-0">
{!collapsed && (
<div className="flex items-center gap-[2px]">
<button
className={ICON_BTN}
onClick={refreshAll}
disabled={loading}
title={t('logs.refresh')}
aria-label={t('logs.refresh_aria')}
>
<RefreshCw size={12} className={loading ? 'motion-safe:animate-spin' : ''} />
</button>
<button
className={ICON_BTN}
onClick={onCopy}
title={t('logs.copy_visible')}
aria-label={t('logs.copy_visible_aria')}
>
<Copy size={12} />
</button>
<button
className={ICON_BTN}
onClick={onClear}
title={t('logs.clear')}
aria-label={t('logs.clear_aria')}
>
<Trash2 size={12} />
</button>
<button
className={ICON_BTN_REPORT}
onClick={onReportIssue}
title={t('logs.report_issue')}
aria-label={t('logs.report_issue_aria')}
>
<Bug size={12} />
</button>
<button
className={ICON_BTN}
onClick={() => setCollapsed(true)}
title={t('logs.close')}
aria-label={t('logs.close_aria')}
>
<X size={12} />
</button>
</div>
)}
{showWhatsNew && (
<button
type="button"
data-testid="whats-new-pill"
className={
'shrink-0 inline-flex items-center gap-[4px] px-[7px] h-[var(--chrome-icon-btn)] rounded-[999px] cursor-pointer ' +
'text-[10px] tracking-[0.02em] border border-[color:var(--chrome-accent)] bg-transparent ' +
'[color:var(--chrome-accent)] hover:opacity-80 transition-opacity duration-150'
}
onClick={openWhatsNew}
title={t('updates.whats_new_in', {
version: APP_VERSION,
defaultValue: "What's new in v{{version}}",
})}
aria-label={t('updates.whats_new_in', {
version: APP_VERSION,
defaultValue: "What's new in v{{version}}",
})}
>
<Sparkles size={11} aria-hidden="true" />
{t('update.whats_new', { defaultValue: "What's new" })}
</button>
)}
<button
type="button"
className={
'shrink-0 px-[6px] h-[var(--chrome-icon-btn)] rounded-[4px] bg-transparent border-0 cursor-pointer ' +
'text-[11px] [font-variant-numeric:tabular-nums] tracking-[0.02em] transition-[opacity,color] duration-150 ' +
'hover:opacity-100 hover:[color:var(--chrome-accent)] hover:underline ' +
(updateReady
? 'relative opacity-100 font-semibold [color:var(--chrome-accent)]'
: 'opacity-55 [color:var(--chrome-fg)]')
}
onClick={() => useAppStore.getState().openSettingsTab?.('updates')}
title={
updateReady
? t('logs.update_available', {
version: updateVersion || '',
defaultValue: 'Update available ({{version}}) — click to update',
})
: t('logs.version_updates', { defaultValue: 'Check for updates' })
}
aria-label={
updateReady
? t('logs.update_available_aria', {
version: updateVersion || '',
defaultValue: 'Update available ({{version}}) — open updates',
})
: t('logs.version_updates_aria', {
defaultValue: 'Open updates — app version {{v}}',
v: APP_VERSION,
})
}
>
v{APP_VERSION}
{updateReady && (
<span
className="inline-block w-[6px] h-[6px] ml-[5px] rounded-full align-middle [background:var(--chrome-accent)] [animation:version-dot-pulse_2s_ease-in-out_infinite]"
aria-hidden="true"
/>
)}
</button>
<NetworkToggle />
<button
type="button"
className={API_REF_BTN}
onClick={() => useAppStore.getState().openSettingsTab?.('openapi')}
title={t('logs.open_api', { defaultValue: 'API reference' })}
aria-label={t('logs.open_api_aria', { defaultValue: 'Open the OpenAPI reference' })}
>
<Braces size={14} aria-hidden="true" />
</button>
<button
type="button"
className={DISCORD_BTN}
onClick={() => {
import('../api/external').then((m) =>
m.openExternal('https://discord.gg/bzQavDfVV9'),
);
}}
title={t('logs.join_discord')}
aria-label={t('logs.join_discord_aria')}
>
<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor">
<path d="M20.317 4.37a19.791 19.791 0 0 0-4.885-1.515.074.074 0 0 0-.079.037c-.21.375-.444.864-.608 1.25a18.27 18.27 0 0 0-5.487 0 12.64 12.64 0 0 0-.617-1.25.077.077 0 0 0-.079-.037A19.736 19.736 0 0 0 3.677 4.37a.07.07 0 0 0-.032.027C.533 9.046-.32 13.58.099 18.057a.082.082 0 0 0 .031.057 19.9 19.9 0 0 0 5.993 3.03.078.078 0 0 0 .084-.028c.462-.63.874-1.295 1.226-1.994a.076.076 0 0 0-.041-.106 13.107 13.107 0 0 1-1.872-.892.077.077 0 0 1-.008-.128 10.2 10.2 0 0 0 .372-.292.074.074 0 0 1 .077-.01c3.928 1.793 8.18 1.793 12.062 0a.074.074 0 0 1 .078.01c.12.098.246.198.373.292a.077.077 0 0 1-.006.127 12.299 12.299 0 0 1-1.873.892.077.077 0 0 0-.041.107c.36.698.772 1.362 1.225 1.993a.076.076 0 0 0 .084.028 19.839 19.839 0 0 0 6.002-3.03.077.077 0 0 0 .032-.054c.5-5.177-.838-9.674-3.549-13.66a.061.061 0 0 0-.031-.03zM8.02 15.33c-1.183 0-2.157-1.085-2.157-2.419 0-1.333.956-2.419 2.157-2.419 1.21 0 2.176 1.096 2.157 2.42 0 1.333-.956 2.418-2.157 2.418zm7.975 0c-1.183 0-2.157-1.085-2.157-2.419 0-1.333.956-2.419 2.157-2.419 1.21 0 2.176 1.096 2.157 2.42 0 1.333-.947 2.418-2.157 2.418z" />
</svg>
</button>
<button
type="button"
className={DISCORD_BTN}
onClick={() => useAppStore.getState().setMode?.('contact')}
title={t('logs.contact', { defaultValue: 'Contact' })}
aria-label={t('logs.contact_aria', { defaultValue: 'Open the contact page' })}
>
<Mail size={14} />
</button>
{/* Sponsors — a compact link (never a logo strip in the 28px bar).
Opens the Support page, whose Sponsors section holds the logo
grid + "Become a sponsor" affordance. */}
<button
type="button"
className={
'shrink-0 inline-flex items-center gap-[4px] px-[7px] h-[var(--chrome-icon-btn)] rounded-[4px] ' +
'bg-transparent border-0 cursor-pointer text-[11px] tracking-[0.02em] ' +
'[color:var(--chrome-fg-muted)] transition-[color,opacity] duration-150 ' +
'hover:[color:var(--chrome-accent)]'
}
onClick={() => useAppStore.getState().setMode?.('donate')}
title={t('logs.sponsors', { defaultValue: 'Sponsors' })}
aria-label={t('logs.sponsors_aria', {
defaultValue: 'View sponsors and support the project',
})}
>
<Gem size={12} aria-hidden="true" />
{t('logs.sponsors', { defaultValue: 'Sponsors' })}
</button>
<div className="relative inline-flex shrink-0 ml-[4px]">
<button
type="button"
className={`${DONATE_BTN} ${donateMoment ? HEART_PULSE : HEART_GLOW}`}
onClick={() => {
// Manual entry is unchanged: the heart always opens the full
// donate view (and quietly retires an open popover).
setDonateMoment(null);
useAppStore.getState().setMode?.('donate');
}}
title={t('logs.support_project')}
aria-label={t('logs.support_project_aria')}
>
<DonateHeart />
</button>
{donateMoment && (
<DonateMomentPopover
line={donateMoment.line}
onLater={() => setDonateMoment(null)}
onOptOut={() => {
optOutOfDonationMoments();
// Mirror into the legacy postcard flag so both engines stay
// permanently silenced no matter which one is wired.
useAppStore.getState().optOutOfDonation?.();
setDonateMoment(null);
}}
/>
)}
</div>
</div>
</div>
{!collapsed && active !== 'notifications' && (
<div
ref={scrollRef}
className="logs-footer__body flex-1 min-h-0 overflow-y-auto overflow-x-auto py-[4px] px-[8px] select-text"
>
{current.length === 0 && (
<div className="p-[12px] [color:var(--chrome-fg-dim)] not-italic text-[11px] text-center">
{active === 'frontend' ? t('logs.empty_frontend_short') : t('logs.empty_lines')}
</div>
)}
{current.map((line, i) => {
const level = classifyLine(line);
const lineBg =
level === 'error'
? '[background:rgba(251,73,52,0.06)]'
: level === 'warn'
? '[background:rgba(250,189,47,0.04)]'
: '';
const lineColor =
level === 'error'
? '[color:#fb4934]'
: level === 'warn'
? '[color:#fabd2f]'
: '[color:#ebdbb2]';
return (
<div
key={i}
className={`flex items-start gap-[6px] px-[2px] py-[1px] rounded-[2px] ${lineBg}`}
>
<span className="pt-[2px] shrink-0">
<SeverityIcon level={level} />
</span>
<pre
className={`m-0 p-0 [font-family:inherit] text-[11.5px] leading-[1.5] whitespace-pre-wrap [word-break:break-word] flex-1 ${lineColor}`}
>
{typeof line === 'string' ? line : JSON.stringify(line)}
</pre>
</div>
);
})}
</div>
)}
{!collapsed && active === 'notifications' && (
<div className="logs-footer__body flex flex-col gap-[2px] px-[8px] py-[6px] flex-1 min-h-0 overflow-y-auto select-text">
{allSourcesReady &&
notifications.length === 0 &&
mergedCounts.error === 0 &&
mergedCounts.warn === 0 ? (
<div className="p-[12px] [color:var(--chrome-fg-dim)] not-italic text-[11px] text-center">
{t('logs.all_clear')}
</div>
) : (
notifications.map((notif) => {
// Severity border-left (literal colors, fixed across themes) +
// 1px transparent on the other sides for layout parity.
const sides =
'[border-top:1px_solid_transparent] [border-right:1px_solid_transparent] [border-bottom:1px_solid_transparent]';
const notifBorder =
notif.level === 'error'
? `[border-left:2px_solid_#fb4934] ${sides}`
: notif.level === 'warn'
? `[border-left:2px_solid_#fabd2f] ${sides}`
: `[border-left:2px_solid_#83a598] ${sides}`;
const notifHover = notif.action
? 'cursor-pointer hover:[background:rgba(255,255,255,0.06)]'
: 'hover:[background:rgba(255,255,255,0.04)]';
return (
<div
key={notif.id}
className={`flex gap-[8px] items-start px-[10px] py-[8px] rounded-md [background:rgba(255,255,255,0.02)] ${notifBorder} ${notifHover}`}
onClick={() => {
if (!notif.action) return;
// Acting on the crash notice acknowledges it — the backend
// stores the seen crash-log size so it doesn't re-fire
// every session until a NEW crash grows the log.
if (notif.id === 'crash-last-session') {
import('../api/client')
.then(({ apiFetch }) => apiFetch('/system/crash/ack', { method: 'POST' }))
.catch(() => {});
}
// Same contract for the run-sentinel notice (#1164):
// acting on it watermarks the record server-side, so it
// stops re-firing — a NEW unclean death re-arms (its id
// carries a fresh detected_at).
if (notif.id?.startsWith('last-run-crash-')) {
import('../api/client')
.then(({ apiFetch }) =>
apiFetch('/system/last-run-crash/ack', { method: 'POST' }),
)
.catch(() => {});
}
if (notif.action.type === 'navigate') {
useAppStore.getState().setMode?.(notif.action.target);
setCollapsed(true);
} else if (notif.action.type === 'settings-tab') {
useAppStore.getState().openSettingsTab?.(notif.action.target);
setCollapsed(true);
} else if (notif.action.type === 'link') {
import('../api/external').then((m) => m.openExternal(notif.action.target));
}
}}
role={notif.action ? 'button' : undefined}
tabIndex={notif.action ? 0 : undefined}
>
<span className="shrink-0 mt-[2px]">
<SeverityIcon level={notif.level} />
</span>
<div className="flex flex-col gap-[2px] flex-1 min-w-0">
<strong className="text-[12px] [color:var(--color-fg)]">{notif.title}</strong>
<span className="text-[11px] text-fg-muted leading-[1.5]">{notif.message}</span>
</div>
{notif.action && (
<span className="shrink-0 text-[11px] font-semibold text-brand whitespace-nowrap">
{notif.action.label} →
</span>
)}
{isDismissibleNotification(notif) && notif.id && (
<button
className="shrink-0 flex h-[18px] w-[18px] cursor-pointer items-center justify-center rounded border-0 bg-transparent p-0 text-fg-muted transition-colors hover:text-fg hover:[background:rgba(255,255,255,0.08)]"
onClick={(e) => {
// The row itself may navigate; hiding must not.
e.stopPropagation();
dismissNotification(notif.id);
}}
aria-label={t('common.dismiss')}
title={t('common.dismiss')}
>
<X size={11} />
</button>
)}
</div>
);
})
)}
</div>
)}
</div>
);
}
@@ -1,50 +0,0 @@
.nav-rail {
position: relative;
width: 48px;
justify-self: start;
min-height: 0;
}
.nav-rail[data-side="right"] { justify-self: end; }
.nav-rail[data-expanded="true"] {
width: min(232px, 80vw);
/* Solid themed base keeps the workspace from showing through. Elliptical
washes form quiet waves without moving behind text or clipping tooltips. */
background-color: color-mix(in srgb, var(--chrome-accent) 2%, var(--chrome-bg));
background-image:
radial-gradient(ellipse at 0% 25%, color-mix(in srgb, var(--chrome-accent) 4%, transparent), transparent 60%),
radial-gradient(ellipse at 110% 100%, color-mix(in srgb, var(--chrome-accent) 3%, transparent), transparent 65%);
box-shadow: 8px 0 24px rgb(0 0 0 / 18%);
}
.nav-rail-waves { position: absolute; inset: 0; width: 100%; height: 100%; pointer-events: none; fill: none; stroke: var(--chrome-accent); stroke-width: .7; opacity: .055; }
.nav-rail[data-expanded="true"] > :not(.nav-rail-waves) { position: relative; }
.nav-rail[data-side="right"][data-expanded="true"] { box-shadow: -8px 0 24px rgb(0 0 0 / 18%); }
.nav-rail[data-expanded="true"] > div { width: 100%; padding-inline: 12px; }
.nav-rail-links { min-height: 0; }
.nav-rail[data-expanded="true"] .nav-rail-links { gap: 4px; overflow-y: auto; }
.nav-rail-item[data-expanded="true"],
.nav-rail[data-expanded="true"] .nav-rail-toggle {
width: 100%;
justify-content: flex-start;
gap: 12px;
padding-inline: 12px;
}
.nav-rail-item { flex-shrink: 0; }
.nav-rail-item[data-expanded="true"] { height: 42px; border-radius: 8px; }
.nav-rail-item[data-expanded="true"] span { font-weight: 450; }
.nav-rail-item[data-expanded="true"][aria-current="page"] {
border-color: transparent;
background: color-mix(in srgb, var(--rail-accent) 13%, var(--color-bg));
}
.nav-rail-item[data-expanded="true"][aria-current="page"] span { font-weight: 600; }
.nav-rail-item[data-expanded="true"]::before { left: 0; right: auto; width: 2px; box-shadow: none; }
.nav-rail[data-side="right"] .nav-rail-item[data-expanded="true"]::before { right: 0; left: auto; }
.nav-rail[data-expanded="true"] .nav-rail-toggle { width: calc(100% - 24px); margin-bottom: 8px; justify-content: space-between; }
.nav-rail[data-expanded="true"] .nav-rail-toggle span { order: -1; font-size: 11px; font-weight: 600; letter-spacing: .08em; text-transform: uppercase; }
.nav-rail[data-expanded="true"] .nav-rail-footer { padding-top: 12px; border-top: 1px solid var(--chrome-border); }
.nav-rail-item:focus-visible, .nav-rail-toggle:focus-visible { outline: 2px solid var(--chrome-accent); outline-offset: 2px; }
.nav-rail-item svg { flex-shrink: 0; transition: transform 160ms ease-out; }
.nav-rail-item:is(:hover, :focus-visible) svg { transform: translateY(-1px) rotate(-5deg); }
.nav-rail-item:active svg { transform: scale(0.94); }
@media (prefers-reduced-motion: reduce) {
.nav-rail, .nav-rail-item svg { transition: none; transform: none !important; }
}
-158
View File
@@ -1,158 +0,0 @@
import React from 'react';
import { useTranslation } from 'react-i18next';
import { ArrowLeftRight, PanelLeftOpen, PanelLeftClose } from 'lucide-react';
import './NavRail.css';
import { NAV_ITEMS as ITEM_DEFS, NAV_FOOTER_ITEMS as FOOTER_DEFS } from './navItems';
// Shared icon-button base for the chrome rail (was `.rail-btn`). `group` enables
// the hover-reveal of the per-button tooltip label below.
const RAIL_BTN_BASE =
'group relative inline-flex h-[36px] w-[36px] cursor-pointer items-center justify-center rounded-[var(--chrome-radius-pill)] [transition:background_0.14s,color_0.14s,border-color_0.14s]';
// Hover-reveal tooltip label (was `.rail-btn .rail-label`); flips to the opposite
// edge when the rail sits on the right.
function railLabelCls(side) {
const sideCls =
side === 'right'
? 'left-auto right-[48px] [transform:translate(4px,-50%)]'
: 'left-[46px] [transform:translate(-4px,-50%)]';
return `pointer-events-none absolute top-1/2 z-[10000] whitespace-nowrap rounded-[var(--chrome-radius-pill)] bg-[var(--chrome-bg)] px-[8px] py-[3px] font-sans text-[11px] font-medium text-[var(--chrome-fg)] opacity-0 [border:1px_solid_var(--chrome-border-strong)] [transition:opacity_0.15s,transform_0.15s] group-hover:opacity-100 group-hover:[transform:translate(0,-50%)] ${sideCls}`;
}
function RailBtn({ active, Icon, label, accent, side, onClick, expanded }) {
// Active = accent-tinted fill/border + an accent indicator bar (`::before`)
// hanging off the rail edge; flips edges with the rail side.
const stateCls = active
? `text-[var(--rail-accent,var(--chrome-accent))] bg-[color-mix(in_srgb,var(--rail-accent,var(--chrome-accent))_12%,transparent)] [border:1px_solid_color-mix(in_srgb,var(--rail-accent,var(--chrome-accent))_35%,transparent)] before:absolute before:top-[20%] before:bottom-[20%] before:w-[3px] before:rounded-[2px] before:bg-[var(--rail-accent,#f3a5b6)] before:content-[''] before:[box-shadow:0_0_10px_color-mix(in_srgb,var(--rail-accent,#f3a5b6)_50%,transparent)] ${
side === 'right' ? 'before:right-[-8px]' : 'before:left-[-8px]'
}`
: 'bg-transparent text-[var(--chrome-fg-dim)] [border:1px_solid_transparent] hover:bg-[var(--chrome-hover-bg)] hover:text-[var(--chrome-fg)]';
return (
<button
onClick={onClick}
aria-label={label}
aria-current={active ? 'page' : undefined}
className={`nav-rail-item ${RAIL_BTN_BASE} ${stateCls}`}
data-expanded={expanded}
style={{ '--rail-accent': accent }}
>
<Icon size={18} aria-hidden="true" />
<span className={expanded ? 'min-w-0 truncate text-sm' : railLabelCls(side)}>{label}</span>
</button>
);
}
export default function NavRail({ mode, setMode, side = 'left', onFlipSide }) {
const { t } = useTranslation();
const [expanded, setExpanded] = React.useState(false);
const railRef = React.useRef(null);
React.useEffect(() => {
if (!expanded) return;
const closeOutside = (event) => {
if (!railRef.current?.contains(event.target)) setExpanded(false);
};
const escape = (event) => {
if (event.key === 'Escape') {
setExpanded(false);
railRef.current?.querySelector('[aria-expanded]')?.focus();
}
};
document.addEventListener('pointerdown', closeOutside);
document.addEventListener('keydown', escape);
return () => {
document.removeEventListener('pointerdown', closeOutside);
document.removeEventListener('keydown', escape);
};
}, [expanded]);
const items = React.useMemo(
() => ITEM_DEFS.map((d) => ({ ...d, label: t(`nav.${d.tKey}`) })),
[t],
);
const footerItems = React.useMemo(
() => FOOTER_DEFS.map((d) => ({ ...d, label: t(`nav.${d.tKey}`) })),
[t],
);
// `nav-rail` is retained purely as the layout hook the (out-of-scope)
// `.app-container > .nav-rail` grid rules position by; all visual styling now
// lives in the utilities below. Border flips to the inner edge when on the right.
const asideBorder =
side === 'right'
? '[border-left:1px_solid_var(--chrome-border)]'
: '[border-right:1px_solid_var(--chrome-border)]';
return (
<aside
ref={railRef}
data-expanded={expanded}
data-side={side}
className={`nav-rail z-50 flex select-none flex-col items-center gap-[10px] bg-[var(--chrome-bg)] pb-[10px] pt-[18px] ${asideBorder}`}
>
{expanded && (
<svg
className="nav-rail-waves"
viewBox="0 0 232 1000"
preserveAspectRatio="none"
aria-hidden="true"
focusable="false"
>
{[0, 12, 24, 36].map((offset) => (
<path
key={offset}
transform={`translate(${offset} 0)`}
d="M-90 80 C270 240 -170 450 60 650 S270 860 120 1040"
/>
))}
</svg>
)}
<button
type="button"
aria-label={t('nav.workspaces')}
aria-expanded={expanded}
onClick={() => setExpanded((value) => !value)}
className="nav-rail-toggle inline-flex h-9 w-9 shrink-0 items-center justify-center rounded-md border-0 bg-transparent text-[var(--chrome-fg-muted)] cursor-pointer hover:bg-[var(--chrome-hover-bg)]"
>
{expanded ? <PanelLeftClose size={18} /> : <PanelLeftOpen size={18} />}
{expanded && <span className="text-sm">{t('nav.workspaces')}</span>}
</button>
<div className="nav-rail-links flex flex-1 flex-col items-center gap-[9px]">
{items.map((it) => (
<RailBtn
key={it.id}
{...it}
side={side}
expanded={expanded}
active={mode === it.id}
onClick={() => {
setMode(it.id);
setExpanded(false);
}}
/>
))}
</div>
<div className="nav-rail-footer flex flex-col items-center gap-[8px]">
{footerItems.map((it) => (
<RailBtn
key={it.id}
{...it}
side={side}
expanded={expanded}
active={mode === it.id}
onClick={() => {
setMode(it.id);
setExpanded(false);
}}
/>
))}
<button
onClick={onFlipSide}
title={side === 'left' ? t('nav.move_rail_right') : t('nav.move_rail_left')}
aria-label={t('nav.flip_rail')}
className="relative mt-[6px] inline-flex h-[30px] w-[36px] cursor-pointer items-center justify-center rounded-none bg-transparent pt-[10px] text-[var(--chrome-fg-dim)] [border-top:1px_solid_var(--chrome-border)] [border-right:1px_solid_transparent] [border-bottom:1px_solid_transparent] [border-left:1px_solid_transparent] [transition:background_0.14s,color_0.14s,border-color_0.14s] hover:bg-transparent hover:text-[var(--chrome-accent)] hover:[transform:rotate(180deg)]"
>
<ArrowLeftRight size={15} />
</button>
</div>
</aside>
);
}
@@ -1,33 +0,0 @@
import React from 'react';
import { render, screen, fireEvent } from '@testing-library/react';
import { describe, it, expect, vi } from 'vitest';
import NavRail from './NavRail';
describe('expandable workspace rail', () => {
it('reveals labels without duplicate tooltips and collapses on selection', () => {
const setMode = vi.fn();
render(<NavRail mode="launchpad" setMode={setMode} />);
const toggle = screen.getByRole('button', { name: 'Workspaces' });
fireEvent.click(toggle);
expect(toggle).toHaveAttribute('aria-expanded', 'true');
const voice = screen.getByRole('button', { name: 'Voice', exact: true });
expect(voice).not.toHaveAttribute('title');
expect(voice).toHaveAttribute('data-expanded', 'true');
expect(screen.getByRole('button', { name: 'Home studio', exact: true })).toHaveAttribute(
'aria-current',
'page',
);
fireEvent.click(voice);
expect(setMode).toHaveBeenCalledWith('studio');
expect(toggle).toHaveAttribute('aria-expanded', 'false');
});
it('closes on Escape and restores toggle focus', () => {
render(<NavRail mode="studio" setMode={vi.fn()} side="right" />);
const toggle = screen.getByRole('button', { name: 'Workspaces' });
fireEvent.click(toggle);
fireEvent.keyDown(document, { key: 'Escape' });
expect(toggle).toHaveAttribute('aria-expanded', 'false');
expect(toggle).toHaveFocus();
});
});
@@ -1,197 +0,0 @@
// electron/src/shared/components/NetworkToggle.jsx
import { useEffect, useState, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { copyText } from '../utils/copyText';
import QRCode from 'qrcode';
import { Wifi, WifiOff, Copy, ExternalLink } from 'lucide-react';
import toast from 'react-hot-toast';
import { apiJson, apiPost } from '../api/client';
import { openExternal } from '../api/external';
export default function NetworkToggle() {
const { t } = useTranslation();
const [st, setSt] = useState({ enabled: false });
const [busy, setBusy] = useState(false);
const [open, setOpen] = useState(false);
const [confirming, setConfirming] = useState(false);
const [qrs, setQrs] = useState({});
const refresh = useCallback(async () => {
try {
setSt(await apiJson('/system/network/state'));
} catch {
/* loopback only; ignore */
}
}, []);
useEffect(() => {
refresh();
}, [refresh]);
useEffect(() => {
if (!st.enabled || !st.pin) {
setQrs({});
return;
}
let cancelled = false;
(async () => {
const next = {};
for (const ip of st.lan_addresses || []) {
next[ip] = await QRCode.toDataURL(`http://${ip}:${st.share_port}/?pin=${st.pin}`);
}
if (!cancelled) setQrs(next);
})();
return () => {
cancelled = true;
};
}, [st.enabled, st.pin, st.share_port, st.lan_addresses]);
// NOTE: do NOT use window.confirm here — it's a no-op in the Tauri webview
// (returns false), which silently swallowed the enable action.
const enable = async () => {
setBusy(true);
try {
setSt(await apiPost('/system/network/enable'));
setConfirming(false);
setOpen(true);
} catch (e) {
toast.error(t('network.enable_error', { message: e.message }));
} finally {
setBusy(false);
}
};
const disable = async () => {
setBusy(true);
try {
await apiPost('/system/network/disable');
await refresh();
setOpen(false);
} catch (e) {
toast.error(t('network.disable_error', { message: e.message }));
} finally {
setBusy(false);
}
};
const copy = (text) => {
copyText(text);
toast.success(t('network.copied'));
};
return (
<div className="relative inline-flex items-center flex-shrink-0">
<button
className={`inline-flex items-center gap-[5px] py-[2px] px-[8px] h-[20px] rounded-sm font-medium text-[11px] [font-family:inherit] cursor-pointer [transition:all_0.1s] border border-solid disabled:opacity-50 disabled:cursor-not-allowed ${st.enabled ? 'bg-[rgba(184,187,38,0.12)] border-transparent text-[#b8bb26] hover:bg-[rgba(184,187,38,0.18)]' : 'bg-transparent border-transparent text-[var(--color-fg-muted)] hover:bg-[var(--chrome-hover-bg)] hover:text-fg'}`}
onClick={st.enabled ? () => setOpen((o) => !o) : () => setConfirming((c) => !c)}
disabled={busy}
title={st.enabled ? t('network.sharing_on_title') : t('network.share_on_network')}
>
{/* 14px matches the footer's other right-side icons (Discord, Mail,
donate heart) — keep them optically uniform. */}
{st.enabled ? <Wifi size={14} /> : <WifiOff size={14} />}
<span>
{busy ? t('network.switching') : st.enabled ? t('network.network') : t('network.local')}
</span>
</button>
{!st.enabled && confirming && (
<div className="absolute bottom-[calc(100%+8px)] right-0 z-[60] w-[248px] flex flex-col gap-[8px] p-[12px] bg-[var(--chrome-bg,#1d2021)] border border-solid border-transparent rounded-[8px] shadow-[0_8px_24px_rgba(0,0,0,0.45)] text-fg">
<div className="text-[11px] font-semibold uppercase [letter-spacing:0.06em] text-[#b8bb26]">
{t('network.share_confirm_title')}
</div>
<p className="m-0 text-[11px] [line-height:1.5] text-[#a89984]">
{t('network.share_confirm_hint')}
</p>
<div className="flex gap-[6px] mt-[8px]">
<button
type="button"
className="bg-transparent border border-solid border-transparent [color:inherit] text-[11px] [font-family:inherit] py-[5px] px-[12px] rounded-md cursor-pointer hover:bg-[var(--chrome-hover-bg)] disabled:opacity-50 disabled:cursor-not-allowed"
onClick={() => setConfirming(false)}
disabled={busy}
>
{t('common.cancel')}
</button>
<button
type="button"
className="bg-[rgba(184,187,38,0.15)] border border-solid border-transparent text-[#b8bb26] text-[11px] font-semibold [font-family:inherit] py-[5px] px-[12px] rounded-md cursor-pointer hover:bg-[rgba(184,187,38,0.25)] disabled:opacity-50 disabled:cursor-not-allowed"
onClick={enable}
disabled={busy}
>
{busy ? t('network.enabling') : t('network.enable')}
</button>
</div>
</div>
)}
{st.enabled && open && (
<div className="absolute bottom-[calc(100%+8px)] right-0 z-[60] w-[248px] flex flex-col gap-[8px] p-[12px] bg-[var(--chrome-bg,#1d2021)] border border-solid border-transparent rounded-[8px] shadow-[0_8px_24px_rgba(0,0,0,0.45)] text-fg">
<div className="text-[11px] font-semibold uppercase [letter-spacing:0.06em] text-[#b8bb26]">
{t('network.shared_title')}
</div>
{(st.lan_addresses || []).length === 0 && (
<p className="m-0 text-[11px] [line-height:1.5] text-[#a89984]">
{t('network.no_interface')}
</p>
)}
{(st.lan_addresses || []).map((ip) => {
const url = `http://${ip}:${st.share_port}/?pin=${st.pin}`;
return (
<div
key={ip}
className="flex flex-col items-center gap-[8px] p-[8px] rounded-lg bg-[rgba(255,255,255,0.03)] border border-solid border-transparent"
>
<div className="flex items-center justify-between gap-[8px] w-full">
<code className="[font-family:var(--chrome-font-mono,var(--font-mono,monospace))] text-[11.5px] text-fg break-all">
{ip}:{st.share_port}
</code>
<div className="flex items-center gap-[2px] flex-shrink-0">
<button
type="button"
className="bg-transparent border-0 text-[#a89984] cursor-pointer w-[22px] h-[22px] rounded-sm flex items-center justify-center [transition:all_0.1s] hover:text-[#b8bb26] hover:bg-[rgba(255,255,255,0.06)]"
onClick={() => copy(url)}
aria-label={`Copy ${ip}`}
title={t('network.copy_link')}
>
<Copy size={12} />
</button>
<button
type="button"
className="bg-transparent border-0 text-[#a89984] cursor-pointer w-[22px] h-[22px] rounded-sm flex items-center justify-center [transition:all_0.1s] hover:text-[#b8bb26] hover:bg-[rgba(255,255,255,0.06)]"
onClick={() => openExternal(url)}
aria-label={`Open ${ip}`}
title={t('network.open_in_browser')}
>
<ExternalLink size={12} />
</button>
</div>
</div>
{qrs[ip] && (
<img
className="block w-[104px] h-[104px] rounded-md bg-[#fff] p-[4px]"
src={qrs[ip]}
alt={t('network.qr_alt', { ip })}
width={104}
height={104}
/>
)}
</div>
);
})}
<div className="text-[12px] text-[#a89984] text-center">
{t('network.pin')}{' '}
<strong className="[font-family:var(--chrome-font-mono,var(--font-mono,monospace))] text-[14px] [letter-spacing:0.12em] text-[#b8bb26]">
{st.pin}
</strong>
</div>
<button
type="button"
className="bg-[rgba(251,73,52,0.12)] border border-solid border-transparent text-danger text-[11px] font-semibold [font-family:inherit] py-[5px] px-[10px] rounded-md cursor-pointer [transition:all_0.1s] hover:bg-[rgba(251,73,52,0.2)] disabled:opacity-50 disabled:cursor-not-allowed"
onClick={disable}
disabled={busy}
>
{t('network.stop_sharing')}
</button>
</div>
)}
</div>
);
}
@@ -1,45 +0,0 @@
// electron/src/shared/components/NetworkToggle.test.jsx
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, screen, waitFor, fireEvent } from '@testing-library/react';
import NetworkToggle from './NetworkToggle';
describe('NetworkToggle', () => {
let realFetch;
beforeEach(() => {
realFetch = global.fetch;
});
afterEach(() => {
global.fetch = realFetch;
});
it('defaults to Local when state reports disabled', async () => {
global.fetch = vi.fn(() =>
Promise.resolve({ ok: true, json: async () => ({ enabled: false }) }),
);
render(<NetworkToggle />);
await waitFor(() => expect(screen.getByText(/local/i)).toBeInTheDocument());
});
it('Local → in-app confirm → Enable calls the enable endpoint (regression: no window.confirm)', async () => {
const posts = [];
global.fetch = vi.fn((url, opts) => {
const u = String(url);
if ((opts?.method || 'GET') === 'POST') posts.push(u);
if (u.endsWith('/system/network/enable')) {
return Promise.resolve({
ok: true,
json: async () => ({ enabled: true, share_port: 5050, pin: '123456', lan_addresses: [] }),
});
}
return Promise.resolve({ ok: true, json: async () => ({ enabled: false }) });
});
render(<NetworkToggle />);
const pill = await screen.findByRole('button', { name: /local/i });
fireEvent.click(pill); // opens the in-app confirm — must NOT depend on window.confirm
const enableBtn = await screen.findByRole('button', { name: /^enable$/i });
fireEvent.click(enableBtn);
await waitFor(() => expect(posts.some((u) => u.endsWith('/system/network/enable'))).toBe(true));
});
});
@@ -1,39 +0,0 @@
/**
* NotificationPanel — bell icon in the header that opens the
* Notifications tab in the footer status bar.
*/
import React from 'react';
import { Bell } from 'lucide-react';
import { useVisibleNotifications } from '../api/hooks';
export default function NotificationPanel() {
// Shared TanStack Query cache entry with LogsFooter — one 30s poll,
// minus the notes the user has dismissed (the badge must agree with
// what the footer tab actually shows).
const { notifications: notifs } = useVisibleNotifications();
const count = notifs.length;
const hasErrors = notifs.some((n) => n.level === 'error');
const hasWarns = notifs.some((n) => n.level === 'warn');
const openNotifications = () => {
window.dispatchEvent(new CustomEvent('omni:open-notifications'));
};
return (
<button
className={`relative flex h-[28px] w-[28px] shrink-0 cursor-pointer items-center justify-center rounded-md border-0 bg-transparent p-0 transition-all duration-[0.15s] hover:bg-[rgba(255,255,255,0.04)] hover:text-fg ${count > 0 ? 'text-brand' : 'text-fg-muted'}`}
onClick={openNotifications}
aria-label={`Notifications (${count})`}
title="Notifications"
>
<Bell size={14} className={count > 0 ? '-translate-x-0.5 translate-y-0.5' : ''} />
{count > 0 && (
<span
className={`pointer-events-none absolute top-0 right-0 flex h-[14px] min-w-[14px] items-center justify-center rounded-[7px] px-[3px] font-mono text-[9px] font-bold leading-none text-white shadow-[0_1px_3px_rgba(0,0,0,0.4)] ${!hasErrors && hasWarns ? 'bg-warn' : 'bg-danger'}`}
>
{count}
</span>
)}
</button>
);
}
@@ -1,14 +0,0 @@
import React from 'react';
import { render, screen } from '@testing-library/react';
import { expect, it, vi } from 'vitest';
import NotificationPanel from './NotificationPanel';
vi.mock('../api/hooks', () => ({
useVisibleNotifications: () => ({ notifications: [{ level: 'error' }, { level: 'warn' }] }),
}));
it('keeps the badge inside the title-bar button', () => {
render(<NotificationPanel />);
expect(screen.getByText('2')).toHaveClass('top-0', 'right-0');
expect(screen.getByText('2')).not.toHaveClass('-top-[4px]');
});
@@ -1,132 +0,0 @@
import React, { useCallback, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { toast } from 'react-hot-toast';
import { apiPost } from '../api/client';
import { Dialog, Button } from '../ui';
/**
* PocketTTS license acceptance modal (#1306).
*
* Same shape as SupertonicLicenseDialog: rendered by EngineCompatibilityMatrix
* when the user enables PocketTTS while the backend reports
* ``available=false`` with ``reason`` containing ``"license not accepted"``.
*
* Licenses surfaced:
* - Code: MIT (https://github.com/kyutai-labs/pocket-tts/blob/main/LICENSE)
* - Model weights: CC-BY-4.0 (https://huggingface.co/kyutai/pocket-tts)
*
* The weights are gated on HuggingFace (access agreement + contact info); the
* dialog says so up front so the user knows the first download needs HF auth.
*/
const LICENSE_URLS = {
code: 'https://github.com/kyutai-labs/pocket-tts/blob/main/LICENSE',
model: 'https://huggingface.co/kyutai/pocket-tts',
conditions: 'https://huggingface.co/kyutai/pocket-tts',
};
const LINK_CLS =
'text-[0.83rem] text-[color:var(--accent,#8ab4f8)] no-underline hover:underline focus-visible:underline';
const SECTION_CLS = 'rounded-lg border border-transparent bg-white/[0.04] px-[0.9rem] py-3';
const SECTION_H_CLS =
'm-0 mb-[0.3rem] text-[0.85rem] font-semibold uppercase tracking-[0.02em] opacity-85';
const SECTION_P_CLS = 'm-0 mb-2 text-[0.85rem] leading-[1.5] opacity-90';
export default function PocketTTSLicenseDialog({ open, onClose, onAccepted }) {
const { t } = useTranslation();
const [submitting, setSubmitting] = useState(false);
const accept = useCallback(async () => {
setSubmitting(true);
try {
await apiPost('/api/settings/license', {
engine_id: 'pockettts',
accepted: true,
});
toast.success(t('license.pockettts_accepted_toast'));
onAccepted?.();
onClose?.();
} catch (e) {
const msg = e?.message || String(e);
toast.error(t('license.accept_error', { message: msg }));
} finally {
setSubmitting(false);
}
}, [onAccepted, onClose, t]);
return (
<Dialog
open={open}
onClose={onClose}
size="md"
dismissable={!submitting}
title={t('license.pockettts_title')}
footer={
<>
<Button variant="subtle" onClick={onClose} disabled={submitting}>
{t('common.cancel')}
</Button>
<Button
variant="primary"
onClick={accept}
disabled={submitting}
loading={submitting}
autoFocus
>
{submitting ? t('license.saving') : t('license.accept')}
</Button>
</>
}
>
<p className="m-0 mb-4 text-[0.9rem] leading-[1.5] opacity-85">
{t('license.pockettts_intro')}
</p>
<div className="mb-1 grid gap-[0.85rem]">
<section className={SECTION_CLS}>
<h3 className={SECTION_H_CLS}>{t('license.sdk_heading')}</h3>
<p className={SECTION_P_CLS}>{t('license.pockettts_sdk_desc')}</p>
<a
href={LICENSE_URLS.code}
target="_blank"
rel="noopener noreferrer"
className={LINK_CLS}
>
{t('license.read_mit')}
</a>
</section>
<section className={SECTION_CLS}>
<h3 className={SECTION_H_CLS}>{t('license.pockettts_model_heading')}</h3>
<p className={SECTION_P_CLS}>{t('license.pockettts_model_desc')}</p>
<a
href={LICENSE_URLS.model}
target="_blank"
rel="noopener noreferrer"
className={LINK_CLS}
>
{t('license.read_cc_by')}
</a>
</section>
<section className={SECTION_CLS}>
<h3 className={SECTION_H_CLS}>{t('license.gate_heading')}</h3>
<p className={SECTION_P_CLS}>{t('license.gate_desc')}</p>
<p className={SECTION_P_CLS}>{t('license.pockettts_conditions_desc')}</p>
<a
href={LICENSE_URLS.conditions}
target="_blank"
rel="noopener noreferrer"
className={LINK_CLS}
>
{t('license.review_access_conditions')}
</a>
</section>
</div>
<p className="m-0 mt-3 text-[0.78rem] leading-[1.5] opacity-70">
{t('license.pockettts_footer')}
</p>
</Dialog>
);
}
@@ -1,47 +0,0 @@
import SearchableSelect from './SearchableSelect';
import { DEFAULT_SPLIT_MAX, SPLIT_MODES } from '../utils/splitStoryText';
const FIELD_CLS =
'w-[64px] px-[6px] py-[4px] bg-bg-elev-2 border border-border rounded-sm text-fg [font-family:var(--font-mono)] [font-size:var(--text-xs)]';
/**
* Preset menu + (sentence mode only) character cap for the legacy Paste & Split panel.
* Controlled: the parent owns `preset` and `cap`.
*/
export default function SplitPresetBar({ t, preset, onPreset, cap, onCap }) {
const choices = SPLIT_MODES.map((value) => ({ value, label: t(`stories.split_${value}`) }));
const parseCap = (raw) => {
const n = parseInt(raw, 10);
return Number.isNaN(n) || n <= 0 ? DEFAULT_SPLIT_MAX.sentences : n;
};
return (
<>
<div className="w-[150px]" title={t('stories.splitModeHint')}>
<SearchableSelect
value={preset}
onChange={onPreset}
options={choices}
ariaLabel={t('stories.splitMode')}
menuPortal
size="sm"
/>
</div>
{preset === 'sentences' ? (
<label className="flex items-center gap-[6px] [font-size:var(--text-xs)] text-fg-muted">
{t('stories.maxChars')}
<input
type="number"
min={60}
max={1000}
step={10}
value={cap}
onChange={(e) => onCap(parseCap(e.target.value))}
name="story-segment-length"
inputMode="numeric"
className={FIELD_CLS}
/>
</label>
) : null}
</>
);
}
File diff suppressed because it is too large. Load diff
@@ -1,128 +0,0 @@
import React, { useCallback, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { toast } from 'react-hot-toast';
import { apiPost } from '../api/client';
import { Dialog, Button } from '../ui';
/**
* Supertonic-3 license acceptance modal (Phase 3 Plan 03-01 / TTS-05).
*
* Rendered by ``EngineCompatibilityMatrix`` when the user toggles the
* Supertonic-3 row's Enable / Use button while the backend reports
* ``available=false`` with ``reason`` containing
* ``"license not accepted"``. On Accept the dialog POSTs to
* ``/api/settings/license`` (loopback-gated, allow-list of one engine
* id ‑‑ ``"supertonic3"``); on success it calls ``onAccepted()`` so the
* matrix re-fetches engine status.
*
* Licenses surfaced:
* • SDK code ‑‑ MIT (https://github.com/supertone-inc/supertonic/blob/main/LICENSE)
* • Model weights ‑‑ OpenRAIL-M (https://huggingface.co/Supertone/supertonic-3/blob/main/LICENSE)
*
* Both links open in the user's default browser. The dialog does NOT
* embed the full license text ‑‑ that's the user's call to make on
* github.com / huggingface.co. We only need their explicit click to
* Accept.
*
* Built on the shadcn-backed `src/ui` Dialog primitive (Radix dialog:
* focus-trap, scroll-lock, ESC-to-close, ARIA). While a POST is in flight
* the dialog is non-dismissable so the user can't close mid-save.
*
* Props:
* - open: boolean ‑‑ controls visibility
* - onClose: () => void ‑‑ user clicked Cancel / dismissed
* - onAccepted: () => void‑‑ user clicked Accept and POST succeeded
*/
const LICENSE_URLS = {
code: 'https://github.com/supertone-inc/supertonic/blob/main/LICENSE',
model: 'https://huggingface.co/Supertone/supertonic-3/blob/main/LICENSE',
};
const LINK_CLS =
'text-[0.83rem] text-[color:var(--accent,#8ab4f8)] no-underline hover:underline focus-visible:underline';
const SECTION_CLS = 'rounded-lg border border-transparent bg-white/[0.04] px-[0.9rem] py-3';
const SECTION_H_CLS =
'm-0 mb-[0.3rem] text-[0.85rem] font-semibold uppercase tracking-[0.02em] opacity-85';
const SECTION_P_CLS = 'm-0 mb-2 text-[0.85rem] leading-[1.5] opacity-90';
export default function SupertonicLicenseDialog({ open, onClose, onAccepted }) {
const { t } = useTranslation();
const [submitting, setSubmitting] = useState(false);
const accept = useCallback(async () => {
setSubmitting(true);
try {
await apiPost('/api/settings/license', {
engine_id: 'supertonic3',
accepted: true,
});
toast.success(t('license.accepted_toast'));
onAccepted?.();
onClose?.();
} catch (e) {
const msg = e?.message || String(e);
toast.error(t('license.accept_error', { message: msg }));
} finally {
setSubmitting(false);
}
}, [onAccepted, onClose, t]);
return (
<Dialog
open={open}
onClose={onClose}
size="md"
dismissable={!submitting}
title={t('license.title')}
footer={
<>
<Button variant="subtle" onClick={onClose} disabled={submitting}>
{t('common.cancel')}
</Button>
<Button
variant="primary"
onClick={accept}
disabled={submitting}
loading={submitting}
autoFocus
>
{submitting ? t('license.saving') : t('license.accept')}
</Button>
</>
}
>
<p className="m-0 mb-4 text-[0.9rem] leading-[1.5] opacity-85">{t('license.intro')}</p>
<div className="mb-1 grid gap-[0.85rem]">
<section className={SECTION_CLS}>
<h3 className={SECTION_H_CLS}>{t('license.sdk_heading')}</h3>
<p className={SECTION_P_CLS}>{t('license.sdk_desc')}</p>
<a
href={LICENSE_URLS.code}
target="_blank"
rel="noopener noreferrer"
className={LINK_CLS}
>
{t('license.read_mit')}
</a>
</section>
<section className={SECTION_CLS}>
<h3 className={SECTION_H_CLS}>{t('license.model_heading')}</h3>
<p className={SECTION_P_CLS}>{t('license.model_desc')}</p>
<a
href={LICENSE_URLS.model}
target="_blank"
rel="noopener noreferrer"
className={LINK_CLS}
>
{t('license.read_openrail')}
</a>
</section>
</div>
<p className="m-0 mt-3 text-[0.78rem] leading-[1.5] opacity-70">{t('license.footer')}</p>
</Dialog>
);
}
@@ -1,123 +0,0 @@
/**
* TitleTabs — the titlebar tab strip, the alternative to the icon rail.
*
* Settings → Appearance → Navigation style swaps this in for `NavRail`
* (`navStyle: 'tabs'`); both render the same `navItems` list, so a workspace
* added there appears in both skins.
*
* The strip lives INSIDE the header row (`Header.jsx`) rather than in its own
* row, so the tabs sit in the window's title bar the way a browser's do — on
* macOS the header's 64px left inset keeps them clear of the traffic lights.
* Everything that makes the tab read as a tab (the connective bottom curl,
* the accent rule, the separators) is in `index.css` under `.tabstrip`.
*/
import React from 'react';
import { useTranslation } from 'react-i18next';
import { NAV_ITEMS, NAV_FOOTER_ITEMS } from './navItems';
function Tab({ item, active, showSeparator, onClick }) {
const { Icon, label, accent } = item;
return (
<button
type="button"
onClick={onClick}
title={label}
aria-current={active ? 'page' : undefined}
data-testid={`titletab-${item.id}`}
className={`tabstrip__tab ${active ? 'is-active' : ''} ${
showSeparator ? 'has-separator' : ''
}`}
style={{ '--tab-accent': accent }}
>
<Icon size={13} className="tabstrip__icon" />
<span className="tabstrip__label">{label}</span>
</button>
);
}
/**
* Labels are all-or-nothing.
*
* Nine tabs sharing a title bar with the status cluster is a width the strip
* loses: letting every tab shrink turns the whole row into "Laun… / V… / D. /
* St…", which is denser AND less legible than the icons alone. So the strip
* measures what it would need with every label shown and, when that doesn't
* fit, keeps the label only on the tab you're in — the one label that says
* something the icon doesn't. The rest keep their tooltips.
*
* Measured, not thresholded: the room available depends on locale (German
* labels run ~40% longer), UI scale, font choice and whether the live-metrics
* cluster is on. Any px breakpoint would be wrong for some combination of
* those. `is-measuring` forces the full layout for one synchronous read so
* the answer never depends on the answer we gave last time.
*/
function useCompactLabels(stripRef, deps) {
const [compact, setCompact] = React.useState(false);
React.useLayoutEffect(() => {
const el = stripRef.current;
if (!el) return undefined;
const measure = () => {
el.classList.add('is-measuring');
const needed = el.scrollWidth;
const available = el.clientWidth;
el.classList.remove('is-measuring');
// 1px of slack: sub-pixel label widths shouldn't decide the layout.
setCompact(needed > available + 1);
};
measure();
// Webfonts land after first paint and change every label's width without
// resizing anything — re-measure once they do.
document.fonts?.ready?.then?.(measure).catch?.(() => {});
if (typeof ResizeObserver === 'undefined') return undefined;
let raf = 0;
const ro = new ResizeObserver(() => {
cancelAnimationFrame(raf);
raf = requestAnimationFrame(measure);
});
ro.observe(el);
return () => {
ro.disconnect();
cancelAnimationFrame(raf);
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, deps);
return compact;
}
export default function TitleTabs({ mode, setMode }) {
const { t } = useTranslation();
const items = React.useMemo(
() => NAV_ITEMS.map((d) => ({ ...d, label: t(`nav.${d.tKey}`) })),
[t],
);
const tailItems = React.useMemo(
() => NAV_FOOTER_ITEMS.map((d) => ({ ...d, label: t(`nav.${d.tKey}`) })),
[t],
);
const stripRef = React.useRef(null);
const compact = useCompactLabels(stripRef, [items, tailItems, mode]);
return (
<nav
ref={stripRef}
className={`tabstrip ${compact ? 'is-compact' : ''}`}
aria-label={t('nav.workspaces', { defaultValue: 'Workspaces' })}
>
{items.map((it, i) => (
<Tab
key={it.id}
item={it}
active={mode === it.id}
// Chrome's hairline between neighbours: drawn by the tab on the left
// of the gap, and only where neither side is the active (raised) tab.
showSeparator={mode !== it.id && mode !== items[i + 1]?.id && i < items.length - 1}
onClick={() => setMode(it.id)}
/>
))}
<span className="tabstrip__gap" aria-hidden="true" />
{tailItems.map((it) => (
<Tab key={it.id} item={it} active={mode === it.id} onClick={() => setMode(it.id)} />
))}
</nav>
);
}
@@ -1,59 +0,0 @@
import { Minus, Plus } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { useAppStore } from '../store';
import { Button } from '../ui';
const MIN_SCALE = 0.6;
const MAX_SCALE = 1.75;
const SCALE_STEP = 0.05;
function clampScale(value) {
return Math.min(MAX_SCALE, Math.max(MIN_SCALE, Math.round(value / SCALE_STEP) * SCALE_STEP));
}
/** Compact escape hatch for startup screens whose suggested scale is hard to read. */
export default function UiScaleControl() {
const { t } = useTranslation();
const uiScale = useAppStore((s) => s.uiScale);
const setUiScale = useAppStore((s) => s.setUiScale);
const setUiScalePreviewed = useAppStore((s) => s.setUiScalePreviewed);
const label = t('settings.ui_scale');
const percent = Math.round(uiScale * 100);
const adjustScale = (nextScale) => {
setUiScale(nextScale);
setUiScalePreviewed(true);
};
return (
<div className="ui-scale-control" aria-label={label} data-testid="ui-scale-control">
<span className="ui-scale-control__label">{label}</span>
<Button
variant="ghost"
size="sm"
iconSize="sm"
onClick={() => adjustScale(clampScale(uiScale - SCALE_STEP))}
disabled={uiScale <= MIN_SCALE}
aria-label={`${label} −`}
title={`${label} −`}
data-testid="ui-scale-decrease"
>
<Minus size={12} aria-hidden="true" />
</Button>
<span className="ui-scale-control__value" aria-live="polite">
{percent}%
</span>
<Button
variant="ghost"
size="sm"
iconSize="sm"
onClick={() => adjustScale(clampScale(uiScale + SCALE_STEP))}
disabled={uiScale >= MAX_SCALE}
aria-label={`${label} +`}
title={`${label} +`}
data-testid="ui-scale-increase"
>
<Plus size={12} aria-hidden="true" />
</Button>
</div>
);
}
@@ -1,29 +0,0 @@
import React from 'react';
import { beforeEach, describe, expect, it } from 'vitest';
import { fireEvent, render, screen } from '@testing-library/react';
import { I18nextProvider } from 'react-i18next';
import i18n from '../i18n';
import { useAppStore } from '../store';
import UiScaleControl from './UiScaleControl';
describe('<UiScaleControl />', () => {
beforeEach(() =>
useAppStore.setState({ uiScale: 1, uiScaleConfigured: false, uiScalePreviewed: false }),
);
it('adjusts the persisted scale in small readable steps', () => {
render(
<I18nextProvider i18n={i18n}>
<UiScaleControl />
</I18nextProvider>,
);
fireEvent.click(screen.getByTestId('ui-scale-increase'));
expect(useAppStore.getState().uiScale).toBe(1.05);
expect(useAppStore.getState().uiScalePreviewed).toBe(true);
expect(screen.getByText('105%')).toBeInTheDocument();
fireEvent.click(screen.getByTestId('ui-scale-decrease'));
expect(useAppStore.getState().uiScale).toBe(1);
});
});
@@ -1,33 +0,0 @@
import React from 'react';
/**
* VoiceStudio's compact mark: a rounded speech waveform with one small spark.
* The desktop icon uses the same silhouette on a dark tile; app chrome keeps
* it transparent so it stays crisp at titlebar sizes and in every theme.
*/
export default function VoiceStudioMark({ className = '', title, ...props }) {
return (
<svg
viewBox="0 0 64 64"
fill="none"
className={className}
role={title ? 'img' : undefined}
aria-hidden={title ? undefined : true}
{...props}
>
{title ? <title>{title}</title> : null}
<path
d="M6 34c4 0 5-7 9-7 5 0 4 14 9 14 5 0 4-23 9-23s4 28 9 28 4-21 9-21c4 0 5 9 8 9"
stroke="currentColor"
strokeWidth="5.5"
strokeLinecap="round"
strokeLinejoin="round"
/>
<path
d="M50 9c.7 4.3 3.7 7.3 8 8-4.3.7-7.3 3.7-8 8-.7-4.3-3.7-7.3-8-8 4.3-.7 7.3-3.7 8-8Z"
fill="currentColor"
opacity="0.72"
/>
</svg>
);
}
@@ -1,114 +0,0 @@
import { cn } from '@/lib/utils';
import SupertonicLicenseDialog from '../SupertonicLicenseDialog';
import PocketTTSLicenseDialog from '../PocketTTSLicenseDialog';
/**
* Presentation helpers shared by the engine list and its detail panel: the
* status phrase / runs-on device for a row, GPU chip styling, license-dialog
* registry and size formatting. No React.
*/
/** Engines that gate first use behind an in-app license acceptance dialog. */
export const LICENSE_DIALOGS = {
supertonic3: SupertonicLicenseDialog,
pockettts: PocketTTSLicenseDialog,
};
/** Heuristic detector for the "license not accepted" backend reason. */
export function reasonMentionsLicense(reason) {
if (!reason || typeof reason !== 'string') return false;
return /license not accepted/i.test(reason);
}
export function fmtDiskBytes(value, unknownLabel, locale) {
if (value == null) return unknownLabel;
const [divisor, unit, digits] =
value >= 1024 ** 3
? [1024 ** 3, 'gigabyte', 2]
: value >= 1024 ** 2
? [1024 ** 2, 'megabyte', 1]
: [1024, 'kilobyte', 0];
return new Intl.NumberFormat(locale, {
style: 'unit',
unit,
unitDisplay: 'short',
minimumFractionDigits: digits,
maximumFractionDigits: digits,
}).format(value / divisor);
}
export const GPU_LABEL = {
cuda: 'CUDA',
mps: 'MPS',
rocm: 'ROCm',
xpu: 'XPU',
cpu: 'CPU',
directml: 'DirectML',
};
// GPU compat chip — base + per-device tint (detail panel only now).
const CHIP_BASE =
'inline-block px-[6px] py-px text-[10px] font-mono font-semibold tracking-[0.04em] uppercase rounded border select-none';
const CHIP_DEVICE = {
cuda: 'text-[#76b900] border-[color:color-mix(in_srgb,#76b900_45%,transparent)] bg-[color:color-mix(in_srgb,#76b900_10%,transparent)]',
mps: 'text-[#b8b8b8] border-[color:color-mix(in_srgb,#b8b8b8_45%,transparent)] bg-[color:color-mix(in_srgb,#b8b8b8_10%,transparent)]',
rocm: 'text-[#ed1c24] border-[color:color-mix(in_srgb,#ed1c24_45%,transparent)] bg-[color:color-mix(in_srgb,#ed1c24_10%,transparent)]',
vulkan:
'text-[#b62e3b] border-[color:color-mix(in_srgb,#b62e3b_45%,transparent)] bg-[color:color-mix(in_srgb,#b62e3b_10%,transparent)]',
xpu: 'text-[#0071c5] border-[color:color-mix(in_srgb,#0071c5_45%,transparent)] bg-[color:color-mix(in_srgb,#0071c5_10%,transparent)]',
cpu: 'text-muted-foreground border-border bg-transparent',
};
// The "device this host actually uses" highlight. `is-effective` is kept as a
// literal marker class — the suite asserts the chip carries it.
const CHIP_EFFECTIVE =
'is-effective shadow-[0_0_0_1px_var(--chrome-accent,#fe8019)] border-[var(--chrome-accent,#fe8019)] text-foreground font-bold';
export const chipCls = (device, effective) =>
cn(CHIP_BASE, CHIP_DEVICE[device] || CHIP_DEVICE.cpu, effective && CHIP_EFFECTIVE);
// routing_status → status phrase + tone. `unavailable` is handled separately
// (it reads "Needs setup"); anything else unknown falls back to "Unknown".
const ROUTING_STATUS = {
accelerated: { tone: 'text-success', k: 'engines.routingAccelerated' },
cpu_fallback: { tone: 'text-warn', k: 'engines.routingCpuFallback' },
cpu_only: { tone: 'text-muted-foreground', k: 'engines.routingCpuOnly' },
'n/a': { tone: 'text-success', k: 'engines.available' },
};
/** Human duration: "0.4s" for ≥1 s, "820 ms" below. */
export function fmtDuration(ms) {
const n = Number(ms) || 0;
return n >= 1000 ? `${(n / 1000).toFixed(1)}s` : `${Math.round(n)} ms`;
}
export const deviceLabel = (t, g) =>
g === 'unknown' ? t('common.unknown') : g === 'vulkan' ? t('engines.gpuVulkan') : GPU_LABEL[g] || g.toUpperCase();
/** The one device this engine would run on here, for the Runs-on column. */
export function runsOn(t, b) {
if (b.routing_status === 'n/a') return { text: t('engines.routingRemote'), muted: false };
if (b.available && b.routing_status && b.routing_status !== 'unavailable' && b.effective_device) {
return { text: deviceLabel(t, b.effective_device), muted: false };
}
// Not runnable right now: name what it would need (its best device).
return { text: deviceLabel(t, b.gpu_compat[0]), muted: true };
}
/** The Status column phrase + colour for a row. */
export function statusOf(t, b, install) {
const job = install?.job;
if (!b.available) {
if (job?.state === 'running') return { text: t('engines.installing'), cls: 'text-accent' };
if (job?.state === 'failed') return { text: t('engines.failed'), cls: 'text-destructive' };
return { text: t('catalogue.status_setup'), cls: 'text-muted-foreground' };
}
if (b.routing_status === 'unavailable') {
return { text: t('catalogue.status_setup'), cls: 'text-muted-foreground' };
}
if (!b.routing_status) return { text: t('engines.available'), cls: 'text-success' };
const known = ROUTING_STATUS[b.routing_status];
return known
? { text: t(known.k), cls: known.tone }
: { text: t('engines.routingUnknown'), cls: 'text-muted-foreground' };
}
export const LABEL =
'font-mono text-[11px] font-medium uppercase tracking-[var(--chrome-label-track)] text-muted-foreground';
@@ -1,45 +0,0 @@
/**
* Workspace navigation model — shared by both navigation presentations.
*
* The icon rail (`NavRail`) and the titlebar tab strip (`TitleTabs`) are two
* skins of the SAME list; Settings → Appearance → Navigation style picks which
* one renders. Declaring the workspaces once here means a new workspace shows
* up in both skins from a single edit and the two can't drift apart.
*
* `accent` is the workspace's hue. Both skins spend it the same way: the
* ACTIVE item wears it (rail indicator bar / tab top rule + icon), inactive
* items stay neutral, so the chrome never turns into a colour chart.
*/
import {
Globe,
Fingerprint,
Film,
FolderOpen,
Settings2,
Library,
FileText,
BookOpen,
BookMarked,
Boxes,
} from 'lucide-react';
/** The workspaces, in navigation order. `tKey` resolves as `nav.<tKey>`. */
export const NAV_ITEMS = [
{ id: 'launchpad', Icon: Globe, tKey: 'launchpad', accent: '#f3a5b6' },
{ id: 'studio', Icon: Fingerprint, tKey: 'voice', accent: '#d3869b' },
{ id: 'dub', Icon: Film, tKey: 'dub', accent: '#fe8019' },
{ id: 'stories', Icon: BookOpen, tKey: 'stories', accent: '#fabd2f' },
{ id: 'audiobook', Icon: BookMarked, tKey: 'audiobook', accent: '#8ec07c' },
{ id: 'gallery', Icon: Library, tKey: 'gallery', accent: '#b8bb26' },
{ id: 'transcriptions', Icon: FileText, tKey: 'transcripts', accent: '#d3869b' },
{ id: 'projects', Icon: FolderOpen, tKey: 'omnidrive', accent: '#83a598' },
// Engines + model weights. Sits last in the workspace list (immediately above
// Settings in the footer) because it configures the app rather than producing
// anything — it is where the defaults every other workspace runs on are set.
{ id: 'catalogue', Icon: Boxes, tKey: 'catalogue', accent: '#689d6a' },
];
/** Pinned to the end of the nav (rail footer / tab-strip tail). */
export const NAV_FOOTER_ITEMS = [
{ id: 'settings', Icon: Settings2, tKey: 'settings', accent: '#fabd2f' },
];
@@ -1,206 +0,0 @@
import React from 'react';
import {
Info,
CheckCircle,
AlertCircle,
Download,
Activity,
Copy,
ExternalLink,
Building2,
} from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { openExternal } from '../../api/external';
import { resolveAboutVersion } from '../../utils/appVersion';
import { REPO_URL } from '../../utils/bugReport';
import { Button, Badge } from '../../ui';
import { SettingsSection } from './primitives';
import { CATEGORY_BY_ID } from './settingsCategories';
import { useAppStore } from '../../store';
import { isTauri } from './native';
import Row from './Row';
import VoiceStudioMark from '../brand/VoiceStudioMark';
/**
* Where a failing self-check can be fixed inside the app — diagnose check id
* (backend/core/diagnose.py) → Settings category id. Checks without an in-app
* fix (python, backend, …) render their hint as plain text only.
*/
const CHECK_FIX_CATEGORY = {
ffmpeg: 'network',
hf_token: 'credentials',
disk: 'storage',
data_dir: 'storage',
engines: 'engines',
gpu_routing: 'engines',
device: 'performance',
ram: 'performance',
deep_synth: 'logs',
};
/** Small "Open <category>" deep-link into the Settings hub. */
function OpenCategoryButton({ categoryId }) {
const { t } = useTranslation();
const cat = CATEGORY_BY_ID[categoryId];
if (!cat) return null;
return (
<Button
size="sm"
variant="subtle"
onClick={() => useAppStore.getState().openSettingsTab(categoryId)}
>
{t('about.open_fix_category', {
defaultValue: 'Open {{category}}',
category: t(cat.labelKey, { defaultValue: cat.defaultLabel }),
})}
</Button>
);
}
/**
* Settings → About.
*
* Identity + diagnostics only. The device / RAM / VRAM / backend readouts moved
* to Performance & Device; the data/outputs paths moved to Storage; the update
* channel + endpoint moved to Updates (the single update home). What remains is
* app identity, the HF-token quick status, and the diagnostics actions.
*/
export default function AboutTab({
appVersion,
tauriVersion,
info,
checkForUpdates,
updateState,
selfCheck,
selfCheckRunning,
runSelfCheck,
bundleBuilding,
saveDiagnosticBundle,
copyDiagnostics,
}) {
const { t } = useTranslation();
return (
<SettingsSection icon={Info} title={t('settings.about')}>
<Row
label={t('about.app')}
value={
<span className="inline-flex items-center gap-[var(--space-2)]" translate="no">
<VoiceStudioMark className="size-5 text-[var(--chrome-accent)]" />
VoiceStudio
</span>
}
/>
<Row label={t('about.version')} value={resolveAboutVersion(appVersion, info)} mono />
<Row
label={t('about.tauri_runtime')}
value={tauriVersion || (isTauri() ? '—' : t('about.web_preview'))}
mono
/>
<Row
label={t('about.hf_token')}
value={
info?.has_hf_token ? (
t('about.yes')
) : (
<span className="inline-flex flex-wrap items-center gap-[var(--space-2)]">
{t('about.no')}
<OpenCategoryButton categoryId="credentials" />
</span>
)
}
/>
<div className="settings-link-row mt-[var(--space-5)] flex flex-wrap gap-[var(--space-4)]">
{isTauri() && (
<Button
variant="primary"
size="md"
leading={<Download size={12} />}
onClick={checkForUpdates}
loading={updateState === 'checking' || updateState === 'downloading'}
>
{updateState === 'downloading' ? t('about.downloading') : t('about.check_updates')}
</Button>
)}
<Button
variant="subtle"
size="md"
leading={!selfCheckRunning && <Activity size={12} />}
onClick={runSelfCheck}
loading={selfCheckRunning}
>
{t('about.self_check')}
</Button>
<Button
variant="subtle"
size="md"
leading={!bundleBuilding && <Download size={12} />}
onClick={saveDiagnosticBundle}
loading={bundleBuilding}
>
{t('about.save_bundle')}
</Button>
<Button variant="subtle" size="md" leading={<Copy size={12} />} onClick={copyDiagnostics}>
{t('about.copy_diagnostics')}
</Button>
<Button
variant="subtle"
size="md"
leading={<ExternalLink size={12} />}
onClick={() => openExternal(REPO_URL)}
>
{t('about.github')}
</Button>
<Button
variant="subtle"
size="md"
leading={<Building2 size={12} />}
onClick={() => {
useAppStore.getState().setMode?.('enterprise');
}}
>
{t('about.commercial_license')}
</Button>
</div>
{selfCheck && (
<div className="settings-selfcheck">
{selfCheck.checks.map((c) => (
<Row
key={c.id}
label={c.label}
value={
<span>
<Badge
tone={c.status === 'ok' ? 'success' : c.status === 'warn' ? 'warn' : 'danger'}
>
{c.status === 'ok' ? <CheckCircle size={11} /> : <AlertCircle size={11} />}{' '}
{t(`about.self_check_${c.status}`)}
</Badge>{' '}
{c.detail}
{c.hint && (
<span className="settings-muted font-sans text-[var(--text-md)] text-[var(--chrome-fg-dim)]">
{' '}
— {c.hint}
</span>
)}
{c.status !== 'ok' && CHECK_FIX_CATEGORY[c.id] && (
<>
{' '}
<OpenCategoryButton categoryId={CHECK_FIX_CATEGORY[c.id]} />
</>
)}
</span>
}
/>
))}
<p className="settings-muted font-sans text-[var(--text-md)] text-[var(--chrome-fg-dim)]">
{selfCheck.summary.ok
? t('about.self_check_healthy')
: t('about.self_check_attention', { count: selfCheck.summary.failures })}
</p>
</div>
)}
</SettingsSection>
);
}
@@ -1,96 +0,0 @@
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { fireEvent, render, screen } from '@testing-library/react';
import React from 'react';
import AboutTab from './AboutTab';
import { REPO_URL } from '../../utils/bugReport';
import { openExternal } from '../../api/external';
import { useAppStore } from '../../store';
vi.mock('../../api/external', () => ({ openExternal: vi.fn() }));
const noop = () => {};
const baseProps = {
appVersion: '0.0.0-test',
tauriVersion: null,
info: { has_hf_token: true },
checkForUpdates: noop,
updateState: 'idle',
selfCheck: null,
selfCheckRunning: false,
runSelfCheck: noop,
bundleBuilding: false,
saveDiagnosticBundle: noop,
copyDiagnostics: noop,
};
describe('AboutTab — external links', () => {
beforeEach(() => {
vi.clearAllMocks();
});
it('the GitHub button opens the canonical repo (derived from the shared REPO_URL constant)', () => {
render(<AboutTab {...baseProps} />);
fireEvent.click(screen.getByRole('button', { name: 'VoiceStudio on GitHub' }));
expect(openExternal).toHaveBeenCalledWith(REPO_URL);
// Belt-and-braces: the constant itself must point at this project, not a
// lookalike (the original bug linked github.com/k2-fsa/OmniVoice).
expect(REPO_URL).toBe('https://github.com/debpalash/VoiceStudio');
});
it('has no "Model card" link — the app is multi-engine with no single model card', () => {
render(<AboutTab {...baseProps} />);
expect(screen.queryByRole('button', { name: /model card/i })).toBeNull();
});
});
describe('AboutTab — fixable problems deep-link into Settings', () => {
beforeEach(() => {
vi.clearAllMocks();
useAppStore.getState().setMode('launchpad');
useAppStore.getState().setPendingSettingsTab(null);
});
it('HF token "no" offers an Open API credentials action instead of dead-ending', () => {
render(<AboutTab {...baseProps} info={{ has_hf_token: false }} />);
fireEvent.click(screen.getByRole('button', { name: 'Open API credentials' }));
expect(useAppStore.getState().mode).toBe('settings');
expect(useAppStore.getState().pendingSettingsTab).toBe('credentials');
});
it('HF token "yes" renders no Credentials action', () => {
render(<AboutTab {...baseProps} info={{ has_hf_token: true }} />);
expect(screen.queryByRole('button', { name: 'Open API credentials' })).toBeNull();
});
it('a failing self-check renders an "Open <category>" button for its fix destination', () => {
const selfCheck = {
checks: [
{
id: 'ffmpeg',
label: 'ffmpeg',
status: 'fail',
detail: 'not found on PATH or FFMPEG_PATH',
hint: 'Dubbing and audio conversion need ffmpeg.',
},
{ id: 'python', label: 'Python runtime', status: 'ok', detail: '3.12', hint: null },
],
summary: { ok: false, failures: 1 },
};
render(<AboutTab {...baseProps} selfCheck={selfCheck} />);
fireEvent.click(screen.getByRole('button', { name: 'Open Network' }));
expect(useAppStore.getState().mode).toBe('settings');
expect(useAppStore.getState().pendingSettingsTab).toBe('network');
});
it('passing checks render no deep-link button', () => {
const selfCheck = {
checks: [
{ id: 'ffmpeg', label: 'ffmpeg', status: 'ok', detail: '/usr/bin/ffmpeg', hint: null },
],
summary: { ok: true, failures: 0 },
};
render(<AboutTab {...baseProps} selfCheck={selfCheck} />);
expect(screen.queryByRole('button', { name: /^Open / })).toBeNull();
});
});
@@ -1,8 +0,0 @@
import React from 'react';
import { SettingRow } from './primitives';
// About/Privacy read-only data rows delegate to the shared SettingRow primitive
// so they pick up the redesigned grid + mono value styling unchanged.
export default function Row({ label, value, mono }) {
return <SettingRow title={label} control={value} mono={mono} />;
}
@@ -1,16 +0,0 @@
import { isTauri as _isTauri } from '../../utils/media';
/** True when running inside the Tauri webview (vs. vite dev / web preview / tests). */
export const isTauri = () => _isTauri;
// Tauri v2's webview disables native window.confirm/alert — they return
// false silently, making Delete/Reinstall buttons appear dead. Route through
// the dialog plugin when running in Tauri, fall back to browser confirm
// elsewhere (vite dev, tests).
export async function askConfirm(message, title = 'Confirm') {
if (isTauri()) {
const { ask } = await import('@tauri-apps/plugin-dialog');
return ask(message, { title, kind: 'warning' });
}
return Promise.resolve(window.confirm(message));
}
@@ -1,62 +0,0 @@
import React, { useState } from 'react';
import { ChevronDown } from 'lucide-react';
import { cn } from '@/lib/utils';
/**
* Collapsible — a chevron-header disclosure for hiding power-user / advanced
* rows. Closed by default.
*
* FAST-mode shadcn migration: styling is now Tailwind utilities on the VoiceStudio
* `--chrome-*` / `--space-*` token bridge (palette preserved exactly); the old
* `.st-collapsible*` rules in primitives.css are gone. The chevron rotates on
* the `is-open` class; the body's last SettingRow drops its bottom padding.
*
* @param {ReactNode} title header label (already translated)
* @param {LucideIcon=} icon optional leading icon (size 14, dim)
* @param {boolean=} defaultOpen start expanded (default false)
* @param {ReactNode=} badge optional small node shown after the title (count/state)
* @param {ReactNode} children the collapsible body
*/
export default function Collapsible({ title, icon: Icon, defaultOpen = false, badge, children }) {
const [open, setOpen] = useState(defaultOpen);
return (
<div
className={cn(
'mt-[var(--space-4)] overflow-hidden rounded-[var(--chrome-radius-pill)] border border-[color-mix(in_srgb,var(--chrome-fg)_7%,transparent)] bg-[var(--chrome-bg)]',
open && 'is-open',
)}
>
<button
type="button"
className="flex w-full cursor-pointer items-center gap-[var(--space-3)] border-0 bg-transparent px-[var(--space-4)] py-[var(--space-4)] [font-family:var(--font-sans)] text-[length:var(--text-sm)] font-semibold text-[color:var(--chrome-fg-muted)] transition-[background,color] duration-[120ms] hover:bg-[var(--chrome-hover-bg)] hover:text-[color:var(--chrome-fg)] focus-visible:outline-none focus-visible:shadow-[var(--focus-ring)]"
aria-expanded={open}
onClick={() => setOpen((v) => !v)}
>
<ChevronDown
size={14}
className="shrink-0 text-[var(--chrome-fg-dim)] transition-transform duration-[160ms] [.is-open_&]:rotate-180"
aria-hidden="true"
/>
{Icon && (
<span
className="inline-flex h-[22px] w-[22px] items-center justify-center rounded-[var(--chrome-radius-pill)] bg-[color-mix(in_srgb,var(--chrome-accent)_9%,transparent)] text-[color:var(--chrome-accent)]"
aria-hidden="true"
>
<Icon size={14} />
</span>
)}
<span className="flex-auto text-left">{title}</span>
{badge != null && (
<span className="shrink-0 [font-family:var(--chrome-font-mono)] text-[length:var(--chrome-label-size)] text-[color:var(--chrome-fg-dim)]">
{badge}
</span>
)}
</button>
{open && (
<div className="border-t border-[color-mix(in_srgb,var(--chrome-fg)_7%,transparent)] px-[var(--space-5)] pb-[var(--space-4)] pt-[var(--space-2)] [&>[data-slot=setting-row]:last-child]:pb-0">
{children}
</div>
)}
</div>
);
}
@@ -1,52 +0,0 @@
import React from 'react';
import { Info } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { Tooltip } from '../../../ui';
import { openExternal } from '../../../api/external';
/**
* InfoHint — a small info affordance that moves long prose OUT of the row body
* and into an on-demand tooltip. Renders a 13px lucide `Info` glyph (dim) that
* opens the shared Tooltip with the help content; an optional "Learn more →"
* link opens an external URL via the app's external-open helper.
*
* Use this anywhere the old design had a multi-line `<p className="…__help">`.
*
* @param {ReactNode} children the help prose shown inside the tooltip
* @param {string=} label accessible label for the trigger (default: "More info")
* @param {string=} learnMoreHref optional URL; renders a "Learn more →" link in the tooltip
*/
export default function InfoHint({ children, label, learnMoreHref }) {
const { t } = useTranslation();
const ariaLabel = label || t('common.more_info', 'More info');
const content = (
<div className="flex flex-col gap-[var(--space-3)] max-w-[260px]">
<div className="[font-family:var(--font-sans)] text-[length:var(--text-base)] leading-[1.5]">
{children}
</div>
{learnMoreHref && (
<button
type="button"
className="self-start p-0 border-0 bg-transparent text-[color:var(--chrome-accent)] [font-family:var(--font-sans)] text-[length:var(--text-base)] font-semibold cursor-pointer hover:underline"
onClick={() => openExternal(learnMoreHref)}
>
{t('common.learn_more', 'Learn more')} →
</button>
)}
</div>
);
return (
<Tooltip content={content} placement="top">
<button
type="button"
className="inline-flex items-center justify-center p-0 m-0 border-0 bg-transparent text-[color:var(--chrome-fg-dim)] cursor-help leading-[0] rounded-[var(--chrome-radius-pill)] transition-[color] duration-[120ms] hover:text-[color:var(--chrome-fg-muted)] focus-visible:text-[color:var(--chrome-fg-muted)] focus-visible:outline-none focus-visible:shadow-[var(--focus-ring)]"
aria-label={ariaLabel}
onClick={(e) => e.preventDefault()}
>
<Info size={13} aria-hidden="true" />
</button>
</Tooltip>
);
}
@@ -1,94 +0,0 @@
import React from 'react';
import { cn } from '@/lib/utils';
import InfoHint from './InfoHint';
/**
* SettingRow — one labelled row in a SettingsSection.
*
* FAST-mode shadcn migration: the grid layout, label/subtitle typography and the
* right-aligned control slot are now Tailwind utilities on the VoiceStudio
* `--chrome-*` / `--space-*` token bridge (palette preserved exactly). The old
* `.st-row*` rules in primitives.css are gone. Row-stacking on a narrow Settings
* column is reproduced with the Tailwind v4 named-container variant
* `@max-[600px]/settings:` (the `settings` container lives on Settings.jsx), with
* the legacy `max-[560px]:` viewport query as the out-of-container fallback.
*
* Layout: [ icon? + title + one-line subtitle ] [ control ].
*
* @param {LucideIcon=} icon optional leading icon — rendered inline (size 14, dim) inside the title
* @param {ReactNode} title the row label (already translated)
* @param {ReactNode=} subtitle optional muted description line under the title (wraps cleanly)
* @param {ReactNode=} note alias for `subtitle` — fallback when `subtitle` is absent.
* A row renders AT MOST ONE muted description line.
* @param {ReactNode=} hint optional long help prose / Learn-more link — rendered as an InfoHint
* @param {ReactNode} control the right-aligned control or value
* @param {boolean=} mono render the control monospace (read-only data value)
* @param {boolean=} stack full-width stacked layout: label on top, control row below
* (replaces the old `st-row--stack` className)
* @param {'center'|'start'=} align vertical alignment of the control (default 'center')
* @param {string=} className extra class on the row
*/
export default function SettingRow({
icon: Icon,
title,
subtitle,
note,
hint,
control,
mono = false,
stack = false,
align = 'center',
className = '',
}) {
return (
<div
data-slot="setting-row"
data-mono={mono ? '' : undefined}
className={cn(
'grid min-h-0 gap-y-[1px] rounded-[var(--chrome-radius-pill)] border-b border-[color-mix(in_srgb,var(--chrome-fg)_7%,transparent)] px-[var(--space-3)] py-[var(--space-5)] [font-family:var(--font-sans)] last:border-b-0',
align === 'start' ? 'items-start' : 'items-center',
stack
? 'grid-cols-[1fr] gap-[var(--space-3)]'
: 'grid-cols-[minmax(0,1fr)_auto] gap-x-[var(--space-5)] @min-[601px]/settings:has-[input:not([type=checkbox]):not([type=radio]):not([type=range])]:[grid-template-columns:minmax(0,1fr)_minmax(0,1.9fr)] @min-[601px]/settings:has-[select]:[grid-template-columns:minmax(0,1fr)_minmax(0,1.9fr)] @min-[601px]/settings:has-[textarea]:[grid-template-columns:minmax(0,1fr)_minmax(0,1.9fr)] @max-[600px]/settings:grid-cols-[1fr] @max-[600px]/settings:gap-[var(--space-2)] max-[560px]:grid-cols-[1fr] max-[560px]:gap-[var(--space-2)]',
className,
)}
>
<div className={cn('min-w-0 flex flex-col gap-[2px]', stack ? 'max-w-none' : 'max-w-[52ch]')}>
<span className="inline-flex items-center gap-[var(--space-2)] text-[length:var(--text-md)] font-medium leading-[1.35] text-[color:var(--chrome-fg)]">
{Icon && (
<span
data-slot="setting-row-icon"
className="inline-flex h-[22px] w-[22px] shrink-0 items-center justify-center rounded-[var(--chrome-radius-pill)] bg-[color-mix(in_srgb,var(--chrome-accent)_9%,transparent)] text-[var(--chrome-accent)]"
aria-hidden="true"
>
<Icon size={13} />
</span>
)}
{title}
{hint && <InfoHint>{hint}</InfoHint>}
</span>
{(subtitle || note) && (
<span className="text-[color:var(--chrome-fg-dim)] text-[length:var(--text-xs)] leading-[1.45] whitespace-normal [text-wrap:pretty] [&_a]:text-[var(--chrome-accent)] [&_a]:no-underline [&_a:hover]:underline">
{subtitle || note}
</span>
)}
</div>
{control != null && (
<div
data-slot="setting-row-control"
className={cn(
'inline-flex items-center gap-[var(--space-3)] min-w-0 box-border pr-[2px]',
'[&_input:not([type=checkbox]):not([type=radio]):not([type=range])]:min-w-0 [&_input:not([type=checkbox]):not([type=radio]):not([type=range])]:max-w-full [&_select]:min-w-0 [&_select]:max-w-full [&_textarea]:min-w-0 [&_textarea]:max-w-full',
stack
? 'justify-self-stretch max-w-full text-left flex-wrap whitespace-normal [&_[data-slot=settings-input]]:max-w-full [&_[data-slot=settings-input]]:flex-[1_1_220px]'
: 'justify-self-end max-w-[85%] text-right whitespace-nowrap has-[input:not([type=checkbox]):not([type=radio]):not([type=range])]:w-full has-[select]:w-full has-[textarea]:w-full @max-[600px]/settings:justify-self-start @max-[600px]/settings:w-full @max-[600px]/settings:max-w-full @max-[600px]/settings:text-left @max-[600px]/settings:whitespace-normal max-[560px]:justify-self-start max-[560px]:w-full max-[560px]:max-w-full max-[560px]:text-left',
mono &&
'[font-family:var(--chrome-font-mono)] text-[length:var(--text-base)] text-[color:var(--chrome-fg-muted)] tabular-nums max-w-[42ch] whitespace-normal [word-break:normal] [overflow-wrap:break-word] leading-[1.45]',
)}
>
{control}
</div>
)}
</div>
);
}
@@ -1,51 +0,0 @@
import React from 'react';
import { cn } from '@/lib/utils';
/**
* SettingsInput — the token-styled text field for Settings.
*
* FAST-mode shadcn migration: styling is now Tailwind utilities on the VoiceStudio
* `--chrome-*` / `--space-*` token bridge (palette preserved exactly); the old
* `.st-input*` rules in primitives.css are gone. Drop it inside a SettingRow's
* `control`, or use it standalone. In a stacked SettingRow it stretches to fill
* (the row's control slot targets `[data-slot=settings-input]`).
*
* @param {string} value
* @param {function} onChange
* @param {function=} onKeyDown
* @param {string=} placeholder
* @param {string=} type input type (default 'text')
* @param {boolean=} mono render the value monospace (tokens, paths)
* @param {boolean=} disabled
* @param {string=} className extra class
* @param {string=} 'aria-label'
*/
export default function SettingsInput({
value,
onChange,
onKeyDown,
placeholder,
type = 'text',
mono = false,
disabled = false,
className = '',
...rest
}) {
return (
<input
data-slot="settings-input"
type={type}
className={cn(
'w-full min-w-0 max-w-[min(360px,100%)] box-border rounded-[var(--chrome-radius-pill)] border border-[color-mix(in_srgb,var(--chrome-fg)_9%,transparent)] bg-[var(--chrome-bg)] px-[var(--space-4)] py-[var(--space-3)] text-[color:var(--chrome-fg)] [font-family:var(--font-sans)] text-[length:var(--text-sm)] transition-[border-color,background] duration-[120ms] hover:border-[color-mix(in_srgb,var(--chrome-fg)_16%,transparent)] focus:border-[var(--chrome-accent)] focus:outline-none disabled:cursor-not-allowed disabled:opacity-50',
mono && '[font-family:var(--chrome-font-mono)]',
className,
)}
value={value}
onChange={onChange}
onKeyDown={onKeyDown}
placeholder={placeholder}
disabled={disabled}
{...rest}
/>
);
}
@@ -1,37 +0,0 @@
import React from 'react';
import { render, screen } from '@testing-library/react';
import { describe, expect, it } from 'vitest';
import { Settings, Volume2 } from 'lucide-react';
import SettingsSection from './SettingsSection';
import SettingRow from './SettingRow';
describe('settings content primitives', () => {
it('gives every settings section the shared elevated card and responsive header', () => {
render(
<SettingsSection
icon={Settings}
title="Audio"
description="Choose how generated audio behaves."
actions={<button type="button">Reset</button>}
>
<SettingRow icon={Volume2} title="Volume" control={<span>80%</span>} />
</SettingsSection>,
);
const section = screen.getByRole('region', { name: 'Audio' });
expect(section.className).toContain('bg-[color-mix');
expect(section.className).toContain('shadow-[');
expect(section.querySelector('[data-slot="settings-section-icon"]')).toBeInTheDocument();
expect(section.querySelector('[data-slot="settings-section-actions"]')).toHaveClass(
'flex-wrap',
);
});
it('uses a consistent divider and icon tile for setting rows', () => {
render(<SettingRow icon={Volume2} title="Volume" control={<span>80%</span>} />);
const row = screen.getByText('Volume').closest('[data-slot="setting-row"]');
expect(row.className).toContain('border-[color-mix');
expect(row.querySelector('[data-slot="setting-row-icon"]')).toBeInTheDocument();
});
});
@@ -1,95 +0,0 @@
import React, { useId } from 'react';
/**
* SettingsSection — the standard header + body wrapper for every Settings card.
*
* FAST-mode shadcn migration: the surface, header, icon tile, titles and actions
* are now Tailwind utilities layered on the VoiceStudio `--chrome-*` / `--space-*`
* token bridge (palette preserved exactly — no hardcoded colors). The old
* `.st-section*` rules in primitives.css are gone.
*
* Renders an icon-tile + title header, an optional wrapping description,
* optional right-aligned actions, then the children body.
*
* @param {LucideIcon} icon lucide icon component (rendered at size 15)
* @param {string} title section title (already translated)
* @param {string=} description optional wrapping subtitle (muted/dim)
* @param {string=} accent optional CSS color for the icon tile (defaults to the page accent)
* @param {ReactNode=} actions optional right-aligned header actions (buttons, badges…)
* @param {ReactNode} children section body
* @param {string=} className extra class on the root <section>
* @param {string=} contentClassName extra class on the body wrapper
* @param {boolean=} compact reduce card/header padding for dense utility panels
*/
// Shared so the raw card surfaces in EnginesTab / ModelStoreTab (which carry a
// custom toolbar + table instead of the icon/title header) stay byte-identical
// to the primitive without re-deriving the token string. `data-slot` is the
// stable hook Settings.css / panel CSS reach into.
export const SETTINGS_SECTION_SURFACE =
'bg-[color-mix(in_srgb,var(--chrome-fg)_3%,var(--chrome-bg))] border border-[color-mix(in_srgb,var(--chrome-fg)_7%,transparent)] rounded-[calc(var(--chrome-radius-pill)*1.4)] shadow-[0_1px_0_color-mix(in_srgb,var(--chrome-fg)_3%,transparent)] px-[var(--space-6)] py-[var(--space-6)] mb-[var(--space-5)] last:mb-0';
export default function SettingsSection({
icon: Icon,
title,
description,
accent,
actions,
children,
className = '',
contentClassName = '',
compact = false,
}) {
const headingId = useId();
return (
<section
data-slot="settings-section"
aria-labelledby={headingId}
className={`${SETTINGS_SECTION_SURFACE} ${
compact ? '!mb-[var(--space-3)] !px-[var(--space-4)] !py-[var(--space-4)]' : ''
} ${className}`.trim()}
>
<header
className={`${
compact
? 'mb-[var(--space-3)] pb-[var(--space-3)]'
: 'mb-[var(--space-5)] pb-[var(--space-4)]'
} flex items-center gap-[var(--space-4)] border-b border-[color-mix(in_srgb,var(--chrome-fg)_7%,transparent)] @max-[560px]/settings:flex-wrap`}
>
{Icon && (
<span
data-slot="settings-section-icon"
className="inline-flex h-[28px] w-[28px] shrink-0 items-center justify-center rounded-[var(--chrome-radius-pill)] border border-transparent bg-[color-mix(in_srgb,currentColor_12%,var(--chrome-bg))] text-[color:var(--chrome-accent)]"
style={accent ? { color: accent } : undefined}
aria-hidden="true"
>
<Icon size={15} />
</span>
)}
<div className="flex min-w-0 flex-auto flex-col gap-[2px]">
<h2
id={headingId}
className="m-0 [font-family:var(--font-sans)] text-[length:var(--text-lg)] font-semibold leading-[1.3] tracking-[-0.01em] text-[color:var(--chrome-fg)]"
>
{title}
</h2>
{description && (
<p className="m-0 [font-family:var(--font-sans)] text-[length:var(--text-xs)] leading-[1.5] text-[color:var(--chrome-fg-dim)] [text-wrap:pretty]">
{description}
</p>
)}
</div>
{actions && (
<div
data-slot="settings-section-actions"
className="ml-[var(--space-4)] inline-flex shrink-0 flex-wrap items-center justify-end gap-[var(--space-3)] @max-[560px]/settings:ml-0 @max-[560px]/settings:w-full @max-[560px]/settings:justify-start"
>
{actions}
</div>
)}
</header>
<div className={contentClassName || undefined}>{children}</div>
</section>
);
}
@@ -1,56 +0,0 @@
import React from 'react';
import { cn } from '@/lib/utils';
/**
* SettingsToggle — a token-styled accessible switch.
*
* FAST-mode shadcn migration: the track + knob are Tailwind utilities on the
* VoiceStudio `--chrome-*` token bridge (palette preserved exactly); the old
* `.st-toggle*` rules in primitives.css are gone. Still renders a real
* `<input type="checkbox" role="switch">` (visually hidden) so label/role-based
* queries and keyboard focus work; the visible track + knob is a sibling. The
* on-state recolors via the `is-on` class on the label (arbitrary `[.is-on_&]`
* variants on the children); focus uses the `peer` on the input.
*
* @param {boolean} checked on/off state
* @param {function} onChange called with the next boolean value
* @param {boolean=} disabled disable interaction
* @param {string=} id id forwarded to the input (for an external <label htmlFor>)
* @param {string=} aria-label accessible label when there's no visible <label>
*/
export default function SettingsToggle({
checked,
onChange,
disabled = false,
id,
'aria-label': ariaLabel,
...rest
}) {
return (
<label
className={cn(
'relative inline-flex shrink-0 w-[42px] h-[24px] cursor-pointer',
checked && 'is-on',
disabled && 'is-disabled cursor-not-allowed opacity-50',
)}
>
<input
type="checkbox"
role="switch"
id={id}
className="peer absolute inset-0 w-full h-full m-0 opacity-0 cursor-[inherit]"
checked={!!checked}
disabled={disabled}
aria-label={ariaLabel}
onChange={(e) => onChange?.(e.target.checked)}
{...rest}
/>
<span
className="absolute inset-0 rounded-[var(--radius-pill)] bg-[color-mix(in_srgb,var(--chrome-fg)_14%,var(--chrome-bg))] shadow-[inset_0_0_0_1px_color-mix(in_srgb,var(--chrome-fg)_8%,transparent)] transition-[background] duration-[160ms] ease-in-out [.is-on_&]:bg-[var(--color-brand)] peer-focus-visible:outline peer-focus-visible:outline-2 peer-focus-visible:outline-[var(--color-ring)] peer-focus-visible:outline-offset-2"
aria-hidden="true"
>
<span className="absolute top-[3px] left-[3px] w-[18px] h-[18px] rounded-full bg-[var(--chrome-fg-muted)] shadow-[var(--shadow-sm)] transition-[transform,background] duration-[160ms] ease-in-out [.is-on_&]:translate-x-[18px] [.is-on_&]:bg-[var(--chrome-bg)]" />
</span>
</label>
);
}
@@ -1,21 +0,0 @@
// ─────────────────────────────────────────────────────────────────
// Settings design-system primitives
//
// Shared building blocks for the Settings redesign. Compose these
// inside every Settings panel/tab instead of re-implementing headers,
// rows, toggles, hints, and disclosures.
//
// import { SettingsSection, SettingRow, InfoHint,
// SettingsToggle, Collapsible } from './primitives';
//
// All styling now lives as Tailwind utilities on the VoiceStudio `--chrome-*` /
// `--space-*` token bridge directly on each primitive's JSX (FAST-mode shadcn
// migration) — there is no longer a primitives.css stylesheet to import.
// ─────────────────────────────────────────────────────────────────
export { default as SettingsSection, SETTINGS_SECTION_SURFACE } from './SettingsSection.jsx';
export { default as SettingRow } from './SettingRow.jsx';
export { default as SettingsInput } from './SettingsInput.jsx';
export { default as InfoHint } from './InfoHint.jsx';
export { default as SettingsToggle } from './SettingsToggle.jsx';
export { default as Collapsible } from './Collapsible.jsx';
@@ -1,444 +0,0 @@
/**
* Settings category registry — the single source of truth for the sidebar IA.
*
* The Settings page is a sidebar-nav + content-pane hub (macOS System Settings
* / VS Code style). This module declares the four sidebar GROUPS and their
* categories (id, group, label, lucide icon, restart flag, and a small set of
* searchable setting keywords). Settings.jsx renders the sidebar from GROUPS
* and switches the content pane on the active category id.
*
* Keep this declarative — no JSX panels here (those need props/hooks and live
* in Settings.jsx's renderCategory switch). `keywords` powers the bonus
* "search matches a setting → jump to its category" behaviour; `keywordKeys`
* lists i18n keys of prominent setting-row titles so the same search works in
* every UI language (the translated titles are matched at query time — no
* separate keyword translations to maintain).
*/
import {
AudioLines,
Palette,
Plug,
Mic,
SpellCheck,
Languages,
Brain,
Gauge,
HardDrive,
Wifi,
Share2,
KeyRound,
LockKeyhole,
Sparkles,
ArrowDownToLine,
ShieldCheck,
FileText,
Info,
Braces,
BarChart3,
} from 'lucide-react';
/** Sidebar groups, in display order. `labelKey` resolves via i18n. */
export const GROUPS = [
{
id: 'general',
labelKey: 'settings.group_general',
defaultLabel: 'General',
items: [
{
id: 'appearance',
labelKey: 'settings.appearance',
defaultLabel: 'Appearance',
icon: Palette,
keywords: [
'theme',
'color theme',
'ui scale',
'font',
'auto-play preview',
'header live stats',
'system metrics',
'navigation style',
'sidebar rail',
'titlebar tabs',
'tabs',
'language',
'locale',
'interface language',
'review mode',
'stage checkpoints',
],
keywordKeys: [
'settings.ui_scale',
'settings.color_theme',
'settings.font',
'settings.autoplay_preview',
'settings.header_live_stats',
'settings.nav_style',
// The visible option labels too, so a non-English search for "tabs"
// / "Leiste" matches what the user actually sees on screen.
'settings.nav_style_rail',
'settings.nav_style_tabs',
'settings.language',
'settings.review_mode',
],
},
],
},
{
id: 'voice',
labelKey: 'settings.group_voice',
defaultLabel: 'Voice & Engines',
items: [
{
id: 'dictation',
labelKey: 'settings.dictation',
defaultLabel: 'Dictation',
icon: Mic,
keywords: [
'dictation',
'hotkey',
'shortcut',
'refinement',
'echo cancellation',
'aec',
'microphone',
'voice capture',
],
keywordKeys: ['settings.shortcut'],
},
{
id: 'pronunciation',
labelKey: 'settings.pronunciation',
defaultLabel: 'Pronunciation',
icon: SpellCheck,
keywords: ['pronunciation', 'lexicon', 'phoneme', 'g2p', 'dictionary'],
},
{
id: 'translation',
labelKey: 'settings.translation',
defaultLabel: 'Translation',
icon: Languages,
keywords: [
'translation',
'translate quality',
'cinematic',
'llm endpoint',
'deepl',
'microsoft',
'openai',
'api key',
],
keywordKeys: ['settings.translate_quality', 'settings.translation_providers'],
},
],
},
{
id: 'system',
labelKey: 'settings.group_system',
defaultLabel: 'System',
items: [
{
id: 'performance',
labelKey: 'settings.performance',
defaultLabel: 'Performance & Device',
icon: Gauge,
restart: true,
keywords: [
'performance',
'torch.compile',
'device',
'gpu',
'ram',
'vram',
'compute',
'platform',
'cuda',
'rocm',
'mps',
'cpu',
'xpu',
'intel',
'timeout',
'generation timeout',
'compute budget',
'compute-time budget',
],
keywordKeys: [
'settings.generate_budget_title',
'settings.generate_timeout_gpu',
'settings.generate_timeout_cpu',
],
},
{
id: 'usage',
labelKey: 'settings.usage',
defaultLabel: 'Usage',
icon: BarChart3,
keywords: [
'usage',
'stats',
'statistics',
'insights',
'analytics',
'history',
'how much',
'privacy',
],
},
{
id: 'storage',
// Hosts a restart-bound panel (models directory / HF mirror).
restart: true,
labelKey: 'settings.storage',
defaultLabel: 'Storage',
icon: HardDrive,
keywords: [
'storage',
'data directory',
'outputs directory',
// "factory reset" is what users search for even though the feature is
// now the broader "Reset & remove" — keep the old name findable.
'factory reset',
'reset',
'wipe',
'delete models',
'uninstall',
'remove all data',
'start over',
'disk usage',
'free space',
'disk space',
'model cache size',
'models directory',
'cache directory',
'model store',
'catalogue',
'catalog',
'download',
'voice previews',
'engine venvs',
'temp files',
'clear logs',
],
keywordKeys: ['settings.storage_usage', 'settings.reset', 'settings.uninstall'],
},
{
id: 'permissions',
// Lives in the permissions.* i18n namespace (not settings.*) so the
// whole feature's strings ship as one additive block per locale.
labelKey: 'permissions.title',
defaultLabel: 'Permissions',
icon: LockKeyhole,
keywords: [
'permission',
'permissions',
'microphone access',
'mic access',
'accessibility',
'privacy & security',
'os permissions',
'grant',
'tcc',
],
keywordKeys: ['permissions.microphone', 'permissions.accessibility'],
},
{
id: 'network',
// Hosts a restart-bound panel (models directory / HF mirror).
restart: true,
labelKey: 'settings.network',
defaultLabel: 'Network',
icon: Wifi,
// Proxy (applies immediately) and the HF download mirror (restart-bound).
keywords: [
'network',
'proxy',
'http proxy',
'socks',
'hugging face mirror',
'hf_endpoint',
'mirror',
],
keywordKeys: ['settings.proxy'],
},
{
id: 'audio-tools',
labelKey: 'settings.audio_tools',
defaultLabel: 'Audio tools',
icon: AudioLines,
// yt-dlp updates land in an overlay read at process start (the row
// renders RestartBadge) — lockstep-guarded in
// settingsCategories.test.jsx like Models / Performance / Sharing.
restart: true,
keywords: [
'ffmpeg',
'ffprobe',
'ffmpeg path',
'yt-dlp',
'ytdlp',
'media engine',
'video downloader',
'bundled binaries',
],
keywordKeys: ['settings.audio_tools', 'settings.ffmpeg', 'settings.audio_tools_ytdlp'],
},
{
id: 'sharing',
labelKey: 'settings.sharing',
defaultLabel: 'Sharing & Remote',
icon: Share2,
restart: true,
keywords: ['sharing', 'remote backend', 'mcp', 'tailscale', 'gpu box', 'bindings'],
},
{
id: 'openapi',
labelKey: 'settings.openapi',
defaultLabel: 'VoiceStudio API',
icon: Braces,
keywords: ['api', 'openapi', 'scalar', 'rest', 'swagger', 'docs', 'reference', 'endpoints'],
},
{
id: 'credentials',
labelKey: 'settings.credentials',
defaultLabel: 'Credentials',
icon: KeyRound,
keywords: ['credentials', 'hugging face token', 'hf token', 'api key', 'secret'],
keywordKeys: ['settings.hf_token_title'],
},
{
id: 'llm-providers',
labelKey: 'settings.llm_providers',
defaultLabel: 'LLM Providers',
icon: Brain,
keywords: [
'llm',
'provider',
'api key',
'openai',
'openrouter',
'orcarouter',
'cheaper inference',
'cheaperinference',
'opper',
'api route',
'groq',
'iflytek',
'ollama',
'gemini',
'cinematic',
'autofit',
'translation quality',
],
keywordKeys: ['settings.llmp_provider', 'settings.llmp_api_key', 'settings.llmp_model'],
},
{
id: 'llm-skills',
labelKey: 'settings.llm_skills',
defaultLabel: 'LLM Skills',
icon: Sparkles,
keywords: [
'llm',
'skills',
'ai features',
'routing',
'local model',
'ollama',
'lm studio',
'cinematic',
'refinement',
'glossary',
'direction',
'slot fitting',
],
},
],
},
{
id: 'app',
labelKey: 'settings.group_app',
defaultLabel: 'App',
items: [
{
id: 'updates',
labelKey: 'settings.updates',
defaultLabel: 'Updates',
icon: ArrowDownToLine,
keywords: ['update', 'channel', 'stable', 'preview', 'releases', 'changelog'],
},
{
id: 'privacy',
labelKey: 'settings.privacy',
defaultLabel: 'Privacy & Reporting',
icon: ShieldCheck,
keywords: ['privacy', 'reporting', 'telemetry', 'tracking', 'network calls'],
},
{
id: 'logs',
labelKey: 'settings.logs',
defaultLabel: 'Logs',
icon: FileText,
keywords: ['logs', 'backend log', 'frontend log', 'tauri log', 'report a bug'],
},
{
id: 'about',
labelKey: 'settings.about',
defaultLabel: 'About',
icon: Info,
keywords: ['about', 'version', 'license', 'diagnostics', 'self check'],
keywordKeys: ['about.version', 'about.self_check'],
},
],
},
];
/** Flat list of every category, in sidebar order. */
export const CATEGORIES = GROUPS.flatMap((g) => g.items.map((it) => ({ ...it, group: g.id })));
/** Fast lookup: category id → category record. */
export const CATEGORY_BY_ID = Object.fromEntries(CATEGORIES.map((c) => [c.id, c]));
/** The category shown on first open (and the deep-link/persist fallback). */
export const DEFAULT_CATEGORY = 'appearance';
/**
* Map legacy Settings tab ids (the old 11-tab shell, still used by deep-links
* like the footer version badge → 'updates') onto the new category ids. Any id
* not listed is assumed to already be a valid new category id.
*/
export const LEGACY_TAB_MAP = {
general: 'appearance',
capture: 'dictation',
// The Models category (models directory, HF mirror pointer) folded into Storage.
models: 'storage',
};
/** Resolve any incoming tab/category id to a valid new category id. */
export function resolveCategoryId(id) {
if (!id) return DEFAULT_CATEGORY;
const mapped = LEGACY_TAB_MAP[id] || id;
return CATEGORY_BY_ID[mapped] ? mapped : DEFAULT_CATEGORY;
}
/**
* Given a lowercased query, return the set of category ids whose label OR any
* keyword matches. Used to filter the sidebar and to power "search a setting →
* jump to its category".
*
* @param {string} query
* @param {function=} labelFor (category) => translated label
* @param {function=} translate i18n `t` — lets `keywordKeys` (setting-row
* title keys) match in the active UI language, so a German user finds
* Appearance by "Schriftart" just like an English user finds it by "font".
* The English `keywords` always match too, in every locale.
*/
export function matchCategories(query, labelFor, translate) {
const q = query.trim().toLowerCase();
if (!q) return CATEGORIES.map((c) => c.id);
return CATEGORIES.filter((c) => {
const label = (labelFor ? labelFor(c) : c.defaultLabel).toLowerCase();
if (label.includes(q)) return true;
if ((c.keywords || []).some((k) => k.toLowerCase().includes(q))) return true;
if (!translate) return false;
return (c.keywordKeys || []).some((key) => String(translate(key)).toLowerCase().includes(q));
}).map((c) => c.id);
}
@@ -1,67 +0,0 @@
import { describe, it, expect } from 'vitest';
import {
CATEGORIES,
CATEGORY_BY_ID,
matchCategories,
resolveCategoryId,
} from './settingsCategories';
import en from '../../i18n/locales/en.json';
describe('matchCategories — search matching', () => {
it('an empty query returns every category', () => {
expect(matchCategories('')).toEqual(CATEGORIES.map((c) => c.id));
});
it('a query matching nothing returns an empty list (drives the sidebar empty state)', () => {
expect(matchCategories('zzz-no-such-setting')).toEqual([]);
});
it('English keywords match in every locale (no translate fn needed)', () => {
expect(matchCategories('proxy')).toContain('network');
expect(matchCategories('ui scale')).toContain('appearance');
expect(matchCategories('language')).toContain('appearance');
});
it('finds a provider by its spaced display name and by the joined spelling', () => {
expect(matchCategories('cheaper inference')).toContain('llm-providers');
expect(matchCategories('cheaperinference')).toContain('llm-providers');
});
it('folds the former General category into Appearance', () => {
expect(CATEGORY_BY_ID.general).toBeUndefined();
expect(resolveCategoryId('general')).toBe('appearance');
});
it('routes the moved panels: mirror searches open Network, models-directory searches open Storage', () => {
expect(CATEGORY_BY_ID.models).toBeUndefined();
expect(CATEGORY_BY_ID.engines).toBeUndefined();
expect(resolveCategoryId('models')).toBe('storage');
expect(matchCategories('mirror')).toContain('network');
expect(matchCategories('mirror')).not.toContain('audio-tools');
expect(matchCategories('hf_endpoint')).toEqual(['network']);
expect(matchCategories('models directory')).toContain('storage');
});
it('uses the concise VoiceStudio API label', () => {
expect(CATEGORY_BY_ID.openapi.defaultLabel).toBe('VoiceStudio API');
expect(en.settings.openapi).toBe('VoiceStudio API');
});
it('keywordKeys match through the active locale, so localized setting names find their category', () => {
// Simulate a German UI: settings.font resolves to "Schriftart".
const t = (key) => (key === 'settings.font' ? 'Schriftart' : key);
expect(matchCategories('schriftart', undefined, t)).toContain('appearance');
// English keywords keep working alongside the translated titles.
expect(matchCategories('font', undefined, t)).toContain('appearance');
});
it('every keywordKey points at a real en.json string (typo guard)', () => {
for (const c of CATEGORIES) {
for (const key of c.keywordKeys || []) {
const value = key.split('.').reduce((node, part) => node?.[part], en);
expect(typeof value, `${c.id}: ${key} missing from en.json`).toBe('string');
}
}
});
});
@@ -1,69 +0,0 @@
import * as React from 'react';
import { Slot } from '@radix-ui/react-slot';
import { cva, type VariantProps } from 'class-variance-authority';
import { cn } from '@/lib/utils';
/**
* shadcn/ui Badge — new-york style, themed through the VoiceStudio token bridge.
*
* Beyond the stock shadcn variants (default / secondary / destructive /
* outline) the CVA carries the VoiceStudio *tones* (neutral / brand / success /
* warn / danger / info / violet) that back the legacy `src/ui/Badge.jsx`
* wrapper. Tones render as chrome chips — a mono uppercase pill with a
* tinted fill (borders removed app-wide) — using palette token utilities so
* each tone recolors with every [data-theme].
*/
const badgeVariants = cva(
'inline-flex items-center gap-[2px] rounded-[var(--chrome-radius-pill)] font-mono font-semibold tracking-[var(--chrome-label-track)] uppercase whitespace-nowrap select-none leading-[1.2] [&>svg]:size-3 [&>svg]:pointer-events-none',
{
variants: {
variant: {
// ── stock shadcn ──
default: 'border border-transparent bg-primary text-primary-foreground',
secondary: 'border border-transparent bg-secondary text-secondary-foreground',
destructive: 'border border-transparent bg-destructive text-destructive-foreground',
outline: 'border border-transparent bg-secondary text-foreground',
// ── VoiceStudio tones ──
neutral: 'text-muted-foreground border border-transparent bg-transparent',
brand: 'text-primary border border-transparent bg-primary/[0.12]',
success: 'text-success border border-transparent bg-success/10',
warn: 'text-accent border border-transparent bg-accent/10',
danger: 'text-destructive border border-transparent bg-destructive/10',
info: 'text-info border border-transparent bg-info/10',
violet: 'text-muted-foreground border border-transparent bg-transparent',
},
size: {
xs: 'px-1.5 py-0 text-[11px]',
sm: 'px-[7px] py-px text-[11px]',
},
},
defaultVariants: {
variant: 'neutral',
size: 'sm',
},
},
);
function Badge({
className,
variant,
size,
asChild = false,
...props
}: React.ComponentProps<'span'> &
VariantProps<typeof badgeVariants> & {
asChild?: boolean;
}) {
const Comp = asChild ? Slot : 'span';
return (
<Comp
data-slot="badge"
className={cn(badgeVariants({ variant, size }), className)}
{...props}
/>
);
}
export { Badge, badgeVariants };
@@ -1,106 +0,0 @@
import * as React from 'react';
import { Slot } from '@radix-ui/react-slot';
import { cva, type VariantProps } from 'class-variance-authority';
import { cn } from '@/lib/utils';
/**
* shadcn/ui Button — new-york style, themed through the VoiceStudio token bridge
* (see index.css). `bg-primary`/`text-primary-foreground`/`bg-destructive`/
* `border-input`/`ring-ring` resolve to the VoiceStudio palette, so this renders
* in brand pink + amber accent + the dark chrome bg, and recolors with every
* [data-theme].
*
* The CVA carries TWO families of variants:
* • the stock shadcn set (default / secondary / outline / ghost / link /
* destructive + sizes default / sm / lg / icon) — used by the foundation
* proof spec; and
* • the VoiceStudio set (primary / subtle / softGhost / danger / chip[+Active] /
* preset[+Active] / iconBtn[+Active] + sizes omniSm / omniMd / chip /
* preset / iconSm / iconMd) — these back the live `src/ui/Button.jsx`
* wrapper, which maps the legacy prop API onto them. They are expressed with
* palette token utilities (bg-primary, border-border, text-success, …) so
* every variant stays on-palette and recolors per theme.
*/
const buttonVariants = cva(
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 aria-invalid:border-destructive",
{
variants: {
variant: {
// ── stock shadcn ──
default: 'bg-primary text-primary-foreground shadow-xs hover:bg-primary/90',
destructive:
'bg-destructive text-destructive-foreground shadow-xs hover:bg-destructive/90 focus-visible:ring-destructive/20',
outline:
'border border-transparent bg-background shadow-xs hover:bg-accent hover:text-accent-foreground',
secondary: 'bg-secondary text-secondary-foreground shadow-xs hover:bg-secondary/80',
ghost: 'hover:bg-accent hover:text-accent-foreground',
link: 'text-primary underline-offset-4 hover:underline',
// ── VoiceStudio (back the legacy src/ui/Button.jsx) ──
// NB: app ships Tailwind WITHOUT Preflight, so a bare <button> keeps its
// native UA border — every variant must set an explicit border (even a
// transparent one) or the default chrome leaks through.
primary:
'border border-transparent bg-primary text-primary-foreground font-semibold shadow-xs hover:bg-primary/90 active:scale-[0.98]',
subtle:
'border border-transparent bg-transparent text-muted-foreground hover:bg-[var(--chrome-hover-bg)] hover:text-foreground hover:border-transparent',
softGhost:
'border border-transparent bg-transparent text-muted-foreground hover:bg-[var(--chrome-hover-bg)] hover:text-foreground',
danger:
'text-destructive bg-destructive/10 border border-transparent hover:bg-destructive/20 hover:border-transparent',
chip: 'border border-transparent bg-transparent text-muted-foreground hover:bg-[var(--chrome-hover-bg)] hover:text-foreground hover:border-transparent',
chipActive: 'text-success bg-success/10 border border-transparent',
preset:
'justify-start text-left border border-transparent bg-transparent text-muted-foreground hover:bg-[var(--chrome-hover-bg)] hover:text-foreground hover:border-transparent',
presetActive:
'justify-start text-left text-primary bg-primary/[0.12] border border-transparent',
iconBtn:
'border border-transparent bg-transparent text-muted-foreground hover:bg-[var(--chrome-hover-bg)] hover:text-foreground hover:border-transparent',
iconBtnActive: 'text-primary bg-primary/[0.12] border border-transparent',
},
size: {
// ── stock shadcn ──
default: 'h-9 px-4 py-2 has-[>svg]:px-3',
sm: 'h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5',
lg: 'h-10 rounded-md px-6 has-[>svg]:px-4',
icon: 'size-9',
// ── VoiceStudio ──
omniSm: 'px-2.5 py-[3px] text-xs',
omniMd: 'px-3 py-1.5 text-sm',
chip: 'px-2 py-0.5 text-xs',
preset: 'px-2 py-[3px] text-xs',
iconSm: 'size-5 p-0',
iconMd: 'size-[22px] p-0',
},
},
defaultVariants: {
variant: 'default',
size: 'default',
},
},
);
function Button({
className,
variant,
size,
asChild = false,
...props
}: React.ComponentProps<'button'> &
VariantProps<typeof buttonVariants> & {
asChild?: boolean;
}) {
const Comp = asChild ? Slot : 'button';
return (
<Comp
data-slot="button"
className={cn(buttonVariants({ variant, size, className }))}
{...props}
/>
);
}
export { Button, buttonVariants };
@@ -1,93 +0,0 @@
import * as React from 'react';
import { Slot } from '@radix-ui/react-slot';
import { cn } from '@/lib/utils';
/**
* shadcn/ui Card — new-york style, themed through the VoiceStudio token bridge
* (see index.css). `bg-card`/`text-card-foreground`/`border` resolve to the
* VoiceStudio palette. `src/ui/Panel.jsx` builds on `Card` (as the surface
* primitive) plus its own header/body structure, layering the glass/solid/flat
* variants + the `.ui-panel*` cross-file hooks while keeping its
* `variant`/`padding`/`title`/`actions`/`as` prop API.
*
* The base `Card` accepts `asChild` (via Radix `Slot`) so a wrapper can render
* the surface as an arbitrary element (Panel's `as` prop) without losing the
* card styling.
*/
function Card({
className,
asChild = false,
...props
}: React.ComponentProps<'div'> & { asChild?: boolean }) {
const Comp = asChild ? Slot : 'div';
return (
<Comp
data-slot="card"
className={cn(
'bg-card text-card-foreground flex flex-col gap-6 rounded-xl border border-transparent py-6 shadow-sm',
className,
)}
{...props}
/>
);
}
function CardHeader({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="card-header"
className={cn(
'@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-1.5 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6',
className,
)}
{...props}
/>
);
}
function CardTitle({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="card-title"
className={cn('leading-none font-semibold', className)}
{...props}
/>
);
}
function CardDescription({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="card-description"
className={cn('text-muted-foreground text-sm', className)}
{...props}
/>
);
}
function CardAction({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="card-action"
className={cn('col-start-2 row-span-2 row-start-1 self-start justify-self-end', className)}
{...props}
/>
);
}
function CardContent({ className, ...props }: React.ComponentProps<'div'>) {
return <div data-slot="card-content" className={cn('px-6', className)} {...props} />;
}
function CardFooter({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="card-footer"
className={cn('flex items-center px-6 [.border-t]:pt-6', className)}
{...props}
/>
);
}
export { Card, CardHeader, CardFooter, CardTitle, CardAction, CardDescription, CardContent };
@@ -1,137 +0,0 @@
import * as React from 'react';
import * as DialogPrimitive from '@radix-ui/react-dialog';
import { XIcon } from 'lucide-react';
import { cn } from '@/lib/utils';
/**
* shadcn/ui Dialog — new-york style, themed through the VoiceStudio token bridge
* (see index.css). `bg-background`/`border`/`ring-ring` resolve to the
* VoiceStudio palette and the enter/exit transitions use tw-animate-css
* `animate-in`/`animate-out` keyed off Radix `data-[state]`.
*
* The app-facing primitive `src/ui/Dialog.jsx` wraps these parts, layering the
* glass surface + per-size widths and rendering its own close button
* (`showCloseButton={false}`) so call sites keep their existing prop API.
*/
function Dialog({ ...props }: React.ComponentProps<typeof DialogPrimitive.Root>) {
return <DialogPrimitive.Root data-slot="dialog" {...props} />;
}
function DialogTrigger({ ...props }: React.ComponentProps<typeof DialogPrimitive.Trigger>) {
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />;
}
function DialogPortal({ ...props }: React.ComponentProps<typeof DialogPrimitive.Portal>) {
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />;
}
function DialogClose({ ...props }: React.ComponentProps<typeof DialogPrimitive.Close>) {
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />;
}
function DialogOverlay({
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Overlay>) {
return (
<DialogPrimitive.Overlay
data-slot="dialog-overlay"
className={cn(
'data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50',
className,
)}
{...props}
/>
);
}
function DialogContent({
className,
children,
showCloseButton = true,
...props
}: React.ComponentProps<typeof DialogPrimitive.Content> & {
showCloseButton?: boolean;
}) {
return (
<DialogPortal data-slot="dialog-portal">
<DialogOverlay />
<DialogPrimitive.Content
data-slot="dialog-content"
className={cn(
'bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border border-transparent p-6 shadow-lg duration-200',
className,
)}
{...props}
>
{children}
{showCloseButton && (
<DialogPrimitive.Close
data-slot="dialog-close"
className="ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-none disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4"
>
<XIcon />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
)}
</DialogPrimitive.Content>
</DialogPortal>
);
}
function DialogHeader({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="dialog-header"
className={cn('flex flex-col gap-2 text-center sm:text-left', className)}
{...props}
/>
);
}
function DialogFooter({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="dialog-footer"
className={cn('flex flex-col-reverse gap-2 sm:flex-row sm:justify-end', className)}
{...props}
/>
);
}
function DialogTitle({ className, ...props }: React.ComponentProps<typeof DialogPrimitive.Title>) {
return (
<DialogPrimitive.Title
data-slot="dialog-title"
className={cn('text-lg leading-none font-semibold', className)}
{...props}
/>
);
}
function DialogDescription({
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Description>) {
return (
<DialogPrimitive.Description
data-slot="dialog-description"
className={cn('text-muted-foreground text-sm', className)}
{...props}
/>
);
}
export {
Dialog,
DialogClose,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogOverlay,
DialogPortal,
DialogTitle,
DialogTrigger,
};
@@ -1,123 +0,0 @@
import * as React from 'react';
import * as DropdownMenuPrimitive from '@radix-ui/react-dropdown-menu';
import { cn } from '@/lib/utils';
/**
* shadcn/ui DropdownMenu — new-york style, themed through the VoiceStudio token
* bridge (see index.css). `src/ui/Menu.jsx` wraps `DropdownMenu` + `Trigger` +
* `Content` + `Item` + `Separator`, layering the VoiceStudio glass surface +
* destructive/disabled item states via className while keeping its
* `items`/`placement`/`open`/`onOpenChange`/`width` prop API. Keyboard nav,
* collision-aware positioning, and ARIA come from Radix; enter/exit transitions
* use tw-animate-css `animate-in`/`animate-out`.
*/
function DropdownMenu({ ...props }: React.ComponentProps<typeof DropdownMenuPrimitive.Root>) {
return <DropdownMenuPrimitive.Root data-slot="dropdown-menu" {...props} />;
}
function DropdownMenuPortal({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Portal>) {
return <DropdownMenuPrimitive.Portal data-slot="dropdown-menu-portal" {...props} />;
}
function DropdownMenuTrigger({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Trigger>) {
return <DropdownMenuPrimitive.Trigger data-slot="dropdown-menu-trigger" {...props} />;
}
function DropdownMenuContent({
className,
sideOffset = 4,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Content>) {
return (
<DropdownMenuPrimitive.Portal>
<DropdownMenuPrimitive.Content
data-slot="dropdown-menu-content"
sideOffset={sideOffset}
className={cn(
'bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border border-transparent p-1 shadow-md',
className,
)}
{...props}
/>
</DropdownMenuPrimitive.Portal>
);
}
function DropdownMenuItem({
className,
inset,
variant = 'default',
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Item> & {
inset?: boolean;
variant?: 'default' | 'destructive';
}) {
return (
<DropdownMenuPrimitive.Item
data-slot="dropdown-menu-item"
data-inset={inset}
data-variant={variant}
className={cn(
"focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className,
)}
{...props}
/>
);
}
function DropdownMenuLabel({
className,
inset,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Label> & {
inset?: boolean;
}) {
return (
<DropdownMenuPrimitive.Label
data-slot="dropdown-menu-label"
data-inset={inset}
className={cn('px-2 py-1.5 text-sm font-medium data-[inset]:pl-8', className)}
{...props}
/>
);
}
function DropdownMenuSeparator({
className,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Separator>) {
return (
<DropdownMenuPrimitive.Separator
data-slot="dropdown-menu-separator"
className={cn('bg-border -mx-1 my-1 h-px', className)}
{...props}
/>
);
}
function DropdownMenuShortcut({ className, ...props }: React.ComponentProps<'span'>) {
return (
<span
data-slot="dropdown-menu-shortcut"
className={cn('text-muted-foreground ml-auto text-xs tracking-widest', className)}
{...props}
/>
);
}
export {
DropdownMenu,
DropdownMenuPortal,
DropdownMenuTrigger,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuShortcut,
};
@@ -1,32 +0,0 @@
import * as React from 'react';
import { cn } from '@/lib/utils';
/**
* shadcn/ui Input — new-york style, themed through the VoiceStudio token bridge
* (see index.css). `border-input`/`text-foreground`/`placeholder:text-muted-
* foreground`/`focus-visible:ring-ring`/`aria-invalid:border-destructive`
* resolve to the VoiceStudio palette, so it shows the chrome border, muted
* placeholder, and brand-pink focus ring, recoloring with every [data-theme].
* Shared form primitives in ../../ui/Input.jsx wrap this input shell.
*/
/**
* inputBaseClass — the shadcn/ui Input shell: chrome border, transparent fill,
* muted placeholder, brand focus ring, destructive invalid state, all resolved
* through the VoiceStudio token bridge so it tracks every [data-theme].
*
* Exported for the legacy form wrappers in ../../ui/Input.jsx. Existing native-select
* callers retain their event API; new or redesigned choices use the shared
* SearchableSelect (VoiceSelector for voices), per AGENTS.md.
* The fixed `h-9` lives here; wrappers supply their own padding-based size scale.
*/
const inputBaseClass =
'file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground border-input flex h-9 w-full min-w-0 rounded-md border bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 aria-invalid:border-destructive';
function Input({ className, type, ...props }: React.ComponentProps<'input'>) {
return (
<input type={type} data-slot="input" className={cn(inputBaseClass, className)} {...props} />
);
}
export { Input, inputBaseClass };
@@ -1,49 +0,0 @@
import * as React from 'react';
import * as ProgressPrimitive from '@radix-ui/react-progress';
import { cn } from '@/lib/utils';
/**
* shadcn/ui Progress — new-york style, built on @radix-ui/react-progress for
* correct ARIA value attributes, themed through the VoiceStudio token bridge
* (`bg-secondary` track resolves to the dark elevated surface).
*
* Adapted from the stock shadcn source so it can back the legacy
* `src/ui/Progress.jsx` wrapper, which adds per-tone gradient fills, sizes, a
* shimmer overlay, and an indeterminate mode:
* • `indicatorClassName` styles the fill (the wrapper passes the tone gradient
* + shimmer hook classes there);
* • `indeterminate` omits the inline width so the unlayered
* `.ui-progress.is-indeterminate` rule (residual.css) can drive the sliding
* animation;
* • determinate fill uses a width style (not the stock translateX) so the
* shimmer overlay covers only the filled portion, matching the prior look.
*/
function Progress({
className,
indicatorClassName,
value,
indeterminate = false,
...props
}: React.ComponentProps<typeof ProgressPrimitive.Root> & {
indicatorClassName?: string;
indeterminate?: boolean;
}) {
return (
<ProgressPrimitive.Root
data-slot="progress"
value={indeterminate ? null : value}
max={100}
className={cn('relative w-full overflow-hidden rounded-full bg-secondary', className)}
{...props}
>
<ProgressPrimitive.Indicator
data-slot="progress-indicator"
className={cn('relative h-full transition-all', indicatorClassName)}
style={indeterminate ? undefined : { width: `${value ?? 0}%` }}
/>
</ProgressPrimitive.Root>
);
}
export { Progress };
@@ -1,65 +0,0 @@
import * as React from 'react';
import * as SliderPrimitive from '@radix-ui/react-slider';
import { cn } from '@/lib/utils';
/**
* shadcn/ui Slider — new-york style, themed through the VoiceStudio token bridge
* (see index.css). `bg-muted` track + `bg-primary` range + `border-primary`
* thumb resolve to the VoiceStudio palette (brand-pink fill), recoloring with
* every [data-theme]. The VoiceStudio `Slider` primitive (src/ui/Slider.jsx)
* wraps this and adds the label + value bubble chrome and its number-based
* `onChange` API; track/thumb sizing is tuned from the wrapper via the
* `data-slot` selectors below.
*/
function Slider({
className,
defaultValue,
value,
min = 0,
max = 100,
...props
}: React.ComponentProps<typeof SliderPrimitive.Root>) {
const _values = React.useMemo(
() => (Array.isArray(value) ? value : Array.isArray(defaultValue) ? defaultValue : [min, max]),
[value, defaultValue, min, max],
);
return (
<SliderPrimitive.Root
data-slot="slider"
defaultValue={defaultValue}
value={value}
min={min}
max={max}
className={cn(
'relative flex w-full touch-none items-center select-none data-[disabled]:opacity-50 data-[orientation=vertical]:h-full data-[orientation=vertical]:min-h-44 data-[orientation=vertical]:w-auto data-[orientation=vertical]:flex-col',
className,
)}
{...props}
>
<SliderPrimitive.Track
data-slot="slider-track"
className={cn(
'bg-muted relative grow overflow-hidden rounded-full data-[orientation=horizontal]:h-1.5 data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-1.5',
)}
>
<SliderPrimitive.Range
data-slot="slider-range"
className={cn(
'bg-primary absolute data-[orientation=horizontal]:h-full data-[orientation=vertical]:w-full',
)}
/>
</SliderPrimitive.Track>
{Array.from({ length: _values.length }, (_, index) => (
<SliderPrimitive.Thumb
data-slot="slider-thumb"
key={index}
className="border-primary bg-background ring-ring/50 block size-4 shrink-0 rounded-full border shadow-sm transition-[color,box-shadow] hover:ring-4 focus-visible:ring-4 focus-visible:outline-hidden disabled:pointer-events-none disabled:opacity-50"
/>
))}
</SliderPrimitive.Root>
);
}
export { Slider };
@@ -1,59 +0,0 @@
import * as React from 'react';
import * as TabsPrimitive from '@radix-ui/react-tabs';
import { cn } from '@/lib/utils';
/**
* shadcn/ui Tabs — new-york style, themed through the VoiceStudio token bridge
* (see index.css). `src/ui/Tabs.jsx` wraps `Tabs` + `TabsList` + `TabsTrigger`
* and supplies the VoiceStudio pill/underline rail look via className while
* keeping its `items`/`value`/`onChange`/`size`/`variant` prop API. Provides
* roving tabindex, arrow-key navigation, and proper ARIA roles for free.
*/
function Tabs({ className, ...props }: React.ComponentProps<typeof TabsPrimitive.Root>) {
return (
<TabsPrimitive.Root
data-slot="tabs"
className={cn('flex flex-col gap-2', className)}
{...props}
/>
);
}
function TabsList({ className, ...props }: React.ComponentProps<typeof TabsPrimitive.List>) {
return (
<TabsPrimitive.List
data-slot="tabs-list"
className={cn(
'bg-muted text-muted-foreground inline-flex h-9 w-fit items-center justify-center rounded-lg p-[3px]',
className,
)}
{...props}
/>
);
}
function TabsTrigger({ className, ...props }: React.ComponentProps<typeof TabsPrimitive.Trigger>) {
return (
<TabsPrimitive.Trigger
data-slot="tabs-trigger"
className={cn(
"data-[state=active]:bg-background dark:data-[state=active]:text-foreground focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:outline-ring dark:data-[state=active]:border-input dark:data-[state=active]:bg-input/30 text-foreground dark:text-muted-foreground inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-md border border-transparent px-2 py-1 text-sm font-medium whitespace-nowrap transition-[color,box-shadow] focus-visible:ring-[3px] focus-visible:outline-1 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:shadow-sm [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className,
)}
{...props}
/>
);
}
function TabsContent({ className, ...props }: React.ComponentProps<typeof TabsPrimitive.Content>) {
return (
<TabsPrimitive.Content
data-slot="tabs-content"
className={cn('flex-1 outline-none', className)}
{...props}
/>
);
}
export { Tabs, TabsList, TabsTrigger, TabsContent };
@@ -1,21 +0,0 @@
import * as React from 'react';
import { cn } from '@/lib/utils';
/**
* shadcn/ui Textarea — new-york style, themed through the VoiceStudio token bridge
* (see index.css). Mirrors the Input shell (`border-input`/`bg-transparent`/
* `placeholder:text-muted-foreground`/`focus-visible:ring-ring`/
* `aria-invalid:border-destructive`) so multi-line fields match single-line
* ones and recolor with every [data-theme]. `textareaBaseClass` is exported so
* the VoiceStudio `Textarea` primitive (src/ui/Input.jsx) can layer its
* padding-based size scale on top without re-deriving the shell.
*/
const textareaBaseClass =
'border-input placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 aria-invalid:border-destructive flex field-sizing-content min-h-16 w-full rounded-md border bg-transparent px-3 py-2 text-base shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 md:text-sm';
function Textarea({ className, ...props }: React.ComponentProps<'textarea'>) {
return <textarea data-slot="textarea" className={cn(textareaBaseClass, className)} {...props} />;
}
export { Textarea, textareaBaseClass };
@@ -1,70 +0,0 @@
import * as React from 'react';
import * as ToggleGroupPrimitive from '@radix-ui/react-toggle-group';
import { type VariantProps } from 'class-variance-authority';
import { cn } from '@/lib/utils';
import { toggleVariants } from '@/components/ui/toggle';
/**
* shadcn/ui ToggleGroup — new-york style, built on @radix-ui/react-toggle-group
* for keyboard navigation + single/multiple selection state. The chosen
* `variant`/`size` flow to every item via context. Backs the legacy
* `src/ui/Segmented.jsx` wrapper (variant="seg"); themed through the VoiceStudio
* token bridge.
*/
const ToggleGroupContext = React.createContext<VariantProps<typeof toggleVariants>>({
size: 'default',
variant: 'default',
});
function ToggleGroup({
className,
variant,
size,
children,
...props
}: React.ComponentProps<typeof ToggleGroupPrimitive.Root> & VariantProps<typeof toggleVariants>) {
return (
<ToggleGroupPrimitive.Root
data-slot="toggle-group"
data-variant={variant}
data-size={size}
className={cn('group/toggle-group flex w-fit items-center', className)}
{...props}
>
<ToggleGroupContext.Provider value={{ variant, size }}>
{children}
</ToggleGroupContext.Provider>
</ToggleGroupPrimitive.Root>
);
}
function ToggleGroupItem({
className,
children,
variant,
size,
...props
}: React.ComponentProps<typeof ToggleGroupPrimitive.Item> & VariantProps<typeof toggleVariants>) {
const context = React.useContext(ToggleGroupContext);
return (
<ToggleGroupPrimitive.Item
data-slot="toggle-group-item"
data-variant={context.variant || variant}
data-size={context.size || size}
className={cn(
toggleVariants({
variant: context.variant || variant,
size: context.size || size,
}),
className,
)}
{...props}
>
{children}
</ToggleGroupPrimitive.Item>
);
}
export { ToggleGroup, ToggleGroupItem };
@@ -1,59 +0,0 @@
import * as React from 'react';
import * as TogglePrimitive from '@radix-ui/react-toggle';
import { cva, type VariantProps } from 'class-variance-authority';
import { cn } from '@/lib/utils';
/**
* shadcn/ui Toggle — new-york style, themed through the VoiceStudio token bridge.
*
* `toggleVariants` is shared with ToggleGroup. Beyond the stock variants
* (default / outline + sizes default / sm / lg) it carries the VoiceStudio
* segmented-control option (`variant="seg"` + sizes segXs / segSm) that backs
* the legacy `src/ui/Segmented.jsx` wrapper: a borderless pill whose on/off look
* keys off Radix's `data-state`, styled with palette token utilities so it
* recolors per theme (brand-pink fill when active).
*/
const toggleVariants = cva(
"inline-flex items-center justify-center gap-2 rounded-md text-sm font-medium hover:bg-muted hover:text-muted-foreground disabled:pointer-events-none disabled:opacity-50 data-[state=on]:bg-accent data-[state=on]:text-accent-foreground [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 [&_svg]:shrink-0 focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] outline-none transition-[color,box-shadow] aria-invalid:ring-destructive/20 aria-invalid:border-destructive whitespace-nowrap",
{
variants: {
variant: {
default: 'bg-transparent',
outline:
'border border-input bg-transparent shadow-xs hover:bg-accent hover:text-accent-foreground',
// ── VoiceStudio segmented option ──
seg: 'font-extrabold border-0 cursor-pointer rounded-[var(--radius-pill)] bg-transparent text-fg-subtle transition-[background,color] duration-[var(--dur-fast)] ease-[var(--ease-out)] data-[state=off]:hover:text-fg data-[state=off]:hover:bg-[var(--chrome-hover-bg)] data-[state=on]:bg-primary/25 data-[state=on]:text-fg',
},
size: {
default: 'h-9 px-2 min-w-9',
sm: 'h-8 px-1.5 min-w-8',
lg: 'h-10 px-2.5 min-w-10',
// ── VoiceStudio segmented sizes ──
segXs: 'px-[9px] py-[2px] text-[0.58rem]',
segSm: 'px-[10px] py-[3px] text-[0.62rem]',
},
},
defaultVariants: {
variant: 'default',
size: 'default',
},
},
);
function Toggle({
className,
variant,
size,
...props
}: React.ComponentProps<typeof TogglePrimitive.Root> & VariantProps<typeof toggleVariants>) {
return (
<TogglePrimitive.Root
data-slot="toggle"
className={cn(toggleVariants({ variant, size, className }))}
{...props}
/>
);
}
export { Toggle, toggleVariants };
@@ -1,68 +0,0 @@
import * as React from 'react';
import * as TooltipPrimitive from '@radix-ui/react-tooltip';
import { cn } from '@/lib/utils';
/**
* shadcn/ui Tooltip — new-york style, themed through the VoiceStudio token bridge
* (see index.css). The arrow + body use `bg-primary`/`text-primary-foreground`
* by default; `src/ui/Tooltip.jsx` overrides the surface with the VoiceStudio
* dark chrome look via className and maps the legacy `placement`/`delay` props.
* Enter/exit transitions use tw-animate-css `animate-in`/`animate-out` keyed off
* Radix `data-[state]` + `data-[side]`.
*/
function TooltipProvider({
delayDuration = 0,
...props
}: React.ComponentProps<typeof TooltipPrimitive.Provider>) {
return (
<TooltipPrimitive.Provider
data-slot="tooltip-provider"
delayDuration={delayDuration}
{...props}
/>
);
}
function Tooltip({ ...props }: React.ComponentProps<typeof TooltipPrimitive.Root>) {
return (
<TooltipProvider>
<TooltipPrimitive.Root data-slot="tooltip" {...props} />
</TooltipProvider>
);
}
function TooltipTrigger({ ...props }: React.ComponentProps<typeof TooltipPrimitive.Trigger>) {
return <TooltipPrimitive.Trigger data-slot="tooltip-trigger" {...props} />;
}
function TooltipContent({
className,
sideOffset = 0,
showArrow = true,
children,
...props
}: React.ComponentProps<typeof TooltipPrimitive.Content> & {
showArrow?: boolean;
}) {
return (
<TooltipPrimitive.Portal>
<TooltipPrimitive.Content
data-slot="tooltip-content"
sideOffset={sideOffset}
className={cn(
'bg-primary text-primary-foreground animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-md px-3 py-1.5 text-xs text-balance',
className,
)}
{...props}
>
{children}
{showArrow && (
<TooltipPrimitive.Arrow className="bg-primary fill-primary z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]" />
)}
</TooltipPrimitive.Content>
</TooltipPrimitive.Portal>
);
}
export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider };
@@ -1,114 +0,0 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { useAppStore } from '../store';
import { apiJson } from '../api/client';
import { installRecommendedAsr } from '../utils/asrModelMissing';
// Keep model checks separate from microphone access: checking the page must
// never record audio or start a download. Capture still validates server-side.
export function useDictationReadiness() {
const modelId = useAppStore((store) => store.dictationModelId);
const [state, setState] = useState({ phase: 'checking', missing: null });
const task = useRef(null);
const mounted = useRef(false);
const checking = useRef(false);
const check = useCallback(async () => {
if (task.current || checking.current) return false;
checking.current = true;
try {
const result = await apiJson(
`/dictation/readiness?model_id=${encodeURIComponent(useAppStore.getState().dictationModelId || '')}`,
);
if (mounted.current && !task.current)
setState((previous) => ({
phase: result.ready === true ? 'ready' : result.missing ? 'missing' : 'error',
missing: result.missing,
error: result.ready !== true && previous.error,
}));
return result.ready === true;
} catch {
if (mounted.current && !task.current) setState({ phase: 'error', missing: null });
return false;
} finally {
checking.current = false;
}
}, [modelId]);
useEffect(() => {
mounted.current = true;
void check();
const refresh = () => {
if (document.visibilityState !== 'hidden') void check();
};
const timer = setInterval(refresh, 5000);
window.addEventListener('focus', refresh);
return () => {
mounted.current = false;
clearInterval(timer);
window.removeEventListener('focus', refresh);
task.current?.abort();
};
}, [check]);
// Install a catalogue model (`/dictation/models` row) or, with no argument,
// the backend's recommended one. The chooser on the Transcriptions page lets
// the user pick by accuracy / latency / languages instead of being handed
// the recommended download only; the installer persists the pick as the
// dictation model, so capture uses it the moment the weights land.
const install = useCallback(
async (model) => {
if (task.current) return;
const payload = model?.repo_id
? {
recommended: {
repo_id: model.repo_id,
label: model.label,
size_gb: model.size_gb,
dictation_id: model.id,
},
}
: state.missing;
if (!payload?.recommended?.repo_id) return;
const controller = new AbortController();
task.current = controller;
setState((previous) => ({
...previous,
phase: 'installing',
percent: 0,
error: false,
target: payload.recommended,
}));
try {
const installed = await installRecommendedAsr(payload, {
signal: controller.signal,
onProgress: ({ percent }) => {
if (mounted.current) setState((previous) => ({ ...previous, percent }));
},
});
task.current = null;
if (installed?.dictation_id && mounted.current) {
// The installer persisted this selection; keep the recorder's store
// in sync before the next readiness check and capture request.
useAppStore.setState({ dictationModelId: installed.dictation_id });
}
if (mounted.current) await check();
} catch {
if (mounted.current)
setState((previous) => ({ ...previous, phase: 'missing', error: true, target: null }));
} finally {
task.current = null;
}
},
[state.missing, check],
);
// Switch capture to a model that is already on disk — no download, just the
// pref write the store already does — then re-check so the page unblocks.
const select = useCallback(
async (model) => {
if (task.current || !model?.id) return false;
useAppStore.getState().setDictationModelId(model.id);
return check();
},
[check],
);
return { ...state, check, install, select };
}
@@ -1,50 +0,0 @@
import { useEffect, useState } from 'react';
import { DEFAULT_SHORTCUT, formatShortcut } from '../utils/dictationShortcut';
function fallbackInfo() {
return {
accelerator: DEFAULT_SHORTCUT,
display: formatShortcut(DEFAULT_SHORTCUT),
backend: 'focused',
};
}
/** Live view of the shortcut the OS actually registered. */
export function useEffectiveDictationShortcut(enabled = undefined) {
const desktop =
enabled ??
(typeof window !== 'undefined' &&
Object.prototype.hasOwnProperty.call(window, '__TAURI_INTERNALS__'));
const [state, setState] = useState(() => ({ info: fallbackInfo(), error: null }));
useEffect(() => {
if (!desktop) {
setState({ info: fallbackInfo(), error: null });
return;
}
let cancelled = false;
let unlisten;
const show = (info) => {
if (!cancelled && info?.accelerator) setState({ info, error: null });
};
(async () => {
try {
const [{ invoke }, { listen }] = await Promise.all([
import('@tauri-apps/api/core'),
import('@tauri-apps/api/event'),
]);
unlisten = await listen('dictation-shortcut-changed', ({ payload }) => show(payload));
show(await invoke('get_effective_dictation_shortcut'));
if (cancelled) unlisten?.();
} catch (error) {
if (!cancelled) setState((current) => ({ ...current, error }));
}
})();
return () => {
cancelled = true;
unlisten?.();
};
}, [desktop]);
return state;
}
-125
View File
@@ -1,125 +0,0 @@
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import LanguageDetector from 'i18next-browser-languagedetector';
import en from './locales/en.json';
/**
* Only English ships in the main bundle (it's the fallback and renders the
* first paint). Every other locale is a lazy `import()` — Vite splits each
* JSON into its own chunk, fetched the moment that language is detected or
* selected. This took the i18n chunk from ~1.8 MB down to just en.json.
*/
const LOADERS: Record<string, () => Promise<{ default: Record<string, unknown> }>> = {
'zh-CN': () => import('./locales/zh-CN.json'),
es: () => import('./locales/es.json'),
fr: () => import('./locales/fr.json'),
de: () => import('./locales/de.json'),
ja: () => import('./locales/ja.json'),
pt: () => import('./locales/pt.json'),
it: () => import('./locales/it.json'),
ru: () => import('./locales/ru.json'),
ko: () => import('./locales/ko.json'),
hi: () => import('./locales/hi.json'),
tr: () => import('./locales/tr.json'),
pl: () => import('./locales/pl.json'),
nl: () => import('./locales/nl.json'),
sv: () => import('./locales/sv.json'),
th: () => import('./locales/th.json'),
vi: () => import('./locales/vi.json'),
id: () => import('./locales/id.json'),
uk: () => import('./locales/uk.json'),
ar: () => import('./locales/ar.json'),
'zh-TW': () => import('./locales/zh-TW.json'),
gl: () => import('./locales/gl.json'),
};
const loading = new Set<string>();
async function loadLocale(lng: string): Promise<void> {
const base = lng in LOADERS ? lng : lng.split('-')[0];
const loader = LOADERS[lng] || LOADERS[base];
const key = LOADERS[lng] ? lng : base;
if (!loader || loading.has(key) || i18n.hasResourceBundle(key, 'translation')) return;
loading.add(key);
try {
const mod = await loader();
// deep + overwrite so a re-load after an HMR update wins.
i18n.addResourceBundle(key, 'translation', mod.default, true, true);
} catch (e) {
console.warn(`i18n: failed to load locale "${key}"`, e);
} finally {
loading.delete(key);
}
}
i18n
.use(LanguageDetector)
.use(initReactI18next)
.init({
resources: {
en: { translation: en },
},
// Non-bundled languages arrive via addResourceBundle after a lazy fetch;
// don't treat their initial absence as "missing language".
partialBundledLanguages: true,
fallbackLng: 'en',
interpolation: { escapeValue: false },
detection: {
order: ['querystring', 'navigator', 'htmlTag'],
lookupQuerystring: 'lng',
},
react: {
// Re-render not just on language switch but also when a lazily-loaded
// bundle lands (addResourceBundle emits 'added') — the UI flashes the
// English fallback for the fetch round-trip, then snaps to the locale.
bindI18n: 'languageChanged added',
},
});
// Keep the document's text direction and language in sync with the active
// locale — without this, RTL locales (Arabic today, any future RTL addition)
// render in an LTR layout and screen readers get the wrong language.
function applyDocumentDirection(lng: string): void {
if (typeof document === 'undefined') return;
document.documentElement.dir = i18n.dir(lng);
document.documentElement.lang = lng;
}
// Fetch the bundle whenever a non-English language becomes active — covers
// both the initial browser-detected language and later picker switches.
i18n.on('languageChanged', (lng) => {
applyDocumentDirection(lng);
void loadLocale(lng);
});
if (i18n.language) {
applyDocumentDirection(i18n.language);
if (i18n.language !== 'en') void loadLocale(i18n.language);
}
// Native language names belong here rather than in individual components.
export const LANGUAGES = [
{ code: 'en', label: 'English' },
{ code: 'zh-CN', label: '简体中文' },
{ code: 'es', label: 'Español' },
{ code: 'fr', label: 'Français' },
{ code: 'de', label: 'Deutsch' },
{ code: 'ja', label: '日本語' },
{ code: 'pt', label: 'Português' },
{ code: 'it', label: 'Italiano' },
{ code: 'ru', label: 'Русский' },
{ code: 'ko', label: '한국어' },
{ code: 'hi', label: 'हिन्दी' },
{ code: 'tr', label: 'Türkçe' },
{ code: 'pl', label: 'Polski' },
{ code: 'nl', label: 'Nederlands' },
{ code: 'sv', label: 'Svenska' },
{ code: 'th', label: 'ไทย' },
{ code: 'vi', label: 'Tiếng Việt' },
{ code: 'id', label: 'Bahasa Indonesia' },
{ code: 'uk', label: 'Українська' },
{ code: 'ar', label: 'العربية' },
{ code: 'zh-TW', label: '繁體中文' },
{ code: 'gl', label: 'Galego' },
];
export default i18n;
@@ -1,34 +0,0 @@
import { describe, expect, it } from 'vitest';
import { LANGUAGES } from './index';
describe('selectable UI languages', () => {
it('lists every supported locale with a native label and English first', () => {
expect(LANGUAGES[0].code).toBe('en');
expect(LANGUAGES.map(({ code }) => code)).toEqual([
'en',
'zh-CN',
'es',
'fr',
'de',
'ja',
'pt',
'it',
'ru',
'ko',
'hi',
'tr',
'pl',
'nl',
'sv',
'th',
'vi',
'id',
'uk',
'ar',
'zh-TW',
'gl',
]);
expect(LANGUAGES.every(({ label }) => label.trim().length > 0)).toBe(true);
});
});
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
-14
View File
@@ -1,14 +0,0 @@
import { clsx, type ClassValue } from 'clsx';
import { twMerge } from 'tailwind-merge';
/**
* cn — merge conditional class lists, then resolve Tailwind utility conflicts.
*
* `clsx` flattens the conditional/array/object class inputs; `twMerge` then
* de-dupes conflicting Tailwind utilities so a caller-supplied `className`
* (passed last) wins over the component's defaults — the canonical shadcn/ui
* helper. Used by the shadcn primitives in `src/components/ui/*`.
*/
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}
@@ -1,142 +0,0 @@
/**
* #1376 — the first-run setup screen must not time out while it waits for you.
*
* The splash flips any stage that sits still past a budget to `failed`, so a
* genuinely wedged bootstrap surfaces Retry and logs instead of an info-less
* spinner. That is right for every stage the MACHINE owns.
*
* `awaiting_setup` is not one of them. Rust parks there on purpose — "nothing
* downloads or installs in this stage, complete_setup is the only way out of
* it" (bootstrap.rs) — and waits for a human to choose install mode, storage
* locations, region and mirrors. That screen is built for deliberation, so
* taking longer than a machine stage is the NORMAL case, not a fault.
*
* With the default 120 s budget applied to it, reading the setup screen for
* two minutes replaced it with "Setup failed — the backend never reported
* ready" and stopped the IPC poll. Retry re-enters the bootstrap, which parks
* at awaiting_setup again, and fails again on the same clock — an unescapable
* loop on the very first screen a new user ever sees.
*/
import React from 'react';
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { renderHook, act } from '@testing-library/react';
import { useBootstrapStage } from '../components/BootstrapSplash';
const invokeMock = vi.fn();
vi.mock('@tauri-apps/api/core', () => ({
invoke: (...args) => invokeMock(...args),
}));
vi.mock('@tauri-apps/api/event', () => ({
listen: vi.fn(async () => () => {}),
}));
vi.mock('@tauri-apps/plugin-opener', () => ({
revealItemInDir: vi.fn(),
}));
let warnSpy;
beforeEach(() => {
warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
invokeMock.mockReset();
vi.useFakeTimers();
window.__TAURI_INTERNALS__ = {};
// The hook early-returns 'ready' in dev builds; force the packaged path.
vi.stubEnv('DEV', false);
// Backend genuinely is not up during first-run setup — nothing to fall back
// to over HTTP, which is also what keeps the #879 watchdog out of the way.
vi.stubGlobal(
'fetch',
vi.fn(async () => {
throw new Error('ECONNREFUSED');
}),
);
});
afterEach(() => {
vi.useRealTimers();
vi.unstubAllEnvs();
vi.unstubAllGlobals();
warnSpy.mockRestore();
delete window.__TAURI_INTERNALS__;
});
describe('useBootstrapStage — awaiting_setup is human-gated (#1376)', () => {
it('stays on the setup screen no matter how long the user takes', async () => {
invokeMock.mockImplementation(async (cmd) =>
cmd === 'bootstrap_status' ? { stage: 'awaiting_setup' } : undefined,
);
const { result } = renderHook(() => useBootstrapStage());
await act(async () => {});
expect(result.current.stage).toBe('awaiting_setup');
// Well past the old 120 s budget — a user reading the install plan.
await act(async () => {
await vi.advanceTimersByTimeAsync(10 * 60 * 1000);
});
expect(result.current.stage).toBe('awaiting_setup');
expect(result.current.message ?? '').not.toMatch(/stuck/i);
});
it('still leaves for the install once complete_setup advances the stage', async () => {
// The exemption must not strand the user the other way: when the plan is
// submitted and Rust moves on, the normal progress UI has to take over.
let stage = 'awaiting_setup';
invokeMock.mockImplementation(async (cmd) =>
cmd === 'bootstrap_status' ? { stage } : undefined,
);
const { result } = renderHook(() => useBootstrapStage());
await act(async () => {});
await act(async () => {
await vi.advanceTimersByTimeAsync(5 * 60 * 1000);
});
expect(result.current.stage).toBe('awaiting_setup');
stage = 'installing_deps';
await act(async () => {
await vi.advanceTimersByTimeAsync(5_000);
});
expect(result.current.stage).toBe('installing_deps');
});
it('lets Rust finish its backend startup budget before declaring a wedge', async () => {
// The other half of the contract. Exempting awaiting_setup must not
// disarm the stall detector for stages nothing but the app can advance —
// that would trade this bug for the info-less infinite spinner (#879).
invokeMock.mockImplementation(async (cmd) =>
cmd === 'bootstrap_status' ? { stage: 'starting_backend' } : undefined,
);
const { result } = renderHook(() => useBootstrapStage());
await act(async () => {});
expect(result.current.stage).toBe('starting_backend');
// The shell waits five minutes for slow torch/CUDA imports. The splash
// must not replace that live launch with its old two-minute false failure.
await act(async () => {
await vi.advanceTimersByTimeAsync(3 * 60 * 1000);
});
expect(result.current.stage).toBe('starting_backend');
expect(result.current.message ?? '').not.toMatch(/stuck/i);
// Pin both sides of the six-minute fallback boundary.
await act(async () => {
await vi.advanceTimersByTimeAsync(3 * 60 * 1000 - 1_000);
});
expect(result.current.stage).toBe('starting_backend');
expect(result.current.message ?? '').not.toMatch(/stuck/i);
// A frontend-only deadlock remains bounded if the shell never advances.
await act(async () => {
await vi.advanceTimersByTimeAsync(2_000);
});
expect(result.current.stage).toBe('failed');
expect(result.current.message).toMatch(/stuck/i);
});
});
@@ -1,124 +0,0 @@
/**
* Regression tests for issue #1156 — the "Setup failed" card never
* auto-dismissed when the backend later became healthy.
*
* fail-before/pass-after: `failed` was a fully terminal stage — the IPC poll
* loop stopped AND the successful IPC reply disarmed the #879 HTTP watchdog,
* so neither path could ever observe the backend coming back (supervisor
* restart, completed dependency repair). Users had to F5/relaunch by hand.
* The failed stage now runs a plain-HTTP health poll that flips to 'ready'
* the moment the backend answers.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { renderHook, act } from '@testing-library/react';
import { useBootstrapStage } from '../components/BootstrapSplash';
import { startHealthRecoveryPoll } from '../utils/splashWatchdog';
const invokeMock = vi.fn();
vi.mock('@tauri-apps/api/core', () => ({
invoke: (...args) => invokeMock(...args),
}));
vi.mock('@tauri-apps/api/event', () => ({
listen: vi.fn(async () => () => {}),
}));
vi.mock('@tauri-apps/plugin-opener', () => ({
revealItemInDir: vi.fn(),
}));
let warnSpy;
beforeEach(() => {
warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
invokeMock.mockReset();
vi.useFakeTimers();
window.__TAURI_INTERNALS__ = {};
vi.stubEnv('DEV', false);
});
afterEach(() => {
vi.useRealTimers();
vi.unstubAllEnvs();
vi.unstubAllGlobals();
warnSpy.mockRestore();
delete window.__TAURI_INTERNALS__;
});
describe('useBootstrapStage — #1156 failed-stage auto-recovery', () => {
it("stage 'failed' + backend later healthy over HTTP → auto-recovers to ready", async () => {
invokeMock.mockImplementation(async () => ({
stage: 'failed',
message: 'Backend died early: exit code 1',
}));
let healthy = false;
const fetchMock = vi.fn(async () => ({ ok: healthy }));
vi.stubGlobal('fetch', fetchMock);
const { result } = renderHook(() => useBootstrapStage());
await act(async () => {}); // flush dynamic imports + first tick
expect(result.current.stage).toBe('failed');
// Backend stays dead: the card must stay up (no false dismissal).
await act(async () => {
await vi.advanceTimersByTimeAsync(20_000);
});
expect(result.current.stage).toBe('failed');
// Backend comes back (supervisor restart / repair finished) → dismiss.
healthy = true;
await act(async () => {
await vi.advanceTimersByTimeAsync(5_000);
});
expect(result.current.stage).toBe('ready');
});
it("stage 'failed' with a permanently dead backend stays failed", async () => {
invokeMock.mockImplementation(async () => ({
stage: 'failed',
message: 'Backend died early: exit code 1',
}));
vi.stubGlobal(
'fetch',
vi.fn(async () => ({ ok: false })),
);
const { result } = renderHook(() => useBootstrapStage());
await act(async () => {});
await act(async () => {
await vi.advanceTimersByTimeAsync(120_000);
});
expect(result.current.stage).toBe('failed');
});
});
describe('startHealthRecoveryPoll', () => {
it('fires onHealthy exactly once when /health starts answering, and cancel() stops it', async () => {
let healthy = false;
const onHealthy = vi.fn();
const fetchFn = vi.fn(async () => ({ ok: healthy }));
startHealthRecoveryPoll({ healthUrl: 'http://x/health', onHealthy, fetchFn });
await act(async () => {
await vi.advanceTimersByTimeAsync(6_000);
});
expect(onHealthy).not.toHaveBeenCalled();
healthy = true;
await act(async () => {
await vi.advanceTimersByTimeAsync(6_000);
});
expect(onHealthy).toHaveBeenCalledTimes(1);
const onHealthy2 = vi.fn();
const poll = startHealthRecoveryPoll({
healthUrl: 'http://x/health',
onHealthy: onHealthy2,
fetchFn: vi.fn(async () => ({ ok: false })),
});
poll.cancel();
await act(async () => {
await vi.advanceTimersByTimeAsync(10_000);
});
expect(onHealthy2).not.toHaveBeenCalled();
});
});
Loaded 100 of 208 files, more files were not shown because too many files have changed in this diff. Show more