From 0bb17bf5beeef6a6e01d3dd48a1bddc7aecf9ca7 Mon Sep 17 00:00:00 2001 From: AAA <35992542+TNTcraftHIM@users.noreply.github.com> Date: Sun, 22 Nov 2026 01:32:57 -0500 Subject: [PATCH] feat(app): add voice shortcuts and scoped recovery controls Share selected video URLs for independent browser playback while retaining explicit byte forwarding. Bring original-page sharing into the player list, verify workspace destinations, and keep local startup independent of external site checks. Reuse voice actions for page and Windows background shortcuts, derive troubleshooting from current operation facts, and keep floating tools below the native caption. --- docs/guide/getting-started.md | 4 +- docs/guide/getting-started.zh-CN.md | 4 +- docs/guide/room-tools.md | 12 +- docs/guide/room-tools.zh-CN.md | 7 +- docs/guide/sharing.md | 4 +- docs/guide/sharing.zh-CN.md | 4 +- docs/guide/troubleshooting.md | 19 +- docs/guide/troubleshooting.zh-CN.md | 13 +- docs/research/channel-network-design.md | 8 + docs/research/room-interactions.md | 11 + docs/status.md | 8 +- prototype/channel-native/src/input/windows.rs | 81 +---- prototype/channel-native/src/lib.rs | 2 + .../channel-native/src/windows_hotkeys.rs | 146 ++++++++ prototype/channel-server/README.md | 3 + prototype/channel-server/src/app.rs | 311 +++++++++++++++--- .../src/app_backup_description_tests.rs | 1 + prototype/channel-server/src/app_sites.rs | 2 +- .../channel-server/src/app_voice_shortcuts.rs | 299 +++++++++++++++++ .../src/app_whip_cancel_tests.rs | 1 + .../channel-server/src/app_whip_http_tests.rs | 1 + prototype/channel-server/src/app_windows.rs | 109 +++++- prototype/channel-server/src/domain.rs | 4 +- src/client/channel/app-link.ts | 37 ++- .../components/ChannelDiagnosisHelp.tsx | 21 ++ .../channel/components/ChannelMedia.tsx | 18 +- .../components/ChannelShareControl.tsx | 13 +- .../channel/components/ChannelStage.tsx | 29 +- .../channel/components/ChannelVoiceDock.tsx | 16 +- .../components/ChannelVoiceSettings.tsx | 9 +- .../ChannelVoiceShortcutSettings.tsx | 86 +++++ .../components/channel-diagnosis-help.css | 52 +++ .../channel/components/channel-media.css | 17 +- .../channel/components/channel-stage.css | 11 +- .../components/channel-voice-settings.css | 11 + src/client/channel/diagnosis.ts | 85 +++++ src/client/channel/error-presentation.ts | 17 +- src/client/channel/session.ts | 36 +- src/client/channel/types.ts | 5 +- .../channel/use-background-voice-shortcuts.ts | 67 ++++ src/client/channel/use-voice-shortcuts.ts | 50 +++ src/client/channel/voice-dock-controls.ts | 17 + src/client/channel/voice-shortcut-binding.ts | 50 +++ src/client/channel/watch-page-media.ts | 6 +- src/client/channel/watch-youtube-source.ts | 3 +- .../components/living/AppConnectionButton.tsx | 12 +- .../components/living/FloatingPanel.tsx | 13 +- src/client/components/living/Header.tsx | 5 +- .../components/living/ShareFailureHelp.tsx | 5 +- .../components/living/SiteManagement.tsx | 4 +- src/client/components/living/primitives.tsx | 3 + src/client/lib/room-preferences.ts | 5 + src/client/lib/site-address.ts | 15 + src/client/locales/en.ts | 29 +- src/client/locales/ja.ts | 29 +- src/client/locales/ko.ts | 29 +- src/client/locales/zh-Hant.ts | 29 +- src/client/locales/zh.ts | 29 +- src/client/native/wire.ts | 11 + src/client/pages/AppLauncherPage.tsx | 17 +- src/client/pages/AppSiteBookmarks.tsx | 34 +- src/client/pages/ChannelPreviewPage.tsx | 3 + src/client/room-voice/VoiceAudioButtons.tsx | 2 +- tests/app-launcher-recovery.test.ts | 4 +- tests/channel-app-page.test.ts | 20 ++ tests/channel-diagnosis.test.ts | 32 ++ tests/channel-session.test.ts | 39 ++- tests/retry-picture-controls.test.ts | 3 +- tests/viewer-playback.test.ts | 7 + tests/watch-presentation.test.ts | 3 +- 70 files changed, 1825 insertions(+), 267 deletions(-) create mode 100644 prototype/channel-native/src/windows_hotkeys.rs create mode 100644 prototype/channel-server/src/app_voice_shortcuts.rs create mode 100644 src/client/channel/components/ChannelDiagnosisHelp.tsx create mode 100644 src/client/channel/components/ChannelVoiceShortcutSettings.tsx create mode 100644 src/client/channel/components/channel-diagnosis-help.css create mode 100644 src/client/channel/diagnosis.ts create mode 100644 src/client/channel/use-background-voice-shortcuts.ts create mode 100644 src/client/channel/use-voice-shortcuts.ts create mode 100644 src/client/channel/voice-dock-controls.ts create mode 100644 src/client/channel/voice-shortcut-binding.ts create mode 100644 tests/channel-diagnosis.test.ts diff --git a/docs/guide/getting-started.md b/docs/guide/getting-started.md index afcfb7e4b..cf0f41cb3 100644 --- a/docs/guide/getting-started.md +++ b/docs/guide/getting-started.md @@ -123,8 +123,8 @@ Manage approved sites from the App launcher. See the Read the upgrade instructions supplied with your 3.0 test package, keep the existing data directory unless those instructions require otherwise, and refresh the Web page after updating App. For `unsupported_storage_version` or -`unsupported_domain_checkpoint`, preserve the old data and follow the -[storage-format checks](./troubleshooting.md#the-beta-app-reports-unsupportedstorageversion). +`unsupported_domain_checkpoint`, follow the +[test-data reset steps](./troubleshooting.md#the-beta-app-reports-unsupportedstorageversion). Public 2.x downloads are not the 3.0 test update. ## Share from an existing site diff --git a/docs/guide/getting-started.zh-CN.md b/docs/guide/getting-started.zh-CN.md index fa5c55ce6..97f46e3d9 100644 --- a/docs/guide/getting-started.zh-CN.md +++ b/docs/guide/getting-started.zh-CN.md @@ -104,8 +104,8 @@ ### 版本升级 先阅读 3.0 内测包附带的升级说明;没有另行要求时,沿用原数据目录,更新 App 后刷新所用网页。 -提示 `unsupported_storage_version` 或 `unsupported_domain_checkpoint` 时,保留旧数据, -按[存储格式排查](./troubleshooting.zh-CN.md#内测-app-提示-unsupportedstorageversion)处理。 +提示 `unsupported_storage_version` 或 `unsupported_domain_checkpoint` 时,按 +[内测数据重置步骤](./troubleshooting.zh-CN.md#内测-app-提示-unsupportedstorageversion)重新开始。 公开的 2.x 下载不是本次 3.0 内测更新。 ## 使用已有站点分享 diff --git a/docs/guide/room-tools.md b/docs/guide/room-tools.md index 238c7aa6d..968725650 100644 --- a/docs/guide/room-tools.md +++ b/docs/guide/room-tools.md @@ -28,8 +28,8 @@ then choose grid or focus. The grid arranges separate screens to fit the window; focus keeps the other pictures available. Stopping one picture keeps the others playing. Changing interfaces keeps current shares, watches, drafts and joined voice. -Joined voice retains its controls and leave action. Switch back to **Full workspace** -for the room directory and wider administration. **Invitation → Access settings** +Joined voice retains its controls and leave action. In either view, open **Rooms** +to create or select a room. **Invitation → Access settings** opens the existing room settings in either view. The browser remembers your choice. ## Manage a room @@ -164,6 +164,14 @@ room selector to choose which room's microphone, listening and leave controls you are changing. Switching the conversation or stopping a picture does not leave those voice rooms. Leave each room when you are finished. +**Ctrl+Shift+M** toggles your microphone; **Ctrl+Shift+D** toggles listening. +On macOS, use **Command** instead of Ctrl. Both act on the room selected in the +voice controls. Change or clear a binding in **Voice settings → Keyboard shortcuts**; +press Esc to cancel recording. Page shortcuts work while Piik or its room tool +has focus. Text entry and remote keyboard control take priority. +With a supported Windows App connected, enable **Allow shortcuts in other apps**. +Each binding shows whether Windows registered it. + Browser microphone access requires a secure context, such as accepted HTTPS or localhost. The [App reference](../../prototype/channel-server/README.md#local-app-link) explains local access; [Native media setup](../../prototype/channel-native/README.md) diff --git a/docs/guide/room-tools.zh-CN.md b/docs/guide/room-tools.zh-CN.md index 23b70426f..d4c1bde3c 100644 --- a/docs/guide/room-tools.zh-CN.md +++ b/docs/guide/room-tools.zh-CN.md @@ -24,7 +24,7 @@ 平铺会按窗口宽度排列各个画面;聚焦时仍可切回其他画面,停止其中一路不会结束其他画面。 切换界面会保留正在进行的分享、观看、草稿和已加入的语音;已有语音仍可操作或退出。 -房间列表和完整管理功能在**完整工作区**里使用。两种界面都能从**邀请 → 访问设置**打开房间设置, +两种界面都可打开**房间列表**创建或切换房间,也可从**邀请 → 访问设置**打开房间设置, 浏览器会记住你的界面选择。 ## 管理房间 @@ -116,6 +116,11 @@ GIF、动态 PNG 和动态 WebP 保留动画。动图超过当前消息可用预 可以同时加入多个房间的语音。加入多个房间后,用语音房间选择框确定正在操作哪个房间的 麦克风、收听和退出按钮。切换聊天房间或停止画面分享不会退出这些语音;结束时分别退出即可。 +**Ctrl+Shift+M** 开关麦克风,**Ctrl+Shift+D** 开关收听;macOS 使用 **Command** 代替 Ctrl。 +快捷键作用于语音栏当前选中的房间。在 **语音设置 → 键盘快捷键** 中可更改或清除组合,录制时按 Esc 取消。 +页面或房间工具窗获得焦点时生效,输入文字和远程键盘控制优先。 +连接支持此功能的 Windows App 后,可开启 **在其他应用中使用快捷键**;每行会显示该组合是否注册成功。 + 浏览器开麦需要安全环境,例如已接受的 HTTPS 或 localhost。 本地访问见 [App 使用参考](../../prototype/channel-server/README.md#local-app-link), 平台要求见 [Native 媒体说明](../../prototype/channel-native/README.md)(英文)。 diff --git a/docs/guide/sharing.md b/docs/guide/sharing.md index 0cd9fa80b..f19455bb4 100644 --- a/docs/guide/sharing.md +++ b/docs/guide/sharing.md @@ -52,8 +52,8 @@ If Piik reports an unsupported video format, stop streaming, select **NV12** und In a 3.0 test room, select **Start sharing → Watch together** and paste a direct video URL or copy the page address from your browser’s address bar. - **Direct video link or YouTube.** Select **Play direct video URL** or, for YouTube, **Watch together**. Everyone can use a browser. Each person plays the video from its original source. -- **Watch on the original webpage.** In the Windows App, select **Open webpage and select video**. Sign in on the website if needed and play the video. Return to Piik, select the player and choose **Share original webpage only**. If the player has a **Choose playback source** button, use it to see the options. Each viewer uses Piik App on Windows and selects **Open webpage and select video** in the room. Piik opens the page the sharer chose. Each viewer signs in with their own account if needed and selects the player. The webpage then appears inside the room’s main picture. The sharer controls play, pause and seeking for everyone. -- **Forward to a viewer in a browser.** For a video you can share, open **Choose playback source** and select **Forward through App**. Viewers can select **Receive from sharer**. The video uses the sharer’s internet upload bandwidth and needs a working media connection to the viewers. If access expires, the sharer restores playback on the original website, then the viewer selects **Retry** beside the error. +- **Watch on the original webpage.** In the Windows App, select **Open webpage and select video**. Sign in on the website if needed and play the video. Return to Piik and click **Share original webpage only** beside the player you want. Each viewer uses Piik App on Windows and selects **Open webpage and select video** in the room. Piik opens the page the sharer chose. Each viewer signs in with their own account if needed and selects the player. The webpage then appears inside the room’s main picture. The sharer controls play, pause and seeking for everyone. +- **Share from App to browser viewers.** Under **Choose playback source**, complete video files offer **Share this video**. Viewers first play from the original website; if that fails, they can select **Receive from sharer**. Other sources still offer **Forward through App**. Only viewers receiving from the sharer use the sharer’s or relay’s upload bandwidth and need a working media connection. If access expires, the sharer restores playback on the original website, then the viewer selects **Retry**. If you're already watching a shared webpage video in the Windows App, open **Playback settings → Open webpage and select video** to use the website's player. The current video keeps playing while you choose. Select the player to switch, or close the chooser to keep watching in Piik. When the source supports direct playback, use **Playback settings → Play directly from website** to return to Piik's player. For YouTube, press Play in the preview to switch. diff --git a/docs/guide/sharing.zh-CN.md b/docs/guide/sharing.zh-CN.md index 78b014623..ccf674320 100644 --- a/docs/guide/sharing.zh-CN.md +++ b/docs/guide/sharing.zh-CN.md @@ -44,8 +44,8 @@ Safari 的屏幕采集不包含系统声音,参阅[浏览器兼容记录](http 在 3.0 内测房间里点击 **开始分享 → 同步观看**,粘贴视频直链,或把浏览器地址栏里的网页地址复制过来。 - **视频直链或 YouTube。** 直链点击 **播放视频直链**,YouTube 点击 **同步观看**。大家都可以只用浏览器,视频由各自的设备从原站播放。 -- **一起使用原网页。** 在 Windows Piik App 点击 **打开网页选视频**。在网站上登录并播放想看的视频,回到 Piik 选择播放器,再选 **仅分享原网页**。如果播放器旁有 **选择播放来源**,从这里进入选项。观众也在 Windows 版 Piik App 里进入房间,点击 **打开网页选视频**。Piik 会打开分享者选定的网页,观众按需用自己的账号登录,再选择播放器。选好后,原网页会显示在当前房间的主画面里,可以直接操作。分享者控制大家的播放、暂停和进度。 -- **转发给用浏览器的观众。** 对允许分享的视频,分享者可在 **选择播放来源** 中选 **通过 App 转发**。观众选择 **从分享者接收** 即可观看。视频会占用分享者的网络上传带宽,双方也需要一条可用的媒体连接。如果视频访问失效,分享者先在原网站恢复播放,观众再点错误提示旁的 **重试**。 +- **一起使用原网页。** 在 Windows Piik App 点击 **打开网页选视频**。在网站上登录并播放想看的视频,回到 Piik,点击目标播放器旁的 **仅分享原网页**。观众也在 Windows 版 Piik App 里进入房间,点击 **打开网页选视频**。Piik 会打开分享者选定的网页,观众按需用自己的账号登录,再选择播放器。选好后,原网页会显示在当前房间的主画面里,可以直接操作。分享者控制大家的播放、暂停和进度。 +- **App 分享,浏览器观看。** 在 **选择播放来源** 中,完整视频文件提供 **分享这个视频**。观众优先从原网站播放;无法播放时,可选 **从分享者接收**。其他来源仍可选 **通过 App 转发**。只有从分享者接收的观众使用分享者或中转节点的上行,也需要可用的媒体连接。如果视频访问失效,分享者先在原网站恢复播放,观众再点 **重试**。 如果你正在 Windows 版 Piik 里看朋友分享的网页视频,点 **播放设置 → 打开网页选视频** 可以换到网站自己的播放器。挑选时当前视频会继续播放,选中后才会切换。想继续看原来的画面,点 **取消** 即可。 diff --git a/docs/guide/troubleshooting.md b/docs/guide/troubleshooting.md index 2eaa05193..5462700ba 100644 --- a/docs/guide/troubleshooting.md +++ b/docs/guide/troubleshooting.md @@ -231,17 +231,16 @@ storage to retry; that can remove retained files, identity or a Browser-hosted r ### The beta App reports `unsupported_storage_version` This error, or `unsupported_domain_checkpoint`, means the running version cannot -read the saved format. Stop the affected App or Server, preserve its data and -follow that test package's upgrade instructions. The [saved-data reference](../../prototype/channel-server/README.md#saved-data-and-files) -identifies the App and Server directories. Updating a compatible beta does not -require a reset. If the package has no matching recovery instructions, report -the version and complete error before changing its data. +read the saved format. Internal 3.0 builds do not migrate obsolete formats. +Exit the affected App or Server, then reset its test data: -If your Windows test package supplies `reset-beta-app-data.ps1` and explicitly -requires fresh data, that helper renames the old App directory to a timestamped -backup; it does not migrate the database. It is not an Android or macOS/Linux -reset procedure. Do not uninstall Android App or clear browser storage to retry -a connection. +- Windows: open **重置3.0内测数据.bat** from the test package and choose its default or review data. +- Android: clear **Piik 3.0** application data in system settings. +- Browser-hosted rooms: clear data for the affected Piik site. +- Server: use a new data directory. See the [saved-data reference](../../prototype/channel-server/README.md#saved-data-and-files). + +A reset removes local identity, approvals, rooms and history in the selected scope. +Keep using existing data when the format has not changed. Connection failures do not require a data reset. ## Starting a share diff --git a/docs/guide/troubleshooting.zh-CN.md b/docs/guide/troubleshooting.zh-CN.md index 91d3b0533..ed331387d 100644 --- a/docs/guide/troubleshooting.zh-CN.md +++ b/docs/guide/troubleshooting.zh-CN.md @@ -191,13 +191,14 @@ Piik App 的本地网络邀请使用临时自签名 HTTPS 证书,浏览器可 ### 内测 App 提示 `unsupported_storage_version` 此错误或 `unsupported_domain_checkpoint` 表示当前版本不能读取已有存储格式。 -先停止对应的 App 或 Server,保留原数据,再按该内测包的升级说明处理。 -[数据参考](../../prototype/channel-server/README.md#saved-data-and-files)说明两者的数据目录; -格式兼容的内测更新不需要重置。包内没有对应恢复说明时,先提供版本和完整错误反馈,再处理数据。 +3.0 内测不迁移旧格式。退出对应 App 或 Server,重置该内测资料后重新开始: -只有 Windows 内测包附带 `reset-beta-app-data.ps1` 且明确要求使用新数据时,才按包内说明运行它。 -该脚本会把旧 App 目录改名为带时间戳的备份,不会迁移数据库;它不是 Android 或 macOS/Linux 的重置流程。 -不要为重试连接卸载 Android App 或清空浏览器存储。 +- Windows:双击内测包附带的 **重置3.0内测数据.bat**,选择默认数据或该包的验收数据。 +- Android:在系统设置中清除 **Piik 3.0** 的应用数据。 +- 浏览器托管的房间:清除对应 Piik 站点的数据。 +- Server:使用新的数据目录,目录位置见[数据参考](../../prototype/channel-server/README.md#saved-data-and-files)。 + +重置会删除所选范围内的本地身份、授权、房间和历史。格式未变化的更新继续使用原数据,连接失败也不需要重置数据。 ## 开始分享 diff --git a/docs/research/channel-network-design.md b/docs/research/channel-network-design.md index 1ecc90960..6291cde21 100644 --- a/docs/research/channel-network-design.md +++ b/docs/research/channel-network-design.md @@ -300,6 +300,14 @@ volume and mute follow the viewer across the retry. While a viewer chooses a player on the original webpage, the current player retains its subscription. The candidate replaces it after media readiness and room confirmation. +For an explicitly selected complete file, the App may retain its byte source +and publish the matching media URL in the same activity. Each viewer tries +that URL independently. A viewer that chooses the offered forwarding path +adds byte demand; other viewers keep loading from the origin. Clearing the +byte source retires those transfers without ending direct playback. The +media element can load an ordinary cross-origin file even when a script cannot +read its bytes. Manifest-based formats retain their own fetch and timeline rules. + When a discovered media URL loads in the sharer's Browser player, that player owns playback in the Piik stage. Prepare it before replacing the current share; retire the discovery page after the room confirms the new activity. Loading diff --git a/docs/research/room-interactions.md b/docs/research/room-interactions.md index 9e6b6a2d8..c111952c3 100644 --- a/docs/research/room-interactions.md +++ b/docs/research/room-interactions.md @@ -334,6 +334,17 @@ Room voice from the same source endpoint plays once locally across joined rooms; mute and deafen still apply per room. Different endpoints remain separate, including those of one user. +Voice shortcuts work in the focused Piik page or detached room +tool. Ctrl+Shift+M toggles the microphone and Ctrl+Shift+D toggles listening in +the room shown in the voice dock. macOS uses Command in place of Ctrl. Both keys +can be reassigned or cleared. Text entry, IME composition, shortcut recording +and remote keyboard control have priority. A held key toggles once. + +Windows also supports opt-in background shortcuts. While the user +has joined voice, the App registers the keys with Windows and sends each action +to one user-selected, approved App connection. The page applies the same dock +action. If background registration is unavailable, page shortcuts remain usable. + ### Identity And Share Titles The custom avatar sits upright on the couch as a rounded square. The headset diff --git a/docs/status.md b/docs/status.md index 16551984d..f9115ccdf 100644 --- a/docs/status.md +++ b/docs/status.md @@ -1,6 +1,6 @@ # Current Status -Last updated: 2026-11-21 +Last updated: 2026-11-22 This is the compact execution/deployment index. Product modules own behavior, [verification status](./verification-status.md) summarizes material evidence limits, @@ -57,6 +57,12 @@ Sites open through ordinary URLs, Browser bookmarks or the App's local saved-sit list. Browser invitations can be opened in a running native-window App through local confirmation. Navigation remains separate from device approval; automatic address discovery is not planned. + +The current UI offers configurable microphone and listening shortcuts for the +voice dock's selected room, with opt-in Windows background registration. +Local failure guidance uses current operation facts and links to the matching +3.0 guide. App workspace navigation verifies the target site before leaving the +current page; webpage-video sources retain their separate browsing scope. [Verification status](./verification-status.md) owns evidence and platform limits; [TODO](./todo.md) owns remaining implementation and acceptance work. diff --git a/prototype/channel-native/src/input/windows.rs b/prototype/channel-native/src/input/windows.rs index 66f20c6dc..7f22b901a 100644 --- a/prototype/channel-native/src/input/windows.rs +++ b/prototype/channel-native/src/input/windows.rs @@ -1,5 +1,6 @@ use super::{Action, Bounds, Held, Sink, TargetState}; use crate::capture::{Target, TargetKind}; +use crate::windows_hotkeys::{Binding, Hotkeys}; use ::windows::Win32::{ Foundation::{CloseHandle, FILETIME, HWND, RECT}, Graphics::{ @@ -254,77 +255,31 @@ fn key(scan: u16, flags: KEYBD_EVENT_FLAGS) -> INPUT { /// thread owns its Windows message queue/registration; the executor owns consent. pub(super) struct Shortcut { pub key: u8, - thread_id: u32, - task: Option>, + _hotkeys: Hotkeys, } impl Shortcut { pub fn new(key: u8, owner: std::sync::Weak>) -> Result { - let (ready, started) = std::sync::mpsc::sync_channel(1); - let task = std::thread::Builder::new() - .name("piik-input-stop".into()) - .spawn(move || unsafe { - let mut message = MSG::default(); - // Create the queue before publishing its id to the closing owner. - let _ = PeekMessageW(&mut message, None, 0, 0, PM_NOREMOVE); - if let Err(error) = RegisterHotKey( - None, - 1, - MOD_CONTROL | MOD_ALT | MOD_NOREPEAT, - 0x6f + u32::from(key), - ) { - let _ = ready.send(Err(error)); - return; + let (hotkeys, [result]) = Hotkeys::register( + "piik-input-stop", + [Some(Binding { + modifiers: MOD_CONTROL | MOD_ALT, + key: 0x6f + u32::from(key), + })], + move |_| { + if let Some(owner) = owner.upgrade() { + owner.lock().unwrap().revoke(); } - let id = ::windows::Win32::System::Threading::GetCurrentThreadId(); - if ready.send(Ok(id)).is_ok() { - while GetMessageW(&mut message, None, 0, 0).0 > 0 { - if message.message == WM_HOTKEY { - if let Some(owner) = owner.upgrade() { - owner.lock().unwrap().revoke(); - } - } - } - } - let _ = UnregisterHotKey(None, 1); - })?; - match started.recv() { - Ok(Ok(thread_id)) => Ok(Self { - key, - thread_id, - task: Some(task), - }), - result => { - let _ = task.join(); - anyhow::bail!("input_shortcut_unavailable: {result:?}") - } - } + }, + )?; + let Some(hotkeys) = hotkeys else { + anyhow::bail!("input_shortcut_unavailable: {result:?}") + }; + Ok(Self { key, _hotkeys: hotkeys }) } #[cfg(test)] pub(super) fn notify_test(&self) -> Result<()> { - unsafe { - PostThreadMessageW( - self.thread_id, - WM_HOTKEY, - Default::default(), - Default::default(), - )?; - } + self._hotkeys.notify_test(0)?; Ok(()) } } -impl Drop for Shortcut { - fn drop(&mut self) { - unsafe { - let _ = PostThreadMessageW( - self.thread_id, - WM_QUIT, - Default::default(), - Default::default(), - ); - } - if let Some(task) = self.task.take() { - let _ = task.join(); - } - } -} diff --git a/prototype/channel-native/src/lib.rs b/prototype/channel-native/src/lib.rs index fbbac1111..780b6023f 100644 --- a/prototype/channel-native/src/lib.rs +++ b/prototype/channel-native/src/lib.rs @@ -7,6 +7,8 @@ pub mod diagnostics; mod file; pub mod hosted_room; pub mod input; +#[cfg(target_os = "windows")] +pub mod windows_hotkeys; mod media; pub mod peer; #[cfg(all(feature = "capture", target_os = "linux"))] diff --git a/prototype/channel-native/src/windows_hotkeys.rs b/prototype/channel-native/src/windows_hotkeys.rs new file mode 100644 index 000000000..cd3182be6 --- /dev/null +++ b/prototype/channel-native/src/windows_hotkeys.rs @@ -0,0 +1,146 @@ +use std::{sync::mpsc::sync_channel, thread}; +use windows::{ + core::Error, + Win32::{ + Foundation::WPARAM, + System::Threading::GetCurrentThreadId, + UI::{ + Input::KeyboardAndMouse::{RegisterHotKey, UnregisterHotKey, MOD_NOREPEAT}, + WindowsAndMessaging::{ + GetMessageW, PeekMessageW, PostThreadMessageW, MSG, PM_NOREMOVE, WM_HOTKEY, WM_QUIT, + }, + }, + }, +}; + +pub use windows::Win32::UI::Input::KeyboardAndMouse::{ + HOT_KEY_MODIFIERS, MOD_ALT, MOD_CONTROL, MOD_SHIFT, MOD_WIN, +}; + +pub struct Binding { + pub modifiers: HOT_KEY_MODIFIERS, + pub key: u32, +} + +/// A dedicated Windows message queue owns these registrations until dropped. +pub struct Hotkeys { + thread_id: u32, + task: Option>, +} + +impl Hotkeys { + pub fn register( + name: &str, + bindings: [Option; N], + mut activated: impl FnMut(usize) + Send + 'static, + ) -> std::io::Result<(Option, [Option>; N])> { + let (ready, started) = sync_channel(1); + let task = thread::Builder::new() + .name(name.into()) + .spawn(move || unsafe { + let mut message = MSG::default(); + // Windows requires the queue to exist before another thread posts to it. + let _ = PeekMessageW(&mut message, None, 0, 0, PM_NOREMOVE); + let mut results = [const { None }; N]; + for (id, binding) in bindings.into_iter().enumerate() { + results[id] = binding.map(|binding| { + RegisterHotKey( + None, + id as i32, + binding.modifiers | MOD_NOREPEAT, + binding.key, + ) + }); + } + let registered = results + .each_ref() + .map(|result| matches!(result, Some(Ok(())))); + let active = registered.contains(&true); + if ready.send((GetCurrentThreadId(), active, results)).is_ok() && active { + while GetMessageW(&mut message, None, 0, 0).0 > 0 { + let id = message.wParam.0; + if message.message == WM_HOTKEY && registered.get(id) == Some(&true) { + activated(id); + } + } + } + for (id, registered) in registered.into_iter().enumerate() { + if registered { + let _ = UnregisterHotKey(None, id as i32); + } + } + })?; + match started.recv() { + Ok((thread_id, true, results)) => Ok(( + Some(Self { + thread_id, + task: Some(task), + }), + results, + )), + Ok((_, false, results)) => { + let _ = task.join(); + Ok((None, results)) + } + Err(error) => { + let _ = task.join(); + Err(std::io::Error::other(error)) + } + } + } + + #[cfg(test)] + pub(crate) fn notify_test(&self, id: usize) -> windows::core::Result<()> { + unsafe { PostThreadMessageW(self.thread_id, WM_HOTKEY, WPARAM(id), Default::default()) } + } +} + +impl Drop for Hotkeys { + fn drop(&mut self) { + unsafe { + let _ = PostThreadMessageW(self.thread_id, WM_QUIT, WPARAM(0), Default::default()); + } + if let Some(task) = self.task.take() { + let _ = task.join(); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::time::Duration; + + #[test] + #[ignore = "scoped Win32 registration; only posts to its own queue"] + fn windows_hotkeys_dispatch_registered_ids_and_release_on_drop() -> anyhow::Result<()> { + let key = |key| { + Some(Binding { + modifiers: MOD_CONTROL | MOD_ALT | MOD_SHIFT, + key, + }) + }; + // F9 and F10 with three modifiers avoid the default Piik bindings. + let (reserved, [status]) = Hotkeys::register("piik-hotkey-control", [key(0x78)], |_| {})?; + status.unwrap()?; + let (send, receive) = sync_channel(2); + let (voice, [conflict, free]) = + Hotkeys::register("piik-hotkey-test", [key(0x78), key(0x79)], move |id| { + let _ = send.try_send(id); + })?; + assert!(conflict.unwrap().is_err()); + free.unwrap()?; + let voice = voice.unwrap(); + voice.notify_test(0)?; + voice.notify_test(1)?; + assert_eq!(receive.recv_timeout(Duration::from_secs(2))?, 1); + assert!(receive.try_recv().is_err()); + drop(voice); + drop(reserved); + let (_again, [first, second]) = + Hotkeys::register("piik-hotkey-release", [key(0x78), key(0x79)], |_| {})?; + first.unwrap()?; + second.unwrap()?; + Ok(()) + } +} diff --git a/prototype/channel-server/README.md b/prototype/channel-server/README.md index 764c9741b..aa2173014 100644 --- a/prototype/channel-server/README.md +++ b/prototype/channel-server/README.md @@ -278,6 +278,9 @@ separate its bookmark, App consent and startup preference. Bookmarks store a site address and optional name separately from device approval. Editing or removing a bookmark does not grant or revoke access. A changed invitation address can be updated manually; saved bookmarks contain no room invitation key. +The launcher checks the public Piik marker at the site origin before adding, changing or +opening a site address. A saved bookmark can be renamed offline. An unavailable site can be retried. In the Windows workspace, +external links open in the system Browser. The webpage player accepts ordinary media sites. From a Browser page, **App → Open in client** finds a running native-window App and opens its local confirmation page. The original room invitation can be passed diff --git a/prototype/channel-server/src/app.rs b/prototype/channel-server/src/app.rs index 6c0aa2625..ffa72ed15 100644 --- a/prototype/channel-server/src/app.rs +++ b/prototype/channel-server/src/app.rs @@ -15,6 +15,8 @@ mod sites; mod tunnel; #[path = "app_update.rs"] pub mod update; +#[path = "app_voice_shortcuts.rs"] +mod voice_shortcuts; #[path = "app_whip.rs"] mod whip; @@ -97,16 +99,6 @@ pub struct Config { pub ice_servers: Vec, pub update: update::Config, } -fn entry_url(site: &str, port: u16) -> Result { - if site.is_empty() { - return Ok(format!("http://127.0.0.1:{port}/client")); - } - let mut url = url::Url::parse(&site)?; - url.query_pairs_mut() - .append_pair("piik-client-port", &port.to_string()); - url.set_fragment(Some("piik-client=1")); - Ok(url.into()) -} struct Permission { data_id: Uuid, revoked: watch::Sender, @@ -173,6 +165,7 @@ struct App { closing: watch::Sender, launch: Mutex>, desktop: Desktop, + voice_shortcuts: voice_shortcuts::Owner, external_inputs: whip::Inputs, update: update::Owner, capture_targets: CaptureTargetReader, @@ -432,11 +425,10 @@ pub async fn serve( let owner = lock_directory(&config.data_root)?; let sites = sites::Sites::open(&config.data_root)?; let startup_intent = sites.startup()?; - let entry = match &startup_intent { - sites::StartupIntent::External(site) => entry_url(site, address.port())?, - sites::StartupIntent::Owned(_) => format!("{}?start=1", entry_url("", address.port())?), - sites::StartupIntent::None => entry_url("", address.port())?, - }; + let mut entry = format!("http://{address}/client"); + if !matches!(startup_intent, sites::StartupIntent::None) { + entry.push_str("?start=1"); + } let open_browser = config.open_browser; let terminal_enabled = (config.open_browser || ready.is_some()) && config.page_player.is_none() && std::env::var_os("PIIK_CHANNEL_APP_NO_BROWSER").is_none(); @@ -456,6 +448,7 @@ pub async fn serve( external_inputs: whip::Inputs::default(), capture_targets: CaptureTargetReader::default(), capture_microphones: CaptureTargetReader::default(), + voice_shortcuts: voice_shortcuts::Owner::default(), config, port: address.port(), token: Uuid::new_v4().to_string(), @@ -789,6 +782,9 @@ async fn health(State(app): State>) -> Json { if app.config.page_player.is_some() { state["pagePlayer"] = json!(true); } + if voice_shortcuts::AVAILABLE { + state["backgroundVoiceShortcuts"] = json!(true); + } #[cfg(feature = "capture")] if piik_channel_native::peer::supports_external_input() { state["externalScreenInputAvailable"] = json!(true); @@ -877,19 +873,21 @@ async fn save_bookmark( if origin.len() > 4096 || name.encode_utf16().count() > 40 { return Err(invalid_request("Invalid bookmark")); } - let registry = app.registry.lock().await; - if let Some(id) = request.id { - if !registry - .sites - .bookmarks() - .map_err(operation_failure)? - .iter() - .any(|entry| entry.id == id) - { - return Err(( - StatusCode::NOT_FOUND, - Json(json!({"detail":"Bookmark not found"})), - )); + let mut registry = app.registry.lock().await; + let saved = |registry: &Registry| { + request.id.map(|id| { + registry.sites.bookmarks().map_err(operation_failure)?.into_iter() + .find(|entry| entry.id == id) + .ok_or_else(|| (StatusCode::NOT_FOUND, Json(json!({"detail":"Bookmark not found"})))) + }).transpose() + }; + let previous = saved(®istry)?; + if previous.as_ref().is_none_or(|entry| entry.origin != origin) { + drop(registry); + verify_launcher_site(&app, &origin).await?; + registry = app.registry.lock().await; + if saved(®istry)? != previous { + return Err((StatusCode::PRECONDITION_FAILED, Json(json!({"detail":"Bookmark changed"})))); } } let bookmark = sites::Bookmark { @@ -921,6 +919,37 @@ async fn delete_bookmark(State(app): State>, Path(id): Path) -> A json!({"bookmarks":registry.sites.bookmarks().map_err(operation_failure)?}), )) } +// Check the public marker without sending invitation parameters or App credentials. +async fn verify_launcher_site(app: &App, origin: &str) -> std::result::Result<(), (StatusCode, Json)> { + // An active LAN listener and the loopback listener serve the same App-owned domain. + // Its ephemeral HTTPS certificate belongs to that listener only. + let local = app.registry.lock().await.local.as_ref() + .filter(|local| matches!(local.request.mode, hosted::Mode::Local) && local.invitation == origin) + .map(|local| local.origin.clone()); + verify_site(local.as_deref().unwrap_or(origin)).await +} + +async fn verify_site(origin: &str) -> std::result::Result<(), (StatusCode, Json)> { + let unavailable = || (StatusCode::SERVICE_UNAVAILABLE, Json(json!({"detail":"site_unavailable"}))); + let mismatch = || (StatusCode::UNPROCESSABLE_ENTITY, Json(json!({"detail":"not_piik_site"}))); + let client = reqwest::Client::builder() + .redirect(reqwest::redirect::Policy::none()) + .timeout(IO_TIMEOUT) + .build() + .map_err(|_| unavailable())?; + let mut response = client.get(format!("{origin}/healthz")).send().await.map_err(|_| unavailable())?; + if response.status() == StatusCode::NOT_FOUND { + return Err(mismatch()); + } + if response.status() != StatusCode::OK { + return Err(unavailable()); + } + let mut expected = crate::domain::HEALTH_MARKER.as_bytes(); + while let Some(chunk) = response.chunk().await.map_err(|_| unavailable())? { + expected = expected.strip_prefix(chunk.as_ref()).ok_or_else(mismatch)?; + } + if expected.is_empty() { Ok(()) } else { Err(mismatch()) } +} #[derive(Deserialize)] #[serde(deny_unknown_fields)] struct OpenWindow { @@ -936,11 +965,9 @@ async fn open_window(State(app): State>, Json(request): Json return Err(anyhow!("page_player_event_queue_full")), + event = voice_shortcuts.next() => { + timeout(IO_TIMEOUT, writer.send(Message::Text(event.to_string().into()))).await??; + continue; + } Some(event) = page_queue.recv() => { if event["type"] == "page_closed" { if let Some(id)=event["pageId"].as_str().and_then(|id|Uuid::parse_str(id).ok()){pages.stop_media(id);} } timeout(IO_TIMEOUT, writer.send(Message::Text(event.to_string().into()))).await??; @@ -1914,7 +1947,7 @@ async fn connection( .get("id") .and_then(Value::as_str) .filter(|id| !id.is_empty() && id.len() <= 256); - let response = match (id, serde_json::from_value::(value.clone())) { + let response = match (id, serde_json::from_str::(&text)) { (Some(_), Ok(request)) => { let result: Result = match request.operation { Operation::PrepareExternalInput { @@ -2689,6 +2722,15 @@ async fn connection( Err(error) => Err(error), } } + Operation::VoiceShortcuts(settings) => { + if host.is_none() { + Err(anyhow!("hello_required")) + } else { + // This loop writes the report before polling the new registration's events. + voice_shortcuts.configure(settings) + .and_then(|report| Ok(serde_json::to_value(report)?)) + } + } }; control_reply(request.id, result) } @@ -2969,6 +3011,9 @@ mod lifecycle_tests { let site = "https://owned.test".to_string(); let key = (site.clone(), Uuid::from_u128(1), Uuid::from_u128(2)); let permission = Arc::new(Permission::new(Uuid::from_u128(3))); + let other_site = "https://other.test".to_string(); + let other_key = (other_site.clone(), key.1, key.2); + let other_permission = Arc::new(Permission::new(Uuid::from_u128(4))); let (commands, mut receiver) = mpsc::channel(1); let (ready, admitted) = watch::channel(None); let (stop, mut stopped) = watch::channel(false); @@ -2988,6 +3033,17 @@ mod lifecycle_tests { Ok(()) }), }; + let mut other_stopped = stop.subscribe(); + let other_host = Host { + credential: "owned".into(), + commands: commands.clone(), + ready: watch::channel(Some(Ok(()))).1, + stop: stop.clone(), + task: tokio::spawn(async move { + let _ = other_stopped.changed().await; + Ok(()) + }), + }; let app = Arc::new(App { config: Config { data_root: directory.path().into(), @@ -3005,8 +3061,11 @@ mod lifecycle_tests { token: "owned".into(), registry: Mutex::new(Registry { sites: sites::Sites::open(directory.path()).unwrap(), - approvals: BTreeMap::from([(site.clone(), permission.clone())]), - hosts: BTreeMap::from([(key.clone(), host)]), + approvals: BTreeMap::from([ + (site.clone(), permission.clone()), + (other_site.clone(), other_permission), + ]), + hosts: BTreeMap::from([(key.clone(), host), (other_key, other_host)]), local: None, }), closing: watch::channel(false).0, @@ -3035,6 +3094,7 @@ mod lifecycle_tests { })), ..Default::default() }, + voice_shortcuts: voice_shortcuts::Owner::default(), update: update::Owner::disabled(), }); // The Native readiness producer is held before Welcome/bindings. Restoring @@ -3154,6 +3214,42 @@ mod lifecycle_tests { serde_json::from_str::(hello.to_text().unwrap()).unwrap(), json!({"id":"hello","result":null}) ); + if voice_shortcuts::AVAILABLE { + let exchange = + async |socket: &mut tokio_tungstenite::WebSocketStream<_>, request: Value| { + socket + .send(WsMessage::Text(request.to_string().into())) + .await + .unwrap(); + let reply = timeout(IO_TIMEOUT, socket.next()).await.unwrap().unwrap().unwrap(); + serde_json::from_str::(reply.to_text().unwrap()).unwrap() + }; + let enable = json!({ + "id":"voice","type":"voice_shortcuts","enabled":true,"microphone":null,"listening":null + }); + let result = json!({"id":"voice","result":{"microphone":"unbound","listening":"unbound"}}); + assert_eq!(exchange(&mut socket, enable.clone()).await, result); + + let mut other_request = request.clone(); + let other_origin = if revoke { &other_site } else { &site }; + other_request.headers_mut().insert("Origin", other_origin.parse().unwrap()); + let (mut other, _) = connect_async(other_request).await.unwrap(); + assert_eq!( + exchange(&mut other, json!({ + "id":"hello","type":"hello","channelId":key.1, + "userId":key.2,"credential":"owned","name":"Other tab" + })).await, + json!({"id":"hello","result":null}) + ); + let mut disable = enable.clone(); + disable["enabled"] = json!(false); + assert_eq!(exchange(&mut other, disable).await, result); + assert_eq!( + exchange(&mut other, enable).await, + json!({"id":"voice","error":"voice_shortcuts_in_use"}) + ); + other.close(None).await.unwrap(); + } // A previously approved control remains valid while its Native Host // loses admission. Identity reads do not reuse the readiness gate. ready.send_replace(None); @@ -3247,6 +3343,12 @@ mod lifecycle_tests { .unwrap() else { panic!("pending local endpoint read expected") }; timeout(IO_TIMEOUT, result.closed()).await.unwrap(); assert!(!*stop.borrow(), "control retirement stopped its independent Host"); + if voice_shortcuts::AVAILABLE { + let settings = serde_json::from_value(json!({ + "enabled":true,"microphone":null,"listening":null + })).unwrap(); + assert!(app.voice_shortcuts.connect().configure(settings).is_ok()); + } } timeout(IO_TIMEOUT, app.shutdown()).await.unwrap(); assert!(*stop.borrow()); @@ -3384,6 +3486,7 @@ mod lifecycle_tests { external_inputs: whip::Inputs::default(), capture_targets: CaptureTargetReader::default(), capture_microphones: CaptureTargetReader::default(), + voice_shortcuts: voice_shortcuts::Owner::default(), update: update::Owner::disabled(), }); let server_app = app.clone(); @@ -3535,6 +3638,71 @@ mod lifecycle_tests { net::TcpStream, }; + #[tokio::test] + async fn external_startup_checks_the_site_before_opening_it() { + let _ = rustls::crypto::ring::default_provider().install_default(); + let directory = tempfile::tempdir().unwrap(); + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let site = format!("http://{}", listener.local_addr().unwrap()); + let mut sites = sites::Sites::open(directory.path()).unwrap(); + let bookmark = sites::Bookmark { id: Uuid::new_v4(), origin: site.clone(), name: "Old".into() }; + sites.save_bookmark(&bookmark).unwrap(); + sites.approve(&site, true, false).unwrap(); + sites.set_startup(&sites::StartupIntent::External(site.clone())).unwrap(); + drop(sites); + let release = Arc::new(tokio::sync::Notify::new()); + let waiting = Arc::new(tokio::sync::Notify::new()); + let gate = release.clone(); + let requested = waiting.clone(); + let fixture = tokio::spawn(async move { + let routes = Router::new().route("/healthz", get(move || async move { + requested.notify_one(); + gate.notified().await; + "ordinary page" + })); + axum::serve(listener, routes).await.unwrap(); + }); + let config = Config { + data_root: directory.path().into(), assets: directory.path().into(), + open_browser: false, terminal_notice: None, page_player: None, + website_permission_reset: None, window_navigation: None, + cloudflared: PathBuf::new(), ice_servers: vec![], update: Default::default(), + }; + let (ready, entry) = oneshot::channel(); + let (stop, stopped) = oneshot::channel(); + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let origin = format!("http://{}", listener.local_addr().unwrap()); + let service = tokio::spawn(serve(listener, config, async { let _ = stopped.await; }, Some(ready))); + let client = reqwest::Client::builder().timeout(Duration::from_secs(2)).build().unwrap(); + let health = || client.get(format!("{origin}/health")).header("Origin", &site).send(); + assert_eq!(health().await.expect("local health independent of startup site").status(), StatusCode::OK); + assert_eq!(entry.await.unwrap(), format!("{origin}/client?start=1")); + let state = client.get(format!("{origin}/api/client-launcher")).send().await.unwrap(); + let state: Value = serde_json::from_slice(&state.bytes().await.unwrap()).unwrap(); + assert_eq!(state["startupSite"], site); + let navigation = tokio::spawn(reqwest::Client::new().post(format!("{origin}/api/client-launcher/open")) + .header("Origin", &origin).header("Content-Type", "application/json") + .body(json!({"url":site}).to_string()).send()); + timeout(Duration::from_secs(2), waiting.notified()).await.unwrap(); + assert_eq!(health().await.unwrap().status(), StatusCode::OK); + release.notify_one(); + let rejected = navigation.await.unwrap().unwrap(); + assert_eq!(rejected.status(), StatusCode::UNPROCESSABLE_ENTITY); + let detail: Value = serde_json::from_slice(&rejected.bytes().await.unwrap()).unwrap(); + assert_eq!(detail["detail"], "not_piik_site"); + fixture.abort(); + let _ = fixture.await; + let renamed = reqwest::Client::new().post(format!("{origin}/api/client-launcher/bookmarks")) + .header("Origin", &origin).header("Content-Type", "application/json") + .body(json!({"id":bookmark.id, "origin":site, "name":"Offline rename"}).to_string()) + .send().await.unwrap(); + assert_eq!(renamed.status(), StatusCode::OK); + let result: Value = serde_json::from_slice(&renamed.bytes().await.unwrap()).unwrap(); + assert_eq!(result["bookmarks"][0]["name"], "Offline rename"); + stop.send(()).unwrap(); + service.await.unwrap().unwrap(); + } + #[tokio::test] async fn bookmarks_and_window_navigation_are_local_and_keep_separate_authority() { let _ = rustls::crypto::ring::default_provider().install_default(); @@ -3546,7 +3714,15 @@ mod lifecycle_tests { let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); let address = listener.local_addr().unwrap(); let local = format!("http://{address}"); - let remote = "https://friend.example"; + let site_listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let site_origin = format!("http://{}", site_listener.local_addr().unwrap()); + let remote = site_origin.as_str(); + let lan = web::LanHttps::bind("127.0.0.1".parse().unwrap(), 0).await.unwrap(); + let lan_origin = lan.origin().to_owned(); + let domain = crate::domain::Domain::open( + &directory.path().join("domain"), "owner", site_origin.clone(), Some(lan_origin.clone()), vec![], + ).unwrap(); + let site = tokio::spawn(domain.serve_with_https(site_listener, Some(lan), Router::new(), std::future::pending())); let mut sites = sites::Sites::open(directory.path()).unwrap(); let permission = Arc::new(Permission::new(sites.approve(remote, true, false).unwrap())); sites @@ -3591,6 +3767,7 @@ mod lifecycle_tests { external_inputs: whip::Inputs::default(), capture_targets: CaptureTargetReader::default(), capture_microphones: CaptureTargetReader::default(), + voice_shortcuts: voice_shortcuts::Owner::default(), update: update::Owner::disabled(), }); let router = Router::new() @@ -3692,7 +3869,7 @@ mod lifecycle_tests { .status(), StatusCode::CONFLICT ); - let invitation = "https://friend.example/rooms/abc?view=screen#invite=secret"; + let invitation = format!("{remote}/rooms/abc?view=screen#invite=secret"); let open = format!("{local}/api/client-launcher/open"); assert_eq!( client @@ -3718,7 +3895,7 @@ mod lifecycle_tests { .status(), StatusCode::OK ); - assert_eq!(*navigations.lock().unwrap(), vec![invitation]); + assert_eq!(*navigations.lock().unwrap(), vec![invitation.as_str()]); for url in [ "javascript:alert(1)", "file:///private", @@ -3750,6 +3927,28 @@ mod lifecycle_tests { .status(), StatusCode::SERVICE_UNAVAILABLE ); + for (reply, expected) in [ + (axum::response::Html("Ordinary website").into_response(), StatusCode::UNPROCESSABLE_ENTITY), + (axum::response::Redirect::temporary(remote).into_response(), StatusCode::SERVICE_UNAVAILABLE), + (StatusCode::SERVICE_UNAVAILABLE.into_response(), StatusCode::SERVICE_UNAVAILABLE), + ] { + let fixture = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let origin = format!("http://{}", fixture.local_addr().unwrap()); + let status = reply.status(); + let headers = reply.headers().clone(); + let body = axum::body::to_bytes(reply.into_body(), 1024).await.unwrap(); + let server = tokio::spawn(async move { + let routes = Router::new().route("/healthz", get(move || async move { (status, headers, body) })); + axum::serve(fixture, routes).await.unwrap(); + }); + for (endpoint, request) in [(&open, json!({"url":origin})), (&endpoint, json!({"origin":origin,"name":"Other"}))] { + let response = client.post(endpoint).header("Origin", &local) + .header("Content-Type", "application/json").body(request.to_string()).send().await.unwrap(); + assert_eq!(response.status(), expected); + } + server.abort(); + let _ = server.await; + } let current = client .get(&endpoint) .header("Origin", &local) @@ -3790,6 +3989,22 @@ mod lifecycle_tests { &permission )); drop(registry); + // The very same self-signed entry is unavailable externally and verifiable while App-owned. + assert_eq!(verify_site(&lan_origin).await.unwrap_err().0, StatusCode::SERVICE_UNAVAILABLE); + app.registry.lock().await.local = Some(LocalSite { + origin: site_origin.clone(), invitation: lan_origin.clone(), + request: serde_json::from_value(json!({"mode":"local"})).unwrap(), + permission: Arc::new(Permission::new(Uuid::new_v4())), + }); + available.store(true, Ordering::Relaxed); + for (route, body) in [(&endpoint, json!({"origin":lan_origin,"name":"LAN"})), (&open, json!({"url":lan_origin}))] { + let response = client.post(route).header("Origin", &local).header("Content-Type", "application/json") + .body(body.to_string()).send().await.unwrap(); + assert_eq!(response.status(), StatusCode::OK); + } + assert_eq!(navigations.lock().unwrap().last(), Some(&lan_origin)); + site.abort(); + let _ = site.await; server.abort(); let _ = server.await; } @@ -3831,6 +4046,7 @@ mod lifecycle_tests { external_inputs: whip::Inputs::default(), capture_targets: CaptureTargetReader::default(), capture_microphones: CaptureTargetReader::default(), + voice_shortcuts: voice_shortcuts::Owner::default(), update: update::Owner::disabled(), }); let router = Router::new() @@ -4018,6 +4234,7 @@ mod lifecycle_tests { external_inputs: whip::Inputs::default(), capture_targets: CaptureTargetReader::default(), capture_microphones: CaptureTargetReader::default(), + voice_shortcuts: voice_shortcuts::Owner::default(), update: update::Owner::disabled(), }) }; @@ -4241,6 +4458,7 @@ mod lifecycle_tests { external_inputs: whip::Inputs::default(), capture_targets: CaptureTargetReader::default(), capture_microphones: CaptureTargetReader::default(), + voice_shortcuts: voice_shortcuts::Owner::default(), update: update::Owner::disabled(), }); // Observe the actual HTTP handler future being dropped, without replacing @@ -4362,6 +4580,23 @@ mod lifecycle_tests { mod tests { use super::*; + #[test] + fn voice_shortcut_wire_requires_explicit_slots_and_strict_bindings() { + let valid = r#"{"id":"1","type":"voice_shortcuts","enabled":true,"microphone":null,"listening":{"key":"F10","ctrl":true,"alt":false,"shift":true,"meta":false}}"#; + assert!(matches!( + serde_json::from_str::(valid).unwrap().operation, + Operation::VoiceShortcuts(_) + )); + for invalid in [ + valid.replace(r#""microphone":null,"#, ""), + valid.replace(r#""microphone":null"#, r#""microphone":null,"roomId":"private""#), + valid.replace(r#""meta":false"#, r#""meta":false,"muted":true"#), + valid.replace(r#""meta":false"#, r#""meta":false,"meta":true"#), + ] { + assert!(serde_json::from_str::(&invalid).is_err(), "{invalid}"); + } + } + #[test] fn old_external_ready_and_end_cannot_retire_the_successor_pending_source() { let mut capture = Capture::default(); diff --git a/prototype/channel-server/src/app_backup_description_tests.rs b/prototype/channel-server/src/app_backup_description_tests.rs index 14073b8df..7add6f569 100644 --- a/prototype/channel-server/src/app_backup_description_tests.rs +++ b/prototype/channel-server/src/app_backup_description_tests.rs @@ -81,6 +81,7 @@ impl Fixture { external_inputs: whip::Inputs::default(), capture_targets: Default::default(), capture_microphones: Default::default(), + voice_shortcuts: Default::default(), update: update::Owner::disabled(), }); let router = Router::new() diff --git a/prototype/channel-server/src/app_sites.rs b/prototype/channel-server/src/app_sites.rs index fff8a735d..3b5251916 100644 --- a/prototype/channel-server/src/app_sites.rs +++ b/prototype/channel-server/src/app_sites.rs @@ -8,7 +8,7 @@ use uuid::Uuid; pub(super) struct Sites(Connection); -#[derive(Serialize)] +#[derive(PartialEq, Serialize)] pub(super) struct Bookmark { pub id: Uuid, pub origin: String, diff --git a/prototype/channel-server/src/app_voice_shortcuts.rs b/prototype/channel-server/src/app_voice_shortcuts.rs new file mode 100644 index 000000000..619c2e91e --- /dev/null +++ b/prototype/channel-server/src/app_voice_shortcuts.rs @@ -0,0 +1,299 @@ +use anyhow::{ensure, Result}; +use serde::{Deserialize, Serialize}; + +pub(super) const AVAILABLE: bool = cfg!(all(windows, feature = "capture")); + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +pub(super) struct Settings { + enabled: bool, + #[serde(deserialize_with = "Deserialize::deserialize")] + microphone: Option, + #[serde(deserialize_with = "Deserialize::deserialize")] + listening: Option, +} + +#[derive(Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +struct Binding { + key: String, + ctrl: bool, + alt: bool, + shift: bool, + meta: bool, +} + +impl Binding { + fn virtual_key(&self) -> Result { + ensure!(self.ctrl || self.alt || self.meta, "invalid_voice_shortcut"); + let key = match self.key.as_bytes() { + [key @ (b'A'..=b'Z' | b'0'..=b'9')] => u32::from(*key), + [b'F', digit @ b'1'..=b'9'] => 0x6f + u32::from(digit - b'0'), + b"F10" => 0x79, + b"F11" => 0x7a, + _ => anyhow::bail!("invalid_voice_shortcut"), + }; + Ok(key) + } +} + +#[derive(Clone, Copy, Serialize, Debug, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +enum Status { + Unbound, + #[cfg(all(windows, feature = "capture"))] + Unavailable, + #[cfg(all(windows, feature = "capture"))] + Registered, +} + +#[derive(Serialize)] +pub(super) struct Report { + microphone: Status, + listening: Status, +} + +#[derive(Default)] +pub(super) struct Owner(#[cfg(all(windows, feature = "capture"))] std::sync::atomic::AtomicBool); + +pub(super) struct Connection<'a> { + _owner: &'a Owner, + #[cfg(all(windows, feature = "capture"))] + lease: Option>, +} + +impl Owner { + pub(super) fn connect(&self) -> Connection<'_> { + Connection { + _owner: self, + #[cfg(all(windows, feature = "capture"))] + lease: None, + } + } +} + +impl Connection<'_> { + pub(super) fn configure(&mut self, settings: Settings) -> Result { + let Settings { + enabled, + microphone, + listening, + } = settings; + ensure!( + enabled || (microphone.is_none() && listening.is_none()), + "invalid_voice_shortcut" + ); + ensure!( + microphone.is_none() || microphone != listening, + "invalid_voice_shortcut" + ); + for binding in [µphone, &listening].into_iter().flatten() { + binding.virtual_key()?; + } + ensure!(AVAILABLE, "voice_shortcuts_unavailable"); + #[cfg(all(windows, feature = "capture"))] + if enabled { + if self.lease.is_none() { + self.lease = Some(windows::Lease::acquire(self._owner)?); + } + return self + .lease + .as_mut() + .unwrap() + .register([microphone, listening]); + } else { + self.lease = None; + } + Ok(Report { + microphone: Status::Unbound, + listening: Status::Unbound, + }) + } + + pub(super) async fn next(&mut self) -> serde_json::Value { + #[cfg(all(windows, feature = "capture"))] + if let Some(lease) = &mut self.lease { + if let Some(activation) = lease.receive().await { + return activation.wire(); + } + } + std::future::pending().await + } +} + +#[cfg(all(windows, feature = "capture"))] +mod windows { + use super::{Binding, Owner, Report, Status}; + use anyhow::{ensure, Result}; + use piik_channel_native::windows_hotkeys::{ + Binding as HotkeyBinding, Hotkeys, HOT_KEY_MODIFIERS, MOD_ALT, MOD_CONTROL, MOD_SHIFT, + MOD_WIN, + }; + use serde::Serialize; + use std::{ + sync::atomic::Ordering, + time::{SystemTime, UNIX_EPOCH}, + }; + use tokio::sync::mpsc; + + #[derive(Clone, Copy, Serialize)] + #[serde(rename_all = "snake_case")] + enum Action { + ToggleMicrophone, + ToggleListening, + } + + pub(super) struct Activation { + action: Action, + activated_at_ms: u64, + } + + impl Activation { + fn now(action: Action) -> Option { + let elapsed = SystemTime::now().duration_since(UNIX_EPOCH).ok()?; + Some(Self { + action, + activated_at_ms: elapsed.as_millis().try_into().ok()?, + }) + } + + pub(super) fn wire(self) -> serde_json::Value { + serde_json::json!({ + "type": "voice_shortcut", "action": self.action, "activatedAtMs": self.activated_at_ms + }) + } + } + + pub(super) struct Lease<'a> { + owner: &'a Owner, + hotkeys: Option, + events: Option>, + } + + impl<'a> Lease<'a> { + pub(super) fn acquire(owner: &'a Owner) -> Result { + ensure!( + owner + .0 + .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire) + .is_ok(), + "voice_shortcuts_in_use" + ); + Ok(Self { + owner, + hotkeys: None, + events: None, + }) + } + + pub(super) fn register(&mut self, bindings: [Option; 2]) -> Result { + let mut requested = [false; 2]; + let mut hotkeys = [None, None]; + for (index, binding) in bindings.into_iter().enumerate() { + let Some(binding) = binding else { + continue; + }; + requested[index] = true; + let key = binding.virtual_key()?; + let mut modifiers = HOT_KEY_MODIFIERS::default(); + for (use_modifier, flag) in [ + (binding.ctrl, MOD_CONTROL), + (binding.alt, MOD_ALT), + (binding.shift, MOD_SHIFT), + (binding.meta, MOD_WIN), + ] { + if use_modifier { + modifiers |= flag; + } + } + // Reserve the existing remote-control stop combinations for their owner. + if !(modifiers == (MOD_CONTROL | MOD_ALT) && (0x70..=0x7a).contains(&key)) { + hotkeys[index] = Some(HotkeyBinding { modifiers, key }); + } + } + self.stop(); + let mut status = requested.map(|set| { + if set { + Status::Unavailable + } else { + Status::Unbound + } + }); + if hotkeys.iter().any(Option::is_some) { + let (send, receive) = mpsc::channel(1); + let actions = [Action::ToggleMicrophone, Action::ToggleListening]; + if let Ok((hotkeys, results)) = + Hotkeys::register("piik-voice-shortcuts", hotkeys, move |id| { + if let Some(activation) = Activation::now(actions[id]) { + let _ = send.try_send(activation); + } + }) + { + for (index, result) in results.into_iter().enumerate() { + if matches!(result, Some(Ok(()))) { + status[index] = Status::Registered; + } + } + if hotkeys.is_some() { + self.hotkeys = hotkeys; + self.events = Some(receive); + } + } + } + let [microphone, listening] = status; + Ok(Report { + microphone, + listening, + }) + } + + pub(super) async fn receive(&mut self) -> Option { + self.events.as_mut()?.recv().await + } + + fn stop(&mut self) { + self.events = None; + self.hotkeys = None; + } + } + + impl Drop for Lease<'_> { + fn drop(&mut self) { + self.stop(); + self.owner.0.store(false, Ordering::Release); + } + } + + #[cfg(test)] + #[tokio::test] + async fn voice_shortcut_event_keeps_the_activation_time_after_queuing() { + use std::time::Duration; + + let (send, events) = mpsc::channel(2); + let owner = Owner::default(); + let mut connection = owner.connect(); + let mut lease = Lease::acquire(&owner).unwrap(); + lease.events = Some(events); + connection.lease = Some(lease); + let before = SystemTime::now().duration_since(UNIX_EPOCH).unwrap(); + for action in [Action::ToggleMicrophone, Action::ToggleListening] { + send.try_send(Activation::now(action).unwrap()) + .ok() + .unwrap(); + } + let after = SystemTime::now().duration_since(UNIX_EPOCH).unwrap(); + tokio::time::sleep(Duration::from_millis(1_010)).await; + for expected in ["toggle_microphone", "toggle_listening"] { + let event = tokio::time::timeout(Duration::from_secs(1), connection.next()) + .await + .unwrap(); + assert_eq!(event["type"], "voice_shortcut"); + assert_eq!(event["action"], expected); + let stamp = Duration::from_millis(event["activatedAtMs"].as_u64().unwrap()); + assert!(stamp.as_millis() >= before.as_millis()); + assert!(stamp <= after); + let read_at = SystemTime::now().duration_since(UNIX_EPOCH).unwrap(); + assert!(read_at - stamp >= Duration::from_secs(1)); + } + } +} diff --git a/prototype/channel-server/src/app_whip_cancel_tests.rs b/prototype/channel-server/src/app_whip_cancel_tests.rs index f5fca75b7..c4a44dc1b 100644 --- a/prototype/channel-server/src/app_whip_cancel_tests.rs +++ b/prototype/channel-server/src/app_whip_cancel_tests.rs @@ -74,6 +74,7 @@ async fn native_and_external_cancellation_keep_the_other_preparation_owner() -> let app = Arc::new(App { capture_targets: Default::default(), capture_microphones: Default::default(), + voice_shortcuts: Default::default(), config: Config { data_root: directory.path().into(), assets: directory.path().into(), diff --git a/prototype/channel-server/src/app_whip_http_tests.rs b/prototype/channel-server/src/app_whip_http_tests.rs index 770566027..7abd01766 100644 --- a/prototype/channel-server/src/app_whip_http_tests.rs +++ b/prototype/channel-server/src/app_whip_http_tests.rs @@ -40,6 +40,7 @@ fn fixture() -> ( external_inputs: Inputs::default(), capture_targets: Default::default(), capture_microphones: Default::default(), + voice_shortcuts: Default::default(), update: update::Owner::disabled(), }); let binding = Uuid::new_v4(); diff --git a/prototype/channel-server/src/app_windows.rs b/prototype/channel-server/src/app_windows.rs index 42a35cd25..b8520ece5 100644 --- a/prototype/channel-server/src/app_windows.rs +++ b/prototype/channel-server/src/app_windows.rs @@ -159,7 +159,7 @@ enum ServiceEvent { launcher: url::Url, }, Navigate(String), - ContentLoading, + ContentLoading(String), Mount(watch_mount::Request, String, u64), Finished, PopupClosed(WindowId), @@ -297,6 +297,56 @@ impl Drop for Core { } } +// The App service selects the workspace origin. Page links cannot select another one. +#[derive(Clone, Default)] +struct WorkspaceOrigins { + launcher: Option, + site: Option, + opening: Option, +} +impl WorkspaceOrigins { + fn handles(&self, address: &str, open_external: bool) -> bool { + if address == "about:blank" { + return true; + } + let Ok(url) = url::Url::parse(address) else { return false }; + let origin = url.origin(); + if matches!(url.scheme(), "http" | "https" | "blob") + && (self.launcher.as_ref() == Some(&origin) || self.site.as_ref() == Some(&origin) || self.opening.as_ref() == Some(&origin)) + { + return true; + } + if open_external && matches!(url.scheme(), "http" | "https") && url.username().is_empty() && url.password().is_none() { + if let Err(error) = webbrowser::open(url.as_str()) { + eprintln!("Open link in browser: {error}"); + } + } + false + } +} + +fn workspace_navigation(view: &WebView, origins: Rc>) -> Result<()> { + unsafe { + view.webview().add_NavigationStarting( + &webview2_com::NavigationStartingEventHandler::create(Box::new(move |_, args| { + let Some(args) = args else { return Ok(()) }; + let mut uri = windows_core::PWSTR::null(); + args.Uri(&mut uri)?; + let mut redirected = Default::default(); + args.IsRedirected(&mut redirected)?; + let mut user_initiated = Default::default(); + args.IsUserInitiated(&mut user_initiated)?; + let allowed = origins.borrow().handles( + &webview2_com::take_pwstr(uri), user_initiated.as_bool() && !redirected.as_bool(), + ); + args.SetCancel(!allowed) + })), + &mut Default::default(), + )?; + } + Ok(()) +} + struct PopupWindow { caption: caption::Caption, content: WebView, @@ -308,6 +358,7 @@ impl PopupWindow { environment: webview2_com::Microsoft::Web::WebView2::Win32::ICoreWebView2Environment, events: EventLoopProxy, pending: PendingPermissions, + origins: Rc>, controls: &WindowControls, ) -> Result { let id = window.id(); @@ -316,6 +367,13 @@ impl PopupWindow { let load_events = events.clone(); let webview = WebViewBuilder::new() .with_environment(environment) + .with_new_window_req_handler({ + let origins = origins.clone(); + move |url, _| { + origins.borrow().handles(&url, true); + NewWindowResponse::Deny + } + }) .with_initialization_script(SYSTEM_PRESENTATION) .with_initialization_script(download::SCRIPT) .with_document_title_changed_handler(move |title| { let _ = title_events.send_event(ServiceEvent::PopupTitle(id, title)); }) @@ -333,6 +391,7 @@ impl PopupWindow { }) .build_as_child(window.as_ref())?; let download_events = events.clone(); + workspace_navigation(&webview, origins)?; download::install(&webview, Some(Rc::new(move |url, status| { let _ = download_events.send_event(ServiceEvent::Download(id, url, status)); })), None)?; @@ -378,6 +437,7 @@ type Popups = Rc>>; // Fields drop in this order: both WebViews retire before their native owner. struct MainWindow { + origins: Rc>, receipts: Rc, document: Rc>, caption: caption::Caption, @@ -413,16 +473,18 @@ impl MainWindow { let document = Rc::new(std::cell::Cell::new(0u64)); let loading_document = document.clone(); let ipc_document = document.clone(); + let origins = Rc::new(RefCell::new(WorkspaceOrigins::default())); + let popup_origins = origins.clone(); let content = WebViewBuilder::new_with_web_context(context).with_url("about:blank") .with_initialization_script(CAPABILITY) .with_initialization_script(reveal::SCRIPT) .with_initialization_script_for_main_only(watch_mount::SCRIPT, true) .with_initialization_script(download::SCRIPT) - .with_on_page_load_handler(move |event, _| { + .with_on_page_load_handler(move |event, url| { // Wry maps Started to top-level ContentLoading, after cancellation is resolved. if matches!(event, PageLoadEvent::Started) { loading_document.set(loading_document.get().wrapping_add(1)); - let _ = load_events.send_event(ServiceEvent::ContentLoading); + let _ = load_events.send_event(ServiceEvent::ContentLoading(url)); } }) .with_ipc_handler(move |request| { @@ -439,12 +501,13 @@ impl MainWindow { let _ = content_events.send_event(ServiceEvent::Content(message)); } }) - .with_new_window_req_handler(move |_, features| { + .with_new_window_req_handler(move |url, features| { + if !popup_origins.borrow().handles(&url, true) { return NewWindowResponse::Deny; } let create = || -> Result { let window = Rc::new(popup::builder(window_builder()?, features.size, features.position, &popup_controls) .with_decorations(false).with_undecorated_shadow(true).build(&popup_target)?); let popup = PopupWindow::new(window, features.opener.environment, popup_events.clone(), - popup_pending.clone(), &popup_controls)?; + popup_pending.clone(), popup_origins.clone(), &popup_controls)?; let response = NewWindowResponse::Create { webview: popup.content.webview() }; popups.borrow_mut().push(popup); Ok(response) @@ -458,6 +521,7 @@ impl MainWindow { .build_as_child(window.as_ref())?; let download_events = events.clone(); let id = window.id(); + workspace_navigation(&content, origins.clone())?; download::install(&content, Some(Rc::new(move |url, status| { let _ = download_events.send_event(ServiceEvent::Download(id, url, status)); })), Some(receipts.clone()))?; @@ -482,7 +546,7 @@ impl MainWindow { let caption = caption::Caption::new(&window, &content, events, controls, false)?; let result = Self { - receipts, document, + receipts, document, origins, caption, content, window, @@ -651,10 +715,21 @@ pub fn run(mut config: Config, port: Option) -> Result<()> { Event::UserEvent(ServiceEvent::Mount(request, source, generation)) => { if let Some(main) = &window { request.apply(main, &mut pages, &source, generation); } } - Event::UserEvent(ServiceEvent::ContentLoading) => { + Event::UserEvent(ServiceEvent::ContentLoading(url)) => { pages.release_mounts(); if let Some(main) = &window { if prompt.as_ref().is_some_and(|dialog| dialog.stale(main)) { prompt.take(); } + let origin = url::Url::parse(&url).ok().map(|page| page.origin()); + let mut origins = main.origins.borrow_mut(); + if origins.opening.is_some() && origins.opening == origin { + origins.site = origins.opening.take(); + prompt.take(); + pending.borrow_mut().clear(); + popups.borrow_mut().clear(); + slot = None; + main.window.set_fullscreen(None); + main.position_caption(&controls, None); + } main.caption.content_loading(); } } @@ -786,7 +861,7 @@ pub fn run(mut config: Config, port: Option) -> Result<()> { launcher.set_fragment(Some(&fragment.finish())); let window = Rc::new(popup::builder(window_builder()?, None, None, &controls) .with_decorations(false).with_undecorated_shadow(true).build(target)?); - let popup = PopupWindow::new(window, main.content.environment(), page_events.clone(), pending.clone(), &controls)?; + let popup = PopupWindow::new(window, main.content.environment(), page_events.clone(), pending.clone(), main.origins.clone(), &controls)?; popup.content.load_url(launcher.as_str())?; bookmarks_window = Some(popup.window.id()); popups.borrow_mut().push(popup); @@ -799,20 +874,16 @@ pub fn run(mut config: Config, port: Option) -> Result<()> { } Event::UserEvent(ServiceEvent::Navigate(url)) => { if let Some(main) = &window { + main.origins.borrow_mut().opening = url::Url::parse(&url).ok().map(|u| u.origin()); match main.content.load_url(&url) { Ok(()) => { - // Navigation retires the old page's surfaces and permission requests; - // its App-hosted rooms remain with the service. - prompt.take(); - pending.borrow_mut().clear(); - popups.borrow_mut().clear(); - slot = None; - main.window.set_fullscreen(None); - main.position_caption(&controls, None); main.window.set_minimized(false); main.window.set_focus(); } - Err(error) => eprintln!("Open site in Piik: {error:#}"), + Err(error) => { + main.origins.borrow_mut().opening.take(); + eprintln!("Open site in Piik: {error:#}"); + } } } } @@ -839,6 +910,10 @@ pub fn run(mut config: Config, port: Option) -> Result<()> { } } Event::UserEvent(ServiceEvent::Ready { entry, launcher }) => { + if let Some(main) = &window { + let site = url::Url::parse(&entry).ok().map(|u| u.origin()); + *main.origins.borrow_mut() = WorkspaceOrigins { launcher: Some(launcher.origin()), site, opening: None }; + } launcher_url = Some(launcher); let opened = match &window { Some(main) => main.content.load_url(&entry).map_err(anyhow::Error::from), diff --git a/prototype/channel-server/src/domain.rs b/prototype/channel-server/src/domain.rs index a7b17ff56..55d87c7ba 100644 --- a/prototype/channel-server/src/domain.rs +++ b/prototype/channel-server/src/domain.rs @@ -30,6 +30,8 @@ use std::{ use tokio::sync::{mpsc, watch, Semaphore}; use uuid::Uuid; +pub(crate) const HEALTH_MARKER: &str = "piik-channel-prototype"; + #[derive(Clone)] struct Client { events: mpsc::Sender, @@ -795,7 +797,7 @@ impl Domain { stop: impl Future, ) -> anyhow::Result<()> { let app = Router::new() - .route("/healthz", get(|| async { "piik-channel-prototype" })) + .route("/healthz", get(|| async { HEALTH_MARKER })) .route("/prototype/channel", get(upgrade)) .route("/prototype/channel/identity", get(identify)) .route( diff --git a/src/client/channel/app-link.ts b/src/client/channel/app-link.ts index 186058bc6..58f054218 100644 --- a/src/client/channel/app-link.ts +++ b/src/client/channel/app-link.ts @@ -17,14 +17,17 @@ import { NativeRoomHosting } from "./hosting-api"; import type { CaptureDevice } from "../media/capture-devices"; import type { BrowserVideoCodecMode } from "../webrtc/video-codec"; import { debugEvent } from "../lib/debug"; +import { nativeVoiceShortcutEventSchema, nativeVoiceShortcutsReportSchema, type NativeVoiceShortcutsReport } from "../native/wire"; +import type { VoiceShortcutAction, VoiceShortcuts } from "./voice-shortcut-binding"; export const APP_PROTOCOL = 23; const APP_REQUEST_BYTES = 256 * 1024; const SOURCE_LIST_TIMEOUT_MS = 8_000; +const SHORTCUT_ACTION_MAX_AGE_MS = 1_000; const identitySchema = z.object({ service: z.literal("piik-channel-app"), protocol: z.number().int().positive(), domainProtocol: z.number().int().positive().optional(), port: z.number().int().min(1).max(65535) }); const healthSchema = identitySchema.extend({ protocol: z.literal(APP_PROTOCOL), domainProtocol: z.literal(CHANNEL_PROTOCOL), token: z.string().min(1).max(256).regex(/^[A-Za-z0-9_-]+$/), version: z.string().optional(), revision: z.string().optional(), packageTarget: z.string().optional(), updateSupported: z.boolean().optional(), pagePlayer: z.boolean().optional(), - externalScreenInputAvailable: z.boolean().optional() }); + externalScreenInputAvailable: z.boolean().optional(), backgroundVoiceShortcuts: z.boolean().optional() }); type AppHealth = z.infer; const measured = z.number().finite().nonnegative(); const nativeStreamMetricSchema = z.object({ @@ -244,6 +247,11 @@ export const channelAppDiscovery: AppDiscovery = { isIncompatible, }; +export interface BackgroundVoiceShortcuts { + configure(bindings: VoiceShortcuts | null): Promise; + subscribe(listener: (action: VoiceShortcutAction) => void): () => void; +} + /** Hosting survives this link; captures selected through it belong to this page. */ export class ChannelApp { private socket: WebSocket; @@ -265,6 +273,7 @@ export class ChannelApp { private pages = new Map(); readonly pagePlayer: boolean; readonly externalScreenInputAvailable: boolean; + readonly backgroundVoiceShortcuts?: BackgroundVoiceShortcuts; get connected(): boolean { return this.authenticated && this.socket.readyState === WebSocket.OPEN; } get screens(): ReadonlySet { return new Set([...this.captures.keys(), ...this.externalInputs.keys()]); } @@ -287,10 +296,23 @@ export class ChannelApp { private readonly onClose: () => void, onCaptureState: (publicationId: string, error?: "capture_audio_failed" | "capture_failed") => void, onInputState: (publicationId: string, state: ChannelRemoteControlState) => void = () => {}, private readonly onAudioState: (publicationId: string) => void = () => {}, - onExternalInput: (event: NativeExternalInputState) => void = () => {}) { + onExternalInput: (event: NativeExternalInputState) => void = () => {}, + canReceiveVoiceShortcut: () => boolean = () => false) { const health = healthSchema.parse(verifiedHealth); this.pagePlayer = health.pagePlayer === true; this.externalScreenInputAvailable = health.externalScreenInputAvailable === true; + const voiceShortcutListeners = new Set<(action: VoiceShortcutAction) => void>(); + if (health.backgroundVoiceShortcuts === true) this.backgroundVoiceShortcuts = { + configure: async bindings => { + if (!this.connected) throw new Error("app_disconnected"); + const fields = bindings ?? { microphone: null, listening: null }; + return nativeVoiceShortcutsReportSchema.parse(await this.request({ type: "voice_shortcuts", enabled: bindings !== null, ...fields })); + }, + subscribe: listener => { + voiceShortcutListeners.add(listener); + return () => { voiceShortcutListeners.delete(listener); }; + }, + }; this.roomHosting = new NativeRoomHosting(`http://127.0.0.1:${health.port}/rooms/${channelId}/${userId}`, { Authorization: `Bearer ${health.token}`, "X-Piik-Credential": credential }); const socket = this.socket = new WebSocket(`ws://127.0.0.1:${health.port}/rooms`, `piik-channel-rooms.${health.token}`); @@ -327,6 +349,17 @@ export class ChannelApp { if (this.captures.has(event.publicationId) || this.prepared.has(event.publicationId)) onInputState(event.publicationId, event.state); return; } + if (reply.type === "voice_shortcut") { + if (!this.backgroundVoiceShortcuts || !this.connected || !canReceiveVoiceShortcut()) return; + const event = nativeVoiceShortcutEventSchema.safeParse(reply); + if (!event.success) return; + const timeDifference = Math.abs(Date.now() - event.data.activatedAtMs); + if (timeDifference > SHORTCUT_ACTION_MAX_AGE_MS) return; + const action = event.data.action === "toggle_microphone" ? "microphone" : "listening"; + try { voiceShortcutListeners.forEach(listener => listener(action)); } + catch { debugEvent("native", "voice-shortcut-consumer-failed"); } + return; + } if (reply.type === "capture_audio_failed") { const { publicationId } = captureAudioFailureSchema.parse(reply); failure = "consumer"; diff --git a/src/client/channel/components/ChannelDiagnosisHelp.tsx b/src/client/channel/components/ChannelDiagnosisHelp.tsx new file mode 100644 index 000000000..2e85e8497 --- /dev/null +++ b/src/client/channel/components/ChannelDiagnosisHelp.tsx @@ -0,0 +1,21 @@ +import { Glyph } from "../../ui/icons"; +import { useCopy, type CopyKey } from "../../ui/copy"; +import { diagnosisGuide, type ChannelDiagnosis } from "../diagnosis"; +import "./channel-diagnosis-help.css"; + +export function ChannelDiagnosisHelp({ diagnosis, details }: { + diagnosis: ChannelDiagnosis; + details?: readonly CopyKey[]; +}) { + const { lang, t } = useCopy(); + const guide = diagnosisGuide(diagnosis.topic, lang); + return
+ + {t("diagnosis.guide")} + + {!!details?.length &&
+ {t("diagnosis.details")} +
    {details.map(key =>
  • {t(key)}
  • )}
+
} +
; +} diff --git a/src/client/channel/components/ChannelMedia.tsx b/src/client/channel/components/ChannelMedia.tsx index 646358844..139ededbc 100644 --- a/src/client/channel/components/ChannelMedia.tsx +++ b/src/client/channel/components/ChannelMedia.tsx @@ -30,6 +30,8 @@ import "./channel-media.css"; import type { WatchPlayer } from "../watch-playback"; import type { WatchPlayback } from "../protocol"; import { channelErrorPresentation } from "../error-presentation"; +import { diagnoseChannelFact } from "../diagnosis"; +import { ChannelDiagnosisHelp } from "./ChannelDiagnosisHelp"; import { formatMediaTime } from "../../media/media-time"; import { mediaLanguageLabel } from "../../media/media-language"; @@ -122,6 +124,9 @@ export function ChannelWatchVideo({ player, owned, paused, label, presentation, const hasControls = owned && !embedded || localControls; const failure = channelErrorPresentation(player.error, t, receiving?.mode === "peer" ? "watch.forward.failed" : website && player.video ? "watch.browserFailed" : "watch.failed").message; + const diagnosis = player.error ? diagnoseChannelFact({ area: "error", code: player.error }) : null; + const showDiagnosis = presentation === "full" && !retryPending && !receiving?.pending ? diagnosis : null; + const returnToSource = showDiagnosis && player.error === "watch_media_access_denied" && (owned && !!player.media.page || !!openOriginal); const picture = usePictureInPicture(videoRef); const windowControls = player.video && = 2} quiet theaterMode={theaterMode} onToggleTheater={onToggleTheater} fullscreen={fullscreen} fullscreenFailed={fullscreenFailed} toggleFullscreen={() => { @@ -185,6 +190,7 @@ export function ChannelWatchVideo({ player, owned, paused, label, presentation, return () => { for (const name of events) video.removeEventListener(name, sync); document.removeEventListener("fullscreenchange", sync); }; }, [player]); return
{surface.kind !== "external" && preparing && !player.error && !player.blocked &&
@@ -195,19 +201,25 @@ export function ChannelWatchVideo({ player, owned, paused, label, presentation, {preparing && }{t(preparing ? "watch.waiting" : "watch.inWindow")}
} - {player.error ?
{failure} + {player.error ?
+ {diagnosis ? t(diagnosis.message) : failure} + {returnToSource && } {!owned && receiving?.mode === "direct" && receiving.browserSource && surface.kind !== "external" && } {owned && player.media.retainedByteSource && } - {owned && player.media.page && } - {!owned && website && surface.kind !== "external" && (openOriginal + {!owned && website && surface.kind !== "external" && !returnToSource && (openOriginal ? : !(receiving?.peerAvailable && receiving.peerSupported) && (originalPageUnavailable ? {originalPageUnavailable} : originalPageAvailable && {t("watch.connectApp")}))} {receiving && } + {showDiagnosis && }
: player.blocked &&
} {hasControls &&
diff --git a/src/client/channel/components/ChannelShareControl.tsx b/src/client/channel/components/ChannelShareControl.tsx index ad2e920ee..52781c112 100644 --- a/src/client/channel/components/ChannelShareControl.tsx +++ b/src/client/channel/components/ChannelShareControl.tsx @@ -17,7 +17,7 @@ import { MAX_AUDIO_SEND_BITRATE, QUALITY_PROFILES, VIDEO_CAPTURE_LIMITS, capture import { activateNativePicker } from "../../native/activation"; import type { NativeCaptureSources } from "../app-link"; import type { ChannelController } from "../types"; -import type { WatchMediaSources } from "../watch-page-media"; +import { directForwardFileURL, type WatchMediaSources } from "../watch-page-media"; import { screenTitle } from "../presentation"; import { useLayerHistory } from "../../ui/layer-history"; import { channelErrorPresentation } from "../error-presentation"; @@ -418,11 +418,14 @@ export function WatchSourceDialog({ channel, roomId, activityId, initialURL = "" {pageSources.choices.length > 0 &&
{pageSources.choices.map(choice => { const source = new URL(choice.displayURL), name = choice.name || source.host; + const originFirst = !!directForwardFileURL(choice); return
{ void run(() => channel.selectWatchBrowserSource(roomId, choice.id, false), onClose); }} /> - { void run(() => channel.selectWatchForwardSource(roomId, choice.id, false), onClose); }} />
; + { void run(() => channel.selectWatchForwardSource(roomId, choice.id, false), onClose); }} /> + {originFirst &&

{t("watch.forward.shareFileHelp")}

}
; })}
} {pageSources.indexed.length > 0 && { void run(() => channel.selectWatchBrowserSource(roomId, null, false), onClose); }} /> : page.candidates.length ?
- {page.candidates.map((candidate, index) =>
{ void run(() => channel.selectWatchPage(roomId, candidate.id, activityId, false), committed => { if (committed) onClose(); }); }} /> + {!activityId && { void run(() => channel.selectWatchPage(roomId, candidate.id, undefined, false, "original-page"), onClose); }} />} {!activityId && candidate.url && { void run(() => channel.selectWatchPage(roomId, candidate.id, undefined, false, "choose-source")); }} />}
)} diff --git a/src/client/channel/components/ChannelStage.tsx b/src/client/channel/components/ChannelStage.tsx index 165b23b4b..c3e926234 100644 --- a/src/client/channel/components/ChannelStage.tsx +++ b/src/client/channel/components/ChannelStage.tsx @@ -25,18 +25,26 @@ import { ChannelContentReactions } from "./ChannelContentReactions"; import { BrandLoader } from "../../components/living/BrandMark"; import { AudioVolumeMenu } from "../../components/living/AudioVolumeMenu"; import { ChannelSettingsDialog } from "./ChannelSettingsDialog"; +import { ChannelDiagnosisHelp } from "./ChannelDiagnosisHelp"; +import { diagnoseChannelFact, type ChannelDiagnosis } from "../diagnosis"; +import { Comic } from "../../components/living/Comic"; -function PictureDeliveryHelp() { +function PictureDeliveryHelp({ diagnosis, admitted, onRetry }: { + diagnosis: ChannelDiagnosis; admitted: boolean | undefined; onRetry?: () => void; +}) { const { t } = useCopy(); const [open, setOpen] = useState(false); return <> setOpen(true)} /> {open && setOpen(false)}> -
    -
  1. {t("screen.pictureHelpViewer")}
  2. -
  3. {t("screen.pictureHelpPublisher")}
  4. -
  5. {t("screen.pictureHelpForwarding", { setting: t("room.transit.allow") })}
  6. -
+
+ +

{t(diagnosis.message)}

+ {onRetry && diagnosis.next && { setOpen(false); onRetry(); }} />} + +
} ; } @@ -85,6 +93,8 @@ export interface ScreenStageSource { audience: readonly ScreenAudiencePerson[]; reactions?: MessageReactions; deliveryFailed?: boolean; + roomAdmitted?: boolean; + deliveryScope?: string; awaitingRoute?: boolean; stream?: MediaStream; sourceAudio?: SourceAudioControl; @@ -302,6 +312,9 @@ export function ChannelStage({ theaterMode: [theater, setTheater], buffering, so const microphone = source.sourceMicrophone; const sourceDetail = `${source.name} / ${source.roomName}${source.localSource ? ` / ${t("screen.localPreview")}` : ""}`; const title = screenTitle(source, t); + const diagnosis = canSubscribe && !source.pending && !source.hidden + ? diagnoseChannelFact({ area: "screen", paused: source.paused, deliveryFailed: source.deliveryFailed }) + : null; return
}
}
diff --git a/src/client/channel/components/ChannelVoiceDock.tsx b/src/client/channel/components/ChannelVoiceDock.tsx index c834796a2..83f38d89a 100644 --- a/src/client/channel/components/ChannelVoiceDock.tsx +++ b/src/client/channel/components/ChannelVoiceDock.tsx @@ -11,6 +11,9 @@ import { profileAvatar, roomVoicePeople } from "../presentation"; import { ChannelVoiceSettings } from "./ChannelVoiceSettings"; import { useCallback } from "react"; import { useVoiceLevels } from "../../room-voice/use-voice-levels"; +import { resolveVoiceDockControls } from "../voice-dock-controls"; +import { useVoiceShortcuts } from "../use-voice-shortcuts"; +import { voiceShortcutAria } from "../voice-shortcut-binding"; /** One persistent control surface for this endpoint's independently joined rooms. */ export function ChannelVoiceDock({ channel, selected, onSelect, onBrowse }: { @@ -18,8 +21,9 @@ export function ChannelVoiceDock({ channel, selected, onSelect, onBrowse }: { }) { const { t } = useCopy(); const state = channel.state; - const joined = state?.voice.filter(value => value.sessionId === channel.sessionId) ?? []; - const activity = joined.find(value => value.roomId === selected) ?? joined[0]; + const { joined, activity, microphoneDisabled, toggle } = resolveVoiceDockControls(channel, selected); + const shortcuts = useVoiceShortcuts(activity?.roomId, toggle, + channel.connection === "connected" ? channel.backgroundVoiceShortcuts : undefined); const roomId = activity?.roomId ?? ""; const readLevels = useCallback(() => channel.voiceActivity(roomId), [channel.voiceActivity, roomId]); const levels = useVoiceLevels(readLevels, !!activity); @@ -43,7 +47,7 @@ export function ChannelVoiceDock({ channel, selected, onSelect, onBrowse }: { }
- +
{participants.slice(0, 4).map(user => { @@ -58,12 +62,12 @@ export function ChannelVoiceDock({ channel, selected, onSelect, onBrowse }: {
- run(channel.setMuted(roomId, !muted))} /> + toggle("microphone")} /> run(channel.setDeafened(roomId, !deafened))} /> + keyShortcuts={voiceShortcutAria(shortcuts.bindings.listening)} onClick={() => toggle("listening")} /> run(channel.leaveVoice(roomId))} /> diff --git a/src/client/channel/components/ChannelVoiceSettings.tsx b/src/client/channel/components/ChannelVoiceSettings.tsx index 5cbe43f6d..4e2c7efea 100644 --- a/src/client/channel/components/ChannelVoiceSettings.tsx +++ b/src/client/channel/components/ChannelVoiceSettings.tsx @@ -7,9 +7,13 @@ import { Btn, SwitchItem } from "../../components/living/primitives"; import { useAnchoredPopover } from "../../components/living/use-anchored-popover"; import { useCopy } from "../../ui/copy"; import type { ChannelController } from "../types"; +import type { useVoiceShortcuts } from "../use-voice-shortcuts"; +import { ChannelVoiceShortcutSettings } from "./ChannelVoiceShortcutSettings"; import "./channel-voice-settings.css"; -export function ChannelVoiceSettings({ channel, roomId, available }: { channel: ChannelController; roomId: string; available: boolean }) { +export function ChannelVoiceSettings({ channel, roomId, available, shortcuts }: { + channel: ChannelController; roomId: string; available: boolean; shortcuts: ReturnType; +}) { const { t } = useCopy(); const id = useId(); const trigger = useRef(null), panel = useRef(null); @@ -22,7 +26,7 @@ export function ChannelVoiceSettings({ channel, roomId, available }: { channel: return <> + popoverTarget={id} controls={id} expanded={open} /> ; } diff --git a/src/client/channel/components/ChannelVoiceShortcutSettings.tsx b/src/client/channel/components/ChannelVoiceShortcutSettings.tsx new file mode 100644 index 000000000..d524d52c4 --- /dev/null +++ b/src/client/channel/components/ChannelVoiceShortcutSettings.tsx @@ -0,0 +1,86 @@ +import { useEffect, useId, useState, type KeyboardEvent } from "react"; +import { Btn, SwitchItem } from "../../components/living/primitives"; +import { Tooltip } from "../../components/living/Tooltip"; +import { useCopy } from "../../ui/copy"; +import { useSurfaceDocument } from "../../ui/panel-window"; +import type { useVoiceShortcuts } from "../use-voice-shortcuts"; +import { + ignoresVoiceShortcutKey, matchesVoiceShortcut, voiceShortcutActions, voiceShortcutFromEvent, voiceShortcutLabel, + type VoiceShortcutAction, +} from "../voice-shortcut-binding"; + +const modifiers = new Set(["Control", "Alt", "Shift", "Meta"]); + +export function ChannelVoiceShortcutSettings({ open, bindings, mac, save, reset, recording, setRecording, background }: + { open: boolean } & ReturnType) { + const { t } = useCopy(); + const surface = useSurfaceDocument(); + const id = useId(); + const [feedback, setFeedback] = useState<"duplicate" | "unsupported" | null>(null); + const finish = () => { setRecording(null); setFeedback(null); }; + useEffect(() => { + if (!open) finish(); + const view = surface?.defaultView; + view?.addEventListener("blur", finish); + return () => view?.removeEventListener("blur", finish); + }, [open, surface]); + + const record = (event: KeyboardEvent, action: VoiceShortcutAction) => { + if (!open || recording !== action || event.key === "Tab" || ignoresVoiceShortcutKey(event.nativeEvent)) return; + event.preventDefault(); + if (event.repeat || modifiers.has(event.key)) return; + if (event.key === "Escape") { finish(); return; } + if (!background.recordReady) return; + const binding = voiceShortcutFromEvent(event.nativeEvent); + if (!binding) { setFeedback("unsupported"); return; } + if (voiceShortcutActions.some(other => other !== action && matchesVoiceShortcut(bindings[other], binding))) { + setFeedback("duplicate"); return; + } + save({ [action]: binding }); + finish(); + }; + + return
+
+ {t("voice.shortcuts.title")} + +
+ {background.available ? <> + +

{t(background.error === "in_use" ? "voice.shortcuts.backgroundInUse" + : background.error ? "voice.shortcuts.backgroundFailed" : background.pending && !recording ? "voice.shortcuts.backgroundPending" + : background.report && (background.report.microphone === "registered" || background.report.listening === "registered") + ? "voice.shortcuts.backgroundEnabled" : "voice.shortcuts.scope")}

+ :

{t("voice.shortcuts.scope")}

} + {voiceShortcutActions.map(action => { + const name = t(action === "microphone" ? "host.device.microphone" : "voice.listening"); + const binding = bindings[action]; + const editing = open && recording === action; + const current = binding ? voiceShortcutLabel(binding, mac) : t("voice.shortcuts.unbound"); + const editLabel = t("voice.shortcuts.edit", { action: name, shortcut: current }); + const buttonId = `${id}-${action}`; + return
+ {name} +
+ {binding ? {current} : {current}} + record(event, action)} onBlur={finish} data-voice-shortcut-recording={editing || undefined}> + + { + surface?.getElementById(buttonId)?.focus(); setFeedback(null); setRecording(action); + }} /> + + + save({ [action]: null })} /> +
+

{editing ? t(!background.recordReady + ? background.error ? "voice.shortcuts.backgroundPauseFailed" : "voice.shortcuts.backgroundPausing" + : feedback === "duplicate" ? "voice.shortcuts.duplicate" + : feedback === "unsupported" ? "voice.shortcuts.unsupported" : "voice.shortcuts.record") + : !recording && background.report?.[action] === "unavailable" ? t("voice.shortcuts.backgroundBindingUnavailable") + : !recording && background.report?.[action] === "registered" ? t("voice.shortcuts.backgroundBindingRegistered") : ""}

+
; + })} +
; +} diff --git a/src/client/channel/components/channel-diagnosis-help.css b/src/client/channel/components/channel-diagnosis-help.css new file mode 100644 index 000000000..dcc819087 --- /dev/null +++ b/src/client/channel/components/channel-diagnosis-help.css @@ -0,0 +1,52 @@ +.c3-diagnosis-result, .c3-diagnosis-help { + display: grid; + justify-items: center; + gap: 10px; + min-width: 0; + text-align: center; +} + +.c3-diagnosis-result > svg { + display: block; + width: min(220px, 100%) !important; + height: auto; +} + +.c3-diagnosis-result > .c3-diagnosis-verdict { + color: var(--ink); + font-size: 1rem; + font-weight: 700; +} + +.c3-diagnosis-help { + margin-block-start: 2px; + width: 100%; + font-size: 13px; +} + +.c3-diagnosis-help a { + display: inline-flex; + align-items: center; + gap: 5px; + color: var(--action); +} + +.c3-diagnosis-help details { + width: min(290px, 100%); + padding: 0 12px; + border: 1px solid var(--line); + border-radius: 12px; + background: var(--wall); + text-align: start; +} + +.c3-diagnosis-help summary { + padding-block: 10px; + cursor: pointer; + font-weight: 600; +} + +.c3-diagnosis-help ul { + margin: 0 0 10px; + padding-inline-start: 1.3em; +} diff --git a/src/client/channel/components/channel-media.css b/src/client/channel/components/channel-media.css index 7583c9299..562e28664 100644 --- a/src/client/channel/components/channel-media.css +++ b/src/client/channel/components/channel-media.css @@ -23,12 +23,27 @@ .c3-mini-message .c3-watch-result { flex-direction: column; max-width: min(360px, calc(100% - 24px)); text-align: center; } .c3-monitor-tile:not(.is-thumbnail) > .c3-watch-player:is([data-external], [data-failed]) { min-height: 240px; } .c3-watch-player:is([data-external], [data-failed]) .c3-mini-message { inset: 88px 12px 64px; } -.c3-shell[data-layout="quick"] .c3-monitor:not(.is-theater) .c3-monitor-tile:not(.is-thumbnail) > .c3-watch-player[data-standalone]:not(:fullscreen) { +.c3-shell[data-layout="quick"] .c3-monitor:not(.is-theater) .c3-monitor-tile:not(.is-thumbnail) > .c3-watch-player[data-standalone]:not(:fullscreen), +.c3-video.c3-watch-player[data-diagnosis]:not(:fullscreen) { aspect-ratio: auto; grid-template-rows: minmax(160px, auto) auto; > .c3-mini-message { position: relative; inset: auto; grid-area: 1 / 1; padding: 16px 8px; } > .c3-mini-controls { grid-area: 2 / 1; } } +.c3-video.c3-watch-player[data-diagnosis]:not(:fullscreen) { + display: grid; + > .c3-mini-message { + place-items: safe center; + overflow-y: auto; + pointer-events: auto; + } + > .c3-mini-controls { + position: relative; + inset: auto; + justify-self: center; + margin-block-end: 10px; + } +} .c3-watch-timeline { display: flex; flex: 1 1 160px; flex-direction: column; justify-content: center; min-width: 78px; } .c3-watch-timeline :is(input, progress) { min-width: 0; width: 100%; height: 22px; margin: 0; accent-color: var(--action); } .c3-watch-time { color: var(--muted); font-size: 11px; line-height: 1.2; font-variant-numeric: tabular-nums; white-space: nowrap; } diff --git a/src/client/channel/components/channel-stage.css b/src/client/channel/components/channel-stage.css index 749a31e4d..8b2567689 100644 --- a/src/client/channel/components/channel-stage.css +++ b/src/client/channel/components/channel-stage.css @@ -69,12 +69,19 @@ } .c3-monitor-source-row .lr-btn:not(:where(.c3-monitor-source-row [popover] *)) { --button-size: var(--control-dense-size); --button-padding: 0; min-width: var(--button-size); height: var(--button-size); gap: 2px; } -.c3-monitor-wait { display: flex; align-items: center; justify-content: center; flex-direction: column; gap: 12px; aspect-ratio: 16 / 9; padding: 18px; border-radius: var(--c3-media-radius) var(--c3-media-radius) 0 0; background: var(--stage, var(--wall-2)); color: var(--muted); font-size: 12px; } +.c3-monitor-wait { + --ink: var(--piik-dark-ink); + --muted: var(--piik-dark-muted); + --action: var(--piik-dark-action); + --control-hover: var(--piik-dark-hover); + display: flex; align-items: center; justify-content: center; flex-direction: column; gap: 12px; + aspect-ratio: 16 / 9; padding: 18px; border-radius: var(--c3-media-radius) var(--c3-media-radius) 0 0; + background: var(--stage, var(--wall-2)); color: var(--muted); font-size: 12px; +} .c3-monitor-wait[data-failed] > svg { color: var(--danger); } .c3-monitor-wait-actions { display: flex; flex-wrap: wrap; align-items: center; justify-content: center; gap: 4px; max-width: 100%; } .c3-monitor-tile.is-thumbnail .c3-monitor-wait[data-failed] { padding: 8px; gap: 4px; text-align: center; } .c3-monitor-tile.is-thumbnail .c3-monitor-wait[data-failed] > svg { display: none; } -.c3-picture-help { margin: 0; padding-inline-start: 1.4em; display: grid; gap: 0.75em; } /* Theater changes the existing stage's layout; every subscription stays mounted. */ .c3-app:has(.c3-monitor.is-theater) .c3-shell { visibility: hidden; } .c3-shell:has(.c3-monitor.is-theater) { container-type: normal; } diff --git a/src/client/channel/components/channel-voice-settings.css b/src/client/channel/components/channel-voice-settings.css index 3d740702f..a6551ad4f 100644 --- a/src/client/channel/components/channel-voice-settings.css +++ b/src/client/channel/components/channel-voice-settings.css @@ -2,3 +2,14 @@ .c3-voice-settings > strong { display: block; margin-bottom: 14px; font-size: var(--control-label-size); } .c3-voice-settings > p { margin: 6px 0; color: var(--muted); font-size: 12px; line-height: 1.6; } .c3-voice-settings .lr-switch-item .lr-cap { white-space: normal; } +.c3-voice-shortcuts { margin-top: 14px; padding-top: 8px; border-top: 1px solid var(--control-edge); } +.c3-voice-shortcuts > header { display: flex; align-items: center; justify-content: space-between; } +.c3-voice-shortcuts strong { font-size: var(--control-label-size); } +.c3-voice-shortcuts p { margin: 4px 0 6px; color: var(--muted); font-size: 12px; line-height: 1.5; } +.c3-voice-shortcuts .c3-voice-shortcut-row { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; padding: 0; } +.c3-voice-shortcut-row + .c3-voice-shortcut-row { margin-block-start: 6px; } +.c3-voice-shortcut-row > span { font-size: var(--control-label-size); } +.c3-voice-shortcut-row .lr-capture-device-controls { display: grid; grid-template-columns: minmax(0, auto) auto auto; margin-inline-start: auto; } +.c3-voice-shortcut-row kbd { padding: 2px 5px; border: 1px solid var(--control-edge); border-radius: 4px; font: 11px var(--mono); } +.c3-voice-shortcut-row > p { flex-basis: 100%; margin: 0; } +.c3-voice-shortcut-row > p:empty { position: absolute; } diff --git a/src/client/channel/diagnosis.ts b/src/client/channel/diagnosis.ts new file mode 100644 index 000000000..f87d6e878 --- /dev/null +++ b/src/client/channel/diagnosis.ts @@ -0,0 +1,85 @@ +import type { CopyKey } from "../locales"; +import type { AttachmentProgress } from "./attachments"; +import type { ChannelRoom } from "./protocol"; + +const guideSections = { + troubleshooting: ["troubleshooting", "", ""], + app: ["troubleshooting", "opening-app-and-joining-a-room", "打开-app-与加入房间"], + room: ["troubleshooting", "an-invitation-or-password-is-rejected", "邀请或密码被拒绝"], + offline: ["troubleshooting", "chat-or-history-will-not-load", "聊天或历史记录加载不出来"], + picture: ["troubleshooting", "when-video-will-not-connect", "画面连接不上"], + capture: ["troubleshooting", "app-windows-or-screens-are-missing", "app-找不到窗口或屏幕"], + webpage: ["sharing", "watch-a-webpage-video-together", "一起看网页视频"], + attachment: ["troubleshooting", "an-attachment-will-not-open-or-download", "附件打不开或下载不了"], + storage: ["troubleshooting", "the-beta-app-reports-unsupportedstorageversion", "内测-app-提示-unsupportedstorageversion"], +} as const; + +export type ChannelHelpTopic = keyof typeof guideSections; +export function diagnosisGuide(topic: ChannelHelpTopic, lang: string) { + const zh = lang === "zh"; + const [page, enAnchor, zhAnchor] = guideSections[topic]; + const anchor = zh ? zhAnchor : enAnchor; + const githubAnchor = topic === "storage" ? anchor.replace("unsupportedstorageversion", "unsupported_storage_version") : anchor; + return { + path: `/docs/${zh ? "zh/" : ""}${page}.html${anchor && `#${anchor}`}`, + fallback: `https://github.com/TNTcraftHIM/Piik/blob/feat/channel-prototype/docs/guide/${page}${zh ? ".zh-CN" : ""}.md${githubAnchor && `#${githubAnchor}`}`, + }; +} + +export interface ChannelDiagnosis { + message: CopyKey; + next?: CopyKey; + topic: ChannelHelpTopic; +} + +export type AppConnectionState = "idle" | "waking" | "busy" | "approval" | "approving" | "ready" | "unavailable" | "incompatible"; +type ChannelFact = + | { area: "app"; state: AppConnectionState } + | { area: "screen"; paused: boolean; deliveryFailed?: boolean } + | { area: "room"; room: Pick } + | { area: "attachment"; state: AttachmentProgress["state"] } + | { area: "error"; code: string | null | undefined }; + +/** Read the current operation or selected subscription. A peer transport event alone never diagnoses it. */ +export function diagnoseChannelFact(fact: ChannelFact): ChannelDiagnosis | null { + if (fact.area === "app") { + switch (fact.state) { + case "approval": return { message: "client.connect.found", next: "client.connect.open", topic: "app" }; + case "unavailable": return { message: "client.connect.unavailable", topic: "app" }; + case "incompatible": return { message: "native.incompatible", topic: "app" }; + default: return null; + } + } + if (fact.area === "screen") return !fact.paused && fact.deliveryFailed + ? { message: "diagnosis.noPicture", next: "screen.retryPicture", topic: "picture" } : null; + if (fact.area === "room") { + if (fact.room.available) return null; // Admission can still be requested until the owner explicitly refuses it. + return { message: fact.room.authorized ? "channel.error.roomHostOffline" : "room.offline.access", topic: "offline" }; + } + if (fact.area === "attachment") return fact.state === "waiting-source" + ? { message: "channel.attachment.waitingSource", topic: "attachment" } : null; + + switch (fact.code) { + case "site_not_approved": return { message: "client.sites.notAllowed", next: "client.sites.allow", topic: "app" }; + case "room_host_offline": return { message: "channel.error.roomHostOffline", topic: "offline" }; + case "room_access_required": + case "room_forbidden": return { message: "channel.error.roomAccessDenied", topic: "room" }; + case "capture_targets_failed": return { message: "host.sourcePicker.failed", topic: "capture" }; + case "watch_media_access_denied": return { message: "watch.mediaAccessDenied", topic: "webpage" }; + case "watch_source_inspection_unavailable": return { message: "watch.sourceAccessRequired", topic: "webpage" }; + case "watch_media_unplayable": return { message: "watch.sourceUnplayable", topic: "webpage" }; + case "watch_page_closed": + case "page_player_closed": + case "watch_mpd_invalid": + case "invalid_watch_range_response": return { message: "watch.forward.sourceUnavailable", topic: "webpage" }; + case "attachment_unavailable": + case "file_unavailable": + case "file_source_unavailable": return { message: "channel.attachment.sourceUnavailable", topic: "attachment" }; + case "unsupported_storage_version": + case "unsupported_domain_checkpoint": return { message: "channel.error.unsupportedStorageVersion", topic: "storage" }; + default: + if (fact.code && /^watch_(?:invalid_manifest|page_unavailable|media_(?:unavailable|timeout|credentials_unavailable|changed|truncated)|resource_unavailable|source_(?:unavailable|failed|changed|retired))$/.test(fact.code)) + return { message: "watch.forward.sourceUnavailable", topic: "webpage" }; + return null; + } +} diff --git a/src/client/channel/error-presentation.ts b/src/client/channel/error-presentation.ts index f6e8381cf..fd55e5666 100644 --- a/src/client/channel/error-presentation.ts +++ b/src/client/channel/error-presentation.ts @@ -1,6 +1,7 @@ import type { CopyKey } from "../locales"; import type { UnsupportedVideoFormat } from "../native/wire"; import { isIncompatibleProtocol } from "./protocol"; +import { diagnoseChannelFact } from "./diagnosis"; export interface ChannelErrorPresentation { message: string | null; @@ -12,10 +13,10 @@ export function channelErrorPresentation(error: string | null, t: (key: CopyKey, fallback: CopyKey = "channel.error.actionFailed", unsupportedVideoFormat?: UnsupportedVideoFormat): ChannelErrorPresentation { const display = (key: CopyKey, connectionHelp = false): ChannelErrorPresentation => ({ message: t(key), connectionHelp }); if (!error) return { message: null, connectionHelp: true }; + const diagnosis = diagnoseChannelFact({ area: "error", code: error }); + if (diagnosis) return display(diagnosis.message); if (error === "room_busy") return display("channel.error.busy"); if (error === "room_creation_restricted") return display("channel.error.roomCreationRestricted"); - if (error === "attachment_unavailable" || error === "file_unavailable" || error === "file_source_unavailable") - return display("channel.attachment.sourceUnavailable"); if (error === "file_transfer_interrupted") return display("channel.attachment.transferInterrupted"); if (error === "saved_copy_missing") return display("channel.attachment.savedCopyMissing"); if (error === "reveal_saved_copy_failed") return display("channel.attachment.revealSavedFailed"); @@ -55,8 +56,6 @@ export function channelErrorPresentation(error: string | null, t: (key: CopyKey, return display("channel.error.restoreScratchLimit"); if (error === "backup_room_not_admitted") return display("channel.error.backupRoomNotAdmitted"); - if (error === "unsupported_storage_version") - return display("channel.error.unsupportedStorageVersion"); if (error === "unsupported_backup_version") return display("channel.error.unsupportedBackupVersion"); if (error === "backup_content_limit") @@ -84,12 +83,9 @@ export function channelErrorPresentation(error: string | null, t: (key: CopyKey, } if (error === "external_input_failed") return display("channel.error.externalInputFailed"); - if (error === "watch_media_unplayable") return display("watch.sourceUnplayable"); - if (error === "watch_media_access_denied") return display("watch.mediaAccessDenied"); if (error === "watch_media_decode_failed") return display("watch.decodeFailed"); if (error === "watch_live_position_unavailable") return display("watch.livePositionUnavailable"); - if (error === "watch_source_inspection_unavailable") return display("watch.sourceAccessRequired"); if (error === "watch_live_timeline_unsupported" || error === "watch_live_timeline_unavailable" || error === "watch_timeline_changed" || error === "watch_live_hls_atomic_read_required" || error === "watch_live_hls_timeline_unsupported") return display("watch.liveUnsupported"); @@ -98,11 +94,6 @@ export function channelErrorPresentation(error: string | null, t: (key: CopyKey, if (error === "watch_mpd_unsupported" || error === "watch_indexed_unsupported" || error === "invalid_watch_index" || /^watch_(?:live_hls_unsupported|media_(?:encryption_unsupported|encoding_unsupported|range_unsupported|size_unavailable)|manifest_extension_unsupported|manifest_limit|resource_limit|mp4_parse_failed)$/.test(error)) return display("watch.forward.unsupported"); - if (error === "watch_page_closed" || error === "page_player_closed") - return display("watch.forward.sourceUnavailable"); - if (error === "watch_mpd_invalid") return display("watch.forward.sourceUnavailable"); - if (/^(?:watch_(?:invalid_manifest|page_unavailable|media_(?:unavailable|timeout|credentials_unavailable|changed|truncated)|resource_unavailable|source_(?:unavailable|failed|changed|retired))|invalid_watch_range_response)$/.test(error)) - return display("watch.forward.sourceUnavailable"); if (error === "watch_source_busy" || error === "watch_read_busy") return display("watch.forward.busy"); if (error === "watch_read_timeout") @@ -136,8 +127,6 @@ export function channelErrorPresentation(error: string | null, t: (key: CopyKey, return display("channel.error.ownerMismatch"); if (/room_host_conflict|room_storage_in_use/.test(error)) return display("channel.error.roomHostConflict"); - if (error === "room_host_offline") - return display("channel.error.roomHostOffline"); if (/^(?:room_unavailable|room_not_found|invalid_room_id)$/.test(error)) return display("channel.error.roomUnavailable"); if (/password/i.test(error)) diff --git a/src/client/channel/session.ts b/src/client/channel/session.ts index 7947d5cca..5527b74da 100644 --- a/src/client/channel/session.ts +++ b/src/client/channel/session.ts @@ -1,6 +1,6 @@ import { RoomCreationInterrupted } from "./room-creation"; import { YouTubeMedia } from "./watch-youtube-media"; -import { PageSuppliedMedia, preparePageSuppliedWatchMedia, preparePortableWatchMedia, observeWatchSources, type WatchMediaSources } from "./watch-page-media"; +import { PageSuppliedMedia, preparePageSuppliedWatchMedia, preparePortableWatchMedia, observeWatchSources, directForwardFileURL, type WatchMediaSources } from "./watch-page-media"; import { canMoveYouTubePlayer, canWatchInBrowser, youtubeVideoId, youtubeStartSeconds, youtubeSourceId, originalWatchURL } from "./watch-youtube-source"; import { indexedMediaSelection } from "./watch-indexed-source"; import { WatchBytes } from "./watch-bytes"; @@ -343,6 +343,7 @@ export class ChannelSession { } const remoteControls = new Map([...(patch.remoteControls ?? this.view.remoteControls)].filter(([id]) => ownedScreens.has(id))); this.view = { ...this.view, ...patch, watchPlayers: new Map(this.watchPlayers), pagePlayer: this.app?.pagePlayer ?? false, appConnected: this.app?.connected ?? false, + backgroundVoiceShortcuts: this.app?.connected ? this.app.backgroundVoiceShortcuts : undefined, externalScreenInputAvailable: this.app?.connected === true && this.app.externalScreenInputAvailable, ownedScreens, localScreens, remoteControls }; for (const listener of this.listeners) listener(); } @@ -1064,7 +1065,7 @@ export class ChannelSession { if (this.closed || this.view.connection !== "connected" || this.view.self?.id !== self.id || this.view.state?.channel.id !== state.channel.id) throw new Error("disconnected"); if (!this.app) { - const app = new ChannelApp(health, state.channel.id, self.id, this.credential, self.name, () => { + const app: ChannelApp = new ChannelApp(health, state.channel.id, self.id, this.credential, self.name, () => { if (this.app !== app) return; this.app = undefined; for (const share of this.screenShares.values()) this.forgetInactiveScreen(share.id); @@ -1083,7 +1084,7 @@ export class ChannelSession { if (event.state === "prepared") void this.commitExternalScreen(app, event).catch(() => {}); if (event.state === "closed") this.forgetInactiveScreen(event.publicationId); this.patch({}); - }); + }, () => this.app === app && this.view.connection === "connected" && this.voiceParticipation.size > 0); this.app = app; } } @@ -2539,7 +2540,7 @@ export class ChannelSession { const selection = this.sourceSelections.get(roomId), page = selection?.page; return page ? { url: page.url, candidates: page.candidates, watchSources: selection?.watchSources } : undefined; }; - selectWatchPage = async (roomId: string, candidateId: string, activityId?: string, reportError = true, mode?: "choose-source"): Promise => { + selectWatchPage = async (roomId: string, candidateId: string, activityId?: string, reportError = true, mode?: "choose-source" | "original-page"): Promise => { if (activityId) { await this.selectWatchingPage(activityId, candidateId, reportError); return true; } return this.action(`screen:${roomId}`, async () => { const selection = this.sourceSelections.get(roomId), page = selection?.page; @@ -2550,6 +2551,10 @@ export class ChannelSession { selection.controller.signal.throwIfAborted(); const selected = page.candidates.find(value => value.id === candidateId); if (!selected) throw new Error("watch_page_unavailable"); + if (mode === "original-page") { + await this.commitWatch(roomId, { kind: "website", url: page.url }, new AppPageMedia(page), selection); + return true; + } // Both opaque players and a failed direct URL retain explicit page-source choices. const watchSources: NonNullable = selection.watchSources = { candidateId, choices: [], indexed: [], mpd: [] }; this.patch({}); @@ -2592,10 +2597,12 @@ export class ChannelSession { } selectWatchForwardSource = (roomId: string, choiceId: string, reportError = true): Promise => this.action(`screen:${roomId}`, async () => { const selection = this.sourceSelections.get(roomId), page = selection?.page; - if (!selection || !page || !selection.watchSources?.choices.some(choice => choice.id === choiceId)) throw new Error("watch_page_unavailable"); + const choice = selection?.watchSources?.choices.find(value => value.id === choiceId); + if (!selection || !page || !choice) throw new Error("watch_page_unavailable"); selection.discovery?.unsubscribe(); const source = await page.prepareMedia(choiceId, selection.controller.signal); - await this.commitPageSuppliedWatch(roomId, page, selection, source); + const mediaUrl = source.format === "file" ? directForwardFileURL(choice) : undefined; + await this.commitPageSuppliedWatch(roomId, page, selection, source, mediaUrl); }, reportError); selectWatchIndexedSource = (roomId: string, videoId: string, audioId?: string, reportError = true): Promise => this.action(`screen:${roomId}`, async () => { const selection = this.sourceSelections.get(roomId), page = selection?.page; @@ -2630,9 +2637,9 @@ export class ChannelSession { const byteSource = await page.prepareMpdMedia(selected, selection.controller.signal); await this.commitPageSuppliedWatch(roomId, page, selection, byteSource); }, reportError); - private async commitPageSuppliedWatch(roomId: string, page: AppPage, selection: SourceSelection, byteSource: WatchByteSource): Promise { + private async commitPageSuppliedWatch(roomId: string, page: AppPage, selection: SourceSelection, byteSource: WatchByteSource, mediaUrl?: string): Promise { const media = await preparePageSuppliedWatchMedia(page, byteSource, selection.controller.signal); - await this.commitWatch(roomId, { kind: "website", url: page.url }, media, selection, byteSource); + await this.commitWatch(roomId, { kind: "website", url: page.url, ...(mediaUrl && { mediaUrl }) }, media, selection, byteSource); } focusWatch = async (id: string): Promise => { const media = this.watchPlayers.get(id)?.media; @@ -2821,12 +2828,15 @@ export class ChannelSession { { hlsDeadlineOwner: "reader", timeline: activity.playback.timeline }), mode); return; } - const embed = youtubeSourceId(activity.source); - if (embed && !canWatchInBrowser(activity.source, current)) throw new Error("watch_media_unsupported"); const url = activity.source.kind === "media" ? activity.source.url : activity.source.mediaUrl; - if (!url && !embed) throw new Error("watch_page_required"); - const format = activity.source.kind === "media" ? directWatchFormat(new URL(activity.source.url)) : undefined; - await this.joinWatchMedia(id, embed ? new YouTubeMedia(embed, undefined, true) : new HTMLVideoMedia(url!, format, activity.playback.timeline)); + if (url) { + await this.joinWatchMedia(id, new HTMLVideoMedia(url, directWatchFormat(new URL(url)), activity.playback.timeline)); + return; + } + const embed = youtubeSourceId(activity.source); + if (!embed) throw new Error("watch_page_required"); + if (!canWatchInBrowser(activity.source, current)) throw new Error("watch_media_unsupported"); + await this.joinWatchMedia(id, new YouTubeMedia(embed, undefined, true)); }); private async joinWatchMedia(id: string, media: WatchMedia, mode: WatchMode = "direct"): Promise { const activity = this.view.state?.watchActivities.find(value => value.id === id); diff --git a/src/client/channel/types.ts b/src/client/channel/types.ts index a2ffe1abf..989c91303 100644 --- a/src/client/channel/types.ts +++ b/src/client/channel/types.ts @@ -9,7 +9,7 @@ import type { ChannelAttachments, DraftFile } from "./attachments"; import type { FeedbackCue } from "./feedback-audio"; import type { RoomCopyInfo } from "./backup-archive"; import type { NativeCaptureTarget, EncodingExecution } from "../native/wire"; -import type { NativeCaptureRequest, NativeCaptureSources, NativeExternalInput, ChannelRemoteControlState, NativeConnectionMetrics, NativeRelayCapacity } from "./app-link"; +import type { BackgroundVoiceShortcuts, NativeCaptureRequest, NativeCaptureSources, NativeExternalInput, ChannelRemoteControlState, NativeConnectionMetrics, NativeRelayCapacity } from "./app-link"; import type { RemoteStopShortcut } from "../native/wire"; import type { InputTransport } from "../remote-control/input-route"; import type { RemoteControlMode } from "../remote-control/protocol"; @@ -74,6 +74,7 @@ export interface ChannelView { voicePlaybackByUser: ReadonlyMap; listeningVolume: number; appConnected: boolean; + backgroundVoiceShortcuts?: BackgroundVoiceShortcuts; ownedScreens: ReadonlySet; /** Local playback provenance, independent of this page's capture controls. */ localScreens: ReadonlySet; @@ -112,7 +113,7 @@ export interface ChannelActions { watchEmbed(roomId: string): WatchMedia | undefined; prepareWatchPage(roomId: string, url: string, activityId?: string, reportError?: boolean): Promise; watchPage(roomId: string, activityId?: string): { url: string; candidates: readonly NativePageCandidate[]; activityId?: string; watchSources?: WatchMediaSources } | undefined; - selectWatchPage(roomId: string, candidateId: string, activityId?: string, reportError?: boolean, mode?: "choose-source"): Promise; + selectWatchPage(roomId: string, candidateId: string, activityId?: string, reportError?: boolean, mode?: "choose-source" | "original-page"): Promise; selectWatchBrowserSource(roomId: string, choiceId: string | null, reportError?: boolean): Promise; focusWatch(id: string): Promise; focusWatchPage(roomId: string, activityId?: string): Promise; diff --git a/src/client/channel/use-background-voice-shortcuts.ts b/src/client/channel/use-background-voice-shortcuts.ts new file mode 100644 index 000000000..0d0f90791 --- /dev/null +++ b/src/client/channel/use-background-voice-shortcuts.ts @@ -0,0 +1,67 @@ +import { useEffect, useEffectEvent, useLayoutEffect, useMemo, useRef, useState } from "react"; +import type { NativeVoiceShortcutsReport } from "../native/wire"; +import type { BackgroundVoiceShortcuts } from "./app-link"; +import type { VoiceShortcutAction, VoiceShortcuts } from "./voice-shortcut-binding"; + +const unbound: VoiceShortcuts = { microphone: null, listening: null }; + +export function useBackgroundVoiceShortcuts(port: BackgroundVoiceShortcuts | undefined, bindings: VoiceShortcuts, + roomId: string | undefined, recording: boolean, onShortcut: (action: VoiceShortcutAction) => void) { + const [claim, setClaim] = useState(); + const [lifecycle, setLifecycle] = useState({ frozen: false }); + const awaitingResume = useRef(false); + const enabled = Boolean(port && claim === port); + // A new Dock target waits for an ordered App reply before accepting actions. + const request = useMemo(() => ({ port, enabled, bindings: recording ? unbound : bindings, lifecycle, roomId }), + [port, enabled, bindings, recording, lifecycle, roomId]); + const [response, setResponse] = useState<{ request: typeof request; report?: NativeVoiceShortcutsReport; error?: "in_use" | "failed" }>(); + const current = enabled && response?.request === request ? response : undefined; + const report = current?.report; + const onNativeShortcut = useEffectEvent((action: VoiceShortcutAction) => { + if (!awaitingResume.current && !recording && report?.[action] === "registered") onShortcut(action); + }); + + useEffect(() => { + if (claim && claim !== port) setClaim(undefined); + }, [claim, port]); + + useLayoutEffect(() => { + if (!port || !enabled) return; + const suspend = () => { + awaitingResume.current = true; + setLifecycle({ frozen: true }); + void port.configure(null).catch(() => {}); + }; + const resume = () => setLifecycle({ frozen: false }); + const unsubscribe = port.subscribe(action => onNativeShortcut(action)); + document.addEventListener("freeze", suspend); + document.addEventListener("resume", resume); + return () => { + unsubscribe(); + document.removeEventListener("freeze", suspend); + document.removeEventListener("resume", resume); + void port.configure(null).catch(() => {}); + }; + }, [port, enabled]); + + useLayoutEffect(() => { + if (!request.port || !request.enabled || request.lifecycle.frozen) return; + let live = true; + void request.port.configure(request.bindings).then(result => { + if (!live) return; + awaitingResume.current = false; + setResponse({ request, report: result }); + }, error => { + if (!live) return; + setResponse({ request, error: error instanceof Error && error.message === "voice_shortcuts_in_use" ? "in_use" : "failed" }); + }); + return () => { live = false; }; + }, [request]); + + const enable = (value: boolean) => { + if (value) setLifecycle({ frozen: false }); + setClaim(value ? port : undefined); + }; + return { available: Boolean(port), enabled, enable, + report, error: current?.error, pending: enabled && !current, recordReady: !enabled || Boolean(report) || current?.error === "in_use" }; +} diff --git a/src/client/channel/use-voice-shortcuts.ts b/src/client/channel/use-voice-shortcuts.ts new file mode 100644 index 000000000..6419fb6c4 --- /dev/null +++ b/src/client/channel/use-voice-shortcuts.ts @@ -0,0 +1,50 @@ +import { useEffect, useEffectEvent, useState } from "react"; +import { readRoomPreferences, saveRoomPreferences } from "../lib/room-preferences"; +import { useSurfaceDocument } from "../ui/panel-window"; +import type { BackgroundVoiceShortcuts } from "./app-link"; +import { useBackgroundVoiceShortcuts } from "./use-background-voice-shortcuts"; +import { + ignoresVoiceShortcutKey, matchesVoiceShortcut, voiceShortcutActions, voiceShortcutDefaults, + voiceShortcutFromEvent, type VoiceShortcutAction, type VoiceShortcuts, +} from "./voice-shortcut-binding"; + +function ownsKeyboard(target: EventTarget): boolean { + // The tool window has its own DOM realm. + const element = target as HTMLElement; + return element.nodeType === 1 && (element.isContentEditable + || Boolean(element.closest("input, textarea, select, .lr-remote-input-surface, .lr-remote-keyboard, [data-voice-shortcut-recording]"))); +} + +export function useVoiceShortcuts(roomId: string | undefined, toggle: (action: VoiceShortcutAction) => boolean, native?: BackgroundVoiceShortcuts) { + const surface = useSurfaceDocument(); + const mac = typeof navigator !== "undefined" && navigator.platform.startsWith("Mac"); + const [bindings, setBindings] = useState(() => ({ + ...voiceShortcutDefaults(mac), ...readRoomPreferences().voiceShortcuts, + })); + const [recording, setRecording] = useState(null); + const background = useBackgroundVoiceShortcuts(roomId ? native : undefined, bindings, roomId, Boolean(recording), action => { + const focused = surface?.hasFocus() ? surface : document.hasFocus() ? document : null; + if (!focused?.activeElement || !ownsKeyboard(focused.activeElement)) toggle(action); + }); + const save = (next: Partial) => { + const updated = { ...bindings, ...next }; + saveRoomPreferences({ voiceShortcuts: updated }); + setBindings(updated); + }; + const onShortcut = useEffectEvent((event: KeyboardEvent) => { + if (recording || event.defaultPrevented || event.repeat || ignoresVoiceShortcutKey(event)) return; + if (event.composedPath().some(ownsKeyboard)) return; + const binding = voiceShortcutFromEvent(event); + if (!binding) return; + const action = voiceShortcutActions.find(action => matchesVoiceShortcut(bindings[action], binding)); + if (action && background.report?.[action] !== "registered" && toggle(action)) event.preventDefault(); + }); + useEffect(() => { + if (!roomId || !surface) return; + const owners = new Set([document, surface]); + const keydown = (event: KeyboardEvent) => onShortcut(event); + owners.forEach(owner => owner.addEventListener("keydown", keydown)); + return () => owners.forEach(owner => owner.removeEventListener("keydown", keydown)); + }, [roomId, surface]); + return { bindings, mac, save, reset: () => save(voiceShortcutDefaults(mac)), recording, setRecording, background }; +} diff --git a/src/client/channel/voice-dock-controls.ts b/src/client/channel/voice-dock-controls.ts new file mode 100644 index 000000000..aada3477e --- /dev/null +++ b/src/client/channel/voice-dock-controls.ts @@ -0,0 +1,17 @@ +import type { ChannelController } from "./types"; +import type { VoiceShortcutAction } from "./voice-shortcut-binding"; + +export function resolveVoiceDockControls(channel: ChannelController, selected: string) { + const joined = channel.state?.voice.filter(value => value.sessionId === channel.sessionId) ?? []; + const activity = joined.find(value => value.roomId === selected) ?? joined[0]; + const microphoneDisabled = Boolean(activity?.muted && !channel.canUnmute(activity.roomId)); + const toggle = (action: VoiceShortcutAction): boolean => { + if (!activity) return false; + const { roomId, muted, deafened } = activity; + if (action === "microphone" && muted && !channel.canUnmute(roomId)) return false; + const operation = action === "microphone" ? channel.setMuted(roomId, !muted) : channel.setDeafened(roomId, !deafened); + void operation.catch(() => {}); + return true; + }; + return { joined, activity, microphoneDisabled, toggle }; +} diff --git a/src/client/channel/voice-shortcut-binding.ts b/src/client/channel/voice-shortcut-binding.ts new file mode 100644 index 000000000..85ababdde --- /dev/null +++ b/src/client/channel/voice-shortcut-binding.ts @@ -0,0 +1,50 @@ +import { z } from "zod"; + +export const voiceShortcutActions = ["microphone", "listening"] as const; +export type VoiceShortcutAction = typeof voiceShortcutActions[number]; + +export const voiceShortcutBindingSchema = z.object({ + key: z.string().regex(/^(?:[A-Z0-9]|F(?:[1-9]|10|11))$/), + ctrl: z.boolean(), + alt: z.boolean(), + shift: z.boolean(), + meta: z.boolean(), +}).refine(({ ctrl, alt, meta }) => ctrl || alt || meta); + +export type VoiceShortcutBinding = z.infer; +export type VoiceShortcuts = Record; + +export function voiceShortcutDefaults(mac: boolean): VoiceShortcuts { + const modifiers = { ctrl: !mac, alt: false, shift: true, meta: mac }; + return { microphone: { ...modifiers, key: "M" }, listening: { ...modifiers, key: "D" } }; +} + +export function ignoresVoiceShortcutKey(event: KeyboardEvent): boolean { + return event.isComposing || event.keyCode === 229 || event.getModifierState("AltGraph"); +} + +export function voiceShortcutFromEvent(event: KeyboardEvent): VoiceShortcutBinding | null { + // Use the logical letter so the binding follows the user's keyboard layout. + const result = voiceShortcutBindingSchema.safeParse({ + key: event.key.toUpperCase(), ctrl: event.ctrlKey, alt: event.altKey, shift: event.shiftKey, meta: event.metaKey, + }); + return result.success ? result.data : null; +} + +export function matchesVoiceShortcut(binding: VoiceShortcutBinding | null, candidate: VoiceShortcutBinding): boolean { + return binding?.key === candidate.key && binding.ctrl === candidate.ctrl && binding.alt === candidate.alt + && binding.shift === candidate.shift && binding.meta === candidate.meta; +} + +export function voiceShortcutLabel(binding: VoiceShortcutBinding, mac: boolean): string { + return [ + binding.ctrl && "Ctrl", binding.alt && (mac ? "Option" : "Alt"), binding.shift && "Shift", + binding.meta && (mac ? "⌘" : "Meta"), binding.key, + ].filter(Boolean).join(" + "); +} + +export function voiceShortcutAria(binding: VoiceShortcutBinding | null): string | undefined { + if (!binding) return undefined; + return [binding.ctrl && "Control", binding.alt && "Alt", binding.shift && "Shift", binding.meta && "Meta", binding.key] + .filter(Boolean).join("+"); +} diff --git a/src/client/channel/watch-page-media.ts b/src/client/channel/watch-page-media.ts index 74f1dbbfd..46b006b45 100644 --- a/src/client/channel/watch-page-media.ts +++ b/src/client/channel/watch-page-media.ts @@ -3,12 +3,16 @@ import type { NativePageMediaChoice, NativePageIndexedCandidate, NativePageMpdCa import { inspectIndexedTrack, type IndexedTrackInspection } from "./watch-indexed-source"; import { limitWatchReads } from "./watch-resource"; import { HTMLVideoMedia, createResourceWatchMedia, type WatchMedia, type WatchMediaEvent, type WatchMediaPatch, type WatchMediaState } from "./watch-media"; -import type { WatchByteSource, WatchFormat, WatchTimeline } from "./protocol"; +import { watchSourceSchema, type WatchByteSource, type WatchFormat, type WatchTimeline } from "./protocol"; export interface WatchIndexedChoice { candidate: NativePageIndexedCandidate; inspection?: IndexedTrackInspection; error?: string } export interface WatchMpdChoice { candidate: NativePageMpdCandidate; catalog?: NativePageMpdCatalog; error?: string } export interface WatchMediaSources { choices: readonly NativePageMediaChoice[]; indexed: readonly WatchIndexedChoice[]; mpd: readonly WatchMpdChoice[]; error?: string } +export function directForwardFileURL(choice: NativePageMediaChoice): string | undefined { + if (choice.format === "file" && watchSourceSchema.safeParse({ kind: "media", url: choice.displayURL }).success) return choice.displayURL; +} + /** One page observation owns its resource cache, reads and listener retirement. */ export function observeWatchSources(page: AppPage, lifetime: AbortSignal, publish: (sources: WatchMediaSources) => void): { ready: Promise; unsubscribe(): void } { const controller = new AbortController(), signal = AbortSignal.any([lifetime, controller.signal]); diff --git a/src/client/channel/watch-youtube-source.ts b/src/client/channel/watch-youtube-source.ts index 65b77f206..f83913bc9 100644 --- a/src/client/channel/watch-youtube-source.ts +++ b/src/client/channel/watch-youtube-source.ts @@ -52,7 +52,8 @@ export function youtubeSourceId(source: { kind: string; url: string }): string | } export function canWatchInBrowser(source: WatchSource, current?: Pick): boolean { - if (!youtubeSourceId(source)) return source.kind === "media" || !!source.mediaUrl; + if (source.kind === "media" || source.mediaUrl) return true; + if (!youtubeSourceId(source)) return false; const replacingPage = current?.presentation.kind === "external" && current.mode === "direct"; return !replacingPage || canMoveYouTubePlayer(); } diff --git a/src/client/components/living/AppConnectionButton.tsx b/src/client/components/living/AppConnectionButton.tsx index ba3b1f070..6046a752b 100644 --- a/src/client/components/living/AppConnectionButton.tsx +++ b/src/client/components/living/AppConnectionButton.tsx @@ -17,6 +17,8 @@ import { channelAppDiscovery } from "../../channel/app-link"; import { OpenInClient } from "./OpenInClient"; import { currentTheme, subscribeTheme } from "../../ui/theme"; import type {} from "../../ui/native-window"; +import { diagnoseChannelFact, type AppConnectionState } from "../../channel/diagnosis"; +import { ChannelDiagnosisHelp } from "../../channel/components/ChannelDiagnosisHelp"; interface AppConnectionProps { onConnected?: (health: NonNullable>>, signal: AbortSignal) => void | Promise; @@ -40,7 +42,7 @@ interface ConnectionAttempt { export function AppConnectionButton({ onConnected, discovery = channelAppDiscovery, connected, available = true, targetURL, wakeURL: launchTarget }: AppConnectionProps) { const { lang, t } = useCopy(); const theme = useSyncExternalStore(subscribeTheme, currentTheme, currentTheme); - const [state, setState] = useState<"idle" | "waking" | "busy" | "approval" | "approving" | "ready" | "unavailable" | "incompatible">("idle"); + const [state, setState] = useState("idle"); const wakeURL = launchTarget === undefined ? androidAppIntent("piik://app") : launchTarget; const [helpOpen, setHelpOpen] = useState(false); const downloadURL = useProjectLink("/#download", "https://github.com/TNTcraftHIM/Piik/releases/latest", helpOpen); @@ -264,6 +266,7 @@ export function AppConnectionButton({ onConnected, discovery = channelAppDiscove incompatible: "native.incompatible", } as const)[state]); const failed = state === "unavailable" || state === "incompatible"; + const diagnosis = diagnoseChannelFact({ area: "app", state }); const update = ready ? release : null; const availableUpdate = update?.kind === "update-available" || update?.kind === "major-update"; const title = availableUpdate ? t("client.connect.update", { current: build!.version, version: update.version }) : label; @@ -306,15 +309,15 @@ export function AppConnectionButton({ onConnected, discovery = channelAppDiscove
-

{state === "busy" ? t("client.connect.permissionHint") : label}

+

{state === "busy" ? t("client.connect.permissionHint") : diagnosis ? t(diagnosis.message) : label}

{state === "ready" && build &&

{t("client.launch.version", { version: build.version })}

} {update && }
- {!ready && state !== "busy" && state !== "approving" && } {failed && wakeURL && { event.preventDefault(); void connect(true); }}> {t("client.connect.wakeApp")} @@ -323,6 +326,7 @@ export function AppConnectionButton({ onConnected, discovery = channelAppDiscove {t("client.connect.download")} }
+ {helpOpen && diagnosis && } {targetURL && !(typeof window !== "undefined" && window.piikNativeWindow) && } {state !== "ready" &&

{t("client.connect.browserHint")}

} diff --git a/src/client/components/living/FloatingPanel.tsx b/src/client/components/living/FloatingPanel.tsx index bfd20f047..45be63a20 100644 --- a/src/client/components/living/FloatingPanel.tsx +++ b/src/client/components/living/FloatingPanel.tsx @@ -3,6 +3,7 @@ import { useLayoutEffect, useRef, useState, type PointerEvent, type ReactNode, t import { createPortal } from "react-dom"; import { useCopy } from "../../ui/copy"; import { Glyph } from "../../ui/icons"; +import { surfaceViewport } from "../../ui/window-appearance"; import { usePanelWindow, panelWindowAPI, SurfaceDocument, PANEL_SIZE } from "../../ui/panel-window"; import { Btn } from "./primitives"; import "./floating-panel.css"; @@ -143,10 +144,9 @@ export function FloatingPanel({ id, trigger, title, compact = false, anchorOnOpe // Native hiding/adoption can precede React's effect cleanup. Only this // document's visible panel can update its remembered in-page position. if (panel.ownerDocument !== document || !panel.matches(":popover-open")) return; - const layout = document.documentElement; - const width = viewport?.width ?? layout.clientWidth, height = viewport?.height ?? layout.clientHeight; - const maxWidth = Math.max(0, width - 24), maxHeight = Math.max(0, height - 24); - const left = (viewport?.offsetLeft ?? 0) + 12, top = (viewport?.offsetTop ?? 0) + 12; + const bounds = surfaceViewport(panel.ownerDocument); + const maxWidth = Math.max(0, bounds.width - 24), maxHeight = Math.max(0, bounds.height - 24); + const left = bounds.left + 12, top = bounds.top + 12; let point = change && "x" in change ? change : undefined; if (change && "corner" in change) { const { rect, corner, dx, dy } = change; @@ -180,8 +180,7 @@ export function FloatingPanel({ id, trigger, title, compact = false, anchorOnOpe // movement owner. Retargeting an open palette must not undo a user's drag. const anchor = anchorOnOpen && getTrigger()?.getBoundingClientRect(); if (anchor) { - const top = (viewport?.offsetTop ?? 0) + 12; - const bottom = top + (viewport?.height ?? document.documentElement.clientHeight) - 24; + const bottom = surfaceViewport(panel.ownerDocument).bottom - 12; const below = anchor.bottom + 8; place({ x: anchor.x + anchor.width / 2 - panel.offsetWidth / 2, y: below + panel.offsetHeight <= bottom ? below : anchor.top - panel.offsetHeight - 8 }); @@ -189,6 +188,7 @@ export function FloatingPanel({ id, trigger, title, compact = false, anchorOnOpe viewport?.addEventListener("resize", resize); viewport?.addEventListener("scroll", resize); window.addEventListener("resize", resize); + document.addEventListener("fullscreenchange", resize); // Content changes keep the chosen top-left corner; viewport changes above // retain relative placement. Both still constrain the panel to the viewport. const observer = new ResizeObserver(() => place({ x: panel.offsetLeft, y: panel.offsetTop })); @@ -199,6 +199,7 @@ export function FloatingPanel({ id, trigger, title, compact = false, anchorOnOpe viewport?.removeEventListener("resize", resize); viewport?.removeEventListener("scroll", resize); window.removeEventListener("resize", resize); + document.removeEventListener("fullscreenchange", resize); observer.disconnect(); }; }, [open, trigger, compact, anchorOnOpen, detached]); diff --git a/src/client/components/living/Header.tsx b/src/client/components/living/Header.tsx index 5a0fe3493..7668554d8 100644 --- a/src/client/components/living/Header.tsx +++ b/src/client/components/living/Header.tsx @@ -10,7 +10,7 @@ import { applyTheme, currentTheme, subscribeTheme } from "../../ui/theme"; import { Glyph } from "../../ui/icons"; import { AppConnectionButton } from "./AppConnectionButton"; import { useAnchoredPopover } from "./use-anchored-popover"; -import { useProjectLink } from "../../lib/use-project-link"; +import { diagnosisGuide } from "../../channel/diagnosis"; import { Btn } from "./primitives"; export type LedState = "live" | "busy" | "warn" | "bad" | "off"; @@ -85,8 +85,7 @@ const webRelease = /^v\d+\.\d+\.\d+$/.test(webVersion) function BrowserHelpContent({ active, diagnosticControl }: { active: boolean; diagnosticControl?: React.ReactNode }) { const { lang, t } = useCopy(); - const guide = useProjectLink(`/docs/${lang === "zh" ? "zh/" : ""}troubleshooting.html`, - `https://github.com/TNTcraftHIM/Piik/blob/main/docs/guide/troubleshooting${lang === "zh" ? ".zh-CN" : ""}.md`, active); + const guide = diagnosisGuide("troubleshooting", lang).fallback; return
Piik Web {webRelease ? ("idle"); const copyRequest = useRef(null); const hint = (status.tooltip ?? status.comic)!; - const guide = useProjectLink(`/docs/${lang === "zh" ? "zh/" : ""}troubleshooting.html`, - `https://github.com/TNTcraftHIM/Piik/blob/main/docs/guide/troubleshooting${lang === "zh" ? ".zh-CN" : ""}.md`, open); + const guide = diagnosisGuide("troubleshooting", lang).fallback; return <> { copyRequest.current = null; diff --git a/src/client/components/living/SiteManagement.tsx b/src/client/components/living/SiteManagement.tsx index f704cb6b6..16b59cf99 100644 --- a/src/client/components/living/SiteManagement.tsx +++ b/src/client/components/living/SiteManagement.tsx @@ -2,7 +2,7 @@ import { useId, useLayoutEffect, useRef, useState } from "react"; import { BackButton, Btn, Pill } from "./primitives"; import { Glyph } from "../../ui/icons"; import { useCopy, type CopyKey } from "../../ui/copy"; -import { siteEntryURL } from "../../lib/site-address"; +import { siteEntryError, siteEntryURL } from "../../lib/site-address"; import { isStartupSite, type AppMode } from "../../lib/app-launch"; import type { SiteBookmark } from "../../lib/site-address"; import "./site-management.css"; @@ -76,7 +76,7 @@ export function SiteManagement({ bookmarks, sites, currentOrigin, startupSite, o } setDetail(undefined); } catch (error) { - setBookmarkError(error instanceof Error && error.message === "bookmark_exists" ? "client.bookmarks.duplicate" : "client.connect.saveFailed"); + setBookmarkError(error instanceof Error && error.message === "bookmark_exists" ? "client.bookmarks.duplicate" : siteEntryError(error instanceof Error && error.message) ?? "client.connect.saveFailed"); } finally { setPending(undefined); } } // Device-operation failures belong to the caller's accessError. diff --git a/src/client/components/living/primitives.tsx b/src/client/components/living/primitives.tsx index bcecc661e..5195fab62 100644 --- a/src/client/components/living/primitives.tsx +++ b/src/client/components/living/primitives.tsx @@ -56,6 +56,7 @@ export function Btn({ pressed, expanded, hasPopup, + keyShortcuts, controls, popoverTarget, onClick, @@ -87,6 +88,7 @@ export function Btn({ hasPopup?: AriaAttributes["aria-haspopup"]; controls?: string; popoverTarget?: string; + keyShortcuts?: string; onClick?: () => void; type?: "button" | "submit"; /** Shared hint comic with its localized caption. */ @@ -123,6 +125,7 @@ export function Btn({ aria-pressed={pressed} aria-expanded={expanded} aria-haspopup={hasPopup} + aria-keyshortcuts={keyShortcuts} aria-controls={controls} popoverTarget={popoverTarget} style={softDisabled ? SOFT_DISABLED_STYLE : undefined} diff --git a/src/client/lib/room-preferences.ts b/src/client/lib/room-preferences.ts index 7e00d88e4..70051fdad 100644 --- a/src/client/lib/room-preferences.ts +++ b/src/client/lib/room-preferences.ts @@ -2,6 +2,7 @@ import { z } from "zod"; import { MAX_RELAY_CAPACITY } from "../../shared/relay-capacity"; import { remoteControlModeSchema, remoteShortcutKeySchema } from "../remote-control/protocol"; import { feedbackClipSchema } from "../channel/feedback-clip"; +import { voiceShortcutBindingSchema } from "../channel/voice-shortcut-binding"; const STORAGE_KEY = "piik:room-preferences:v1"; export const CHAT_OVERLAY_LIMITS = { scale: [.8, 1.3], opacity: [.4, 1], speed: [.5, 1.5] } as const; @@ -34,6 +35,10 @@ const roomPreferencesSchema = z.object({ voiceInput: z.object({ deviceId: z.string(), volume: z.number().min(0).max(2), voiceProcessing: z.boolean(), strongerSuppression: z.boolean().optional() }) .default({ deviceId: "", volume: 1, voiceProcessing: true }), voiceListeningVolume: z.number().min(0).max(2).default(1), + voiceShortcuts: z.object({ + microphone: voiceShortcutBindingSchema.nullable().optional(), + listening: voiceShortcutBindingSchema.nullable().optional(), + }).catch({}).default({}), keyboardPage: z.enum(REMOTE_KEYBOARD_PAGES).default("letters"), combineKeys: z.boolean().default(false), remoteReleaseKey: remoteShortcutKeySchema.default(10), diff --git a/src/client/lib/site-address.ts b/src/client/lib/site-address.ts index cc2f88865..cc89beb74 100644 --- a/src/client/lib/site-address.ts +++ b/src/client/lib/site-address.ts @@ -15,3 +15,18 @@ export function publicSiteOrigin(value: string): string | null { const url = siteEntryURL(value); return url?.protocol === "https:" && url.pathname === "/" && !url.search && !url.hash ? url.origin : null; } + +export function siteEntryError(reason: unknown) { + if (reason === "not_piik_site") return "client.bookmarks.notPiik" as const; + if (reason === "site_unavailable") return "client.bookmarks.unavailable" as const; + return undefined; +} + +export async function openLauncherSite(url: string): Promise { + const response = await fetch("/api/client-launcher/open", { + method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ url }), + }); + const result = await response.json(); + if (!response.ok || typeof result.opened !== "boolean") throw new Error(result.detail); + if (!result.opened) location.assign(url); +} diff --git a/src/client/locales/en.ts b/src/client/locales/en.ts index bfcf5467d..2f9e2b8c0 100644 --- a/src/client/locales/en.ts +++ b/src/client/locales/en.ts @@ -37,6 +37,8 @@ export const en: Record = { "watch.forward.prepare": "Choose video to forward", "watch.forward.choose": "Choose the original video resource. Confirming starts using this device’s upload bandwidth.", "watch.forward.enableNamed": "Forward {name}", + "watch.forward.shareFile": "Share this video", + "watch.forward.shareFileHelp": "Viewers get the video link and try the site first. If playback fails, they can receive it from your App.", "watch.forward.none": "No video resource is available to forward on this webpage yet.", "watch.forward.peer": "Receive from sharer", "watch.forward.direct": "Play directly from website", @@ -567,7 +569,12 @@ export const en: Record = { "channel.error.backupRoomMismatch": "Choose a backup for this site and room.", "channel.error.restoreScratchLimit": "The server needs more temporary disk space to restore this room. Ask the site operator to free space, then try again.", "channel.error.backupRoomNotAdmitted": "This site no longer admits the room ID in this backup. Create a new room, or load a room copy if you have one.", - "channel.error.unsupportedStorageVersion": "This room was saved in a different storage format. Open it with the Piik version that saved it.", + "channel.error.unsupportedStorageVersion": "This test data uses an incompatible storage format. Follow the current test package instructions to reset the affected data, then try again.", + "diagnosis.guide": "See the troubleshooting guide", + "diagnosis.details": "Diagnostic details", + "diagnosis.roomAdmitted": "You have joined the room.", + "diagnosis.sourcePageOpen": "The original webpage is still available.", + "diagnosis.noPicture": "No picture has arrived for this share.", "channel.error.unsupportedBackupVersion": "This backup format is not supported. Open it with the version that exported it.", "channel.error.invalidRoomCopy": "This room copy is invalid. Export it again.", "channel.error.appDisconnected": "Connection to the App was lost. Check that it is running, then retry.", @@ -736,6 +743,24 @@ export const en: Record = { "remote.preferredStopKey": "Preferred shortcut", "remote.preferredStopKeyHelp": "Sent to system approval. Use the confirmed stop shortcut shown below.", "remote.shortcutUnbound": "Set when you enable control", + "voice.shortcuts.title": "Keyboard shortcuts", + "voice.shortcuts.scope": "Available while this Piik page or room tool has focus.", + "voice.shortcuts.reset": "Restore default voice shortcuts", + "voice.shortcuts.unbound": "Unassigned", + "voice.shortcuts.edit": "Change {action} shortcut ({shortcut})", + "voice.shortcuts.clear": "Clear {action} shortcut", + "voice.shortcuts.record": "Press a shortcut. Esc cancels.", + "voice.shortcuts.unsupported": "Choose a letter, number or F1–F11 with Ctrl, Alt or Command.", + "voice.shortcuts.duplicate": "This shortcut is already assigned to the other voice action.", + "voice.shortcuts.background": "Allow shortcuts in other apps", + "voice.shortcuts.backgroundPending": "Requesting Windows shortcuts…", + "voice.shortcuts.backgroundEnabled": "Available in other apps for the shortcuts marked below.", + "voice.shortcuts.backgroundInUse": "Another Piik page is using background shortcuts. Turn them off there to enable them here.", + "voice.shortcuts.backgroundFailed": "Couldn’t enable Windows shortcuts. Page shortcuts are still available.", + "voice.shortcuts.backgroundPausing": "Releasing the Windows shortcuts…", + "voice.shortcuts.backgroundPauseFailed": "Turn off background shortcuts to record this key.", + "voice.shortcuts.backgroundBindingRegistered": "Available in other apps", + "voice.shortcuts.backgroundBindingUnavailable": "Windows couldn’t use this shortcut. It still works in this Piik page or room tool.", "remote.hostStopKeyHelp": "Stops control from any app on this computer. Saved for this site.", "remote.releaseKey": "Exit control shortcut", "remote.releaseKeyHelp": "Ends your control from this page or its detached keyboard. Saved in this browser.", @@ -928,6 +953,8 @@ export const en: Record = { "client.bookmarks.switchHint": "Leaving the current site ends that page's voice, sharing and watching. App-hosted rooms keep running.", "client.bookmarks.switchConfirm": "Open", "client.bookmarks.openFailed": "Could not open the site. Try again.", + "client.bookmarks.notPiik": "This address didn’t return a Piik site identifier.", + "client.bookmarks.unavailable": "Couldn’t verify the site. Check the address and connection, then try again.", "client.bookmarks.invalidAddress": "Enter an HTTP or HTTPS site address.", "client.connect.siteAddress": "Site address", "client.connect.continue": "Continue", diff --git a/src/client/locales/ja.ts b/src/client/locales/ja.ts index 7423f5c8e..e3193a892 100644 --- a/src/client/locales/ja.ts +++ b/src/client/locales/ja.ts @@ -19,6 +19,8 @@ export const ja = { "watch.forward.prepare": "転送する動画を選択", "watch.forward.choose": "元の動画リソースを選択してください。確認後、アップロード帯域を使用します。", "watch.forward.enableNamed": "「{name}」を転送", + "watch.forward.shareFile": "この動画を共有", + "watch.forward.shareFileHelp": "視聴者には動画リンクが届き、まずサイトから再生します。再生できない場合は、あなたのアプリから受信できます。", "watch.forward.none": "このページでは転送できる動画がまだ見つかりません。", "watch.forward.peer": "共有者から受信", "watch.forward.direct": "サイトから直接再生", @@ -444,7 +446,12 @@ export const ja = { "channel.error.backupIdentityRequired": "このサイトでバックアップのアカウントを確認できませんでした。", "channel.error.backupRoomMismatch": "このサイトとルームのバックアップを選択してください。", "channel.error.backupRoomNotAdmitted": "このサイトではバックアップ内のルーム ID を復元できません。新しいルームを作成するか、ルームのコピーがあれば読み込んでください。", - "channel.error.unsupportedStorageVersion": "このルームは別の保存形式を使用しています。保存したときの Piik バージョンで開いてください。", + "channel.error.unsupportedStorageVersion": "このテストデータの保存形式には互換性がありません。現在のテスト版の手順に沿って該当するデータをリセットし、もう一度お試しください。", + "diagnosis.guide": "トラブルシューティングを見る", + "diagnosis.details": "診断の詳細", + "diagnosis.roomAdmitted": "ルームに参加済みです。", + "diagnosis.sourcePageOpen": "開いている元のページに戻れます。", + "diagnosis.noPicture": "この共有の映像はまだ届いていません。", "channel.error.unsupportedBackupVersion": "このバックアップ形式はサポートされていません。書き出したバージョンで開いてください。", "channel.error.invalidRoomCopy": "ルームのコピーが無効です。書き出し直してください。", "channel.error.appDisconnected": "App との接続が切れました。起動していることを確認し、再試行してください。", @@ -607,6 +614,24 @@ export const ja = { "remote.preferredStopKey": "希望するショートカット", "remote.preferredStopKeyHelp": "システムの承認に送信します。下に表示される確定済みの停止ショートカットを使用してください。", "remote.shortcutUnbound": "操作を有効にすると設定されます", + "voice.shortcuts.title": "キーボードショートカット", + "voice.shortcuts.scope": "Piik のページまたはルームツールにフォーカスがあるときに使えます。", + "voice.shortcuts.reset": "通話ショートカットを初期設定に戻す", + "voice.shortcuts.unbound": "未設定", + "voice.shortcuts.edit": "{action}のショートカットを変更({shortcut})", + "voice.shortcuts.clear": "{action}のショートカットを解除", + "voice.shortcuts.record": "ショートカットを押してください。Esc でキャンセルできます。", + "voice.shortcuts.unsupported": "Ctrl、Alt、Command のいずれかを英字、数字、F1〜F11 と組み合わせてください。", + "voice.shortcuts.duplicate": "このキーは別の通話操作に割り当てられています。", + "voice.shortcuts.background": "他のアプリでもショートカットを使う", + "voice.shortcuts.backgroundPending": "Windows にショートカットを登録中…", + "voice.shortcuts.backgroundEnabled": "以下の対象ショートカットは他のアプリでも使えます。", + "voice.shortcuts.backgroundInUse": "別の Piik ページがバックグラウンドのショートカットを使用中です。そのページで無効にしてから、ここで有効にしてください。", + "voice.shortcuts.backgroundFailed": "Windows に登録できませんでした。ページ内のショートカットは引き続き使えます。", + "voice.shortcuts.backgroundPausing": "Windows のショートカット登録を一時解除中…", + "voice.shortcuts.backgroundPauseFailed": "このキーを設定するには、バックグラウンドのショートカットを無効にしてください。", + "voice.shortcuts.backgroundBindingRegistered": "他のアプリでも使用可能", + "voice.shortcuts.backgroundBindingUnavailable": "Windows に登録できませんでした。Piik のページやルームツールでは引き続き使えます。", "remote.hostStopKeyHelp": "このパソコンのどのアプリからでも操作を停止できます。このサイト用に保存します。", "remote.releaseKey": "操作終了のショートカット", "remote.releaseKeyHelp": "このページまたは切り離したキーボードから自分の操作を終了します。このブラウザーに保存します。", @@ -789,6 +814,8 @@ export const ja = { "client.bookmarks.switchHint": "現在のサイトを離れると、そのページの通話、共有、視聴は終了します。App がホストするルームは動作を続けます。", "client.bookmarks.switchConfirm": "開く", "client.bookmarks.openFailed": "サイトを開けませんでした。再試行してください。", + "client.bookmarks.notPiik": "このアドレスから Piik サイトの識別子が返されませんでした。", + "client.bookmarks.unavailable": "サイトを確認できません。アドレスと接続を確認して再試行してください。", "client.bookmarks.invalidAddress": "HTTP または HTTPS のサイトアドレスを入力してください。", "client.connect.siteAddress": "サイトのアドレス", "client.connect.continue": "続ける", diff --git a/src/client/locales/ko.ts b/src/client/locales/ko.ts index d6115559f..2e67910e1 100644 --- a/src/client/locales/ko.ts +++ b/src/client/locales/ko.ts @@ -20,6 +20,8 @@ export const ko = { "watch.forward.prepare": "전달할 동영상 선택", "watch.forward.choose": "원본 동영상 리소스를 선택하세요. 확인하면 업로드 대역폭을 사용해요.", "watch.forward.enableNamed": "{name} 전달", + "watch.forward.shareFile": "이 동영상 공유", + "watch.forward.shareFileHelp": "시청자는 동영상 링크를 받아 먼저 사이트에서 재생합니다. 재생에 실패하면 내 앱에서 받을 수 있습니다.", "watch.forward.none": "이 페이지에서 전달할 동영상 리소스를 아직 찾지 못했어요.", "watch.forward.peer": "공유자에게서 받기", "watch.forward.direct": "웹사이트에서 직접 재생", @@ -445,7 +447,12 @@ export const ko = { "channel.error.backupIdentityRequired": "이 사이트에서 백업 계정을 확인하지 못했어요.", "channel.error.backupRoomMismatch": "이 사이트와 방에 해당하는 백업을 선택하세요.", "channel.error.backupRoomNotAdmitted": "이 사이트에서는 백업에 담긴 방 ID를 복원할 수 없어요. 새 방을 만들거나 저장해 둔 방 사본을 불러오세요.", - "channel.error.unsupportedStorageVersion": "이 방은 다른 저장 형식을 사용해요. 방을 저장한 Piik 버전으로 열어 주세요.", + "channel.error.unsupportedStorageVersion": "이 테스트 데이터의 저장 형식은 호환되지 않아요. 현재 테스트 패키지 안내에 따라 해당 데이터를 초기화한 뒤 다시 시도해 주세요.", + "diagnosis.guide": "문제 해결 가이드 보기", + "diagnosis.details": "진단 세부 정보", + "diagnosis.roomAdmitted": "방에 참여했어요.", + "diagnosis.sourcePageOpen": "열려 있는 원래 웹페이지로 돌아갈 수 있어요.", + "diagnosis.noPicture": "이 공유의 화면을 아직 받지 못했어요.", "channel.error.unsupportedBackupVersion": "지원하지 않는 백업 형식이에요. 내보내기에 사용한 버전으로 여세요.", "channel.error.invalidRoomCopy": "유효하지 않은 방 사본이에요. 다시 내보내 주세요.", "channel.error.appDisconnected": "App 연결이 끊겼어요. 실행 중인지 확인하고 다시 시도하세요.", @@ -608,6 +615,24 @@ export const ko = { "remote.preferredStopKey": "사용할 단축키", "remote.preferredStopKeyHelp": "시스템 승인을 요청했어요. 아래에 표시된 확정된 중지 단축키를 사용하세요.", "remote.shortcutUnbound": "제어를 켤 때 설정", + "voice.shortcuts.title": "키보드 단축키", + "voice.shortcuts.scope": "Piik 페이지나 방 도구에 포커스가 있을 때 사용할 수 있어요.", + "voice.shortcuts.reset": "음성 단축키 기본값 복원", + "voice.shortcuts.unbound": "지정 안 됨", + "voice.shortcuts.edit": "{action} 단축키 변경 ({shortcut})", + "voice.shortcuts.clear": "{action} 단축키 지우기", + "voice.shortcuts.record": "단축키를 누르세요. Esc로 취소할 수 있어요.", + "voice.shortcuts.unsupported": "Ctrl, Alt, Command 중 하나를 영문자, 숫자 또는 F1–F11과 함께 누르세요.", + "voice.shortcuts.duplicate": "다른 음성 기능에 이미 지정된 단축키입니다.", + "voice.shortcuts.background": "다른 앱에서도 단축키 사용", + "voice.shortcuts.backgroundPending": "Windows에 단축키를 등록하는 중…", + "voice.shortcuts.backgroundEnabled": "아래에 표시된 단축키는 다른 앱에서도 사용할 수 있어요.", + "voice.shortcuts.backgroundInUse": "다른 Piik 페이지가 백그라운드 단축키를 사용 중이에요. 그 페이지에서 끈 뒤 여기에서 켜세요.", + "voice.shortcuts.backgroundFailed": "Windows 단축키를 켜지 못했어요. 페이지 안에서는 계속 사용할 수 있어요.", + "voice.shortcuts.backgroundPausing": "Windows 단축키 등록을 해제하는 중…", + "voice.shortcuts.backgroundPauseFailed": "이 키를 기록하려면 백그라운드 단축키를 끄세요.", + "voice.shortcuts.backgroundBindingRegistered": "다른 앱에서 사용 가능", + "voice.shortcuts.backgroundBindingUnavailable": "Windows에 이 단축키를 등록하지 못했어요. Piik 페이지나 방 도구에서는 계속 사용할 수 있어요.", "remote.hostStopKeyHelp": "이 컴퓨터의 어떤 앱에서든 제어를 중지해요. 이 사이트에 저장돼요.", "remote.releaseKey": "제어 종료 단축키", "remote.releaseKeyHelp": "이 페이지나 분리된 키보드에서 내 제어를 종료해요. 이 브라우저에 저장돼요.", @@ -792,6 +817,8 @@ export const ko = { "client.bookmarks.switchHint": "현재 사이트를 떠나면 해당 페이지의 음성, 공유, 시청이 종료돼요. App에서 호스팅하는 방은 계속 실행돼요.", "client.bookmarks.switchConfirm": "열기", "client.bookmarks.openFailed": "사이트를 열지 못했어요. 다시 시도하세요.", + "client.bookmarks.notPiik": "이 주소에서 Piik 사이트 식별자를 찾을 수 없습니다.", + "client.bookmarks.unavailable": "사이트를 확인할 수 없습니다. 주소와 연결을 확인한 후 다시 시도하세요.", "client.bookmarks.invalidAddress": "HTTP 또는 HTTPS 사이트 주소를 입력하세요.", "client.connect.siteAddress": "사이트 주소", "client.connect.continue": "계속", diff --git a/src/client/locales/zh-Hant.ts b/src/client/locales/zh-Hant.ts index 8549274be..d5db212cc 100644 --- a/src/client/locales/zh-Hant.ts +++ b/src/client/locales/zh-Hant.ts @@ -19,6 +19,8 @@ export const zhHant = { "watch.forward.prepare": "選擇要轉發的影片", "watch.forward.choose": "選擇原始影片資源。確認後開始使用本機上傳頻寬。", "watch.forward.enableNamed": "轉發 {name}", + "watch.forward.shareFile": "分享這部影片", + "watch.forward.shareFileHelp": "觀眾會收到影片連結並優先從網站播放。播放失敗時,可以從你的 App 接收。", "watch.forward.none": "此網頁暫未發現可轉發的影片資源。", "watch.forward.peer": "從分享者接收", "watch.forward.direct": "從網站直接播放", @@ -444,7 +446,12 @@ export const zhHant = { "channel.error.backupIdentityRequired": "無法使用備份中的帳號,請確認這是你在此站點的備份。", "channel.error.backupRoomMismatch": "請選擇此站點、此房間的備份。", "channel.error.backupRoomNotAdmitted": "此站點已不接受備份中的房間 ID。你可以建立新房間,或在建立時載入已有的房間副本。", - "channel.error.unsupportedStorageVersion": "此房間使用其他版本的儲存格式。請使用儲存它的 Piik 版本開啟。", + "channel.error.unsupportedStorageVersion": "這份內測資料的格式不相容。請依目前測試套件的說明重設受影響的資料後再試一次。", + "diagnosis.guide": "查看疑難排解指南", + "diagnosis.details": "診斷詳情", + "diagnosis.roomAdmitted": "已加入房間。", + "diagnosis.sourcePageOpen": "仍可返回已開啟的原始網頁。", + "diagnosis.noPicture": "這路分享尚未收到畫面。", "channel.error.unsupportedBackupVersion": "此備份格式不受目前版本支援,請使用匯出它的版本讀取。", "channel.error.invalidRoomCopy": "房間副本無效,請重新匯出。", "channel.error.appDisconnected": "與 App 的連線已中斷。請確認 App 正在執行,然後重試。", @@ -607,6 +614,24 @@ export const zhHant = { "remote.preferredStopKey": "偏好的快速鍵", "remote.preferredStopKeyHelp": "提交給系統確認,請使用下方顯示的實際停止快速鍵。", "remote.shortcutUnbound": "啟用控制時設定", + "voice.shortcuts.title": "鍵盤快速鍵", + "voice.shortcuts.scope": "Piik 頁面或房間工具視窗取得焦點時可用。", + "voice.shortcuts.reset": "還原預設語音快速鍵", + "voice.shortcuts.unbound": "未設定", + "voice.shortcuts.edit": "變更{action}快速鍵({shortcut})", + "voice.shortcuts.clear": "清除{action}快速鍵", + "voice.shortcuts.record": "按下快速鍵,Esc 取消。", + "voice.shortcuts.unsupported": "請選擇字母、數字或 F1–F11,並搭配 Ctrl、Alt 或 Command。", + "voice.shortcuts.duplicate": "另一個語音操作已使用此快速鍵。", + "voice.shortcuts.background": "在其他應用程式中使用快速鍵", + "voice.shortcuts.backgroundPending": "正在向 Windows 註冊快速鍵…", + "voice.shortcuts.backgroundEnabled": "下方標示的快速鍵可在其他應用程式中使用。", + "voice.shortcuts.backgroundInUse": "另一個 Piik 頁面正在使用背景快速鍵。請先在該頁關閉,再於此處啟用。", + "voice.shortcuts.backgroundFailed": "無法啟用 Windows 快速鍵。頁面內的快速鍵仍可使用。", + "voice.shortcuts.backgroundPausing": "正在釋放 Windows 快速鍵…", + "voice.shortcuts.backgroundPauseFailed": "請先關閉背景快速鍵,再錄製此組合。", + "voice.shortcuts.backgroundBindingRegistered": "可在其他應用程式中使用", + "voice.shortcuts.backgroundBindingUnavailable": "Windows 無法註冊此快速鍵。在 Piik 頁面或房間工具視窗中仍可使用。", "remote.hostStopKeyHelp": "在本機任何應用程式中按下即可停止控制,設定儲存在目前站點。", "remote.releaseKey": "退出控制快速鍵", "remote.releaseKeyHelp": "在目前頁面或獨立鍵盤視窗中退出控制,由目前瀏覽器儲存。", @@ -789,6 +814,8 @@ export const zhHant = { "client.bookmarks.switchHint": "如果離開目前站點,該頁面的語音、共享和觀看會結束。App 托管的房間繼續執行。", "client.bookmarks.switchConfirm": "開啟", "client.bookmarks.openFailed": "未能開啟站點,請重試。", + "client.bookmarks.notPiik": "這個位址沒有傳回 Piik 站點識別碼。", + "client.bookmarks.unavailable": "暫時無法驗證站點。請檢查位址和網路後再試。", "client.bookmarks.invalidAddress": "請輸入 HTTP 或 HTTPS 站點網址。", "client.connect.siteAddress": "站點網址", "client.connect.continue": "繼續", diff --git a/src/client/locales/zh.ts b/src/client/locales/zh.ts index 4713e17af..1553af6ed 100644 --- a/src/client/locales/zh.ts +++ b/src/client/locales/zh.ts @@ -35,6 +35,8 @@ export const zh = { "watch.forward.prepare": "选择要转发的视频", "watch.forward.choose": "选择原始视频资源。确认后开始使用本机上传带宽。", "watch.forward.enableNamed": "转发 {name}", + "watch.forward.shareFile": "分享这个视频", + "watch.forward.shareFileHelp": "观众会收到视频链接并优先从网站播放。播放失败时,可以从你的 App 接收。", "watch.forward.none": "此网页暂未发现可转发的视频资源。", "watch.forward.peer": "从分享者接收", "watch.forward.direct": "从网站直接播放", @@ -565,7 +567,12 @@ export const zh = { "channel.error.backupRoomMismatch": "请选择此站点、此房间的备份。", "channel.error.restoreScratchLimit": "服务器的临时空间不足。请让站点管理员腾出空间,再恢复房间。", "channel.error.backupRoomNotAdmitted": "此站点已不接受备份中的房间 ID。你可以新建房间,或在创建时载入已有的房间副本。", - "channel.error.unsupportedStorageVersion": "此房间使用其他版本的存储格式。请使用保存它的 Piik 版本打开。", + "channel.error.unsupportedStorageVersion": "这份内测数据的格式不兼容。请按当前测试包的说明重置受影响的数据后重试。", + "diagnosis.guide": "查看排查文档", + "diagnosis.details": "诊断详情", + "diagnosis.roomAdmitted": "已加入房间。", + "diagnosis.sourcePageOpen": "仍可返回已打开的原网页。", + "diagnosis.noPicture": "这路分享尚未收到画面。", "channel.error.unsupportedBackupVersion": "此备份格式不受当前版本支持,请使用导出它的版本读取。", "channel.error.invalidRoomCopy": "房间副本无效,请重新导出。", "channel.error.appDisconnected": "与 App 的连接已断开。请确认 App 正在运行,然后重试。", @@ -734,6 +741,24 @@ export const zh = { "remote.preferredStopKey": "期望快捷键", "remote.preferredStopKeyHelp": "提交给系统确认,请使用下方显示的实际停止快捷键。", "remote.shortcutUnbound": "启用控制时设置", + "voice.shortcuts.title": "键盘快捷键", + "voice.shortcuts.scope": "Piik 页面或房间工具窗获得焦点时可用。", + "voice.shortcuts.reset": "恢复默认语音快捷键", + "voice.shortcuts.unbound": "未设置", + "voice.shortcuts.edit": "更改{action}快捷键({shortcut})", + "voice.shortcuts.clear": "清除{action}快捷键", + "voice.shortcuts.record": "按下快捷键,Esc 取消。", + "voice.shortcuts.unsupported": "请选择字母、数字或 F1–F11,并搭配 Ctrl、Alt 或 Command。", + "voice.shortcuts.duplicate": "另一个语音操作已使用此快捷键。", + "voice.shortcuts.background": "在其他应用中使用快捷键", + "voice.shortcuts.backgroundPending": "正在向 Windows 注册快捷键…", + "voice.shortcuts.backgroundEnabled": "下方标记的快捷键可在其他应用中使用。", + "voice.shortcuts.backgroundInUse": "另一个 Piik 页面正在使用后台快捷键。请先在那一页关闭,再来这里启用。", + "voice.shortcuts.backgroundFailed": "无法启用 Windows 快捷键。页面内快捷键仍可用。", + "voice.shortcuts.backgroundPausing": "正在释放 Windows 快捷键…", + "voice.shortcuts.backgroundPauseFailed": "请先关闭后台快捷键,再录制此组合。", + "voice.shortcuts.backgroundBindingRegistered": "可在其他应用中使用", + "voice.shortcuts.backgroundBindingUnavailable": "Windows 无法注册此快捷键。它仍可用于 Piik 页面或房间工具窗。", "remote.hostStopKeyHelp": "在本机任何应用中按下即可停止控制,设置保存在当前站点。", "remote.releaseKey": "退出控制快捷键", "remote.releaseKeyHelp": "在当前页面或独立键盘窗口中退出控制,由当前浏览器保存。", @@ -926,6 +951,8 @@ export const zh = { "client.bookmarks.switchHint": "如果离开当前站点,该页面的语音、共享和观看会结束。App 托管的房间继续运行。", "client.bookmarks.switchConfirm": "打开", "client.bookmarks.openFailed": "未能打开站点,请重试。", + "client.bookmarks.notPiik": "这个地址没有返回 Piik 站点标识。", + "client.bookmarks.unavailable": "暂时无法验证站点。请检查地址和网络后重试。", "client.bookmarks.invalidAddress": "请输入 HTTP 或 HTTPS 站点地址。", "client.connect.siteAddress": "站点地址", "client.connect.continue": "继续", diff --git a/src/client/native/wire.ts b/src/client/native/wire.ts index 206e41001..e6dc44137 100644 --- a/src/client/native/wire.ts +++ b/src/client/native/wire.ts @@ -1,6 +1,17 @@ import { z } from "zod"; import { watchFormatSchema } from "../../shared/watch-format"; +const voiceShortcutStatusSchema = z.enum(["registered", "unavailable", "unbound"]); +export const nativeVoiceShortcutsReportSchema = z.strictObject({ + microphone: voiceShortcutStatusSchema, listening: voiceShortcutStatusSchema, +}); +export type NativeVoiceShortcutsReport = z.infer; + +export const nativeVoiceShortcutEventSchema = z.strictObject({ + type: z.literal("voice_shortcut"), action: z.enum(["toggle_microphone", "toggle_listening"]), + activatedAtMs: z.number().int().positive().safe(), +}); + export const unsupportedVideoFormatSchema = z.object({ codec: z.literal("h264"), profileIdc: z.number().int().min(0).max(255), constraintFlags: z.number().int().min(0).max(255), levelIdc: z.number().int().min(0).max(255), diff --git a/src/client/pages/AppLauncherPage.tsx b/src/client/pages/AppLauncherPage.tsx index 5adb43189..25717dda6 100644 --- a/src/client/pages/AppLauncherPage.tsx +++ b/src/client/pages/AppLauncherPage.tsx @@ -21,7 +21,7 @@ import { useReleaseUpdate } from "../lib/use-release-update"; import { AppSiteBookmarks } from "./AppSiteBookmarks"; import type { SiteManagementProps } from "../components/living/SiteManagement"; import { downloadBlob } from "../lib/download"; -import { publicSiteOrigin } from "../lib/site-address"; +import { openLauncherSite, publicSiteOrigin } from "../lib/site-address"; const localCertificateSchema = z.object({ origin: z.string().url(), sha256Fingerprint: z.string().regex(/^[A-Fa-f0-9]{64}$/) }); const launcherStateSchema = z.object({ @@ -146,9 +146,11 @@ export function AppLauncherPage() { setError(previous => state.detail ? { kind: "launch", reason: state.reason, detail: state.detail } : state.target || previous?.kind === "load" ? null : previous); setLoading(false); + // External startup is opened by the launcher's site-navigation controls. + if (state.startupSite && !state.startupMode) enterOnReady = false; if (enterOnReady && (state.target || state.detail)) { enterOnReady = false; - if (state.target) window.location.replace(launchURL(state.target, { debug: state.debug === true, controlPort: state.controlPort })); + if (state.target) void enterOwnedSite(launchURL(state.target, { debug: state.debug === true, controlPort: state.controlPort }), state.windowNavigation); } if (state.starting) timer = setTimeout(() => void readState(), 750); }) @@ -219,6 +221,12 @@ export function AppLauncherPage() { return clientLaunchURL(target, presentation, settings.debug, settings.controlPort); } + async function enterOwnedSite(url: string, integrated: boolean): Promise { + if (!integrated) { window.location.replace(url); return; } + try { await openLauncherSite(url); } + catch { setError({ kind: "launch" }); setLaunching(false); } + } + function changeMode(next: AppMode): void { setMode(next); savePreferredAppMode(next); @@ -258,7 +266,7 @@ export function AppLauncherPage() { return; } const result = launcherResultSchema.parse(await response.json()); - window.location.replace(launchURL(result.target)); + await enterOwnedSite(launchURL(result.target), windowNavigation); } catch { setError({ kind: "launch" }); setLaunching(false); @@ -418,7 +426,7 @@ export function AppLauncherPage() { bookmarks={navigation.bookmarks} bookmarksError={navigation.loadError} onRetryBookmarks={navigation.retry} onOpenBookmark={navigation.open} onManageBookmarks={navigation.manage} ready={!!target} starting={starting} invitationForm={navigation.invitationForm} footer={footer} - localSiteAction={target ? + localSiteAction={target ? { event.preventDefault(); void enterOwnedSite(event.currentTarget.href, windowNavigation); }}> {t("client.connect.continue")} : setPanel("launch")} />} @@ -438,6 +446,7 @@ export function AppLauncherPage() { {starting ? :
{ event.preventDefault(); void enterOwnedSite(event.currentTarget.href, windowNavigation); }} port={sitePort === undefined ? undefined : { value: sitePort, onChange: setPortDraft }} publicEntry={localAddress ? { ...publicEntry, localAddress, error: publicEntryError ? t("client.launch.invalidPublicAddress") : undefined, diff --git a/src/client/pages/AppSiteBookmarks.tsx b/src/client/pages/AppSiteBookmarks.tsx index 1e4981348..a632f1e87 100644 --- a/src/client/pages/AppSiteBookmarks.tsx +++ b/src/client/pages/AppSiteBookmarks.tsx @@ -6,7 +6,7 @@ import { Btn } from "../components/living/primitives"; import { ChannelSettingsDialog } from "../channel/components/ChannelSettingsDialog"; import { Glyph } from "../ui/icons"; import { useCopy } from "../ui/copy"; -import { siteEntryURL } from "../lib/site-address"; +import { openLauncherSite, siteEntryError, siteEntryURL } from "../lib/site-address"; import "../components/living/site-bookmarks.css"; const bookmarksSchema = z.object({ bookmarks: z.array(z.object({ id: z.string(), origin: z.string().url(), name: z.string() })) }); @@ -23,7 +23,9 @@ export function AppSiteBookmarks({ windowNavigation, entryURL, closeOnOpen = fal const { t } = useCopy(); const [entry] = useState(() => { const hash = new URLSearchParams(location.hash.slice(1)); - return { site: hash.get("site"), open: hash.get("open") }; + const startup = render && !access.ownedStartup && new URLSearchParams(location.search).get("start") === "1" + ? access.startupSite : undefined; + return { site: hash.get("site"), open: hash.get("open") ?? startup, startup }; }); const [bookmarks, setBookmarks] = useState["bookmarks"]>(); const [loadError, setLoadError] = useState(false); @@ -36,7 +38,14 @@ export function AppSiteBookmarks({ windowNavigation, entryURL, closeOnOpen = fal const [bookmarkBusy, setBookmarkBusy] = useState(false); const busy = bookmarkBusy || access.busy; useEffect(() => { - if (entry.site || entry.open) history.replaceState(history.state, "", location.pathname + location.search); + const url = new URL(location.href); + if (entry.startup && url.searchParams.get("start") === "1") { + url.searchParams.delete("start"); + history.replaceState(history.state, "", url); + void open(entry.startup); + } else if (entry.site || entry.open) { + history.replaceState(history.state, "", location.pathname + location.search); + } }, [entry]); useEffect(() => { const abort = new AbortController(); @@ -54,7 +63,7 @@ export function AppSiteBookmarks({ windowNavigation, entryURL, closeOnOpen = fal const response = await fetch(`/api/client-launcher/bookmarks${id ? `/${encodeURIComponent(id)}` : ""}`, { method, headers: { "Content-Type": "application/json" }, body: body ? JSON.stringify(body) : undefined, }); - if (!response.ok) throw new Error(response.status === 409 ? "bookmark_exists" : "save_failed"); + if (!response.ok) throw new Error(response.status === 409 ? "bookmark_exists" : (await response.json()).detail); setBookmarks(bookmarksSchema.parse(await response.json()).bookmarks); } finally { setBookmarkBusy(false); } } @@ -65,25 +74,20 @@ export function AppSiteBookmarks({ windowNavigation, entryURL, closeOnOpen = fal setOpenError(undefined); if (!url) { setOpenError(t("client.bookmarks.invalidAddress")); return; } if (windowNavigation) setPending(url.href); - else location.assign(entryURL(url.href)); + else void open(url.href); } function cancelNavigation(): void { setPending(undefined); setOpenError(undefined); } - async function open(): Promise { - if (!pending || busy || opening) return; - if (!windowNavigation) { location.assign(entryURL(pending)); return; } + async function open(target = pending): Promise { + if (!target || busy || opening) return; setOpening(true); setOpenError(undefined); try { - const response = await fetch("/api/client-launcher/open", { - method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ url: entryURL(pending) }), - }); - if (!response.ok) throw new Error(); - z.object({ opened: z.literal(true) }).parse(await response.json()); + await openLauncherSite(entryURL(target)); setPending(undefined); - if (closeOnOpen) window.close(); - } catch { setOpenError(t("client.bookmarks.openFailed")); } + if (closeOnOpen && windowNavigation) window.close(); + } catch (error) { setOpenError(t(siteEntryError(error instanceof Error && error.message) ?? "client.bookmarks.openFailed")); } finally { setOpening(false); } } const editor = bookmarks ? value.id === publication.roomId)?.authorized, + deliveryScope: JSON.stringify([roomId, sessionId, publication.sessionId, + rooms.find(value => value.id === publication.roomId)?.delivery?.bindingId]), awaitingRoute: connected && !channel.localScreens.has(publication.id) && !channel.ownedScreens.has(publication.id) && state?.subscriptions.includes(publication.id) && !selectedInputs.has(publication.id), available: rooms.find(value => value.id === publication.roomId)?.available ?? false, diff --git a/src/client/room-voice/VoiceAudioButtons.tsx b/src/client/room-voice/VoiceAudioButtons.tsx index 0717ee2bf..043c925d2 100644 --- a/src/client/room-voice/VoiceAudioButtons.tsx +++ b/src/client/room-voice/VoiceAudioButtons.tsx @@ -2,7 +2,7 @@ import type { ComponentProps } from "react"; import { Btn } from "../components/living/primitives"; import { MicrophoneLevel } from "./MicrophoneLevel"; -type ButtonState = Pick, "disabled" | "busy" | "quiet" | "hint" | "hintText" | "onClick">; +type ButtonState = Pick, "disabled" | "busy" | "quiet" | "hint" | "hintText" | "keyShortcuts" | "onClick">; export function VoiceMicrophoneButton({ active, level, ...button }: ButtonState & { active: boolean; level?: number }) { return , { debug = false, mode, startup = const actions = runInNewContext(executable, { ...setters, z, fetch, window, URLSearchParams, AbortController, downloadBlob: downloads, stateChanges: { current: { revision: 0, pending: 0 } }, - siteBusy: false, debugBusy: false, starting: false, sites: saved.sites, startupSite: saved.startupSite, openOnApproval: false, + windowNavigation: false, siteBusy: false, debugBusy: false, starting: false, sites: saved.sites, startupSite: saved.startupSite, openOnApproval: false, mode: initialMode, lang: "en", appDebug: debug, lan: saved.lan, sitePort: saved.sitePort, savePreferredAppMode, publicEntry: { existing: publicOrigin !== undefined, origin: publicOrigin ?? "" }, publicSiteOrigin, consoleLanguage: () => "en", clientLaunchURL, currentThemePreference: () => null, hasCopyPreference: () => false, diff --git a/tests/channel-app-page.test.ts b/tests/channel-app-page.test.ts index e0716d59a..4acd8b966 100644 --- a/tests/channel-app-page.test.ts +++ b/tests/channel-app-page.test.ts @@ -34,6 +34,26 @@ async function openPage(app: ChannelApp, socket: Socket) { } const state = { position: 12, paused: false, rate: 1, duration: null, readyState: 4, ended: false, buffered: [[0, 60]] as [number, number][] }; +test("background voice shortcuts accept small clock differences and discard delayed or far-future events", async () => { + vi.stubGlobal("WebSocket", Socket); + const app = new ChannelApp({ service: "piik-channel-app", protocol: APP_PROTOCOL, domainProtocol: CHANNEL_PROTOCOL, + token: "test-token", port: 8793, backgroundVoiceShortcuts: true }, "site", "user", "credential", "Me", + () => {}, () => {}, undefined, undefined, undefined, () => true); + const socket = Socket.current; + socket.onopen?.(); socket.reply(null); await app.ready; + const listener = vi.fn(); + const unsubscribe = app.backgroundVoiceShortcuts!.subscribe(listener); + const now = 1_795_326_377_608; + const clock = vi.spyOn(Date, "now").mockReturnValue(now); + try { + socket.receive({ type: "voice_shortcut", action: "toggle_microphone", activatedAtMs: now + 1 }); + socket.receive({ type: "voice_shortcut", action: "toggle_listening", activatedAtMs: now }); + socket.receive({ type: "voice_shortcut", action: "toggle_microphone", activatedAtMs: now - 1_450 }); + socket.receive({ type: "voice_shortcut", action: "toggle_listening", activatedAtMs: now + 10_000 }); + expect(listener.mock.calls).toEqual([["microphone"], ["listening"]]); + } finally { clock.mockRestore(); unsubscribe(); app.close(); } +}); + test("page readiness rechecks events delivered before an older read reply", async () => { vi.useFakeTimers(); const { app, socket } = await setup(), cancel = new AbortController(); diff --git a/tests/channel-diagnosis.test.ts b/tests/channel-diagnosis.test.ts new file mode 100644 index 000000000..c137cc757 --- /dev/null +++ b/tests/channel-diagnosis.test.ts @@ -0,0 +1,32 @@ +import { describe, expect, it } from "vitest"; +import { diagnoseChannelFact } from "../src/client/channel/diagnosis"; +import { channelErrorPresentation } from "../src/client/channel/error-presentation"; + +describe("diagnosis using the current operation", () => { + it("offers the local approval page when discovery succeeds, and asserts denied access only on an explicit refusal", () => { + expect(diagnoseChannelFact({ area: "app", state: "approval" })).toMatchObject({ message: "client.connect.found", next: "client.connect.open" }); + expect(diagnoseChannelFact({ area: "app", state: "approving" })).toBeNull(); + expect(channelErrorPresentation("site_not_approved", key => key).message).toBe("client.sites.notAllowed"); + expect(diagnoseChannelFact({ area: "app", state: "unavailable" })?.message).toBe("client.connect.unavailable"); + }); + + it("keeps room availability, admission and the selected picture's retry separate", () => { + expect(diagnoseChannelFact({ area: "room", room: { available: false, authorized: false } })?.message).toBe("room.offline.access"); + expect(diagnoseChannelFact({ area: "room", room: { available: true, authorized: false } })).toBeNull(); + expect(diagnoseChannelFact({ area: "error", code: "room_access_required" })?.topic).toBe("room"); + expect(diagnoseChannelFact({ area: "error", code: "ice_failed" })).toBeNull(); + expect(diagnoseChannelFact({ area: "screen", paused: false, deliveryFailed: true })?.message).toBe("diagnosis.noPicture"); + expect(diagnoseChannelFact({ area: "screen", paused: true, deliveryFailed: true })).toBeNull(); + expect(diagnoseChannelFact({ area: "screen", paused: false, deliveryFailed: false })).toBeNull(); + }); + + it("keeps source permissions, failed reads, attachment waits and incompatible storage tied to their own operations", () => { + expect(diagnoseChannelFact({ area: "error", code: "watch_media_access_denied" })?.message).toBe("watch.mediaAccessDenied"); + expect(diagnoseChannelFact({ area: "error", code: "watch_media_timeout" })?.message).toBe("watch.forward.sourceUnavailable"); + expect(diagnoseChannelFact({ area: "error", code: "capture_targets_failed" })?.topic).toBe("capture"); + expect(diagnoseChannelFact({ area: "attachment", state: "waiting-source" })?.topic).toBe("attachment"); + expect(diagnoseChannelFact({ area: "attachment", state: "connecting" })).toBeNull(); + expect(diagnoseChannelFact({ area: "error", code: "unsupported_storage_version" })?.topic).toBe("storage"); + expect(diagnoseChannelFact({ area: "error", code: "unsupported_backup_version" })).toBeNull(); + }); +}); diff --git a/tests/channel-session.test.ts b/tests/channel-session.test.ts index 22777219a..feb52a6be 100644 --- a/tests/channel-session.test.ts +++ b/tests/channel-session.test.ts @@ -10958,15 +10958,16 @@ test('webpage sharing commits the current top-level URL delivered before selecti } finally { session.close(); } }); -test('selecting a child webpage keeps its updated URL through empty source discovery and explicit confirmation', async () => { +test.each(['original-page', 'choose-source'] as const)('selecting a child webpage keeps its updated URL in %s mode', async mode => { const { session } = await setup(1000, false); const pageId = crypto.randomUUID(), candidateId = crypto.randomUUID(); let confirm!: (state: unknown) => void; const ready = { position: 12, paused: false, rate: 1, duration: 60, readyState: 4, ended: false, buffered: [[0, 60]] }; const dispose = vi.fn(); + const discover = vi.fn(async () => ({ choices: [], indexedCandidates: [], mpdCandidates: [], byteSource: null })); const page = new appLink.AppPage(pageId, 'https://video.test/', command => { if (command.type === 'page_select') return new Promise(resolve => { confirm = resolve; }); - if (command.type === 'page_media_sources') return Promise.resolve({ choices: [], indexedCandidates: [], byteSource: null }); + if (command.type === 'page_media_sources') return discover(); return Promise.resolve(ready); }, dispose, () => {}); const app = { preparePage: vi.fn(async () => page), stopCaptures: vi.fn(), close: () => page.close() } as unknown as appLink.ChannelApp; @@ -10975,16 +10976,27 @@ test('selecting a child webpage keeps its updated URL through empty source disco const commit = vi.spyOn(session as unknown as { commitWatch(roomId: string, source: unknown, media: unknown, selection: unknown): Promise }, 'commitWatch').mockResolvedValue(); try { await session.prepareWatchPage('first', page.url); - page.receive({ type: 'page_candidates', pageId, url: page.url, candidates: [{ id: candidateId, title: 'Child video', url: null, duration: 60 }] }); - const selecting = session.selectWatchPage('first', candidateId); - // Native resolves the selected view before confirming page_select; the homepage stays open. - page.receive({ type: 'page_candidates', pageId, url: 'https://video.test/video/child', candidates: [{ id: candidateId, title: 'Child video', url: null, duration: 60 }] }); - confirm(ready); - await expect(selecting).resolves.toBe(false); - expect(session.watchPage('first')).toMatchObject({ url: 'https://video.test/video/child', watchSources: { candidateId, choices: [], indexed: [] } }); + const candidates = [ + { id: crypto.randomUUID(), title: 'Homepage trailer', url: null, duration: 10 }, + { id: candidateId, title: 'Child video', url: 'https://media.test/child.mp4', duration: 60 }, + ]; + expect(session.watchPage('first')?.candidates).toHaveLength(0); + page.receive({ type: 'page_candidates', pageId, url: page.url, candidates }); expect(commit).not.toHaveBeenCalled(); + const selecting = session.selectWatchPage('first', candidateId, undefined, false, mode); + // Native resolves the selected view before confirming page_select; the homepage stays open. + page.receive({ type: 'page_candidates', pageId, url: 'https://video.test/video/child', candidates }); + confirm(ready); + await expect(selecting).resolves.toBe(mode === 'original-page'); + expect(page.selectedCandidateId).toBe(candidateId); expect(dispose).not.toHaveBeenCalled(); - await session.selectWatchBrowserSource('first', null); + if (mode === 'original-page') { + expect(discover).not.toHaveBeenCalled(); + } else { + expect(session.watchPage('first')).toMatchObject({ url: 'https://video.test/video/child', watchSources: { candidateId, choices: [], indexed: [] } }); + expect(commit).not.toHaveBeenCalled(); + await session.selectWatchBrowserSource('first', null); + } expect(commit.mock.calls[0]?.[1]).toEqual({ kind: 'website', url: 'https://video.test/video/child' }); } finally { session.close(); } }); @@ -11241,6 +11253,7 @@ test.each(['portable', 'forward'] as const)('a live %s selection keeps the prepa const start = socket.sent.findLast(command => command.type === 'start_watch')!; expect(start.playback).toMatchObject({ timeline: 'program', position: epoch + 6 }); expect(start.byteSource).toEqual(mode === 'forward' ? source : undefined); + expect(start.source).toEqual({ kind: 'website', url: page.url, ...(mode === 'portable' && { mediaUrl: choice.displayURL }) }); expect(prepare).toHaveBeenCalledTimes(mode === 'forward' ? 1 : 0); socket.receive({ type: 'room_reply', roomId: 'first', requestId: start.requestId, result: { type: 'watch_ready', serverTime: 1000 } }); await vi.waitFor(() => expect(socket.sent.some(command => command.type === 'update_watch')).toBe(true)); @@ -11997,8 +12010,8 @@ test.each(['direct', 'choice'] as const)('portable %s preparation failure retain } finally { session.close(); } }); -test('a direct URL inspection failure discovers page resources before explicit forwarding commits', async () => { - const choice = { id: crypto.randomUUID(), displayURL: 'https://media.test/no-cors.mp4', name: 'Original video', format: 'file' as const }; +test('explicit file forwarding publishes the selected direct URL and retains the App reader', async () => { + const choice = { id: crypto.randomUUID(), displayURL: 'https://media.test/no-cors.mp4?signature=fixture', name: 'Original video', format: 'file' as const }; const discover = vi.fn(async () => ({ choices: [choice], indexedCandidates: [], byteSource: null })); const { session, page, candidateId, commit, dispose, socket } = await websiteSourceSelection(discover); commit.mockRestore(); @@ -12024,7 +12037,7 @@ test('a direct URL inspection failure discovers page resources before explicit f await vi.waitFor(() => expect(socket.sent.some(command => command.type === 'start_watch')).toBe(true)); const start = socket.sent.findLast(command => command.type === 'start_watch')!; expect(prepare).toHaveBeenCalledWith(choice.id, expect.any(AbortSignal)); - expect(start.source).toEqual({ kind: 'website', url: page.url }); + expect(start.source).toEqual({ kind: 'website', url: page.url, mediaUrl: choice.displayURL }); expect(start.byteSource).toEqual(byteSource); socket.receive({ type: 'room_reply', roomId: 'first', requestId: start.requestId, result: { type: 'watch_ready', serverTime: 1000 } }); await vi.waitFor(() => expect(socket.sent.some(command => command.type === 'update_watch')).toBe(true)); diff --git a/tests/retry-picture-controls.test.ts b/tests/retry-picture-controls.test.ts index 8792e489d..d73415107 100644 --- a/tests/retry-picture-controls.test.ts +++ b/tests/retry-picture-controls.test.ts @@ -18,8 +18,7 @@ test("picture retry is immediately available for waiting remote screens",()=>{ const help = buttons.find(tag => tag.includes('aria-label="Picture help"')); const disabledAttribute = /\s(?:disabled(?=[\s=>])|aria-disabled="true")/; expect(retry).toMatch(disabledAttribute); - expect(help).toBeDefined(); - expect(help).not.toMatch(disabledAttribute); + expect(help).toBeUndefined(); for (const state of [{ deliveryFailed: false }, { paused: true }, { owned: true }, { localSource: true }, { stream }, { hidden: true }]) { const markup = renderToStaticMarkup(createElement(ChannelStage, { ...props, sources: [{ ...source, ...state }] })); expect(markup).not.toContain('aria-label="Picture help"'); diff --git a/tests/viewer-playback.test.ts b/tests/viewer-playback.test.ts index 1face4d82..4eedd054d 100644 --- a/tests/viewer-playback.test.ts +++ b/tests/viewer-playback.test.ts @@ -160,6 +160,7 @@ describe("Screen delivery result", () => { onInputPolicy: vi.fn(), onInputDecide: vi.fn(), onInputSimultaneous: vi.fn(), onInputShortcut: vi.fn() }; const failed = renderToStaticMarkup(createElement(ChannelStage, props)); expect(failed).toContain("Picture delivery failed. Retrying."); + expect(failed).toContain('aria-label="Picture help"'); expect(failed).not.toContain("Connecting picture"); expect(failed).toContain('aria-label="Stop watching Shared screen"'); @@ -170,6 +171,12 @@ describe("Screen delivery result", () => { expect(retained).toContain('aria-label="Stop watching Shared screen"'); const paused = renderToStaticMarkup(createElement(ChannelStage, { ...props, sources: [{ ...source, paused: true }] })); expect(paused).not.toContain("Picture delivery failed"); + expect(paused).not.toContain('aria-label="Picture help"'); + + const reconnecting = renderToStaticMarkup(createElement(ChannelStage, { ...props, canSubscribe: false })); + expect(reconnecting).not.toContain('aria-label="Picture help"'); + const retrying = renderToStaticMarkup(createElement(ChannelStage, { ...props, sources: [{ ...source, pending: true }] })); + expect(retrying).not.toContain('aria-label="Picture help"'); }); }); diff --git a/tests/watch-presentation.test.ts b/tests/watch-presentation.test.ts index e026273f7..381f0b170 100644 --- a/tests/watch-presentation.test.ts +++ b/tests/watch-presentation.test.ts @@ -205,7 +205,8 @@ describe("Webpage watch presentation", () => { expect(html).toContain(t("en", "watch.browserSource.originalHelp")); expect(html.indexOf(t("en", "watch.browserSource.originalHelp"))).toBeLessThan(html.indexOf('aria-label="Share original webpage only"')); expect(html.includes('aria-label="Play Owned video in Piik"')).toBe(direct); - expect(html.includes('aria-label="Forward Owned video"')).toBe(direct); + expect(html.includes(`aria-label="${t("en", "watch.forward.shareFile")}"`)).toBe(direct); + expect(html.includes(t("en", "watch.forward.shareFileHelp"))).toBe(direct); });