From 1b55a86ba59882d6bdaa1c268b522f89ef15256b Mon Sep 17 00:00:00 2001 From: pavel444-byte Date: Sun, 6 Sep 2026 18:47:42 +0500 Subject: [PATCH] DUNGEONS-34: keep host screen awake while streaming Co-authored-by: multica-agent --- README.md | 5 + docs/MANUAL_TEST_PLAN.md | 8 ++ frontend/components/KeepHostAwakeSetting.vue | 18 +++ frontend/composables/useKeepHostAwake.ts | 38 ++++++ frontend/i18n/locales/en.json | 12 ++ frontend/i18n/locales/es.json | 12 ++ frontend/i18n/locales/ru.json | 12 ++ frontend/pages/host.vue | 10 ++ frontend/pages/settings/general.vue | 7 ++ frontend/scripts/test-wake-lock.mjs | 122 +++++++++++++++++++ frontend/utils/screenWakeLock.ts | 62 ++++++++++ package.json | 1 + 12 files changed, 307 insertions(+) create mode 100644 frontend/components/KeepHostAwakeSetting.vue create mode 100644 frontend/composables/useKeepHostAwake.ts create mode 100644 frontend/scripts/test-wake-lock.mjs create mode 100644 frontend/utils/screenWakeLock.ts diff --git a/README.md b/README.md index 79ec6c6..98c19b8 100644 --- a/README.md +++ b/README.md @@ -119,6 +119,10 @@ Back up `WEBKA_DATA` securely. On Unix the data directory is owner-only and secr Quality presets control the host’s per-peer send bitrate; the viewer shows actual received resolution. Capture is video-only. Closing/navigating away from the host tab stops capture; a browser may also suspend hosting when the device locks or the tab is backgrounded. Screen share support varies, particularly on mobile. Back-camera discovery becomes reliable after granting camera permission. Physical-device tests are documented in `docs/MANUAL_TEST_PLAN.md`. +Enable **Settings → Host screen → Do not turn off the host** to keep the capturing device's screen awake while hosting. The preference defaults to off and is saved in this browser. The same toggle is on the host screen so you can change it without leaving a live stream. An indicator shows whether the request is active, unavailable, or unsupported; a failed request never stops the stream. + +This uses the browser's [Screen Wake Lock API](https://www.w3.org/TR/screen-wake-lock/). Use HTTPS (or localhost) and leave Webka visible. The lock is released on stop, navigation, logout, or when the page becomes hidden, and is requested again on return if hosting is still active. Power-saving settings can deny or release it; a retry button is provided. It cannot override manual locking, closing the lid, or background suspension, and does not keep the separate server computer awake. Keeping the screen on uses more battery. No scrolling or simulated input is needed. + Nuxt 3 is retained to match the requested stack. Its upstream documentation now marks it end-of-life; plan a Nuxt 4 upgrade before broader distribution. Reference: https://nuxt.com/docs/3.x/getting-started/installation. ## Validation @@ -126,6 +130,7 @@ Nuxt 3 is retained to match the requested stack. Its upstream documentation now ```sh npm run test:install npm run test:launcher +npm run test:wake-lock cargo fmt --manifest-path backend/Cargo.toml --check cargo test --manifest-path backend/Cargo.toml cargo clippy --manifest-path backend/Cargo.toml --all-targets -- -D warnings diff --git a/docs/MANUAL_TEST_PLAN.md b/docs/MANUAL_TEST_PLAN.md index 6c3a0b0..a67df91 100644 --- a/docs/MANUAL_TEST_PLAN.md +++ b/docs/MANUAL_TEST_PLAN.md @@ -20,6 +20,14 @@ These are required manual checks, not a claim that physical devices have been te 7. Switch bitrate between low/adaptive/high. Inspect browser WebRTC stats: max bitrate changes (actual resolution depends on capture and congestion). 8. Stop hosting, navigate to settings, close the tab, and log out separately. Each must stop the host camera and close outgoing peer streams. +## Keep the host screen awake + +1. In Settings, enable **Do not turn off the host**. Refresh and confirm it remains enabled. Check the label and hint in English, Russian, and Spanish, including keyboard/Space operation of the switch. +2. Open the host screen: preview alone must not acquire a lock. Go live over HTTPS with the setting enabled: the status should confirm the screen stays on. Leave the device untouched beyond its normal auto-lock timeout and confirm the screen and stream remain active. Repeat on a phone and computer. +3. Toggle the setting off/on directly on the host screen without interrupting video. Stop hosting, navigate away, and sign out separately: the screen lock must be released. The viewer page must never request a lock. +4. Background Webka, then return while still hosting: the wake lock should be acquired again if the platform allows it. Manually locking the device may suspend video; the setting does not bypass that. +5. Test an unsupported browser, insecure HTTP, denied screen-wake-lock policy, and a battery-saving mode where available. Confirm a translated unavailable/unsupported message and no false active status. If denied, remove the restriction and use the retry button. No automatic retry loop or scrolling should occur. + ## Viewer lifecycle and session revocation 1. Join before the host is live; automatic playback should start once the host starts. Check fullscreen, language switching while fullscreen, quality/resolution, and disconnect. diff --git a/frontend/components/KeepHostAwakeSetting.vue b/frontend/components/KeepHostAwakeSetting.vue new file mode 100644 index 0000000..fd84a98 --- /dev/null +++ b/frontend/components/KeepHostAwakeSetting.vue @@ -0,0 +1,18 @@ + + + diff --git a/frontend/composables/useKeepHostAwake.ts b/frontend/composables/useKeepHostAwake.ts new file mode 100644 index 0000000..93ec163 --- /dev/null +++ b/frontend/composables/useKeepHostAwake.ts @@ -0,0 +1,38 @@ +import { createScreenWakeLock, type WakeStatus } from "../utils/screenWakeLock"; +import type { Ref } from "vue"; + +export function useKeepHostAwakePreference() { + return useCookie("webka_keep_host_awake", { + default: () => false, + maxAge: 60 * 60 * 24 * 365, + sameSite: "lax", + path: "/", + }); +} + +export function useHostWakeLock(hosting: Ref) { + const enabled = useKeepHostAwakePreference(); + const status = ref("off"); + let controller: ReturnType | undefined; + let unwatch: (() => void) | undefined; + const refresh = () => controller?.refresh(); + onMounted(() => { + controller = createScreenWakeLock({ + request: window.isSecureContext && navigator.wakeLock?.request + ? () => navigator.wakeLock.request("screen") + : undefined, + visible: () => document.visibilityState === "visible", + status: (value) => { status.value = value; }, + }); + unwatch = watch([enabled, hosting], () => { + controller?.update(enabled.value === true && hosting.value); + }, { immediate: true, flush: "sync" }); + document.addEventListener("visibilitychange", refresh); + }); + onBeforeUnmount(() => { + unwatch?.(); + document.removeEventListener("visibilitychange", refresh); + controller?.dispose(); + }); + return { status, retry: refresh }; +} diff --git a/frontend/i18n/locales/en.json b/frontend/i18n/locales/en.json index 8f48e67..f635521 100644 --- a/frontend/i18n/locales/en.json +++ b/frontend/i18n/locales/en.json @@ -173,5 +173,17 @@ "OverconstrainedError": "This camera source is unavailable. Try the front camera.", "clipboard": "Couldn’t copy automatically. Select and copy the address above.", "fullscreen": "Fullscreen isn’t available in this browser." + }, + "wake": { + "section": "Host screen", + "title": "Do not turn off the host", + "hint": "Keep this device’s screen on while hosting. Leave Webka visible. Saved in this browser; uses more battery.", + "off": "Screen keep-awake is off or hosting has not started.", + "waiting": "Return to Webka to keep the screen awake.", + "requesting": "Requesting screen keep-awake…", + "active": "Screen stays on while hosting.", + "unavailable": "The browser or power-saving settings released or denied keep-awake. Keep this page visible and try again.", + "unsupported": "Screen keep-awake is unavailable here. Use HTTPS and a supported browser, or adjust your device’s auto-lock setting.", + "retry": "Try keep-awake again" } } diff --git a/frontend/i18n/locales/es.json b/frontend/i18n/locales/es.json index 8711d49..23812f9 100644 --- a/frontend/i18n/locales/es.json +++ b/frontend/i18n/locales/es.json @@ -173,5 +173,17 @@ "OverconstrainedError": "Esta fuente no está disponible. Prueba la cámara frontal.", "clipboard": "No se pudo copiar automáticamente. Selecciona y copia la dirección.", "fullscreen": "La pantalla completa no está disponible en este navegador." + }, + "wake": { + "section": "Pantalla del anfitrión", + "title": "No apagar la pantalla del anfitrión", + "hint": "Mantén encendida la pantalla de este dispositivo durante la transmisión. Deja Webka visible. Se guarda en este navegador; consume más batería.", + "off": "Mantener la pantalla encendida está desactivado o la transmisión no ha comenzado.", + "waiting": "Vuelve a Webka para mantener la pantalla encendida.", + "requesting": "Solicitando mantener la pantalla encendida…", + "active": "La pantalla permanece encendida durante la transmisión.", + "unavailable": "El navegador o el ahorro de energía ha desactivado o rechazado esta función. Mantén la página visible e inténtalo de nuevo.", + "unsupported": "Esta función no está disponible aquí. Usa HTTPS y un navegador compatible, o ajusta el bloqueo automático del dispositivo.", + "retry": "Volver a intentarlo" } } diff --git a/frontend/i18n/locales/ru.json b/frontend/i18n/locales/ru.json index 11c56aa..6393005 100644 --- a/frontend/i18n/locales/ru.json +++ b/frontend/i18n/locales/ru.json @@ -173,5 +173,17 @@ "OverconstrainedError": "Этот источник недоступен. Попробуйте переднюю камеру.", "clipboard": "Не удалось скопировать автоматически. Выделите и скопируйте адрес выше.", "fullscreen": "Полноэкранный режим недоступен в этом браузере." + }, + "wake": { + "section": "Экран хоста", + "title": "Не выключать экран хоста", + "hint": "Не давать экрану этого устройства гаснуть во время трансляции. Оставьте Webka на экране. Сохраняется в этом браузере; расходует больше заряда.", + "off": "Удержание экрана выключено или трансляция ещё не началась.", + "waiting": "Вернитесь в Webka, чтобы экран не гас.", + "requesting": "Запрашиваем удержание экрана…", + "active": "Экран не гаснет во время трансляции.", + "unavailable": "Браузер или режим энергосбережения отключил или запретил удержание экрана. Оставьте страницу видимой и повторите попытку.", + "unsupported": "Удержание экрана недоступно. Используйте HTTPS и поддерживаемый браузер или измените автоблокировку устройства.", + "retry": "Повторить удержание экрана" } } diff --git a/frontend/pages/host.vue b/frontend/pages/host.vue index 5b7ae9a..03184d3 100644 --- a/frontend/pages/host.vue +++ b/frontend/pages/host.vue @@ -47,6 +47,8 @@ const qr = ref(""), const apiError = useApiError(); let timer: ReturnType; const live = computed(() => state.value === "live"); +const hosting = computed(() => state.value !== "offline"); +const { status: wakeStatus, retry: retryWakeLock } = useHostWakeLock(hosting); const elapsed = computed(() => { const seconds = status.value?.since ? Math.max(0, Math.floor(tick.value / 1000) - status.value.since) @@ -239,6 +241,14 @@ async function fullscreen() {